├── .gitignore ├── rebar ├── .mailmap ├── .travis.yml ├── rebar.config ├── src ├── folsom.app.src ├── folsom_metrics_gauge.erl ├── folsom_sample_none.erl ├── folsom_sample_slide_sorted.erl ├── folsom_sample_slide_sup.erl ├── folsom.erl ├── folsom_metrics_counter.erl ├── folsom_sample_uniform.erl ├── folsom_sample_slide.erl ├── folsom_metrics_histogram.erl ├── folsom_metrics_history.erl ├── folsom_ewma.erl ├── folsom_sample_slide_server.erl ├── folsom_sample.erl ├── folsom_sample_slide_uniform.erl ├── folsom_metrics_duration.erl ├── folsom_metrics_spiral.erl ├── folsom_utils.erl ├── folsom_sup.erl ├── folsom_metrics_meter.erl ├── folsom_sample_exdec.erl ├── folsom_metrics_meter_reader.erl ├── folsom_metrics_histogram_ets.erl ├── folsom_meter_timer_server.erl ├── folsom_metrics.erl ├── folsom_vm_metrics.erl └── folsom_ets.erl ├── test ├── folsom_tests.erl ├── cpu_topo_data ├── slide_statem_eqc.erl ├── slide_uniform_eqc.erl ├── folsom_sample_slide_test.erl ├── mochinum.erl └── folsom_erlang_checks.erl ├── include └── folsom.hrl ├── README.md └── LICENSE /.gitignore: -------------------------------------------------------------------------------- 1 | /deps 2 | /.eunit 3 | ebin/* 4 | *# 5 | *~ 6 | -------------------------------------------------------------------------------- /rebar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/boundary/folsom/HEAD/rebar -------------------------------------------------------------------------------- /.mailmap: -------------------------------------------------------------------------------- 1 | Joe Williams 2 | Joe Williams 3 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: erlang 2 | 3 | script: rebar get-deps compile && rebar skip_deps=true eunit 4 | 5 | otp_release: 6 | - 17.3 7 | - 17.1 8 | - 17.0 9 | - R16B03-1 10 | - R16B03 11 | - R16B02 12 | -------------------------------------------------------------------------------- /rebar.config: -------------------------------------------------------------------------------- 1 | {sub_dirs, ["deps"]}. 2 | 3 | {deps, [ 4 | {'bear', ".*", {git, "git://github.com/boundary/bear.git", {tag, "0.8.2"}}}, 5 | {meck, ".*", {git, "git://github.com/eproxus/meck", {tag, "0.8.2"}}} 6 | ]}. 7 | 8 | {erl_opts, [debug_info]}. 9 | {cover_enabled, true}. 10 | -------------------------------------------------------------------------------- /src/folsom.app.src: -------------------------------------------------------------------------------- 1 | %% -*- mode: erlang -*- 2 | {application, folsom, 3 | [ 4 | {description, "Erlang based metrics system"}, 5 | {vsn, git}, 6 | {modules, []}, 7 | {registered, [folsom_meter_timer_server, 8 | folsom_metrics_histogram_ets, 9 | folsom_sup]}, 10 | {applications, [ 11 | kernel, 12 | stdlib, 13 | bear 14 | ]}, 15 | {env, []}, 16 | {mod, {folsom, []}} 17 | ]}. 18 | -------------------------------------------------------------------------------- /src/folsom_metrics_gauge.erl: -------------------------------------------------------------------------------- 1 | %%% 2 | %%% Copyright 2011, Boundary 3 | %%% 4 | %%% Licensed under the Apache License, Version 2.0 (the "License"); 5 | %%% you may not use this file except in compliance with the License. 6 | %%% You may obtain a copy of the License at 7 | %%% 8 | %%% http://www.apache.org/licenses/LICENSE-2.0 9 | %%% 10 | %%% Unless required by applicable law or agreed to in writing, software 11 | %%% distributed under the License is distributed on an "AS IS" BASIS, 12 | %%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | %%% See the License for the specific language governing permissions and 14 | %%% limitations under the License. 15 | %%% 16 | 17 | 18 | %%%------------------------------------------------------------------- 19 | %%% File: folsom_metrics_gauge.erl 20 | %%% @author joe williams 21 | %%% @doc 22 | %%% @end 23 | %%%----------------------------------------------------------------- 24 | 25 | -module(folsom_metrics_gauge). 26 | 27 | -export([new/1, 28 | update/2, 29 | clear/1, 30 | get_value/1]). 31 | 32 | -include("folsom.hrl"). 33 | 34 | new(Name) -> 35 | Gauge = {Name, 0}, 36 | ets:insert(?GAUGE_TABLE, Gauge). 37 | 38 | update(Name, Value) -> 39 | Gauge = {Name, Value}, 40 | ets:insert(?GAUGE_TABLE, Gauge). 41 | 42 | clear(Name) -> 43 | new(Name). 44 | 45 | get_value(Name) -> 46 | [{_, Values}] = ets:lookup(?GAUGE_TABLE, Name), 47 | Values. 48 | -------------------------------------------------------------------------------- /src/folsom_sample_none.erl: -------------------------------------------------------------------------------- 1 | %%% 2 | %%% Copyright 2011, Boundary 3 | %%% 4 | %%% Licensed under the Apache License, Version 2.0 (the "License"); 5 | %%% you may not use this file except in compliance with the License. 6 | %%% You may obtain a copy of the License at 7 | %%% 8 | %%% http://www.apache.org/licenses/LICENSE-2.0 9 | %%% 10 | %%% Unless required by applicable law or agreed to in writing, software 11 | %%% distributed under the License is distributed on an "AS IS" BASIS, 12 | %%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | %%% See the License for the specific language governing permissions and 14 | %%% limitations under the License. 15 | %%% 16 | 17 | 18 | %%%------------------------------------------------------------------- 19 | %%% File: folsom_sample_none.erl 20 | %%% @author joe williams 21 | %%% @doc 22 | %%% no sampling, just a capped circular buffer 23 | %%% @end 24 | %%%----------------------------------------------------------------- 25 | 26 | -module(folsom_sample_none). 27 | 28 | -export([ 29 | new/1, 30 | update/2, 31 | get_values/1 32 | ]). 33 | 34 | -include("folsom.hrl"). 35 | 36 | new(Size) -> 37 | #none{size = Size}. 38 | 39 | update(#none{size = Size, reservoir = Reservoir, n = N} = Sample, Value) 40 | when N =:= Size -> 41 | ets:insert(Reservoir, {N, Value}), 42 | Sample#none{n = 1}; 43 | update(#none{reservoir = Reservoir, n = N} = Sample, Value) -> 44 | ets:insert(Reservoir, {N, Value}), 45 | Sample#none{n = N + 1}. 46 | 47 | get_values(#none{reservoir = Reservoir}) -> 48 | {_, Values} = lists:unzip(ets:tab2list(Reservoir)), 49 | Values. 50 | -------------------------------------------------------------------------------- /src/folsom_sample_slide_sorted.erl: -------------------------------------------------------------------------------- 1 | %%% 2 | %%% Copyright 2011, Boundary 3 | %%% 4 | %%% Licensed under the Apache License, Version 2.0 (the "License"); 5 | %%% you may not use this file except in compliance with the License. 6 | %%% You may obtain a copy of the License at 7 | %%% 8 | %%% http://www.apache.org/licenses/LICENSE-2.0 9 | %%% 10 | %%% Unless required by applicable law or agreed to in writing, software 11 | %%% distributed under the License is distributed on an "AS IS" BASIS, 12 | %%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | %%% See the License for the specific language governing permissions and 14 | %%% limitations under the License. 15 | %%% 16 | 17 | 18 | %%%------------------------------------------------------------------- 19 | %%% File: folsom_sample_slide_sorted.erl 20 | %%% @author Ramon Lastres 21 | %%% @doc 22 | %%% simple sliding window histogram. 23 | %%% @end 24 | %%%----------------------------------------------------------------- 25 | 26 | -module(folsom_sample_slide_sorted). 27 | 28 | -export([ 29 | new/1, 30 | update/2, 31 | get_values/1 32 | ]). 33 | 34 | -include("folsom.hrl"). 35 | 36 | new(Size) -> 37 | #slide_sorted{size = Size}. 38 | 39 | update(#slide_sorted{size = Size, reservoir = Reservoir, n = N} = Sample, Value) 40 | when N < Size -> 41 | ets:insert(Reservoir, {os:timestamp(), Value}), 42 | Sample#slide_sorted{n = N + 1}; 43 | update(#slide_sorted{reservoir = Reservoir, n = N, size = Size} = Sample, Value) 44 | when N == Size -> 45 | Oldest = ets:first(Reservoir), 46 | ets:delete(Reservoir, Oldest), 47 | ets:insert(Reservoir, {os:timestamp(), Value}), 48 | Sample. 49 | 50 | get_values(#slide_sorted{reservoir = Reservoir}) -> 51 | {_, Values} = lists:unzip(ets:tab2list(Reservoir)), 52 | Values. 53 | -------------------------------------------------------------------------------- /src/folsom_sample_slide_sup.erl: -------------------------------------------------------------------------------- 1 | %% ------------------------------------------------------------------- 2 | %% 3 | %% Copyright (c) 2011 Basho Technologies, Inc. 4 | %% 5 | %% This file is provided to you under the Apache License, 6 | %% Version 2.0 (the "License"); you may not use this file 7 | %% except in compliance with the License. You may obtain 8 | %% 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, 13 | %% software distributed under the License is distributed on an 14 | %% "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 15 | %% KIND, either express or implied. See the License for the 16 | %% specific language governing permissions and limitations 17 | %% under the License. 18 | %% 19 | %% ------------------------------------------------------------------- 20 | %%%------------------------------------------------------------------- 21 | %%% File: folsom_sample_slide_sup.erl 22 | %%% @author Russell Brown 23 | %%% @doc 24 | %%% Starts simple_one_for_one children per slide sample 25 | %%% @end 26 | %%%----------------------------------------------------------------- 27 | -module(folsom_sample_slide_sup). 28 | -behaviour(supervisor). 29 | 30 | %% beahvior functions 31 | -export([start_link/0, 32 | init/1 33 | ]). 34 | 35 | %% public functions 36 | -export([start_slide_server/3]). 37 | 38 | start_link () -> 39 | supervisor:start_link({local,?MODULE},?MODULE,[]). 40 | 41 | start_slide_server(SampleMod, Reservoir, Window) -> 42 | {ok, Pid} = supervisor:start_child(?MODULE, [SampleMod, Reservoir, Window]), 43 | Pid. 44 | 45 | %% @private 46 | init ([]) -> 47 | {ok,{{simple_one_for_one, 3, 180}, 48 | [ 49 | {undefined, {folsom_sample_slide_server, start_link, []}, 50 | transient, brutal_kill, worker, [folsom_sample_slide_server]} 51 | ]}}. 52 | -------------------------------------------------------------------------------- /src/folsom.erl: -------------------------------------------------------------------------------- 1 | %%% 2 | %%% Copyright 2011, Boundary 3 | %%% 4 | %%% Licensed under the Apache License, Version 2.0 (the "License"); 5 | %%% you may not use this file except in compliance with the License. 6 | %%% You may obtain a copy of the License at 7 | %%% 8 | %%% http://www.apache.org/licenses/LICENSE-2.0 9 | %%% 10 | %%% Unless required by applicable law or agreed to in writing, software 11 | %%% distributed under the License is distributed on an "AS IS" BASIS, 12 | %%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | %%% See the License for the specific language governing permissions and 14 | %%% limitations under the License. 15 | %%% 16 | 17 | 18 | %%%------------------------------------------------------------------- 19 | %%% File: folsom.erl 20 | %%% @author joe williams 21 | %%% @doc 22 | %%% @end 23 | %%%------------------------------------------------------------------ 24 | 25 | -module(folsom). 26 | -export([start/0, stop/0]). 27 | -export([start/2, stop/1]). 28 | -behaviour(application). 29 | -define(APP, ?MODULE). 30 | 31 | start() -> 32 | application:start(?APP). 33 | 34 | stop() -> 35 | application:stop(?APP). 36 | 37 | start(_Type, _Args) -> 38 | {ok, Pid} = folsom_sup:start_link(), 39 | lists:foreach(fun configure/1, 40 | [{counter, new_counter}, 41 | {gauge, new_gauge}, 42 | {histogram, new_histogram}, 43 | {history, new_history}, 44 | {meter, new_meter}, 45 | {spiral, new_spiral}, 46 | {meter_reader, new_meter_reader}]), 47 | {ok, Pid}. 48 | 49 | stop(_State) -> 50 | ok. 51 | 52 | %% internal 53 | configure({K, New}) -> 54 | case application:get_env(?APP, K) of 55 | {ok, Specs} when is_list(Specs) -> 56 | [configure_metric(New, Spec) || Spec <- Specs]; 57 | {ok, Spec} -> 58 | configure_metric(New, Spec); 59 | undefined -> ok 60 | end. 61 | 62 | configure_metric(New, Spec) when is_list(Spec) -> 63 | apply(folsom_metrics, New, Spec); 64 | configure_metric(New, Name) -> 65 | folsom_metrics:New(Name). 66 | -------------------------------------------------------------------------------- /src/folsom_metrics_counter.erl: -------------------------------------------------------------------------------- 1 | %%% 2 | %%% Copyright 2011, Boundary 3 | %%% 4 | %%% Licensed under the Apache License, Version 2.0 (the "License"); 5 | %%% you may not use this file except in compliance with the License. 6 | %%% You may obtain a copy of the License at 7 | %%% 8 | %%% http://www.apache.org/licenses/LICENSE-2.0 9 | %%% 10 | %%% Unless required by applicable law or agreed to in writing, software 11 | %%% distributed under the License is distributed on an "AS IS" BASIS, 12 | %%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | %%% See the License for the specific language governing permissions and 14 | %%% limitations under the License. 15 | %%% 16 | 17 | 18 | %%%------------------------------------------------------------------- 19 | %%% File: folsom_metrics_counter.erl 20 | %%% @author joe williams 21 | %%% @doc 22 | %%% @end 23 | %%%----------------------------------------------------------------- 24 | 25 | -module(folsom_metrics_counter). 26 | 27 | -export([new/1, 28 | inc/1, 29 | inc/2, 30 | dec/1, 31 | dec/2, 32 | get_value/1, 33 | clear/1, 34 | delete/1]). 35 | 36 | -define(WIDTH, 16). %% Keep this a power of two 37 | 38 | -include("folsom.hrl"). 39 | 40 | new(Name) -> 41 | Counters = [{{Name,N}, 0} || N <- lists:seq(0,?WIDTH-1)], 42 | ets:insert(?COUNTER_TABLE, Counters). 43 | 44 | inc(Name) -> 45 | ets:update_counter(?COUNTER_TABLE, key(Name), 1). 46 | 47 | inc(Name, Value) -> 48 | ets:update_counter(?COUNTER_TABLE, key(Name), Value). 49 | 50 | dec(Name) -> 51 | ets:update_counter(?COUNTER_TABLE, key(Name), -1). 52 | 53 | dec(Name, Value) -> 54 | ets:update_counter(?COUNTER_TABLE, key(Name), -Value). 55 | 56 | get_value(Name) -> 57 | Count = lists:sum(ets:select(?COUNTER_TABLE, [{{{Name,'_'},'$1'},[],['$1']}])), 58 | Count. 59 | 60 | clear(Name) -> 61 | new(Name). 62 | 63 | delete(Name) -> 64 | Counters = [{Name,N} || N <- lists:seq(0,?WIDTH-1)], 65 | [ets:delete(?COUNTER_TABLE, Counter) || Counter <- Counters], 66 | ok. 67 | 68 | key(Name) -> 69 | X = erlang:system_info(scheduler_id), 70 | Rnd = X band (?WIDTH-1), 71 | {Name, Rnd}. 72 | -------------------------------------------------------------------------------- /src/folsom_sample_uniform.erl: -------------------------------------------------------------------------------- 1 | %%% 2 | %%% Copyright 2011, Boundary 3 | %%% 4 | %%% Licensed under the Apache License, Version 2.0 (the "License"); 5 | %%% you may not use this file except in compliance with the License. 6 | %%% You may obtain a copy of the License at 7 | %%% 8 | %%% http://www.apache.org/licenses/LICENSE-2.0 9 | %%% 10 | %%% Unless required by applicable law or agreed to in writing, software 11 | %%% distributed under the License is distributed on an "AS IS" BASIS, 12 | %%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | %%% See the License for the specific language governing permissions and 14 | %%% limitations under the License. 15 | %%% 16 | 17 | 18 | %%%------------------------------------------------------------------- 19 | %%% File: folsom_sample_uniform.erl 20 | %%% @author joe williams 21 | %%% @doc 22 | %%% erlang implementation of a uniform random sample 23 | %%% based on a java implementation by coda hale, which can be found at: 24 | %%% 25 | %%% https://github.com/codahale/metrics/blob/development/src/main/java/com/yammer/metrics/core/UniformSample.java 26 | %%% 27 | %%% that implementation is based on algorithm R in: 28 | %%% 29 | %%% http://www.cs.umd.edu/~samir/498/vitter.pdf 30 | %%% @end 31 | %%%----------------------------------------------------------------- 32 | 33 | -module(folsom_sample_uniform). 34 | 35 | -export([ 36 | new/1, 37 | update/2, 38 | get_values/1 39 | ]). 40 | 41 | -include("folsom.hrl"). 42 | 43 | new(Size) -> 44 | #uniform{size = Size}. 45 | 46 | update(#uniform{size = Size, reservoir = Reservoir, n = N} = Sample, Value) when N =< Size -> 47 | ets:insert(Reservoir, {N, Value}), 48 | Sample#uniform{n = N + 1}; 49 | 50 | update(#uniform{reservoir = Reservoir, size = Size, n = N, seed = Seed} = Sample, 51 | Value) -> 52 | {Rnd, New_seed} = random:uniform_s(N, Seed), 53 | maybe_update(Rnd, Size, Value, Reservoir), 54 | Sample#uniform{n = N + 1, seed = New_seed}. 55 | 56 | get_values(#uniform{reservoir = Reservoir}) -> 57 | {_, Values} = lists:unzip(ets:tab2list(Reservoir)), 58 | Values. 59 | 60 | maybe_update(Rnd, Size, Value, Reservoir) when Rnd < Size -> 61 | ets:insert(Reservoir, {Rnd, Value}); 62 | maybe_update(_Rnd, _Size, _Value, _Reservoir) -> 63 | ok. 64 | -------------------------------------------------------------------------------- /src/folsom_sample_slide.erl: -------------------------------------------------------------------------------- 1 | %%% 2 | %%% Copyright 2012, Basho Technologies, Inc. All Rights Reserved. 3 | %%% 4 | %%% Licensed under the Apache License, Version 2.0 (the "License"); 5 | %%% you may not use this file except in compliance with the License. 6 | %%% You may obtain a copy of the License at 7 | %%% 8 | %%% http://www.apache.org/licenses/LICENSE-2.0 9 | %%% 10 | %%% Unless required by applicable law or agreed to in writing, software 11 | %%% distributed under the License is distributed on an "AS IS" BASIS, 12 | %%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | %%% See the License for the specific language governing permissions and 14 | %%% limitations under the License. 15 | %%% 16 | %%%------------------------------------------------------------------- 17 | %%% File: folsom_sample_slide.erl 18 | %%% @author Russell Brown 19 | %%% @doc 20 | %%% Sliding window sample. Last Window seconds readings are recorded. 21 | %%% @end 22 | %%%----------------------------------------------------------------- 23 | 24 | -module(folsom_sample_slide). 25 | 26 | -export([ 27 | new/1, 28 | update/2, 29 | get_values/1, 30 | moment/0, 31 | trim/2, 32 | resize/2 33 | ]). 34 | 35 | -include("folsom.hrl"). 36 | 37 | -define(WIDTH, 16). %% Keep this a power of two 38 | 39 | new(Size) -> 40 | Sample = #slide{window = Size}, 41 | Pid = folsom_sample_slide_sup:start_slide_server(?MODULE, Sample#slide.reservoir, Sample#slide.window), 42 | Sample#slide{server=Pid}. 43 | 44 | update(#slide{reservoir = Reservoir} = Sample, Value) -> 45 | Moment = moment(), 46 | X = erlang:system_info(scheduler_id), 47 | Rnd = X band (?WIDTH-1), 48 | ets:insert(Reservoir, {{Moment, Rnd}, Value}), 49 | Sample. 50 | 51 | resize(Sample, NewSize) -> 52 | folsom_sample_slide_server:resize(Sample#slide.server, NewSize), 53 | Sample#slide{window = NewSize}. 54 | 55 | get_values(#slide{window = Window, reservoir = Reservoir}) -> 56 | Oldest = moment() - Window, 57 | ets:select(Reservoir, [{{{'$1','_'},'$2'},[{'>=', '$1', Oldest}],['$2']}]). 58 | 59 | moment() -> 60 | folsom_utils:now_epoch(). 61 | 62 | trim(Reservoir, Window) -> 63 | Oldest = moment() - Window, 64 | ets:select_delete(Reservoir, [{{{'$1','_'},'_'},[{'<', '$1', Oldest}],['true']}]). 65 | -------------------------------------------------------------------------------- /src/folsom_metrics_histogram.erl: -------------------------------------------------------------------------------- 1 | %%% 2 | %%% Copyright 2011, Boundary 3 | %%% 4 | %%% Licensed under the Apache License, Version 2.0 (the "License"); 5 | %%% you may not use this file except in compliance with the License. 6 | %%% You may obtain a copy of the License at 7 | %%% 8 | %%% http://www.apache.org/licenses/LICENSE-2.0 9 | %%% 10 | %%% Unless required by applicable law or agreed to in writing, software 11 | %%% distributed under the License is distributed on an "AS IS" BASIS, 12 | %%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | %%% See the License for the specific language governing permissions and 14 | %%% limitations under the License. 15 | %%% 16 | 17 | 18 | %%%------------------------------------------------------------------- 19 | %%% File: folsom_metrics_histogram.erl 20 | %%% @author joe williams 21 | %%% @doc 22 | %%% @end 23 | %%%------------------------------------------------------------------ 24 | 25 | -module(folsom_metrics_histogram). 26 | 27 | -export([new/1, 28 | new/2, 29 | new/3, 30 | new/4, 31 | update/2, 32 | get_value/1, 33 | get_values/1 34 | ]). 35 | 36 | -include("folsom.hrl"). 37 | 38 | new(Name) -> 39 | new(Name, uniform). 40 | 41 | new(Name, slide) -> 42 | new(Name, slide, ?DEFAULT_SLIDING_WINDOW); 43 | new(Name, slide_uniform) -> 44 | new(Name, slide_uniform, {?DEFAULT_SLIDING_WINDOW, ?DEFAULT_SIZE}); 45 | new(Name, SampleType) -> 46 | new(Name, SampleType, ?DEFAULT_SIZE). 47 | 48 | new(Name, SampleType, SampleSize) -> 49 | Sample = folsom_sample:new(SampleType, SampleSize), 50 | Hist = #histogram{type = SampleType, sample = Sample}, 51 | ets:insert(?HISTOGRAM_TABLE, {Name, Hist}). 52 | 53 | new(Name, SampleType, SampleSize, Alpha) -> 54 | Sample = folsom_sample:new(SampleType, SampleSize, Alpha), 55 | Hist = #histogram{type = SampleType, sample = Sample}, 56 | ets:insert(?HISTOGRAM_TABLE, {Name, Hist}). 57 | 58 | update(Name, Value) -> 59 | Hist = get_value(Name), 60 | Sample = Hist#histogram.sample, 61 | case folsom_sample:update(Hist#histogram.type, Hist#histogram.sample, Value) of 62 | Sample -> 63 | %% sample didn't change, don't need to write it back 64 | true; 65 | NewSample -> 66 | ets:insert(?HISTOGRAM_TABLE, {Name, Hist#histogram{sample = NewSample}}) 67 | end. 68 | 69 | % gets the histogram record from ets 70 | get_value(Name) -> 71 | [{_, Value}] = ets:lookup(?HISTOGRAM_TABLE, Name), 72 | Value. 73 | 74 | % pulls the sample out of the record gotten from ets 75 | get_values(Name) -> 76 | Hist = get_value(Name), 77 | folsom_sample:get_values(Hist#histogram.type, Hist#histogram.sample). 78 | -------------------------------------------------------------------------------- /src/folsom_metrics_history.erl: -------------------------------------------------------------------------------- 1 | %%% 2 | %%% Copyright 2011, Boundary 3 | %%% 4 | %%% Licensed under the Apache License, Version 2.0 (the "License"); 5 | %%% you may not use this file except in compliance with the License. 6 | %%% You may obtain a copy of the License at 7 | %%% 8 | %%% http://www.apache.org/licenses/LICENSE-2.0 9 | %%% 10 | %%% Unless required by applicable law or agreed to in writing, software 11 | %%% distributed under the License is distributed on an "AS IS" BASIS, 12 | %%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | %%% See the License for the specific language governing permissions and 14 | %%% limitations under the License. 15 | %%% 16 | 17 | 18 | %%%------------------------------------------------------------------- 19 | %%% File: folsom_metrics_history.erl 20 | %%% @author joe williams 21 | %%% @doc 22 | %%% @end 23 | %%%------------------------------------------------------------------ 24 | 25 | -module(folsom_metrics_history). 26 | 27 | -export([new/1, 28 | update/3, 29 | get_events/1, 30 | get_events/2, 31 | get_value/1 32 | ]). 33 | 34 | -include("folsom.hrl"). 35 | 36 | -define(ETSOPTS, [ 37 | ordered_set, 38 | public, 39 | {write_concurrency, true} 40 | ]). 41 | 42 | new(Name) -> 43 | Tid = ets:new(history, ?ETSOPTS), 44 | ets:insert(?HISTORY_TABLE, {Name, #history{tid=Tid}}), 45 | ok. 46 | 47 | update(Name, Size, Value) -> 48 | #history{tid=Tid} = get_value(Name), 49 | Key = folsom_utils:now_epoch_micro(), 50 | insert(Tid, Key, Size, Value, ets:info(Tid, size)). 51 | 52 | get_value(Name) -> 53 | [{_, Value}] = ets:lookup(?HISTORY_TABLE, Name), 54 | Value. 55 | 56 | get_events(Name) -> 57 | get_events(Name, ?DEFAULT_LIMIT). 58 | 59 | get_events(Name, Count) -> 60 | #history{tid=Tid} = get_value(Name), 61 | get_last_events(Tid, Count). 62 | 63 | % Internal API 64 | 65 | insert(Name, Key, Size, Value, Count) when Count < Size -> 66 | true = ets:insert(Name, {Key, [{event, Value}]}); 67 | insert(Name, Key, _, Value, _) -> 68 | FirstKey = ets:first(Name), 69 | true = ets:delete(Name, FirstKey), 70 | true = ets:insert(Name, {Key, [{event, Value}]}). 71 | 72 | get_last_events(Name, Count) -> 73 | LastKey = ets:last(Name), 74 | get_prev_event(Name, LastKey, Count, []). 75 | 76 | % get_prev_event/4 used by get_last_events/2 77 | get_prev_event(_, '$end_of_table', _, Acc) -> 78 | Acc; 79 | get_prev_event(Name, Key, Count, Acc) when length(Acc) < Count -> 80 | Event = ets:lookup(Name, Key), 81 | get_prev_event(Name, ets:prev(Name, Key), Count, lists:append(Acc, Event)); 82 | get_prev_event(_, _, _, Acc) -> 83 | Acc. 84 | -------------------------------------------------------------------------------- /src/folsom_ewma.erl: -------------------------------------------------------------------------------- 1 | %%% 2 | %%% Copyright 2011, Boundary 3 | %%% 4 | %%% Licensed under the Apache License, Version 2.0 (the "License"); 5 | %%% you may not use this file except in compliance with the License. 6 | %%% You may obtain a copy of the License at 7 | %%% 8 | %%% http://www.apache.org/licenses/LICENSE-2.0 9 | %%% 10 | %%% Unless required by applicable law or agreed to in writing, software 11 | %%% distributed under the License is distributed on an "AS IS" BASIS, 12 | %%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | %%% See the License for the specific language governing permissions and 14 | %%% limitations under the License. 15 | %%% 16 | 17 | 18 | %%%------------------------------------------------------------------- 19 | %%% File: folsom_ewma.erl 20 | %%% @author joe williams 21 | %%% @doc 22 | %%% based on https://github.com/codahale/metrics/blob/development/src/main/java/com/yammer/metrics/stats/EWMA.java 23 | %%% references: 24 | %%% http://www.teamquest.com/pdfs/whitepaper/ldavg1.pdf 25 | %%% http://www.teamquest.com/pdfs/whitepaper/ldavg2.pdf 26 | %%% @end 27 | %%%----------------------------------------------------------------- 28 | 29 | 30 | -module(folsom_ewma). 31 | 32 | -define(M1_ALPHA, 1 - math:exp(-5 / 60.0)). 33 | -define(M5_ALPHA, 1 - math:exp(-5 / 60.0 / 5)). 34 | -define(M15_ALPHA, 1 - math:exp(-5 / 60.0 / 15)). 35 | -define(D1_ALPHA, 1 - math:exp(-5 / 60.0 / 1440)). 36 | 37 | -record(ewma, { 38 | alpha, 39 | interval = 5, % seconds 40 | initialized = false, 41 | rate = 0, 42 | total = 0 43 | }). 44 | 45 | -export([update/2, 46 | new/2, 47 | rate/1, 48 | tick/1, 49 | one_minute_ewma/0, 50 | five_minute_ewma/0, 51 | fifteen_minute_ewma/0, 52 | one_day_ewma/0]). 53 | 54 | 55 | % API 56 | 57 | one_minute_ewma() -> 58 | new(?M1_ALPHA, 5). 59 | 60 | five_minute_ewma() -> 61 | new(?M5_ALPHA, 5). 62 | 63 | fifteen_minute_ewma() -> 64 | new(?M15_ALPHA, 5). 65 | 66 | one_day_ewma() -> 67 | new(?D1_ALPHA, 5). 68 | 69 | new(Alpha, Interval) -> 70 | #ewma{alpha = Alpha, interval = Interval}. 71 | 72 | update(#ewma{total = Total} = EWMA, Value) -> 73 | EWMA#ewma{total = Total + Value}. 74 | 75 | tick(#ewma{total = Total, rate = Rate, initialized = Init, interval = Interval, alpha = Alpha} = EWMA) -> 76 | InstantRate = Total / Interval, 77 | Rate1 = rate_calc(Init, Alpha, Rate, InstantRate), 78 | EWMA#ewma{rate = Rate1, initialized = true, total = 0}. 79 | 80 | rate(#ewma{rate = Rate}) -> 81 | Rate. 82 | 83 | % Internal API 84 | 85 | rate_calc(true, Alpha, Rate, InstantRate) -> 86 | Rate1 = Rate + (Alpha * (InstantRate - Rate)), 87 | Rate1; 88 | rate_calc(false, _, _, InstantRate) -> 89 | InstantRate. 90 | -------------------------------------------------------------------------------- /src/folsom_sample_slide_server.erl: -------------------------------------------------------------------------------- 1 | %% ------------------------------------------------------------------- 2 | %% 3 | %% Copyright (c) 2011 Basho Technologies, Inc. 4 | %% 5 | %% This file is provided to you under the Apache License, 6 | %% Version 2.0 (the "License"); you may not use this file 7 | %% except in compliance with the License. You may obtain 8 | %% 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, 13 | %% software distributed under the License is distributed on an 14 | %% "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 15 | %% KIND, either express or implied. See the License for the 16 | %% specific language governing permissions and limitations 17 | %% under the License. 18 | %% 19 | %% ------------------------------------------------------------------- 20 | %%%------------------------------------------------------------------- 21 | %%% File: folsom_sample_slide_server.erl 22 | %%% @author Russell Brown 23 | %%% @doc 24 | %%% Serialization point for folsom_sample_slide. Handles 25 | %%% pruning of older smaples. One started per histogram. 26 | %%% See folsom.hrl, folsom_sample_slide, folsom_sample_slide_sup 27 | %%% @end 28 | %%%----------------------------------------------------------------- 29 | -module(folsom_sample_slide_server). 30 | 31 | -behaviour(gen_server). 32 | 33 | %% API 34 | -export([start_link/3, stop/1, resize/2]). 35 | 36 | -record(state, {sample_mod, reservoir, window}). 37 | 38 | %% gen_server callbacks 39 | -export([init/1, handle_call/3, handle_cast/2, handle_info/2, 40 | terminate/2, code_change/3]). 41 | 42 | start_link(SampleMod, Reservoir, Window) -> 43 | gen_server:start_link(?MODULE, [SampleMod, Reservoir, Window], []). 44 | 45 | stop(Pid) -> 46 | gen_server:cast(Pid, stop). 47 | 48 | init([SampleMod, Reservoir, Window]) -> 49 | {ok, #state{sample_mod = SampleMod, reservoir = Reservoir, window = Window}, timeout(Window)}. 50 | 51 | resize(Pid, NewWindow) -> 52 | gen_server:call(Pid, {resize, NewWindow}). 53 | 54 | handle_call({resize, NewWindow}, _From, State) -> 55 | NewState = State#state{window=NewWindow}, 56 | Reply = ok, 57 | {reply, Reply, NewState, timeout(NewWindow)}; 58 | handle_call(_Request, _From, State) -> 59 | Reply = ok, 60 | {reply, Reply, State}. 61 | 62 | handle_cast(stop, State) -> 63 | {stop, normal, State}; 64 | handle_cast(_Msg, State) -> 65 | {noreply, State}. 66 | 67 | handle_info(timeout, State=#state{sample_mod = SampleMod, reservoir = Reservoir, window = Window}) -> 68 | SampleMod:trim(Reservoir, Window), 69 | {noreply, State, timeout(Window)}; 70 | handle_info(_Info, State) -> 71 | {noreply, State}. 72 | 73 | terminate(_Reason, _State) -> 74 | ok. 75 | 76 | code_change(_OldVsn, State, _Extra) -> 77 | {ok, State}. 78 | 79 | timeout(Window) -> 80 | timer:seconds(Window) div 2. 81 | -------------------------------------------------------------------------------- /src/folsom_sample.erl: -------------------------------------------------------------------------------- 1 | %%% 2 | %%% Copyright 2011, Boundary 3 | %%% 4 | %%% Licensed under the Apache License, Version 2.0 (the "License"); 5 | %%% you may not use this file except in compliance with the License. 6 | %%% You may obtain a copy of the License at 7 | %%% 8 | %%% http://www.apache.org/licenses/LICENSE-2.0 9 | %%% 10 | %%% Unless required by applicable law or agreed to in writing, software 11 | %%% distributed under the License is distributed on an "AS IS" BASIS, 12 | %%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | %%% See the License for the specific language governing permissions and 14 | %%% limitations under the License. 15 | %%% 16 | 17 | 18 | %%%------------------------------------------------------------------- 19 | %%% File: folsom_sample.erl 20 | %%% @author joe williams 21 | %%% @doc 22 | %%% @end 23 | %%%------------------------------------------------------------------ 24 | 25 | -module(folsom_sample). 26 | 27 | -export([ 28 | new/1, 29 | new/2, 30 | new/3, 31 | update/3, 32 | get_values/2 33 | ]). 34 | 35 | -include("folsom.hrl"). 36 | 37 | %% API 38 | 39 | new(slide) -> 40 | new(slide, ?DEFAULT_SLIDING_WINDOW); 41 | new(slide_uniform) -> 42 | new(slide_uniform, {?DEFAULT_SLIDING_WINDOW, ?DEFAULT_SIZE}); 43 | new(Type) -> 44 | new(Type, ?DEFAULT_SIZE, ?DEFAULT_ALPHA). 45 | 46 | new(Type, Size) -> 47 | new(Type, Size, ?DEFAULT_ALPHA). 48 | 49 | new(slide, Size, _) -> 50 | folsom_sample_slide:new(Size); 51 | new(slide_uniform, Sizes, _) -> 52 | folsom_sample_slide_uniform:new(Sizes); 53 | new(uniform, Size, _) -> 54 | folsom_sample_uniform:new(Size); 55 | new(none, Size, _) -> 56 | folsom_sample_none:new(Size); 57 | new(slide_sorted, Size, _) -> 58 | folsom_sample_slide_sorted:new(Size); 59 | new(exdec, Size, Alpha) -> 60 | folsom_sample_exdec:new(Size, Alpha). 61 | 62 | update(uniform, Sample, Value) -> 63 | folsom_sample_uniform:update(Sample, Value); 64 | update(none, Sample, Value) -> 65 | folsom_sample_none:update(Sample, Value); 66 | update(slide_sorted, Sample, Value) -> 67 | folsom_sample_slide_sorted:update(Sample, Value); 68 | update(exdec, Sample, Value) -> 69 | folsom_sample_exdec:update(Sample, Value); 70 | update(slide, Sample, Value) -> 71 | folsom_sample_slide:update(Sample, Value); 72 | update(slide_uniform, Sample, Value) -> 73 | folsom_sample_slide_uniform:update(Sample, Value). 74 | 75 | 76 | get_values(uniform, Sample) -> 77 | folsom_sample_uniform:get_values(Sample); 78 | get_values(none, Sample) -> 79 | folsom_sample_none:get_values(Sample); 80 | get_values(slide_sorted, Sample) -> 81 | folsom_sample_slide_sorted:get_values(Sample); 82 | get_values(exdec, Sample) -> 83 | folsom_sample_exdec:get_values(Sample); 84 | get_values(slide, Sample) -> 85 | folsom_sample_slide:get_values(Sample); 86 | get_values(slide_uniform, Sample) -> 87 | folsom_sample_slide_uniform:get_values(Sample). 88 | -------------------------------------------------------------------------------- /src/folsom_sample_slide_uniform.erl: -------------------------------------------------------------------------------- 1 | %%% 2 | %%% Copyright 2012, Basho Technologies, Inc. All Rights Reserved. 3 | %%% 4 | %%% Licensed under the Apache License, Version 2.0 (the "License"); 5 | %%% you may not use this file except in compliance with the License. 6 | %%% You may obtain a copy of the License at 7 | %%% 8 | %%% http://www.apache.org/licenses/LICENSE-2.0 9 | %%% 10 | %%% Unless required by applicable law or agreed to in writing, software 11 | %%% distributed under the License is distributed on an "AS IS" BASIS, 12 | %%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | %%% See the License for the specific language governing permissions and 14 | %%% limitations under the License. 15 | %%% 16 | %%%------------------------------------------------------------------- 17 | %%% File: folsom_sample_slide.erl 18 | %%% @author Russell Brown 19 | %%% @doc 20 | %%% Sliding window sample. Last Window seconds readings are recorded. 21 | %%% @end 22 | %%%----------------------------------------------------------------- 23 | 24 | -module(folsom_sample_slide_uniform). 25 | 26 | -export([ 27 | new/1, 28 | update/2, 29 | get_values/1, 30 | moment/0, 31 | trim/2, 32 | resize/2 33 | ]). 34 | 35 | -include("folsom.hrl"). 36 | 37 | new({Window, SampleSize}) -> 38 | Sample = #slide_uniform{window = Window, size = SampleSize}, 39 | Pid = folsom_sample_slide_sup:start_slide_server(?MODULE, Sample#slide_uniform.reservoir, Sample#slide_uniform.window), 40 | Sample#slide_uniform{server=Pid}. 41 | 42 | update(#slide_uniform{reservoir = Reservoir, size = Size} = Sample0, Value) -> 43 | Now = folsom_utils:timestamp(), 44 | Moment = folsom_utils:now_epoch(Now), 45 | MCnt = folsom_utils:update_counter(Reservoir, Moment, 1), 46 | Sample = case MCnt > Size of 47 | true -> 48 | {Rnd, _NewSeed} = random:uniform_s(MCnt, Now), 49 | maybe_update(Reservoir, {{Moment, Rnd}, Value}, Size), 50 | Sample0; 51 | false -> 52 | ets:insert(Reservoir, {{Moment, MCnt}, Value}), 53 | Sample0 54 | end, 55 | Sample. 56 | 57 | resize(Sample, NewSize) -> 58 | folsom_sample_slide_server:resize(Sample#slide.server, NewSize), 59 | Sample#slide{window = NewSize}. 60 | 61 | maybe_update(Reservoir, {{_Moment, Rnd}, _Value}=Obj, Size) when Rnd =< Size -> 62 | ets:insert(Reservoir, Obj); 63 | maybe_update(_Reservoir, _Obj, _Size) -> 64 | ok. 65 | 66 | get_values(#slide_uniform{window = Window, reservoir = Reservoir}) -> 67 | Oldest = moment() - Window, 68 | ets:select(Reservoir, [{{{'$1', '_'},'$2'},[{'>=', '$1', Oldest}],['$2']}]). 69 | 70 | moment() -> 71 | folsom_utils:now_epoch(). 72 | 73 | trim(Reservoir, Window) -> 74 | Oldest = moment() - Window, 75 | ets:select_delete(Reservoir, [{{{'$1', '_'},'_'},[{'<', '$1', Oldest}],['true']}]), 76 | %% and trim the counters 77 | ets:select_delete(Reservoir, [{{'$1','_'},[{is_integer, '$1'}, {'<', '$1', Oldest}],['true']}]). 78 | -------------------------------------------------------------------------------- /src/folsom_metrics_duration.erl: -------------------------------------------------------------------------------- 1 | %% ------------------------------------------------------------------- 2 | %% 3 | %% Copyright (c) 2007-2012 Basho Technologies, Inc. All Rights Reserved. 4 | %% 5 | %% This file is provided to you under the Apache License, 6 | %% Version 2.0 (the "License"); you may not use this file 7 | %% except in compliance with the License. You may obtain 8 | %% 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, 13 | %% software distributed under the License is distributed on an 14 | %% "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 15 | %% KIND, either express or implied. See the License for the 16 | %% specific language governing permissions and limitations 17 | %% under the License. 18 | %% 19 | %% ------------------------------------------------------------------- 20 | 21 | %%%------------------------------------------------------------------- 22 | %%% File: folsom_metrics_duration.erl 23 | %%% @author Russell Brown 24 | %%% @doc Tracks the time something takes. If 25 | %%% you can, use folsom_metrics:histogram_timed_update/2,3,4. 26 | %%% This is for the case when you can't wrap your timed action 27 | %%% in a fun. Calling timer_start / timer_end in the correct 28 | %%% order is the calling code's responsibility. 29 | %%% @end 30 | %%%------------------------------------------------------------------ 31 | 32 | -module(folsom_metrics_duration). 33 | 34 | -export([new/1, 35 | update/2, 36 | get_value/1, 37 | get_values/1 38 | ]). 39 | 40 | -include("folsom.hrl"). 41 | 42 | new(Name) -> 43 | %% {Name, count, start, last} 44 | Dur = {Name, 0, undefined, 0}, 45 | ets:insert(?DURATION_TABLE, Dur). 46 | 47 | update(Name, timer_start) -> 48 | StartTime = os:timestamp(), 49 | ets:update_element(?DURATION_TABLE, Name, {3, StartTime}); 50 | update(Name, timer_end) -> 51 | EndTime = os:timestamp(), 52 | case ets:lookup_element(?DURATION_TABLE, Name, 3) of 53 | undefined -> 54 | ok; 55 | StartTime -> 56 | %% potential race, but then you're using it wrong 57 | ets:update_element(?DURATION_TABLE, Name, {3, undefined}), 58 | Duration = timer:now_diff(EndTime, StartTime), 59 | ets:update_counter(?DURATION_TABLE, Name, {2, 1}), 60 | ets:update_element(?DURATION_TABLE, Name, {4, Duration}), 61 | folsom_metrics_histogram:update(Name, Duration) 62 | end. 63 | 64 | % gets the duration tuple from ets 65 | get_value(Name) -> 66 | [Dur] = ets:lookup(?DURATION_TABLE, Name), 67 | Dur. 68 | 69 | % pulls the sample out of the record gotten from ets 70 | % and the duration 71 | get_values(Name) -> 72 | Values = folsom_metrics_histogram:get_values(Name), 73 | {Name, Cnt, _Start, Last} = get_value(Name), 74 | WantedMetrics = application:get_env(folsom, enabled_metrics, ?DEFAULT_METRICS), 75 | Stats = bear:get_statistics_subset(Values, WantedMetrics), 76 | [{count, Cnt}, {last, Last} | Stats]. 77 | -------------------------------------------------------------------------------- /src/folsom_metrics_spiral.erl: -------------------------------------------------------------------------------- 1 | %%% 2 | %%% Copyright 2012, Basho Technologies, Inc. All Rights Reserved. 3 | %%% 4 | %%% Licensed under the Apache License, Version 2.0 (the "License"); 5 | %%% you may not use this file except in compliance with the License. 6 | %%% You may obtain a copy of the License at 7 | %%% 8 | %%% http://www.apache.org/licenses/LICENSE-2.0 9 | %%% 10 | %%% Unless required by applicable law or agreed to in writing, software 11 | %%% distributed under the License is distributed on an "AS IS" BASIS, 12 | %%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | %%% See the License for the specific language governing permissions and 14 | %%% limitations under the License. 15 | %%% 16 | 17 | 18 | %%%------------------------------------------------------------------- 19 | %%% File: folsom_metrics_spiral.erl 20 | %%% @author Russell Brown 21 | %%% @doc A total count, and sliding window count of events over the last 22 | %%% minute. 23 | %%% @end 24 | %%%------------------------------------------------------------------ 25 | 26 | -module(folsom_metrics_spiral). 27 | 28 | -export([new/1, 29 | new/2, 30 | update/2, 31 | trim/2, 32 | get_value/1, 33 | get_values/1 34 | ]). 35 | 36 | %% size of the window in seconds 37 | -define(WINDOW, 60). 38 | -define(WIDTH, 16). %% Keep this a power of two 39 | 40 | -include("folsom.hrl"). 41 | 42 | new(Name) -> 43 | new(Name, fast). 44 | 45 | new(Name, Update) when Update == fast orelse Update == no_exceptions -> 46 | UpdateFun = case Update of 47 | fast -> 48 | update_counter; 49 | no_exceptions -> 50 | update_counter_no_exceptions 51 | end, 52 | Spiral = #spiral{update=UpdateFun}, 53 | Pid = folsom_sample_slide_sup:start_slide_server(?MODULE, 54 | Spiral#spiral.tid, 55 | ?WINDOW), 56 | ets:insert_new(Spiral#spiral.tid, 57 | [{{count, N}, 0} || N <- lists:seq(0,?WIDTH-1)]), 58 | ets:insert(?SPIRAL_TABLE, {Name, Spiral#spiral{server=Pid}}). 59 | 60 | update(Name, Value) -> 61 | #spiral{tid=Tid, update=Update} = get_value(Name), 62 | Moment = folsom_utils:now_epoch(), 63 | X = erlang:system_info(scheduler_id), 64 | Rnd = X band (?WIDTH-1), 65 | folsom_utils:Update(Tid, {Moment, Rnd}, Value), 66 | ets:update_counter(Tid, {count, Rnd}, Value). 67 | 68 | get_value(Name) -> 69 | [{Name, Spiral}] = ets:lookup(?SPIRAL_TABLE, Name), 70 | Spiral. 71 | 72 | trim(Tid, _Window) -> 73 | Oldest = oldest(), 74 | ets:select_delete(Tid, [{{{'$1','_'},'_'}, [{is_integer, '$1'}, {'<', '$1', Oldest}], ['true']}]). 75 | 76 | get_values(Name) -> 77 | Oldest = oldest(), 78 | #spiral{tid=Tid} = get_value(Name), 79 | Count = lists:sum(ets:select(Tid, [{{{count,'_'},'$1'},[],['$1']}])), 80 | One = lists:sum(ets:select(Tid, [{{{'$1','_'},'$2'},[{is_integer, '$1'}, {'>=', '$1', Oldest}],['$2']}])), 81 | 82 | [{count, Count}, {one, One}]. 83 | 84 | oldest() -> 85 | folsom_utils:now_epoch() - ?WINDOW. 86 | 87 | 88 | -------------------------------------------------------------------------------- /src/folsom_utils.erl: -------------------------------------------------------------------------------- 1 | %%% 2 | %%% Copyright 2011, Boundary 3 | %%% 4 | %%% Licensed under the Apache License, Version 2.0 (the "License"); 5 | %%% you may not use this file except in compliance with the License. 6 | %%% You may obtain a copy of the License at 7 | %%% 8 | %%% http://www.apache.org/licenses/LICENSE-2.0 9 | %%% 10 | %%% Unless required by applicable law or agreed to in writing, software 11 | %%% distributed under the License is distributed on an "AS IS" BASIS, 12 | %%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | %%% See the License for the specific language governing permissions and 14 | %%% limitations under the License. 15 | %%% 16 | 17 | 18 | %%%------------------------------------------------------------------- 19 | %%% File: folsom_utils.erl 20 | %%% @author joe williams 21 | %%% @doc 22 | %%% various util functions 23 | %%% @end 24 | %%%------------------------------------------------------------------ 25 | -module(folsom_utils). 26 | 27 | -export([ 28 | to_atom/1, 29 | convert_tags/1, 30 | now_epoch/0, 31 | now_epoch/1, 32 | now_epoch_micro/0, 33 | timestamp/0, 34 | get_ets_size/1, 35 | update_counter/3, 36 | update_counter_no_exceptions/3 37 | ]). 38 | 39 | to_atom(Binary) when is_binary(Binary) -> 40 | list_to_atom(binary_to_list(Binary)); 41 | to_atom(List) when is_list(List) -> 42 | list_to_atom(List). 43 | 44 | convert_tags(Tags) -> 45 | [to_atom(Tag) || Tag <- Tags]. 46 | 47 | now_epoch() -> 48 | now_epoch(os:timestamp()). 49 | 50 | now_epoch({Mega, Sec, _}) -> 51 | (Mega * 1000000 + Sec). 52 | 53 | now_epoch_micro() -> 54 | {Mega, Sec, Micro} = os:timestamp(), 55 | (Mega * 1000000 + Sec) * 1000000 + Micro. 56 | 57 | %% useful because you can't meck os:timestamp for some reason 58 | timestamp() -> 59 | os:timestamp(). 60 | 61 | get_ets_size(Tab) -> 62 | ets:info(Tab, size). 63 | 64 | %% @doc 65 | %% Same as {@link ets:update_counter/3} but inserts `{Key, Value}' if object 66 | %% is missing in the table. 67 | update_counter(Tid, Key, Value) when is_integer(Value) -> 68 | %% try to update the counter, will badarg if it doesn't exist 69 | try ets:update_counter(Tid, Key, Value) of 70 | Res -> 71 | Res 72 | catch 73 | error:badarg -> 74 | %% row didn't exist, create it 75 | %% use insert_new to avoid races 76 | case ets:insert_new(Tid, {Key, Value}) of 77 | true -> 78 | Value; 79 | false -> 80 | %% someone beat us to it 81 | ets:update_counter(Tid, Key, Value) 82 | end 83 | end. 84 | 85 | %% @doc 86 | %% Same as {@link ets:update_counter/3} but inserts `{Key, Value}' if object 87 | %% is missing in the table, avoiding exceptions by reading first. 88 | %% Won't be required after https://github.com/erlang/otp/pull/362 89 | update_counter_no_exceptions(Tid, Key, Value) when is_integer(Value) -> 90 | %% Read counter first to avoid an exception 91 | case ets:lookup(Tid, Key) of 92 | [] -> 93 | %% row didn't exist, create it 94 | %% use insert_new to avoid races 95 | case ets:insert_new(Tid, {Key, Value}) of 96 | true -> 97 | Value; 98 | false -> 99 | %% someone beat us to it 100 | ets:update_counter(Tid, Key, Value) 101 | end; 102 | _ -> 103 | ets:update_counter(Tid, Key, Value) 104 | end. 105 | -------------------------------------------------------------------------------- /test/folsom_tests.erl: -------------------------------------------------------------------------------- 1 | %%% 2 | %%% Copyright 2011, Boundary 3 | %%% 4 | %%% Licensed under the Apache License, Version 2.0 (the "License"); 5 | %%% you may not use this file except in compliance with the License. 6 | %%% You may obtain a copy of the License at 7 | %%% 8 | %%% http://www.apache.org/licenses/LICENSE-2.0 9 | %%% 10 | %%% Unless required by applicable law or agreed to in writing, software 11 | %%% distributed under the License is distributed on an "AS IS" BASIS, 12 | %%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | %%% See the License for the specific language governing permissions and 14 | %%% limitations under the License. 15 | %%% 16 | 17 | 18 | %%%------------------------------------------------------------------- 19 | %%% File: folsom_tests.erl 20 | %%% @author joe williams 21 | %%% @doc 22 | %%% @end 23 | %%%------------------------------------------------------------------ 24 | 25 | -module(folsom_tests). 26 | 27 | -include_lib("eunit/include/eunit.hrl"). 28 | 29 | run_test_() -> 30 | {setup, 31 | fun() -> {ok, Apps} = application:ensure_all_started(folsom), 32 | Apps 33 | end, 34 | fun(Apps) -> [application:stop(App) || App <- Apps] end, 35 | [{"creating metrics", 36 | fun folsom_erlang_checks:create_metrics/0}, 37 | {"tagging metrics", 38 | fun folsom_erlang_checks:tag_metrics/0}, 39 | {"populating metrics", 40 | {timeout, 30, fun folsom_erlang_checks:populate_metrics/0}}, 41 | {"checking metrics", 42 | fun folsom_erlang_checks:check_metrics/0}, 43 | {"checking counter metric", 44 | fun () -> 45 | folsom_erlang_checks:counter_metric(10000, testcounter) 46 | end}, 47 | {"checking group metrics", 48 | fun folsom_erlang_checks:check_group_metrics/0}, 49 | {"checking erlang vm metrics", 50 | fun folsom_erlang_checks:vm_metrics/0}, 51 | {"deleting metrics", 52 | fun folsom_erlang_checks:delete_metrics/0}, 53 | {"cpu topology test", 54 | fun folsom_erlang_checks:cpu_topology/0}, 55 | {"c compiler test", 56 | fun folsom_erlang_checks:c_compiler_used/0}, 57 | {"create and delete tests", 58 | fun folsom_erlang_checks:create_delete_metrics/0}]}. 59 | 60 | configure_test_() -> 61 | {foreach, fun setup_app/0, fun cleanup_app/1, 62 | [{"start with configured metrics", 63 | fun() -> 64 | ?assertMatch(ok, application:start(folsom)), 65 | [counter, slide, <<"gauge">>, <<"uniform">>] = 66 | lists:sort(folsom_metrics:get_metrics()) 67 | end}]}. 68 | 69 | setup_app() -> 70 | application:unload(folsom), 71 | Env = [{counter, counter}, 72 | {gauge, <<"gauge">>}, 73 | {histogram, [[<<"uniform">>, uniform, 5000], 74 | [slide, slide_uniform, {60, 1028}]]}], 75 | application:load({application, folsom, [{mod, {folsom, []}}, {env, Env}]}), 76 | ok. 77 | 78 | cleanup_app(ok) -> 79 | lists:foreach(fun folsom_metrics:delete_metric/1, 80 | [counter, slide, <<"gauge">>, <<"uniform">>]), 81 | application:stop(folsom), 82 | application:unload(folsom), 83 | ok. 84 | 85 | update_counter_test() -> 86 | Tid = ets:new(sometable, [public, set]), 87 | Workers = [spawn_monitor(fun() -> timer:sleep(100-N), folsom_utils:update_counter(Tid, hello, N) end) || N <- lists:seq(1, 100)], 88 | wait_for_results(Workers), 89 | ?assertEqual([{hello, 5050}], ets:lookup(Tid, hello)). 90 | 91 | wait_for_results([]) -> 92 | ok; 93 | wait_for_results(Workers) -> 94 | receive 95 | {'DOWN', _, _, Pid, Reason} -> 96 | case lists:keyfind(Pid, 1, Workers) of 97 | false -> 98 | wait_for_results(Workers); 99 | _ -> 100 | case Reason of 101 | normal -> 102 | wait_for_results(lists:keydelete(Pid, 1, Workers)); 103 | _ -> 104 | erlang:error(Reason) 105 | end 106 | end 107 | end. 108 | -------------------------------------------------------------------------------- /src/folsom_sup.erl: -------------------------------------------------------------------------------- 1 | %% 2 | %%% Copyright 2011, Boundary 3 | %%% 4 | %%% Licensed under the Apache License, Version 2.0 (the "License"); 5 | %%% you may not use this file except in compliance with the License. 6 | %%% You may obtain a copy of the License at 7 | %%% 8 | %%% http://www.apache.org/licenses/LICENSE-2.0 9 | %%% 10 | %%% Unless required by applicable law or agreed to in writing, software 11 | %%% distributed under the License is distributed on an "AS IS" BASIS, 12 | %%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | %%% See the License for the specific language governing permissions and 14 | %%% limitations under the License. 15 | %%% 16 | 17 | 18 | %%%------------------------------------------------------------------- 19 | %%% File: folsom_sup.erl 20 | %%% @author joe williams 21 | %%% @doc 22 | %%% 23 | %%% @end 24 | %%%------------------------------------------------------------------- 25 | 26 | -module(folsom_sup). 27 | 28 | -behaviour(supervisor). 29 | 30 | %% API 31 | -export([start_link/0, create_tables/0]). 32 | 33 | %% Supervisor callbacks 34 | -export([init/1]). 35 | 36 | -include("folsom.hrl"). 37 | 38 | -define(SERVER, ?MODULE). 39 | 40 | %%%=================================================================== 41 | %%% API functions 42 | %%%=================================================================== 43 | 44 | %%-------------------------------------------------------------------- 45 | %% @doc 46 | %% Starts the supervisor 47 | %% 48 | %% @spec start_link() -> {ok, Pid} | ignore | {error, Error} 49 | %% @end 50 | %%-------------------------------------------------------------------- 51 | start_link() -> 52 | supervisor:start_link({local, ?SERVER}, ?MODULE, []). 53 | 54 | %%%=================================================================== 55 | %%% Supervisor callbacks 56 | %%%=================================================================== 57 | 58 | %%-------------------------------------------------------------------- 59 | %% @private 60 | %% @doc 61 | %% Whenever a supervisor is started using supervisor:start_link/[2,3], 62 | %% this function is called by the new process to find out about 63 | %% restart strategy, maximum restart frequency and child 64 | %% specifications. 65 | %% 66 | %% @spec init(Args) -> {ok, {SupFlags, [ChildSpec]}} | 67 | %% ignore | 68 | %% {error, Reason} 69 | %% @end 70 | %%-------------------------------------------------------------------- 71 | init([]) -> 72 | create_tables(), 73 | 74 | RestartStrategy = one_for_one, 75 | MaxRestarts = 1000, 76 | MaxSecondsBetweenRestarts = 3600, 77 | 78 | SupFlags = {RestartStrategy, MaxRestarts, MaxSecondsBetweenRestarts}, 79 | 80 | Restart = permanent, 81 | Shutdown = 2000, 82 | Type = worker, 83 | 84 | TimerServer = {folsom_meter_timer_server, 85 | {folsom_meter_timer_server, start_link, []}, 86 | Restart, Shutdown, Type, [folsom_meter_timer_server]}, 87 | 88 | HistETSServer = {folsom_metrics_histogram_ets, 89 | {folsom_metrics_histogram_ets, start_link, []}, 90 | Restart, Shutdown, Type, [folsom_metrics_histogram_ets]}, 91 | 92 | SlideSup = {folsom_sample_slide_sup, {folsom_sample_slide_sup, start_link, []}, 93 | permanent, 5000, supervisor, [folsom_sample_slide_sup]}, 94 | 95 | {ok, {SupFlags, [SlideSup, TimerServer, HistETSServer]}}. 96 | 97 | %%%=================================================================== 98 | %%% Internal functions 99 | %%%=================================================================== 100 | 101 | create_tables() -> 102 | Tables = [ 103 | {?FOLSOM_TABLE, [set, named_table, public, {read_concurrency, true}]}, 104 | {?COUNTER_TABLE, [set, named_table, public, {write_concurrency, true}]}, 105 | {?GAUGE_TABLE, [set, named_table, public, {write_concurrency, true}]}, 106 | {?HISTOGRAM_TABLE, [set, named_table, public, {write_concurrency, true}]}, 107 | {?METER_TABLE, [set, named_table, public, {write_concurrency, true}]}, 108 | {?METER_READER_TABLE, [set, named_table, public, {write_concurrency, true}]}, 109 | {?HISTORY_TABLE, [set, named_table, public, {write_concurrency, true}]}, 110 | {?DURATION_TABLE, [ordered_set, named_table, public, {write_concurrency, true}]}, 111 | {?SPIRAL_TABLE, [set, named_table, public, {write_concurrency, true}]} 112 | ], 113 | [maybe_create_table(ets:info(Name), Name, Opts) || {Name, Opts} <- Tables], 114 | ok. 115 | 116 | maybe_create_table(undefined, Name, Opts) -> 117 | ets:new(Name, Opts); 118 | maybe_create_table(_, _, _) -> 119 | ok. 120 | -------------------------------------------------------------------------------- /src/folsom_metrics_meter.erl: -------------------------------------------------------------------------------- 1 | %%% 2 | %%% Copyright 2011, Boundary 3 | %%% 4 | %%% Licensed under the Apache License, Version 2.0 (the "License"); 5 | %%% you may not use this file except in compliance with the License. 6 | %%% You may obtain a copy of the License at 7 | %%% 8 | %%% http://www.apache.org/licenses/LICENSE-2.0 9 | %%% 10 | %%% Unless required by applicable law or agreed to in writing, software 11 | %%% distributed under the License is distributed on an "AS IS" BASIS, 12 | %%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | %%% See the License for the specific language governing permissions and 14 | %%% limitations under the License. 15 | %%% 16 | 17 | 18 | %%%------------------------------------------------------------------- 19 | %%% File: folsom_metrics_meter.erl 20 | %%% @author joe williams 21 | %%% @doc 22 | %%% @end 23 | %%%------------------------------------------------------------------ 24 | 25 | -module(folsom_metrics_meter). 26 | 27 | -export([new/1, 28 | tick/1, 29 | mark/1, 30 | mark/2, 31 | get_values/1, 32 | get_acceleration/1 33 | ]). 34 | 35 | 36 | -record(meter, { 37 | one, 38 | five, 39 | fifteen, 40 | day, 41 | count = 0, 42 | start_time 43 | }). 44 | 45 | -include("folsom.hrl"). 46 | 47 | new(Name) -> 48 | OneMin = folsom_ewma:one_minute_ewma(), 49 | FiveMin = folsom_ewma:five_minute_ewma(), 50 | FifteenMin = folsom_ewma:fifteen_minute_ewma(), 51 | OneDay = folsom_ewma:one_day_ewma(), 52 | 53 | ets:insert(?METER_TABLE, 54 | {Name, #meter{one = OneMin, 55 | five = FiveMin, 56 | fifteen = FifteenMin, 57 | day = OneDay, 58 | start_time = folsom_utils:now_epoch_micro()}}). 59 | 60 | tick(Name) -> 61 | #meter{one = OneMin, 62 | five = FiveMin, 63 | fifteen = FifteenMin, 64 | day = OneDay} = Meter = get_value(Name), 65 | 66 | OneMin1 = folsom_ewma:tick(OneMin), 67 | FiveMin1 = folsom_ewma:tick(FiveMin), 68 | FifteenMin1 = folsom_ewma:tick(FifteenMin), 69 | OneDay1 = folsom_ewma:tick(OneDay), 70 | 71 | ets:insert(?METER_TABLE, 72 | {Name, Meter#meter{one = OneMin1, 73 | five = FiveMin1, 74 | fifteen = FifteenMin1, 75 | day = OneDay1}}). 76 | 77 | mark(Name) -> 78 | mark(Name, 1). 79 | 80 | mark(Name, Value) -> 81 | #meter{count = Count, 82 | one = OneMin, 83 | five = FiveMin, 84 | fifteen = FifteenMin, 85 | day = OneDay} = Meter = get_value(Name), 86 | 87 | OneMin1 = folsom_ewma:update(OneMin, Value), 88 | FiveMin1 = folsom_ewma:update(FiveMin, Value), 89 | FifteenMin1 = folsom_ewma:update(FifteenMin, Value), 90 | OneDay1 = folsom_ewma:update(OneDay, Value), 91 | 92 | ets:insert(?METER_TABLE, {Name, Meter#meter{count = Count + Value, 93 | one = OneMin1, 94 | five = FiveMin1, 95 | fifteen = FifteenMin1, 96 | day = OneDay1}}). 97 | 98 | get_values(Name) -> 99 | #meter{one = OneMin, 100 | five = FiveMin, 101 | fifteen = FifteenMin, 102 | day = OneDay, 103 | count = Count} = Meter = get_value(Name), 104 | 105 | L = [ 106 | {count, Count}, 107 | {one, get_rate(OneMin)}, 108 | {five, get_rate(FiveMin)}, 109 | {fifteen, get_rate(FifteenMin)}, 110 | {day, get_rate(OneDay)}, 111 | {mean, get_mean_rate(Meter)}, 112 | {acceleration, get_acceleration(Name)} 113 | ], 114 | 115 | [ {K,V} || {K,V} <- L, V /= undefined ]. 116 | 117 | get_acceleration(Name) -> 118 | #meter{one = OneMin, 119 | five = FiveMin, 120 | fifteen = FifteenMin} = get_value(Name), 121 | 122 | [ 123 | {one_to_five, calc_acceleration(get_rate(OneMin), get_rate(FiveMin), 300)}, 124 | {five_to_fifteen, calc_acceleration(get_rate(FiveMin), get_rate(FifteenMin), 600)}, 125 | {one_to_fifteen, calc_acceleration(get_rate(OneMin), get_rate(FifteenMin), 900)} 126 | ]. 127 | 128 | % internal functions 129 | 130 | get_rate(EWMA) -> 131 | folsom_ewma:rate(EWMA). 132 | 133 | get_mean_rate(#meter{count = Count, start_time = Start}) -> 134 | calc_mean_rate(Start, Count). 135 | 136 | get_value(Name) -> 137 | [{_, Value}] = ets:lookup(?METER_TABLE, Name), 138 | Value. 139 | 140 | calc_mean_rate(_, 0) -> 141 | 0.0; 142 | calc_mean_rate(Start, Count) -> 143 | Elapsed = folsom_utils:now_epoch_micro() - Start, 144 | Count / Elapsed. 145 | 146 | calc_acceleration(Rate1, Rate2, Interval) -> 147 | % most current velocity minus previous velocity 148 | get_rate(Rate1, Rate2, Interval). 149 | 150 | get_rate(Value1, Value2, Interval) -> 151 | Delta = Value1 - Value2, 152 | Delta / Interval. 153 | 154 | -------------------------------------------------------------------------------- /src/folsom_sample_exdec.erl: -------------------------------------------------------------------------------- 1 | %%% 2 | %%% Copyright 2011, Boundary 3 | %%% 4 | %%% Licensed under the Apache License, Version 2.0 (the "License"); 5 | %%% you may not use this file except in compliance with the License. 6 | %%% You may obtain a copy of the License at 7 | %%% 8 | %%% http://www.apache.org/licenses/LICENSE-2.0 9 | %%% 10 | %%% Unless required by applicable law or agreed to in writing, software 11 | %%% distributed under the License is distributed on an "AS IS" BASIS, 12 | %%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | %%% See the License for the specific language governing permissions and 14 | %%% limitations under the License. 15 | %%% 16 | 17 | 18 | %%%------------------------------------------------------------------- 19 | %%% File: folsom_sample_exdec.erl 20 | %%% @author joe williams 21 | %%% @doc 22 | %%% erlang implementation of a exponentially-decaying random sample 23 | %%% based on a java implementation by coda hale, which can be found at: 24 | %%% 25 | %%% https://github.com/codahale/metrics/blob/development/src/main/java/com/yammer/metrics/core/ExponentiallyDecayingSample.java 26 | %%% 27 | %%% that implementation is based on: 28 | %%% 29 | %%% http://dimacs.rutgers.edu/~graham/pubs/papers/fwddecay.pdf 30 | %%% @end 31 | %%%------------------------------------------------------------------ 32 | 33 | -module(folsom_sample_exdec). 34 | 35 | -export([ 36 | new/2, 37 | update/2, 38 | get_values/1 39 | ]). 40 | 41 | -define(HOURSECS, 3600). 42 | 43 | -include("folsom.hrl"). 44 | 45 | new(Size, Alpha) -> 46 | Now = folsom_utils:now_epoch(), 47 | #exdec{start = Now, next = Now + ?HOURSECS, alpha = Alpha, size = Size}. 48 | 49 | update(#exdec{reservoir = Reservoir, alpha = Alpha, start = Start, next = Next} = Sample, Value) -> 50 | Timestamp = folsom_utils:now_epoch(), 51 | 52 | % immediately see if we need to rescale 53 | {NewRes, NewStart, NewNext} = rescale(Reservoir, Timestamp, Next, Start, Alpha), 54 | 55 | % now lets update the sample if the new value is worthy 56 | update(Sample#exdec{reservoir = NewRes, next = NewNext, start = NewStart}, Value, Timestamp). 57 | 58 | get_values(#exdec{reservoir = Reservoir}) -> 59 | {_, Values} = lists:unzip(ets:tab2list(Reservoir)), 60 | Values. 61 | 62 | % internal api 63 | 64 | update(#exdec{reservoir = Reservoir, alpha = Alpha, start = Start, n = N, size = Size, seed = Seed} = Sample, Value, Timestamp) when N =< Size -> 65 | % since N is =< Size we can just add the new value to the sample 66 | 67 | {Rand, New_seed} = random:uniform_s(N, Seed), 68 | Priority = priority(Alpha, Timestamp, Start, Rand), 69 | true = ets:insert(Reservoir, {Priority, Value}), 70 | 71 | Sample#exdec{n = folsom_utils:get_ets_size(Reservoir), seed = New_seed}; 72 | update(#exdec{reservoir = Reservoir, alpha = Alpha, start = Start, n = N, seed = Seed} = Sample, Value, Timestamp) -> 73 | % when N is not =< Size we need to check to see if the priority of 74 | % the new value is greater than the first (smallest) existing priority 75 | 76 | {Rand, NewSeed} = random:uniform_s(N, Seed), 77 | Priority = priority(Alpha, Timestamp, Start, Rand), 78 | First = ets:first(Reservoir), 79 | 80 | update_on_priority(Sample, First, Priority, NewSeed, Value). 81 | 82 | update_on_priority(#exdec{reservoir = Reservoir} = Sample, First, Priority, NewSeed, Value) when First < Priority -> 83 | true = case ets:insert_new(Reservoir, {Priority, Value}) of 84 | true -> 85 | % priority didnt already exist, so we created it and need to delete the first one 86 | ets:delete(Reservoir, First); 87 | false -> 88 | % priority existed, we dont need to do anything 89 | true 90 | end, 91 | Sample#exdec{n = folsom_utils:get_ets_size(Reservoir), seed = NewSeed}; 92 | update_on_priority(Sample, _, _, _, _) -> 93 | Sample. 94 | 95 | % gaurd against a possible bug, T should always be =< ?HOURSECS 96 | % also to prevent overflow issues make sure alpha is always =< 97 | % math:log(1.79769313486231570815e+308) / 3599 = 0.19721664709457737 98 | weight(Alpha, T) when T =< ?HOURSECS, Alpha =< 0.19721664709457737 -> 99 | math:exp(Alpha * T). 100 | 101 | priority(Alpha, Time, Start, Rand) -> 102 | weight(Alpha, Time - Start) / Rand. 103 | 104 | rescale(Reservoir, Now, Next, OldStart, Alpha) when Now >= Next -> 105 | NewStart = Now + ?HOURSECS, 106 | NewRes = delete_and_rescale(Reservoir, NewStart, OldStart, Alpha), 107 | {NewRes, Now, NewStart}; 108 | rescale(Reservoir, _, Next, Start, _) -> 109 | {Reservoir, Start, Next}. 110 | 111 | delete_and_rescale(Reservoir, NewStart, OldStart, Alpha) -> 112 | % get the existing reservoir 113 | ResList = ets:tab2list(Reservoir), 114 | 115 | % create a new ets table to use 116 | NewRes = folsom_metrics_histogram_ets:new(folsom_exdec,[ordered_set, {write_concurrency, true}, public]), 117 | 118 | % populate it with new priorities and the existing values 119 | [true = ets:insert(NewRes, {recalc_priority(Priority, Alpha, NewStart, OldStart) ,Value}) || {Priority, Value} <- ResList], 120 | 121 | % delete the old ets table 122 | true = ets:delete(Reservoir), 123 | 124 | % return the new ets table 125 | NewRes. 126 | 127 | recalc_priority(Priority, Alpha, Start, OldStart) -> 128 | Priority * math:exp(-Alpha * (Start - OldStart)). 129 | -------------------------------------------------------------------------------- /src/folsom_metrics_meter_reader.erl: -------------------------------------------------------------------------------- 1 | %%% 2 | %%% Copyright 2011, Boundary 3 | %%% Copyright 2011, Opscode 4 | %%% 5 | %%% Licensed under the Apache License, Version 2.0 (the "License"); 6 | %%% you may not use this file except in compliance with the License. 7 | %%% You may obtain a copy of the License at 8 | %%% 9 | %%% http://www.apache.org/licenses/LICENSE-2.0 10 | %%% 11 | %%% Unless required by applicable law or agreed to in writing, software 12 | %%% distributed under the License is distributed on an "AS IS" BASIS, 13 | %%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | %%% See the License for the specific language governing permissions and 15 | %%% limitations under the License. 16 | %%% 17 | 18 | 19 | %%%------------------------------------------------------------------- 20 | %%% File: folsom_metrics_meter_reader.erl 21 | %%% @author Seth Falcon 22 | %%% @author joe williams 23 | %%% @doc 24 | %%% @end 25 | %%%------------------------------------------------------------------ 26 | 27 | -module(folsom_metrics_meter_reader). 28 | 29 | -export([new/1, 30 | tick/1, 31 | mark/1, 32 | mark/2, 33 | get_values/1, 34 | get_acceleration/1 35 | ]). 36 | 37 | 38 | -record(meter_reader, { 39 | one, 40 | five, 41 | fifteen, 42 | count = 0, 43 | start_time, 44 | last_count = unset 45 | }). 46 | 47 | -include("folsom.hrl"). 48 | 49 | new(Name) -> 50 | OneMin = folsom_ewma:one_minute_ewma(), 51 | FiveMin = folsom_ewma:five_minute_ewma(), 52 | FifteenMin = folsom_ewma:fifteen_minute_ewma(), 53 | 54 | ets:insert(?METER_READER_TABLE, 55 | {Name, #meter_reader{one = OneMin, 56 | five = FiveMin, 57 | fifteen = FifteenMin, 58 | start_time = folsom_utils:now_epoch_micro()}}). 59 | 60 | tick(Name) -> 61 | #meter_reader{one = OneMin, 62 | five = FiveMin, 63 | fifteen = FifteenMin} = Meter = get_value(Name), 64 | 65 | OneMin1 = folsom_ewma:tick(OneMin), 66 | FiveMin1 = folsom_ewma:tick(FiveMin), 67 | FifteenMin1 = folsom_ewma:tick(FifteenMin), 68 | 69 | ets:insert(?METER_READER_TABLE, 70 | {Name, Meter#meter_reader{one = OneMin1, 71 | five = FiveMin1, 72 | fifteen = FifteenMin1}}). 73 | 74 | mark(Name) -> 75 | mark(Name, 1). 76 | 77 | mark(Name, Value) -> 78 | % skip first reading to bootstrap last value 79 | #meter_reader{count = Count, 80 | last_count = LastCount, 81 | one = OneMin, 82 | five = FiveMin, 83 | fifteen = FifteenMin} = Meter = get_value(Name), 84 | 85 | NewMeter = case LastCount of 86 | unset -> 87 | Meter#meter_reader{last_count = Value}; 88 | _ -> 89 | Delta = Value - LastCount, 90 | OneMin1 = folsom_ewma:update(OneMin, Delta), 91 | FiveMin1 = folsom_ewma:update(FiveMin, Delta), 92 | FifteenMin1 = folsom_ewma:update(FifteenMin, Delta), 93 | Meter#meter_reader{count = Count + Delta, 94 | last_count = Value, 95 | one = OneMin1, 96 | five = FiveMin1, 97 | fifteen = FifteenMin1} 98 | end, 99 | 100 | ets:insert(?METER_READER_TABLE, {Name, NewMeter}). 101 | 102 | get_values(Name) -> 103 | #meter_reader{one = OneMin, 104 | five = FiveMin, 105 | fifteen = FifteenMin} = Meter = get_value(Name), 106 | 107 | L = [ 108 | {one, get_rate(OneMin)}, 109 | {five, get_rate(FiveMin)}, 110 | {fifteen, get_rate(FifteenMin)}, 111 | {mean, get_mean_rate(Meter)}, 112 | {acceleration, get_acceleration(Name)} 113 | ], 114 | 115 | [ {K,V} || {K,V} <- L, V /= undefined ]. 116 | 117 | get_acceleration(Name) -> 118 | #meter_reader{one = OneMin, 119 | five = FiveMin, 120 | fifteen = FifteenMin} = get_value(Name), 121 | 122 | [ 123 | {one_to_five, calc_acceleration(get_rate(OneMin), get_rate(FiveMin), 300)}, 124 | {five_to_fifteen, calc_acceleration(get_rate(FiveMin), get_rate(FifteenMin), 600)}, 125 | {one_to_fifteen, calc_acceleration(get_rate(OneMin), get_rate(FifteenMin), 900)} 126 | ]. 127 | 128 | % internal functions 129 | 130 | get_rate(EWMA) -> 131 | folsom_ewma:rate(EWMA). 132 | 133 | get_mean_rate(#meter_reader{count = Count, start_time = Start}) -> 134 | calc_mean_rate(Start, Count). 135 | 136 | get_value(Name) -> 137 | [{_, Value}] = ets:lookup(?METER_READER_TABLE, Name), 138 | Value. 139 | 140 | calc_mean_rate(_, 0) -> 141 | 0.0; 142 | calc_mean_rate(Start, Count) -> 143 | Elapsed = folsom_utils:now_epoch_micro() - Start, 144 | Count / Elapsed. 145 | 146 | calc_acceleration(Rate1, Rate2, Interval) -> 147 | % most current velocity minus previous velocity 148 | get_rate(Rate1, Rate2, Interval). 149 | 150 | get_rate(Value1, Value2, Interval) -> 151 | Delta = Value1 - Value2, 152 | Delta / Interval. 153 | -------------------------------------------------------------------------------- /src/folsom_metrics_histogram_ets.erl: -------------------------------------------------------------------------------- 1 | %%% 2 | %%% Copyright 2011, Boundary 3 | %%% 4 | %%% Licensed under the Apache License, Version 2.0 (the "License"); 5 | %%% you may not use this file except in compliance with the License. 6 | %%% You may obtain a copy of the License at 7 | %%% 8 | %%% http://www.apache.org/licenses/LICENSE-2.0 9 | %%% 10 | %%% Unless required by applicable law or agreed to in writing, software 11 | %%% distributed under the License is distributed on an "AS IS" BASIS, 12 | %%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | %%% See the License for the specific language governing permissions and 14 | %%% limitations under the License. 15 | %%% 16 | 17 | 18 | %%%------------------------------------------------------------------- 19 | %%% File: folsom_metrics_histogram_ets.erl 20 | %%% @author joe williams 21 | %%% @doc 22 | %%% this module creates ets tables for histograms as to be the parent 23 | %%% process for those histograms so the apps using folsom dont have to 24 | %%% @end 25 | %%%------------------------------------------------------------------ 26 | 27 | -module(folsom_metrics_histogram_ets). 28 | 29 | -behaviour(gen_server). 30 | 31 | %% API 32 | -export([start_link/0, new/2]). 33 | 34 | %% gen_server callbacks 35 | -export([init/1, handle_call/3, handle_cast/2, handle_info/2, 36 | terminate/2, code_change/3]). 37 | 38 | -define(SERVER, ?MODULE). 39 | 40 | -record(state, {}). 41 | 42 | %%%=================================================================== 43 | %%% API 44 | %%%=================================================================== 45 | 46 | %%-------------------------------------------------------------------- 47 | %% @doc 48 | %% Starts the server 49 | %% 50 | %% @spec start_link() -> {ok, Pid} | ignore | {error, Error} 51 | %% @end 52 | %%-------------------------------------------------------------------- 53 | start_link() -> 54 | gen_server:start_link({local, ?SERVER}, ?MODULE, [], []). 55 | 56 | %%%=================================================================== 57 | %%% gen_server callbacks 58 | %%%=================================================================== 59 | 60 | %%-------------------------------------------------------------------- 61 | %% @private 62 | %% @doc 63 | %% Initializes the server 64 | %% 65 | %% @spec init(Args) -> {ok, State} | 66 | %% {ok, State, Timeout} | 67 | %% ignore | 68 | %% {stop, Reason} 69 | %% @end 70 | %%-------------------------------------------------------------------- 71 | init([]) -> 72 | {ok, #state{}}. 73 | 74 | %%-------------------------------------------------------------------- 75 | %% @private 76 | %% @doc 77 | %% Handling call messages 78 | %% 79 | %% @spec handle_call(Request, From, State) -> 80 | %% {reply, Reply, State} | 81 | %% {reply, Reply, State, Timeout} | 82 | %% {noreply, State} | 83 | %% {noreply, State, Timeout} | 84 | %% {stop, Reason, Reply, State} | 85 | %% {stop, Reason, State} 86 | %% @end 87 | %%-------------------------------------------------------------------- 88 | handle_call({new, {Table, Opts}}, _From, State) -> 89 | Reply = ets:new(Table, Opts), 90 | {reply, Reply, State}. 91 | 92 | %%-------------------------------------------------------------------- 93 | %% @private 94 | %% @doc 95 | %% Handling cast messages 96 | %% 97 | %% @spec handle_cast(Msg, State) -> {noreply, State} | 98 | %% {noreply, State, Timeout} | 99 | %% {stop, Reason, State} 100 | %% @end 101 | %%-------------------------------------------------------------------- 102 | handle_cast(_Msg, State) -> 103 | {noreply, State}. 104 | 105 | %%-------------------------------------------------------------------- 106 | %% @private 107 | %% @doc 108 | %% Handling all non call/cast messages 109 | %% 110 | %% @spec handle_info(Info, State) -> {noreply, State} | 111 | %% {noreply, State, Timeout} | 112 | %% {stop, Reason, State} 113 | %% @end 114 | %%-------------------------------------------------------------------- 115 | handle_info(_Info, State) -> 116 | {noreply, State}. 117 | 118 | %%-------------------------------------------------------------------- 119 | %% @private 120 | %% @doc 121 | %% This function is called by a gen_server when it is about to 122 | %% terminate. It should be the opposite of Module:init/1 and do any 123 | %% necessary cleaning up. When it returns, the gen_server terminates 124 | %% with Reason. The return value is ignored. 125 | %% 126 | %% @spec terminate(Reason, State) -> void() 127 | %% @end 128 | %%-------------------------------------------------------------------- 129 | terminate(_Reason, _State) -> 130 | ok. 131 | 132 | %%-------------------------------------------------------------------- 133 | %% @private 134 | %% @doc 135 | %% Convert process state when code is changed 136 | %% 137 | %% @spec code_change(OldVsn, State, Extra) -> {ok, NewState} 138 | %% @end 139 | %%-------------------------------------------------------------------- 140 | code_change(_OldVsn, State, _Extra) -> 141 | {ok, State}. 142 | 143 | %%%=================================================================== 144 | %%% Internal functions 145 | %%%=================================================================== 146 | 147 | new(Table, Opts) -> 148 | gen_server:call(?SERVER, {new, {Table, Opts}}). 149 | -------------------------------------------------------------------------------- /test/cpu_topo_data: -------------------------------------------------------------------------------- 1 | [ 2 | %% Intel(R) Xeon(R) CPU X5647 @ 2.93GHz (Dual CPU) 3 | 4 | [{node,[{processor,[{core,[{thread,{logical,1}}, 5 | {thread,{logical,9}}]}, 6 | {core,[{thread,{logical,3}},{thread,{logical,11}}]}, 7 | {core,[{thread,{logical,5}},{thread,{logical,13}}]}, 8 | {core,[{thread,{logical,7}},{thread,{logical,15}}]}]}]}, 9 | {node,[{processor,[{core,[{thread,{logical,0}}, 10 | {thread,{logical,8}}]}, 11 | {core,[{thread,{logical,2}},{thread,{logical,10}}]}, 12 | {core,[{thread,{logical,4}},{thread,{logical,12}}]}, 13 | {core,[{thread,{logical,6}},{thread,{logical,14}}]}]}]}], 14 | 15 | %% Intel(R) Xeon(R) CPU X5647 @ 2.93GHz 16 | 17 | [{processor,[{core,[{thread,{logical,0}}, 18 | {thread,{logical,4}}]}, 19 | {core,[{thread,{logical,1}},{thread,{logical,5}}]}, 20 | {core,[{thread,{logical,2}},{thread,{logical,6}}]}, 21 | {core,[{thread,{logical,3}},{thread,{logical,7}}]}]}], 22 | 23 | %% Intel Core 2 Quad Q8300 LGA775 'Yorkfield' 2.5GHz 4MB-cache (1333FSB) Processor 24 | 25 | [{processor,[{core,{logical,0}}, 26 | {core,{logical,1}}, 27 | {core,{logical,2}}, 28 | {core,{logical,3}}]}], 29 | 30 | %% Intel® Xeon® Six Core E5-2620 (2.0 GHz, 7.20 GT/s, 15M L3 Cache) 31 | 32 | [{processor,[{core,[{thread,{logical,0}}, 33 | {thread,{logical,6}}]}, 34 | {core,[{thread,{logical,1}},{thread,{logical,7}}]}, 35 | {core,[{thread,{logical,2}},{thread,{logical,8}}]}, 36 | {core,[{thread,{logical,3}},{thread,{logical,9}}]}, 37 | {core,[{thread,{logical,4}},{thread,{logical,10}}]}, 38 | {core,[{thread,{logical,5}},{thread,{logical,11}}]}]}], 39 | 40 | %% OSX 41 | 42 | undefined, 43 | 44 | %% Intel(R) Xeon(R) CPU W3530 @ 2.80GHz 45 | 46 | [{processor,[{core,[{thread,{logical,0}}, 47 | {thread,{logical,4}}]}, 48 | {core,[{thread,{logical,1}},{thread,{logical,5}}]}, 49 | {core,[{thread,{logical,2}},{thread,{logical,6}}]}, 50 | {core,[{thread,{logical,3}},{thread,{logical,7}}]}]}], 51 | 52 | %% Intel(R) Atom(TM) CPU N2800 @ 1.86GHz (8GB memory) 53 | 54 | [{processor,[{core,[{thread,{logical,0}}, 55 | {thread,{logical,1}}]}, 56 | {core,[{thread,{logical,2}},{thread,{logical,3}}]}]}], 57 | 58 | %% Intel(R) Core(TM) i7-2675QM CPU @ 2.20GHz 59 | 60 | [{processor,[{core,[{thread,{logical,0}}, 61 | {thread,{logical,4}}]}, 62 | {core,[{thread,{logical,1}},{thread,{logical,5}}]}, 63 | {core,[{thread,{logical,2}},{thread,{logical,6}}]}, 64 | {core,[{thread,{logical,3}},{thread,{logical,7}}]}]}], 65 | 66 | %% Intel(R) Xeon(R) CPU L3426 @ 1.87GHz 67 | 68 | [{processor,[{core,[{thread,{logical,0}}, 69 | {thread,{logical,4}}]}, 70 | {core,[{thread,{logical,1}},{thread,{logical,5}}]}, 71 | {core,[{thread,{logical,2}},{thread,{logical,6}}]}, 72 | {core,[{thread,{logical,3}},{thread,{logical,7}}]}]}], 73 | 74 | %% Intel(R) Core(TM) i7 CPU M 640 @ 2.80GHz (in a vmware fusion vm, one cpu enabled) 75 | 76 | [{processor,{logical,0}}], 77 | 78 | %% Intel(R) Core(TM) i7 CPU M 640 @ 2.80GHz (in a vmware fusion vm, two cpus enabled) 79 | 80 | [{processor,{logical,0}},{processor,{logical,1}}], 81 | 82 | %% Intel(R) Core(TM) i7 CPU M 640 @ 2.80GHz (in a vmware fusion vm, four cpus enabled) 83 | 84 | [{processor,{logical,0}}, 85 | {processor,{logical,1}}, 86 | {processor,{logical,2}}, 87 | {processor,{logical,3}}], 88 | 89 | %% Intel(R) Xeon(R) CPU E5620 @ 2.40GHz (EC2 hi1.4xlarge) 90 | 91 | [{processor,[{thread,{logical,0}}, 92 | {thread,{logical,1}}, 93 | {thread,{logical,2}}, 94 | {thread,{logical,3}}, 95 | {thread,{logical,4}}, 96 | {thread,{logical,5}}, 97 | {thread,{logical,6}}, 98 | {thread,{logical,7}}, 99 | {thread,{logical,8}}, 100 | {thread,{logical,9}}, 101 | {thread,{logical,10}}, 102 | {thread,{logical,11}}, 103 | {thread,{logical,12}}, 104 | {thread,{logical,13}}, 105 | {thread,{logical,14}}, 106 | {thread,{logical,15}}]}], 107 | 108 | %% Intel(R) Xeon(R) CPU E5-2670 0 @ 2.60GHz (EC2 cc2.8xlarge) 109 | 110 | [{processor,[{core,[{thread,{logical,0}}, 111 | {thread,{logical,16}}]}, 112 | {core,[{thread,{logical,1}},{thread,{logical,17}}]}, 113 | {core,[{thread,{logical,2}},{thread,{logical,18}}]}, 114 | {core,[{thread,{logical,3}},{thread,{logical,19}}]}, 115 | {core,[{thread,{logical,4}},{thread,{logical,20}}]}, 116 | {core,[{thread,{logical,5}},{thread,{logical,21}}]}, 117 | {core,[{thread,{logical,6}},{thread,{logical,22}}]}, 118 | {core,[{thread,{logical,7}},{thread,{logical,23}}]}]}, 119 | {processor,[{core,[{thread,{logical,8}}, 120 | {thread,{logical,24}}]}, 121 | {core,[{thread,{logical,9}},{thread,{logical,25}}]}, 122 | {core,[{thread,{logical,10}},{thread,{logical,26}}]}, 123 | {core,[{thread,{logical,11}},{thread,{logical,27}}]}, 124 | {core,[{thread,{logical,12}},{thread,{logical,28}}]}, 125 | {core,[{thread,{logical,13}},{thread,{logical,29}}]}, 126 | {core,[{thread,{logical,14}},{thread,{logical,30}}]}, 127 | {core,[{thread,{logical,15}},{thread,{logical,31}}]}]}], 128 | 129 | %% Unknown 130 | 131 | [{processor,{logical,0}},{processor,{logical,1}}], 132 | 133 | %% single-core ppc32 134 | 135 | {logical,0} 136 | 137 | ]. 138 | -------------------------------------------------------------------------------- /test/slide_statem_eqc.erl: -------------------------------------------------------------------------------- 1 | %%% 2 | %%% Copyright 2012 - Basho Technologies, Inc. All Rights Reserved. 3 | %%% 4 | %%% Licensed under the Apache License, Version 2.0 (the "License"); 5 | %%% you may not use this file except in compliance with the License. 6 | %%% You may obtain a copy of the License at 7 | %%% 8 | %%% http://www.apache.org/licenses/LICENSE-2.0 9 | %%% 10 | %%% Unless required by applicable law or agreed to in writing, software 11 | %%% distributed under the License is distributed on an "AS IS" BASIS, 12 | %%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | %%% See the License for the specific language governing permissions and 14 | %%% limitations under the License. 15 | %%% 16 | 17 | %%%------------------------------------------------------------------- 18 | %%% File: slide_statem_eqc.erl 19 | %%% @author Russell Brown 20 | %%% @doc quickcheck test for the folsom_sample_slide.erl 21 | %%% @end 22 | %%%------------------------------------------------------------------ 23 | 24 | -module(slide_statem_eqc). 25 | 26 | -compile(export_all). 27 | 28 | -ifdef(TEST). 29 | -ifdef(EQC). 30 | 31 | -include("folsom.hrl"). 32 | 33 | -include_lib("eqc/include/eqc.hrl"). 34 | -include_lib("eqc/include/eqc_statem.hrl"). 35 | -include_lib("eunit/include/eunit.hrl"). 36 | 37 | 38 | 39 | -define(QC_OUT(P), 40 | eqc:on_output(fun(Str, Args) -> 41 | io:format(user, Str, Args) end, P)). 42 | 43 | -define(WINDOW, 60). 44 | 45 | -record(state, {moment=1000, 46 | sample, 47 | name, 48 | values=[]}). 49 | 50 | initial_state() -> 51 | meck:expect(folsom_utils, now_epoch, fun() -> 1000 end), 52 | #state{}. 53 | 54 | command(S) -> 55 | oneof( 56 | [{call, ?MODULE, new_histo, []} || S#state.sample == undefined] ++ 57 | [{call, ?MODULE, tick, [S#state.moment]} || S#state.sample /= undefined] ++ 58 | [{call, ?MODULE, update, [S#state.sample, int()]} || S#state.sample /= undefined] ++ 59 | [{call, ?MODULE, trim, [S#state.sample, ?WINDOW]} || S#state.sample /= undefined] ++ 60 | [{call, ?MODULE, get_values, [S#state.sample]} || S#state.sample /= undefined] 61 | ). 62 | 63 | %% Next state transformation, S is the current state 64 | next_state(S, V, {call, ?MODULE, new_histo, []}) -> 65 | S#state{name={call, erlang, element, [1, V]}, sample={call, erlang, element, [2, V]}}; 66 | next_state(S, V, {call, ?MODULE, tick, [_Moment]}) -> 67 | S#state{moment=V}; 68 | next_state(#state{moment=Moment, values=Values0}=S, V, {call, ?MODULE, update, [_, _Val]}) -> 69 | S#state{values=Values0 ++ [{Moment, V}]}; 70 | next_state(#state{values=Values, moment=Moment}=S, _V, {call, ?MODULE, trim, _}) -> 71 | %% trim the model 72 | S#state{values = trim(Values, Moment, ?WINDOW)}; 73 | next_state(S,_V,{call, ?MODULE, _, _}) -> 74 | S. 75 | 76 | %% Precondition, checked before command is added to the command sequence 77 | precondition(S, {call, _, new_histo, _}) -> 78 | S#state.sample == undefined; 79 | precondition(S, _) when S#state.sample == undefined -> 80 | false; 81 | precondition(_S, {call, _, _, _}) -> 82 | true. 83 | 84 | %% Postcondition, checked after command has been evaluated 85 | %% OBS: S is the state before next_state(S,_,) 86 | postcondition(#state{values=Values0, moment=Moment}, {call, ?MODULE, get_values, _}, Res) -> 87 | Values = [V || {K, V} <- Values0, K >= Moment - ?WINDOW], 88 | case lists:sort(Values) == lists:sort(Res) of 89 | true -> 90 | true; 91 | _ -> 92 | {"get values", {"model", lists:sort(Values)}, 93 | {"smaple", lists:sort(Res)}} 94 | end; 95 | postcondition(#state{values=Values, sample=Sample, moment=Moment}, {call, ?MODULE, trim, _}, _TrimCnt) -> 96 | %% check that values and the actual table contents are the same after a trim 97 | Table0 = ets:tab2list(Sample#slide.reservoir), 98 | Table = [{X, Y} || {{X, _}, Y} <- Table0], 99 | Model = lists:sort(trim(Values, Moment, ?WINDOW)), 100 | case Model == lists:sort(Table) of 101 | true -> 102 | true; 103 | _ -> 104 | {"after trim", {"model", Model}, {"sample", lists:sort(Table)}} 105 | end; 106 | postcondition(_S, {call, ?MODULE, _, _}, _Res) -> 107 | true. 108 | 109 | prop_window_test_() -> 110 | Seconds = 10, 111 | {setup, 112 | fun() -> ok end, 113 | fun(_X) -> (catch meck:unload(folsom_utils)), folsom:stop() end, 114 | [{"QuickCheck Test", 115 | {timeout, Seconds*2, fun() -> true = eqc:quickcheck(eqc:testing_time(Seconds, ?QC_OUT(prop_window()))) end 116 | }}]}. 117 | 118 | prop_window() -> 119 | folsom:start(), 120 | (catch meck:new(folsom_utils)), 121 | ?FORALL(Cmds, commands(?MODULE), 122 | aggregate(command_names(Cmds), 123 | begin 124 | {H, S, Res} = run_commands(?MODULE, Cmds), 125 | {Actual, Expected} = case S#state.sample of 126 | undefined -> 127 | {S#state.values, []}; 128 | Sample -> 129 | A = folsom_metrics:get_metric_value(S#state.name), 130 | E = [V || {K, V} <- S#state.values, K >= S#state.moment - ?WINDOW], 131 | folsom_metrics:delete_metric(S#state.name), 132 | {A, E} 133 | end, 134 | ?WHENFAIL( 135 | io:format("History: ~p~nState: ~p~nActual: ~p~nExpected: ~p~nRes: ~p~n", [H, S, Actual, Expected, Res]), 136 | conjunction([{total, equals(lists:sort(Actual), lists:sort(Expected))}, 137 | {eq, equals(Res, ok)}])) 138 | end)). 139 | 140 | %% Commands 141 | new_histo() -> 142 | Ref = make_ref(), 143 | folsom_metrics:new_histogram(Ref, slide, ?WINDOW), 144 | #histogram{sample=Slide} = folsom_metrics_histogram:get_value(Ref), 145 | ok = folsom_sample_slide_server:stop(Slide#slide.server), 146 | {Ref, Slide}. 147 | 148 | tick(Moment) -> 149 | IncrBy = trunc(random:uniform(10)), 150 | meck:expect(folsom_utils, now_epoch, fun() -> Moment + IncrBy end), 151 | Moment+IncrBy. 152 | 153 | update(Sample, Val) -> 154 | Sample = folsom_sample_slide:update(Sample, Val), 155 | Val. 156 | 157 | trim(Sample, Window) -> 158 | folsom_sample_slide:trim(Sample#slide.reservoir, Window). 159 | 160 | get_values(Sample) -> 161 | folsom_sample_slide:get_values(Sample). 162 | 163 | %% private 164 | trim(L, Moment, Window) -> 165 | [{K, V} || {K, V} <- L, K >= Moment - Window]. 166 | 167 | -endif. 168 | -endif. 169 | -------------------------------------------------------------------------------- /src/folsom_meter_timer_server.erl: -------------------------------------------------------------------------------- 1 | %%% 2 | %%% Copyright 2011, Boundary 3 | %%% 4 | %%% Licensed under the Apache License, Version 2.0 (the "License"); 5 | %%% you may not use this file except in compliance with the License. 6 | %%% You may obtain a copy of the License at 7 | %%% 8 | %%% http://www.apache.org/licenses/LICENSE-2.0 9 | %%% 10 | %%% Unless required by applicable law or agreed to in writing, software 11 | %%% distributed under the License is distributed on an "AS IS" BASIS, 12 | %%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | %%% See the License for the specific language governing permissions and 14 | %%% limitations under the License. 15 | %%% 16 | 17 | 18 | %%%------------------------------------------------------------------- 19 | %%% File: folsom_meter_timer_server.erl 20 | %%% @author joe williams 21 | %%% @doc 22 | %%% gen_server for registering meter ticks 23 | %%% @end 24 | %%%----------------------------------------------------------------- 25 | 26 | -module(folsom_meter_timer_server). 27 | 28 | -behaviour(gen_server). 29 | 30 | %% API 31 | -export([start_link/0, register/2, unregister/1, dump/0]). 32 | 33 | %% gen_server callbacks 34 | -export([init/1, handle_call/3, handle_cast/2, handle_info/2, 35 | terminate/2, code_change/3]). 36 | 37 | -define(SERVER, ?MODULE). 38 | 39 | -include("folsom.hrl"). 40 | 41 | -record(state, { 42 | registered_timers = [] 43 | }). 44 | 45 | %%%=================================================================== 46 | %%% API 47 | %%%=================================================================== 48 | 49 | %%-------------------------------------------------------------------- 50 | %% @doc 51 | %% Starts the server 52 | %% 53 | %% @spec start_link() -> {ok, Pid} | ignore | {error, Error} 54 | %% @end 55 | %%-------------------------------------------------------------------- 56 | start_link() -> 57 | gen_server:start_link({local, ?SERVER}, ?MODULE, [], []). 58 | 59 | %%%=================================================================== 60 | %%% gen_server callbacks 61 | %%%=================================================================== 62 | 63 | %%-------------------------------------------------------------------- 64 | %% @private 65 | %% @doc 66 | %% Initializes the server 67 | %% 68 | %% @spec init(Args) -> {ok, State} | 69 | %% {ok, State, Timeout} | 70 | %% ignore | 71 | %% {stop, Reason} 72 | %% @end 73 | %%-------------------------------------------------------------------- 74 | init([]) -> 75 | {ok, #state{}}. 76 | 77 | %%-------------------------------------------------------------------- 78 | %% @private 79 | %% @doc 80 | %% Handling call messages 81 | %% 82 | %% @spec handle_call(Request, From, State) -> 83 | %% {reply, Reply, State} | 84 | %% {reply, Reply, State, Timeout} | 85 | %% {noreply, State} | 86 | %% {noreply, State, Timeout} | 87 | %% {stop, Reason, Reply, State} | 88 | %% {stop, Reason, State} 89 | %% @end 90 | %%-------------------------------------------------------------------- 91 | handle_call({register, Name, Module}, _From, State) -> 92 | NewState = case proplists:is_defined(Name, State#state.registered_timers) of 93 | true -> 94 | State; 95 | false -> 96 | {ok, Ref} = timer:apply_interval(?DEFAULT_INTERVAL, Module, tick, [Name]), 97 | NewList = [{Name, Ref} | State#state.registered_timers], 98 | #state{registered_timers = NewList} 99 | end, 100 | {reply, ok, NewState}; 101 | handle_call({unregister, Name}, _From, State) -> 102 | NewState = case proplists:is_defined(Name, State#state.registered_timers) of 103 | true -> 104 | Ref = proplists:get_value(Name, State#state.registered_timers), 105 | {ok, cancel} = timer:cancel(Ref), 106 | #state{registered_timers = proplists:delete(Name, State#state.registered_timers)}; 107 | false -> State 108 | end, 109 | {reply, ok, NewState}; 110 | handle_call(dump, _From, State) -> 111 | {reply, State, State}. 112 | 113 | %%-------------------------------------------------------------------- 114 | %% @private 115 | %% @doc 116 | %% Handling cast messages 117 | %% 118 | %% @spec handle_cast(Msg, State) -> {noreply, State} | 119 | %% {noreply, State, Timeout} | 120 | %% {stop, Reason, State} 121 | %% @end 122 | %%-------------------------------------------------------------------- 123 | handle_cast(_Msg, State) -> 124 | {noreply, State}. 125 | 126 | %%-------------------------------------------------------------------- 127 | %% @private 128 | %% @doc 129 | %% Handling all non call/cast messages 130 | %% 131 | %% @spec handle_info(Info, State) -> {noreply, State} | 132 | %% {noreply, State, Timeout} | 133 | %% {stop, Reason, State} 134 | %% @end 135 | %%-------------------------------------------------------------------- 136 | handle_info(_Info, State) -> 137 | {noreply, State}. 138 | 139 | %%-------------------------------------------------------------------- 140 | %% @private 141 | %% @doc 142 | %% This function is called by a gen_server when it is about to 143 | %% terminate. It should be the opposite of Module:init/1 and do any 144 | %% necessary cleaning up. When it returns, the gen_server terminates 145 | %% with Reason. The return value is ignored. 146 | %% 147 | %% @spec terminate(Reason, State) -> void() 148 | %% @end 149 | %%-------------------------------------------------------------------- 150 | terminate(_Reason, _State) -> 151 | ok. 152 | 153 | %%-------------------------------------------------------------------- 154 | %% @private 155 | %% @doc 156 | %% Convert process state when code is changed 157 | %% 158 | %% @spec code_change(OldVsn, State, Extra) -> {ok, NewState} 159 | %% @end 160 | %%-------------------------------------------------------------------- 161 | code_change(_OldVsn, State, _Extra) -> 162 | {ok, State}. 163 | 164 | %%%=================================================================== 165 | %%% Internal functions 166 | %%%=================================================================== 167 | 168 | %% Name of the metric and name of the module used to tick said metric 169 | register(Name, Module) -> 170 | gen_server:call(?SERVER, {register, Name, Module}). 171 | 172 | unregister(Name) -> 173 | gen_server:call(?SERVER, {unregister, Name}). 174 | 175 | dump() -> 176 | gen_server:call(?SERVER, dump). 177 | -------------------------------------------------------------------------------- /src/folsom_metrics.erl: -------------------------------------------------------------------------------- 1 | %%% 2 | %%% Copyright 2011, Boundary 3 | %%% 4 | %%% Licensed under the Apache License, Version 2.0 (the "License"); 5 | %%% you may not use this file except in compliance with the License. 6 | %%% You may obtain a copy of the License at 7 | %%% 8 | %%% http://www.apache.org/licenses/LICENSE-2.0 9 | %%% 10 | %%% Unless required by applicable law or agreed to in writing, software 11 | %%% distributed under the License is distributed on an "AS IS" BASIS, 12 | %%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | %%% See the License for the specific language governing permissions and 14 | %%% limitations under the License. 15 | %%% 16 | 17 | 18 | %%%------------------------------------------------------------------- 19 | %%% File: folsom_metrics.erl 20 | %%% @author joe williams 21 | %%% @doc 22 | %%% @end 23 | %%%------------------------------------------------------------------ 24 | 25 | -module(folsom_metrics). 26 | 27 | -export([ 28 | new_counter/1, 29 | new_gauge/1, 30 | new_histogram/1, 31 | new_histogram/2, 32 | new_histogram/3, 33 | new_histogram/4, 34 | new_history/1, 35 | new_history/2, 36 | new_meter/1, 37 | new_meter_reader/1, 38 | new_duration/1, 39 | new_duration/2, 40 | new_duration/3, 41 | new_duration/4, 42 | new_spiral/1, 43 | new_spiral/2, 44 | delete_metric/1, 45 | tag_metric/2, 46 | untag_metric/2, 47 | notify/1, 48 | notify/2, 49 | notify/3, 50 | notify/4, 51 | safely_notify/1, 52 | safely_notify/2, 53 | safely_notify/3, 54 | safely_notify/4, 55 | notify_existing_metric/3, 56 | get_metrics/0, 57 | metric_exists/1, 58 | get_metrics_info/0, 59 | get_metrics_value/1, 60 | get_metrics_value/2, 61 | get_metric_info/1, 62 | get_metric_value/1, 63 | get_histogram_statistics/1, 64 | get_histogram_statistics/2, 65 | get_history_values/2, 66 | get_tags/1, 67 | histogram_timed_update/2, 68 | histogram_timed_update/3, 69 | histogram_timed_update/4, 70 | histogram_timed_begin/1, 71 | histogram_timed_notify/1, 72 | safely_histogram_timed_update/2, 73 | safely_histogram_timed_update/3, 74 | safely_histogram_timed_update/4, 75 | safely_histogram_timed_notify/1 76 | ]). 77 | 78 | -include("folsom.hrl"). 79 | 80 | %% Metrics API 81 | 82 | new_counter(Name) -> 83 | folsom_ets:add_handler(counter, Name). 84 | 85 | new_gauge(Name) -> 86 | folsom_ets:add_handler(gauge, Name). 87 | 88 | new_histogram(Name) -> 89 | folsom_metrics:new_histogram(Name, ?DEFAULT_SAMPLE_TYPE, ?DEFAULT_SIZE, ?DEFAULT_ALPHA). 90 | 91 | new_histogram(Name, slide_uniform) -> 92 | folsom_metrics:new_histogram(Name, slide_uniform, {?DEFAULT_SLIDING_WINDOW, ?DEFAULT_SIZE}, ?DEFAULT_ALPHA); 93 | new_histogram(Name, SampleType) -> 94 | folsom_metrics:new_histogram(Name, SampleType, ?DEFAULT_SIZE, ?DEFAULT_ALPHA). 95 | 96 | new_histogram(Name, SampleType, SampleSize) -> 97 | folsom_metrics:new_histogram(Name, SampleType, SampleSize, ?DEFAULT_ALPHA). 98 | 99 | new_histogram(Name, SampleType, SampleSize, Alpha) -> 100 | folsom_ets:add_handler(histogram, Name, SampleType, SampleSize, Alpha). 101 | 102 | new_history(Name) -> 103 | folsom_metrics:new_history(Name, ?DEFAULT_SIZE). 104 | 105 | new_history(Name, SampleSize) -> 106 | folsom_ets:add_handler(history, Name, SampleSize). 107 | 108 | new_meter(Name) -> 109 | folsom_ets:add_handler(meter, Name). 110 | 111 | new_meter_reader(Name) -> 112 | folsom_ets:add_handler(meter_reader, Name). 113 | 114 | new_duration(Name) -> 115 | folsom_metrics:new_duration(Name, ?DEFAULT_SAMPLE_TYPE, ?DEFAULT_SIZE, ?DEFAULT_ALPHA). 116 | 117 | new_duration(Name, SampleType) -> 118 | folsom_metrics:new_duration(Name, SampleType, ?DEFAULT_SIZE, ?DEFAULT_ALPHA). 119 | 120 | new_duration(Name, SampleType, SampleSize) -> 121 | folsom_metrics:new_duration(Name, SampleType, SampleSize, ?DEFAULT_ALPHA). 122 | 123 | new_duration(Name, SampleType, SampleSize, Alpha) -> 124 | folsom_ets:add_handler(duration, Name, SampleType, SampleSize, Alpha). 125 | 126 | new_spiral(Name) -> 127 | folsom_ets:add_handler(spiral, Name). 128 | 129 | new_spiral(Name, Update) -> 130 | folsom_ets:add_handler(spiral, Name, Update). 131 | 132 | tag_metric(Name, Tag) -> 133 | folsom_ets:tag_handler(Name, Tag). 134 | 135 | untag_metric(Name, Tag) -> 136 | folsom_ets:untag_handler(Name, Tag). 137 | 138 | delete_metric(Name) -> 139 | folsom_ets:delete_handler(Name). 140 | 141 | notify(Event) -> 142 | folsom_ets:notify(Event). 143 | 144 | notify(Name, Event) -> 145 | folsom_ets:notify(Name, Event). 146 | 147 | notify(Name, Event, Type) -> 148 | folsom_ets:notify(Name, Event, Type). 149 | 150 | notify(Name, Event, Type, Tags) -> 151 | folsom_ets:tagged_notify(Name, Event, Type, Tags). 152 | 153 | safely_notify(Event) -> 154 | catch notify(Event). 155 | 156 | safely_notify(Name, Event) -> 157 | catch notify(Name, Event). 158 | 159 | safely_notify(Name, Event, Type) -> 160 | catch notify(Name, Event, Type). 161 | 162 | safely_notify(Name, Event, Type, Tags) -> 163 | catch notify(Name, Event, Type, Tags). 164 | 165 | notify_existing_metric(Name, Event, Type) -> 166 | folsom_ets:notify_existing_metric(Name, Event, Type). 167 | 168 | get_metrics() -> 169 | folsom_ets:get_handlers(). 170 | 171 | metric_exists(Name) -> 172 | folsom_ets:handler_exists(Name). 173 | 174 | get_metrics_info() -> 175 | folsom_ets:get_handlers_info(). 176 | 177 | get_metrics_value(Tag) -> 178 | folsom_ets:get_group_values(Tag). 179 | 180 | get_metrics_value(Tag, Type) -> 181 | folsom_ets:get_group_values(Tag, Type). 182 | 183 | get_metric_info(Name) -> 184 | [folsom_ets:get_info(Name)]. 185 | 186 | get_metric_value(Name) -> 187 | folsom_ets:get_values(Name). 188 | 189 | get_histogram_statistics(Name) -> 190 | Values = folsom_ets:get_values(Name), 191 | WantedMetrics = application:get_env(folsom, enabled_metrics, ?DEFAULT_METRICS), 192 | bear:get_statistics_subset(Values, WantedMetrics). 193 | 194 | get_histogram_statistics(Name1, Name2) -> 195 | Values1 = get_metric_value(Name1), 196 | Values2 = get_metric_value(Name2), 197 | bear:get_statistics(Values1, Values2). 198 | 199 | get_history_values(Name, Count) -> 200 | folsom_ets:get_history_values(Name, Count). 201 | 202 | get_tags(Name) -> 203 | folsom_ets:get_tags(Name). 204 | 205 | histogram_timed_update(Name, Fun) -> 206 | {Time, Value} = timer:tc(Fun), 207 | ok = notify({Name, Time}), 208 | Value. 209 | 210 | histogram_timed_update(Name, Fun, Args) -> 211 | {Time, Value} = timer:tc(Fun, Args), 212 | ok = notify({Name, Time}), 213 | Value. 214 | 215 | histogram_timed_update(Name, Mod, Fun, Args) -> 216 | {Time, Value} = timer:tc(Mod, Fun, Args), 217 | ok = notify({Name, Time}), 218 | Value. 219 | 220 | histogram_timed_begin(Name) -> 221 | {Name, os:timestamp()}. 222 | 223 | histogram_timed_notify({Name, Begin}) -> 224 | Now = os:timestamp(), 225 | Time = timer:now_diff(Now, Begin), 226 | ok = notify({Name, Time}). 227 | 228 | safely_histogram_timed_update(Name, Fun) -> 229 | {Time, Value} = timer:tc(Fun), 230 | _ = safely_notify({Name, Time}), 231 | Value. 232 | 233 | safely_histogram_timed_update(Name, Fun, Args) -> 234 | {Time, Value} = timer:tc(Fun, Args), 235 | _ = safely_notify({Name, Time}), 236 | Value. 237 | 238 | safely_histogram_timed_update(Name, Mod, Fun, Args) -> 239 | {Time, Value} = timer:tc(Mod, Fun, Args), 240 | _ = safely_notify({Name, Time}), 241 | Value. 242 | 243 | safely_histogram_timed_notify({Name, Begin}) -> 244 | Now = os:timestamp(), 245 | Time = timer:now_diff(Now, Begin), 246 | safely_notify({Name, Time}). 247 | -------------------------------------------------------------------------------- /include/folsom.hrl: -------------------------------------------------------------------------------- 1 | -define(FOLSOM_TABLE, folsom). 2 | -define(COUNTER_TABLE, folsom_counters). 3 | -define(GAUGE_TABLE, folsom_gauges). 4 | -define(HISTOGRAM_TABLE, folsom_histograms). 5 | -define(METER_TABLE, folsom_meters). 6 | -define(METER_READER_TABLE, folsom_meter_readers). 7 | -define(HISTORY_TABLE, folsom_histories). 8 | -define(DURATION_TABLE, folsom_durations). 9 | -define(SPIRAL_TABLE, folsom_spirals). 10 | 11 | -define(DEFAULT_LIMIT, 5). 12 | -define(DEFAULT_SIZE, 1028). % mimic codahale's metrics 13 | -define(DEFAULT_SLIDING_WINDOW, 60). % sixty second sliding window 14 | -define(DEFAULT_ALPHA, 0.015). % mimic codahale's metrics 15 | -define(DEFAULT_INTERVAL, 5000). 16 | -define(DEFAULT_SAMPLE_TYPE, uniform). 17 | 18 | -record(spiral, { 19 | tid = folsom_metrics_histogram_ets:new(folsom_spiral, 20 | [set, 21 | {write_concurrency, true}, 22 | public]), 23 | server, 24 | update = update_counter :: update_counter | 25 | update_counter_no_exception 26 | }). 27 | 28 | -record(slide, { 29 | window = ?DEFAULT_SLIDING_WINDOW, 30 | reservoir = folsom_metrics_histogram_ets:new(folsom_slide, 31 | [duplicate_bag, {write_concurrency, true}, public]), 32 | server 33 | }). 34 | 35 | -record(slide_uniform, { 36 | window = ?DEFAULT_SLIDING_WINDOW, 37 | size = ?DEFAULT_SIZE, 38 | reservoir = folsom_metrics_histogram_ets:new(folsom_slide_uniform,[set, {write_concurrency, true}, public]), 39 | seed = os:timestamp(), 40 | server 41 | }). 42 | 43 | -record(uniform, { 44 | size = ?DEFAULT_SIZE, 45 | n = 1, 46 | reservoir = folsom_metrics_histogram_ets:new(folsom_uniform,[set, {write_concurrency, true}, public]), 47 | seed = os:timestamp() 48 | }). 49 | 50 | -record(exdec, { 51 | start = 0, 52 | next = 0, 53 | alpha = ?DEFAULT_ALPHA, 54 | size = ?DEFAULT_SIZE, 55 | seed = os:timestamp(), 56 | n = 1, 57 | reservoir = folsom_metrics_histogram_ets:new(folsom_exdec,[ordered_set, {write_concurrency, true}, public]) 58 | }). 59 | 60 | -record(none, { 61 | size = ?DEFAULT_SIZE, 62 | n = 1, 63 | reservoir = folsom_metrics_histogram_ets:new(folsom_none,[ordered_set, {write_concurrency, true}, public]) 64 | }). 65 | 66 | -record(slide_sorted, { 67 | size = ?DEFAULT_SIZE, 68 | n = 0, 69 | reservoir = folsom_metrics_histogram_ets:new(folsom_slide_sorted,[ordered_set, {write_concurrency, true}, public]) 70 | }). 71 | 72 | -record(histogram, { 73 | type = uniform, 74 | sample = #uniform{} 75 | }). 76 | 77 | -record(history, { 78 | tid 79 | }). 80 | 81 | -define(SYSTEM_INFO, [ 82 | allocated_areas, 83 | allocator, 84 | alloc_util_allocators, 85 | build_type, 86 | c_compiler_used, 87 | check_io, 88 | compat_rel, 89 | cpu_topology, 90 | creation, 91 | debug_compiled, 92 | dist, 93 | dist_ctrl, 94 | driver_version, 95 | elib_malloc, 96 | dist_buf_busy_limit, 97 | %fullsweep_after, % included in garbage_collection 98 | garbage_collection, 99 | %global_heaps_size, % deprecated 100 | heap_sizes, 101 | heap_type, 102 | info, 103 | kernel_poll, 104 | loaded, 105 | logical_processors, 106 | logical_processors_available, 107 | logical_processors_online, 108 | machine, 109 | %min_heap_size, % included in garbage_collection 110 | %min_bin_vheap_size, % included in garbage_collection 111 | modified_timing_level, 112 | multi_scheduling, 113 | multi_scheduling_blockers, 114 | otp_release, 115 | port_count, 116 | process_count, 117 | process_limit, 118 | scheduler_bind_type, 119 | scheduler_bindings, 120 | scheduler_id, 121 | schedulers, 122 | schedulers_online, 123 | smp_support, 124 | system_version, 125 | system_architecture, 126 | threads, 127 | thread_pool_size, 128 | trace_control_word, 129 | update_cpu_info, 130 | version, 131 | wordsize 132 | ]). 133 | 134 | -define(STATISTICS, [ 135 | context_switches, 136 | %exact_reductions, % use reductions instead 137 | garbage_collection, 138 | io, 139 | reductions, 140 | run_queue, 141 | runtime, 142 | wall_clock 143 | ]). 144 | 145 | -define(PROCESS_INFO, [ 146 | backtrace, 147 | binary, 148 | catchlevel, 149 | current_function, 150 | %dictionary, 151 | error_handler, 152 | garbage_collection, 153 | group_leader, 154 | heap_size, 155 | initial_call, 156 | links, 157 | last_calls, 158 | memory, 159 | %message_binary, 160 | message_queue_len, 161 | messages, 162 | min_heap_size, 163 | min_bin_vheap_size, 164 | monitored_by, 165 | monitors, 166 | priority, 167 | reductions, 168 | registered_name, 169 | sequential_trace_token, 170 | stack_size, 171 | status, 172 | suspending, 173 | total_heap_size, 174 | trace, 175 | trap_exit 176 | ]). 177 | 178 | -define(SOCKET_OPTS, [ 179 | active, 180 | broadcast, 181 | delay_send, 182 | dontroute, 183 | exit_on_close, 184 | header, 185 | keepalive, 186 | nodelay, 187 | packet, 188 | packet_size, 189 | read_packets, 190 | recbuf, 191 | reuseaddr, 192 | send_timeout, 193 | send_timeout_close, 194 | sndbuf, 195 | priority, 196 | tos 197 | ]). 198 | 199 | -define(DEFAULT_METRICS, [ 200 | arithmetic_mean, 201 | geometric_mean, 202 | harmonic_mean, 203 | histogram, 204 | kurtosis, 205 | n, 206 | max, 207 | median, 208 | min, 209 | {percentile, [50, 75, 95, 99, 999]}, 210 | skewness, 211 | standard_deviation, 212 | variance 213 | ]). 214 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | ### folsom 2 | 3 | Folsom is an Erlang based metrics system inspired by Coda Hale's metrics (https://github.com/dropwizard/metrics). The metrics API's purpose is to collect realtime metrics from your Erlang applications and publish them via Erlang APIs and output plugins. folsom is *not* a persistent store. There are 6 types of metrics: counters, gauges, histograms (and timers), histories, meter_readers and meters. Metrics can be created, read and updated via the `folsom_metrics` module. 4 | 5 | #### Building and running 6 | 7 | First, regarding using folsom and folsom_webmachine together. To make sure you have compatible versions of each, make sure you use code from the same version tags, ie 0.5 of folsom is known to work with 0.5 folsom_webmachine. HEAD on each repo may have broken API compatibility. 8 | 9 | You need a (preferably recent) version of Erlang installed but that should be it. 10 | 11 | ./rebar get-deps compile 12 | 13 | folsom can be run standalone or embedded in an Erlang application. 14 | 15 | $ erl -pa ebin deps/*/ebin 16 | 17 | > folsom:start(). % this creates the needed ETS tables and starts a gen_server 18 | 19 | You can also start it as an application: 20 | 21 | $ erl -pa ebin deps/*/ebin 22 | > application:start(folsom). 23 | 24 | $ erl -pa ebin deps/*/ebin -s folsom 25 | 26 | The application can be configured to create individual or lists of metrics at 27 | startup on the command line or in an application config file: 28 | 29 | $ erl -pa ebin deps/*/ebin -s folsom \ 30 | -folsom history '[hist1,hist2]' \ 31 | -folsom gauge gauge1 32 | 33 | $ echo '[{folsom, [{history, [hist1, hist2]}, {gauge, gauge1}]}].' \ 34 | > myapp.config 35 | $ erl -pa ebin deps/*/ebin -config myapp.config -s folsom 36 | 37 | #### Metrics API 38 | 39 | folsom_metrics.erl is the API module you will need to use most of the time. 40 | 41 | Retrieve a list of current installed metrics: 42 | 43 | > folsom_metrics:get_metrics(). 44 | 45 | Query a specific metric: 46 | 47 | > folsom_metrics:get_metric_value(Name). 48 | 49 | Generally names of metrics are atoms or binaries. 50 | 51 | ##### Counters 52 | 53 | Counter metrics provide increment and decrement capabilities for a single scalar value. 54 | 55 | > folsom_metrics:new_counter(Name). 56 | > folsom_metrics:notify({Name, {inc, Value}}). 57 | > folsom_metrics:notify({Name, {dec, Value}}). 58 | 59 | ##### Gauges 60 | 61 | Gauges are point-in-time single value metrics. 62 | 63 | > folsom_metrics:new_gauge(Name). 64 | > folsom_metrics:notify({Name, Value}). 65 | 66 | ##### Histograms (and Timers) 67 | 68 | Histograms are collections of values that have statistical analysis done to them, such as mean, min, max, kurtosis and percentile. They can be used like "timers" as well with the timed update functions. 69 | 70 | > folsom_metrics:new_histogram(Name). 71 | > folsom_metrics:histogram_timed_update(Name, Mod, Fun, Args). 72 | > folsom_metrics:histogram_timed_update(Name, Fun, Args). 73 | > folsom_metrics:histogram_timed_update(Name, Fun). 74 | > folsom_metrics:notify({Name, Value}). 75 | 76 | ###### Histogram sample types 77 | 78 | Each histogram draws its values from a `reservoir` of readings. You can select a `sample type` for a histogram by passing the name of the sample type as an atom when you create a new histogram. 79 | Some sample types have further arguments. The purpose of a sample type is to control the size and charecteristics of the reservoir of readings the histogram performs analysis upon. 80 | 81 | Folsom currently provides the following sample types: 82 | 83 | ###### `uniform` 84 | 85 | This is a random uniform sample over the stream of readings. This is the default sample type, bounded in size to 1028 readings. When `size` readings have been taken, new readings replace older readings 86 | in the reservoir at random. You can set the sample size at creation time: 87 | 88 | > folsom_metrics:new_histogram(Name, uniform, Size::integer()). 89 | 90 | Be sure you understand _why_ before you do this. 91 | 92 | ###### `exdec` 93 | 94 | This is a sample that exponentially decays less significant readings over time so as to give greater significance to newer readings. Read more here - 95 | [Forward Decay...](http://www.research.att.com/people/Cormode_Graham/library/publications/CormodeShkapenyukSrivastavaXu09.pdf). 96 | Again you can change defaults at creation time, if you think you need to: 97 | 98 | > folsom_metrics:new_histogram(Name, exdec, Size::integer(), Alpha::float()). 99 | 100 | ###### `slide` 101 | 102 | This is a sliding window in time over a stream of readings. The default window size is 60 seconds. Every reading that occurs in a sliding sixty second window is stored, 103 | with older readings being discarded. If you have a lot of readings per 104 | minute the `reservoir` may get pretty big and so it will take more time to calculate statistics. You can set the `window` size by providing a number of seconds. 105 | 106 | > folsom_metrics:new_histogram(Name, slide, Seconds::integer()). 107 | 108 | ###### `slide_uniform` 109 | 110 | This is a sliding window in time over a stream of readings with a random uniform sample per second, to bound the size of the total number of readings. The maximum size of the reservoir will be 111 | `window size * sample size`. Default is a window of 60 seconds and a sample size of 1028. Again, you can change these at creation time: 112 | 113 | > folsom_metrics:new_histogram(Name, slide_uniform, {Secs::interger(), Size::integer()). 114 | 115 | ##### Histories 116 | 117 | Histories are a collection of past events, such as errors or log messages. 118 | 119 | > folsom_metrics:new_history(Name). 120 | > folsom_metrics:get_history_values(Name, Count). % get more than the default number of history items back 121 | > folsom_metrics:notify({Name, Value}). 122 | 123 | ##### Meters 124 | 125 | Meters are increment only counters with mean rates and exponentially weighted moving averages applied to them, similar to a unix load average. 126 | 127 | > folsom_metrics:new_meter(Name). 128 | > folsom_metrics:notify({Name, Value}). 129 | 130 | ###### `Spiral` meter 131 | 132 | A `spiral` is a type of meter that has a one minute sliding window count. The meter tracks an increment only counter and a total for the last minute. This is a sliding count with older readings dropping off per second. 133 | 134 | > folsom_metrics:new_spiral(Name). 135 | > folsom_metrics:notify({Name, Count}). 136 | 137 | ##### Meter Reader 138 | 139 | Meter readers are like a meter except that the values passed to it are monotonically increasing, e.g., reading from a water or gas meter, CPU jiffies, or I/O operation count. 140 | 141 | > folsom_metrics:new_meter_reader(Name). 142 | > folsom_metrics:notify({Name, Value}). 143 | 144 | ##### Metrics groups/tags 145 | 146 | Certain users might want to group and query metrics monitoring a common task. In order to do so, they can 147 | tag metrics: 148 | 149 | > folsom_metrics:tag_metric(Name, Tag). 150 | 151 | and untag metrics: 152 | 153 | > folsom_metrics:untag_metric(Name, Tag). 154 | 155 | Users can query a list of tuples `[{Name, Value}]` of all metrics with a given tag: 156 | 157 | > folsom_metrics:get_metrics_value(Tag). 158 | 159 | If only a certain type of metrics from a given group is desired, one can specify so: 160 | 161 | > folsom_metrics:get_metrics_value(Tag, Type). 162 | 163 | where Type is one of `counter`, `gauge`, `histogram`, `history`, `meter`, `meter_reader`, `duration` or `spiral`. 164 | 165 | ##### Erlang VM 166 | 167 | folsom also produces Erlang VM statistics. 168 | 169 | The result of `erlang:memory/0`: 170 | 171 | > folsom_vm_metrics:get_memory(). 172 | 173 | The result of `erlang:system_info/1`: 174 | 175 | > folsom_vm_metrics:get_system_info(). 176 | 177 | The result of `erlang:statistics/1`: 178 | 179 | > folsom_vm_metrics:get_statistics(). 180 | 181 | The result of `erlang:process_info/1`: 182 | 183 | > folsom_vm_metrics:get_process_info(). %% use with caution 184 | 185 | The result of `inet:getstat/1`, `prim_inet:getstatus/1`, `erlang:port_info/1`, `prim_inet:gettype/1`, `inet:getopts/1`, `inet:sockname/1`: 186 | 187 | > folsom_vm_metrics:get_port_info(). %% use with caution 188 | 189 | The result from `ets:info/1` and `dets:info/1` across all tables 190 | 191 | > folsom_vm_metrics:get_ets_info(). 192 | > folsom_vm_metrics:get_dets_info(). 193 | -------------------------------------------------------------------------------- /test/slide_uniform_eqc.erl: -------------------------------------------------------------------------------- 1 | %%% 2 | %%% Copyright 2012 - Basho Technologies, Inc. All Rights Reserved. 3 | %%% 4 | %%% Licensed under the Apache License, Version 2.0 (the "License"); 5 | %%% you may not use this file except in compliance with the License. 6 | %%% You may obtain a copy of the License at 7 | %%% 8 | %%% http://www.apache.org/licenses/LICENSE-2.0 9 | %%% 10 | %%% Unless required by applicable law or agreed to in writing, software 11 | %%% distributed under the License is distributed on an "AS IS" BASIS, 12 | %%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | %%% See the License for the specific language governing permissions and 14 | %%% limitations under the License. 15 | %%% 16 | 17 | %%%------------------------------------------------------------------- 18 | %%% File: slide_uniform_eqc.erl 19 | %%% @author Russell Brown 20 | %%% @doc quickcheck test for the folsom_sample_slide.erl 21 | %%% @end 22 | %%%------------------------------------------------------------------ 23 | 24 | -module(slide_uniform_eqc). 25 | 26 | -compile(export_all). 27 | 28 | -ifdef(TEST). 29 | -ifdef(EQC). 30 | -include("folsom.hrl"). 31 | 32 | -include_lib("eqc/include/eqc.hrl"). 33 | -include_lib("eqc/include/eqc_statem.hrl"). 34 | -include_lib("eunit/include/eunit.hrl"). 35 | 36 | -define(NUMTESTS, 200). 37 | -define(QC_OUT(P), 38 | eqc:on_output(fun(Str, Args) -> 39 | io:format(user, Str, Args) end, P)). 40 | 41 | -define(WINDOW, 60). 42 | -define(SIZE, 5). 43 | 44 | -record(state, {moment=1000, 45 | sample, 46 | name, 47 | count=orddict:new(), 48 | values=[]}). 49 | 50 | initial_state() -> 51 | meck:expect(folsom_utils, now_epoch, fun(_Now) -> 1000 end), 52 | meck:expect(folsom_utils, now_epoch, fun() -> 1000 end), 53 | #state{}. 54 | 55 | command(S) -> 56 | oneof( 57 | [{call, ?MODULE, new_histo, []} || S#state.sample == undefined] ++ 58 | [{call, ?MODULE, tick, [S#state.moment]} || S#state.sample /= undefined] ++ 59 | [{call, ?MODULE, update, [S#state.sample, int()]} || S#state.sample /= undefined] ++ 60 | [{call, ?MODULE, trim, [S#state.sample, ?WINDOW]} || S#state.sample /= undefined] ++ 61 | [{call, ?MODULE, get_values, [S#state.sample]} || S#state.sample /= undefined] 62 | ). 63 | 64 | %% Next state transformation, S is the current state 65 | next_state(S, V, {call, ?MODULE, new_histo, []}) -> 66 | S#state{name={call, erlang, element, [1, V]}, sample={call, erlang, element, [2, V]}}; 67 | next_state(S, V, {call, ?MODULE, tick, [_Moment]}) -> 68 | S#state{moment=V}; 69 | next_state(#state{moment=Moment, values=Values0, sample=Sample, count=Count}=S, NewSample, {call, ?MODULE, update, [_, Val]}) -> 70 | S#state{values={call, slide_uniform_eqc, new_state_values, [Sample, Moment, Values0, Val, Count]}, 71 | count={call, orddict, update_counter, [Moment, 1, Count]}, 72 | sample=NewSample}; 73 | next_state(#state{values=Values, moment=Moment}=S, _V, {call, ?MODULE, trim, _}) -> 74 | %% trim the model 75 | S#state{values={call, ?MODULE, trim, [Values, Moment, ?WINDOW]}}; 76 | next_state(S,_V,{call, ?MODULE, _, _}) -> 77 | S. 78 | 79 | %% Precondition, checked before command is added to the command sequence 80 | precondition(S, {call, _, new_histo, _}) -> 81 | S#state.sample == undefined; 82 | precondition(S, _) when S#state.sample == undefined -> 83 | false; 84 | precondition(_S, {call, _, _, _}) -> 85 | true. 86 | 87 | %% Postcondition, checked after command has been evaluated 88 | %% OBS: S is the state before next_state(S,_,) 89 | postcondition(#state{values=Values0, moment=Moment}, {call, ?MODULE, get_values, _}, Res) -> 90 | Values = [V || {{M, _C}, V} <- Values0, M >= Moment - ?WINDOW], 91 | case lists:sort(Values) == lists:sort(Res) of 92 | true -> 93 | true; 94 | _ -> 95 | {"get values", {"model", lists:sort(Values)}, {"sample", lists:sort(Res)}} 96 | end; 97 | postcondition(#state{values=Values, sample=Sample, moment=Moment}, {call, ?MODULE, trim, _}, _TrimCnt) -> 98 | %% check that values and the actual table contents are the same after a trim 99 | Table = [ Elem || {K, _V}=Elem <- ets:tab2list(Sample#slide_uniform.reservoir) 100 | , is_tuple(K)], %% filter out counter, 101 | case lists:sort(trim(Values, Moment, ?WINDOW)) == lists:sort(Table) of 102 | true -> 103 | true; 104 | _ -> 105 | {"after trim", {"model", lists:sort(trim(Values, Moment, ?WINDOW))}, {"sample", lists:sort(Table)}} 106 | end; 107 | postcondition(_S, {call, ?MODULE, _, _}, _Res) -> 108 | true. 109 | 110 | prop_window_test_() -> 111 | {setup, fun() -> ok end, fun(_X) -> (catch meck:unload(folsom_utils)), folsom:stop() end, 112 | fun(_X) -> 113 | {timeout, 30, 114 | ?_assert(eqc:quickcheck(eqc:numtests(?NUMTESTS, ?QC_OUT(prop_window()))))} end}. 115 | 116 | prop_window() -> 117 | folsom:start(), 118 | (catch meck:new(folsom_utils)), 119 | (catch meck:expect(folsom_utils, update_counter, fun(Tid, Key, Value) -> meck:passthrough([Tid, Key, Value]) end)), 120 | (catch meck:expect(folsom_utils, timestamp, fun() -> Res = os:timestamp(), put(timestamp, Res), Res end)), 121 | ?FORALL(Cmds, commands(?MODULE), 122 | aggregate(command_names(Cmds), 123 | begin 124 | {H, S, Res} = run_commands(?MODULE, Cmds), 125 | {Actual, Expected, Tab} = case S#state.sample of 126 | undefined -> 127 | {S#state.values, [], []}; 128 | Sample -> 129 | A = folsom_metrics:get_metric_value(S#state.name), 130 | E = [V || {{M, _C}, V} <- S#state.values, M >= S#state.moment - ?WINDOW], 131 | T = ets:tab2list(Sample#slide_uniform.reservoir), 132 | folsom_metrics:delete_metric(S#state.name), 133 | {A, E, T} 134 | end, 135 | ?WHENFAIL( 136 | io:format("History: ~p~nState: ~p~nActual: ~p~nExpected: ~p~nRes: ~p~nTab: ~p~n", 137 | [H, S, Actual, Expected, Res, Tab]), 138 | conjunction([{total, equals(lists:sort(Actual), lists:sort(Expected))}, 139 | {eq, equals(Res, ok)}])) 140 | end)). 141 | 142 | %% Commands 143 | new_histo() -> 144 | Ref = make_ref(), 145 | folsom_metrics:new_histogram(Ref, slide_uniform, {?WINDOW, ?SIZE}), 146 | #histogram{sample=Slide} = folsom_metrics_histogram:get_value(Ref), 147 | ok = folsom_sample_slide_server:stop(Slide#slide_uniform.server), 148 | {Ref, Slide}. 149 | 150 | tick(Moment) -> 151 | IncrBy = trunc(random:uniform(10)), 152 | meck:expect(folsom_utils, now_epoch, fun() -> Moment + IncrBy end), 153 | meck:expect(folsom_utils, now_epoch, fun(_Now) -> Moment + IncrBy end), 154 | Moment+IncrBy. 155 | 156 | update(Sample, Val) -> 157 | folsom_sample_slide_uniform:update(Sample, Val). 158 | 159 | trim(Sample, Window) -> 160 | folsom_sample_slide_uniform:trim(Sample#slide_uniform.reservoir, Window). 161 | 162 | get_values(Sample) -> 163 | folsom_sample_slide_uniform:get_values(Sample). 164 | 165 | %% private 166 | trim(L, Moment, Window) -> 167 | [{K, V} || {{M, _C}=K, V} <- L, M >= Moment - Window]. 168 | 169 | new_state_values(_Sample, Moment, Values, Val, Count) -> 170 | %Cnt = length([true || {{M, _C}, _V} <- Values, M == Moment]), 171 | Cnt = 172 | case orddict:find(Moment, Count) of 173 | error -> 174 | 1; 175 | {ok, V} -> 176 | V+1 177 | end, 178 | case Cnt > ?SIZE of 179 | true -> 180 | %% replace 181 | {Rnd, _} = random:uniform_s(Cnt, get(timestamp)), 182 | case Rnd =< ?SIZE of 183 | true -> 184 | lists:keyreplace({Moment, Rnd}, 1, Values, {{Moment, Rnd}, Val}); 185 | false -> 186 | Values 187 | end; 188 | false -> 189 | %% insert 190 | Values ++ [{{Moment, Cnt}, Val}] 191 | end. 192 | 193 | -endif. 194 | -endif. 195 | -------------------------------------------------------------------------------- /test/folsom_sample_slide_test.erl: -------------------------------------------------------------------------------- 1 | %%% 2 | %%% Copyright 2012 - Basho Technologies, Inc. All Rights Reserved. 3 | %%% 4 | %%% Licensed under the Apache License, Version 2.0 (the "License"); 5 | %%% you may not use this file except in compliance with the License. 6 | %%% You may obtain a copy of the License at 7 | %%% 8 | %%% http://www.apache.org/licenses/LICENSE-2.0 9 | %%% 10 | %%% Unless required by applicable law or agreed to in writing, software 11 | %%% distributed under the License is distributed on an "AS IS" BASIS, 12 | %%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | %%% See the License for the specific language governing permissions and 14 | %%% limitations under the License. 15 | %%% 16 | 17 | %%%------------------------------------------------------------------- 18 | %%% File: folsom_sample_slide.erl 19 | %%% @author Russell Brown 20 | %%% @doc eunit test for folsom_sample_slide.erl 21 | %%% @end 22 | %%%------------------------------------------------------------------ 23 | 24 | -module(folsom_sample_slide_test). 25 | 26 | -include_lib("eunit/include/eunit.hrl"). 27 | -include("folsom.hrl"). 28 | 29 | -define(HISTO, test_slide). 30 | -define(HISTO2, test_slide2). 31 | -define(WINDOW, 30). 32 | -define(DOUBLE_WINDOW, 60). 33 | -define(RUNTIME, 90). 34 | -define(READINGS, 10). 35 | 36 | slide_test_() -> 37 | {setup, 38 | fun () -> {ok, Apps} = application:ensure_all_started(folsom), 39 | meck:new(folsom_utils), 40 | Apps 41 | end, 42 | fun (Apps) -> meck:unload(folsom_utils), 43 | [application:stop(App) || App <- Apps] 44 | end, 45 | [{"Create sliding window", 46 | fun create/0}, 47 | {"test sliding window", 48 | {timeout, 30, fun exercise/0}}, 49 | {"resize sliding window (expand)", 50 | {timeout, 30, fun expand_window/0}}, 51 | {"resize sliding window (shrink)", 52 | {timeout, 30, fun shrink_window/0}} 53 | 54 | ]}. 55 | 56 | create() -> 57 | ok = folsom_metrics:new_histogram(?HISTO, slide, ?WINDOW), 58 | #histogram{sample=Slide} = folsom_metrics_histogram:get_value(?HISTO), 59 | ?assert(is_pid(Slide#slide.server)), 60 | ?assertEqual(?WINDOW, Slide#slide.window), 61 | ?assertEqual(0, ets:info(Slide#slide.reservoir, size)). 62 | 63 | exercise() -> 64 | %% don't want a trim to happen 65 | %% unless we call trim 66 | %% so kill the trim server process 67 | #histogram{sample=Slide} = folsom_metrics_histogram:get_value(?HISTO), 68 | ok = folsom_sample_slide_server:stop(Slide#slide.server), 69 | Moments = lists:seq(1, ?RUNTIME), 70 | %% pump in 90 seconds worth of readings 71 | Moment = lists:foldl(fun(_X, Tick) -> 72 | Tock = tick(Tick), 73 | [folsom_sample_slide:update(Slide, N) || 74 | N <- lists:duplicate(?READINGS, Tock)], 75 | Tock end, 76 | 0, 77 | Moments), 78 | %% are all readings in the table? 79 | check_table(Slide, Moments), 80 | %% get values only returns last ?WINDOW seconds 81 | ExpectedValues = lists:sort(lists:flatten([lists:duplicate(?READINGS, N) || 82 | N <- lists:seq(?RUNTIME - ?WINDOW, ?RUNTIME)])), 83 | Values = lists:sort(folsom_sample_slide:get_values(Slide)), 84 | ?assertEqual(ExpectedValues, Values), 85 | %% trim the table 86 | Trimmed = folsom_sample_slide:trim(Slide#slide.reservoir, ?WINDOW), 87 | ?assertEqual((?RUNTIME - ?WINDOW - 1) * ?READINGS, Trimmed), 88 | check_table(Slide, lists:seq(?RUNTIME - ?WINDOW, ?RUNTIME)), 89 | %% increment the clock past the window 90 | tick(Moment, ?WINDOW * 2), 91 | %% get values should be empty 92 | ?assertEqual([], folsom_sample_slide:get_values(Slide)), 93 | %% trim, and table should be empty 94 | Trimmed2 = folsom_sample_slide:trim(Slide#slide.reservoir, ?WINDOW), 95 | ?assertEqual((?RUNTIME * ?READINGS) - ((?RUNTIME - ?WINDOW - 1) * ?READINGS), Trimmed2), 96 | check_table(Slide, []), 97 | ok. 98 | 99 | expand_window() -> 100 | %% create a new histogram 101 | %% will leave the trim server running, as resize() needs it 102 | ok = folsom_metrics:new_histogram(?HISTO2, slide, ?WINDOW), 103 | #histogram{sample=Slide} = folsom_metrics_histogram:get_value(?HISTO2), 104 | Moments = lists:seq(1, ?RUNTIME ), 105 | %% pump in 90 seconds worth of readings 106 | Moment = lists:foldl(fun(_X, Tick) -> 107 | Tock = tick(Tick), 108 | [folsom_sample_slide:update(Slide, N) || 109 | N <- lists:duplicate(?READINGS, Tock)], 110 | Tock end, 111 | 0, 112 | Moments), 113 | %% are all readings in the table? 114 | check_table(Slide, Moments), 115 | 116 | %% get values only returns last ?WINDOW seconds 117 | ExpectedValues = lists:sort(lists:flatten([lists:duplicate(?READINGS, N) || 118 | N <- lists:seq(?RUNTIME - ?WINDOW, ?RUNTIME)])), 119 | Values = lists:sort(folsom_sample_slide:get_values(Slide)), 120 | ?assertEqual(ExpectedValues, Values), 121 | 122 | %%expand the sliding window 123 | NewSlide = folsom_sample_slide:resize(Slide, ?DOUBLE_WINDOW), 124 | 125 | %% get values only returns last ?WINDOW*2 seconds 126 | NewExpectedValues = lists:sort(lists:flatten([lists:duplicate(?READINGS, N) || 127 | N <- lists:seq(?RUNTIME - ?DOUBLE_WINDOW, ?RUNTIME)])), 128 | NewValues = lists:sort(folsom_sample_slide:get_values(NewSlide)), 129 | ?assertEqual(NewExpectedValues, NewValues), 130 | 131 | 132 | %% trim the table 133 | Trimmed = folsom_sample_slide:trim(NewSlide#slide.reservoir, ?DOUBLE_WINDOW), 134 | ?assertEqual((?RUNTIME - ?DOUBLE_WINDOW - 1) * ?READINGS, Trimmed), 135 | check_table(NewSlide, lists:seq(?RUNTIME - ?DOUBLE_WINDOW, ?RUNTIME)), 136 | %% increment the clock past the window 137 | tick(Moment, ?DOUBLE_WINDOW*2), 138 | %% get values should be empty 139 | ?assertEqual([], folsom_sample_slide:get_values(NewSlide)), 140 | %% trim, and table should be empty 141 | Trimmed2 = folsom_sample_slide:trim(NewSlide#slide.reservoir, ?DOUBLE_WINDOW), 142 | ?assertEqual((?RUNTIME * ?READINGS) - ((?RUNTIME - ?DOUBLE_WINDOW - 1) * ?READINGS), Trimmed2), 143 | check_table(NewSlide, []), 144 | ok = folsom_metrics:delete_metric(?HISTO2). 145 | 146 | 147 | shrink_window() -> 148 | %% create a new histogram 149 | %% will leave the trim server running, as resize() needs it 150 | ok = folsom_metrics:new_histogram(?HISTO2, slide, ?DOUBLE_WINDOW), 151 | #histogram{sample=Slide} = folsom_metrics_histogram:get_value(?HISTO2), 152 | Moments = lists:seq(1, ?RUNTIME ), 153 | %% pump in 90 seconds worth of readings 154 | Moment = lists:foldl(fun(_X, Tick) -> 155 | Tock = tick(Tick), 156 | [folsom_sample_slide:update(Slide, N) || 157 | N <- lists:duplicate(?READINGS, Tock)], 158 | Tock end, 159 | 0, 160 | Moments), 161 | %% are all readings in the table? 162 | check_table(Slide, Moments), 163 | 164 | %% get values only returns last ?DOUBLE_WINDOW seconds 165 | ExpectedValues = lists:sort(lists:flatten([lists:duplicate(?READINGS, N) || 166 | N <- lists:seq(?RUNTIME - ?DOUBLE_WINDOW, ?RUNTIME)])), 167 | Values = lists:sort(folsom_sample_slide:get_values(Slide)), 168 | ?assertEqual(ExpectedValues, Values), 169 | 170 | %%shrink the sliding window 171 | NewSlide = folsom_sample_slide:resize(Slide, ?WINDOW), 172 | 173 | %% get values only returns last ?WINDOW*2 seconds 174 | NewExpectedValues = lists:sort(lists:flatten([lists:duplicate(?READINGS, N) || 175 | N <- lists:seq(?RUNTIME - ?WINDOW, ?RUNTIME)])), 176 | NewValues = lists:sort(folsom_sample_slide:get_values(NewSlide)), 177 | ?assertEqual(NewExpectedValues, NewValues), 178 | 179 | 180 | %% trim the table 181 | Trimmed = folsom_sample_slide:trim(NewSlide#slide.reservoir, ?WINDOW), 182 | ?assertEqual((?RUNTIME - ?WINDOW - 1) * ?READINGS, Trimmed), 183 | check_table(NewSlide, lists:seq(?RUNTIME - ?WINDOW, ?RUNTIME)), 184 | %% increment the clock past the window 185 | tick(Moment, ?WINDOW*2), 186 | %% get values should be empty 187 | ?assertEqual([], folsom_sample_slide:get_values(NewSlide)), 188 | %% trim, and table should be empty 189 | Trimmed2 = folsom_sample_slide:trim(NewSlide#slide.reservoir, ?WINDOW), 190 | ?assertEqual((?RUNTIME * ?READINGS) - ((?RUNTIME - ?WINDOW - 1) * ?READINGS), Trimmed2), 191 | check_table(NewSlide, []), 192 | ok. 193 | 194 | tick(Moment0, IncrBy) -> 195 | Moment = Moment0 + IncrBy, 196 | meck:expect(folsom_utils, now_epoch, fun() -> 197 | Moment end), 198 | Moment. 199 | 200 | tick(Moment) -> 201 | tick(Moment, 1). 202 | 203 | check_table(Slide, Moments) -> 204 | Tab = lists:sort(ets:tab2list(Slide#slide.reservoir)), 205 | {Ks, Vs} = lists:unzip(Tab), 206 | ExpectedVs = lists:sort(lists:flatten([lists:duplicate(10, N) || N <- Moments])), 207 | StrippedKeys = lists:usort([X || {X, _} <- Ks]), 208 | ?assertEqual(Moments, StrippedKeys), 209 | ?assertEqual(ExpectedVs, lists:sort(Vs)). 210 | -------------------------------------------------------------------------------- /src/folsom_vm_metrics.erl: -------------------------------------------------------------------------------- 1 | %%% 2 | %%% Copyright 2011, Boundary 3 | %%% 4 | %%% Licensed under the Apache License, Version 2.0 (the "License"); 5 | %%% you may not use this file except in compliance with the License. 6 | %%% You may obtain a copy of the License at 7 | %%% 8 | %%% http://www.apache.org/licenses/LICENSE-2.0 9 | %%% 10 | %%% Unless required by applicable law or agreed to in writing, software 11 | %%% distributed under the License is distributed on an "AS IS" BASIS, 12 | %%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | %%% See the License for the specific language governing permissions and 14 | %%% limitations under the License. 15 | %%% 16 | 17 | 18 | %%%------------------------------------------------------------------- 19 | %%% File: folsom_vm_metrics.erl 20 | %%% @author joe williams 21 | %%% @doc 22 | %%% convert erlang system metrics to proplists 23 | %%% @end 24 | %%%----------------------------------------------------------------- 25 | 26 | -module(folsom_vm_metrics). 27 | 28 | -export([get_system_info/0, 29 | get_statistics/0, 30 | get_memory/0, 31 | get_process_info/0, 32 | get_port_info/0, 33 | get_ets_info/0, 34 | get_dets_info/0 35 | ]). 36 | 37 | %% exported for eunit test 38 | -export([convert_system_info/2]). 39 | 40 | -include("folsom.hrl"). 41 | 42 | 43 | % api 44 | 45 | get_memory() -> 46 | erlang:memory(). 47 | 48 | get_statistics() -> 49 | [{Key, convert_statistics(Key, get_statistics(Key))} || Key <- ?STATISTICS]. 50 | 51 | get_system_info() -> 52 | [{Key, convert_system_info(Key, get_system_info(Key))} || Key <- ?SYSTEM_INFO]. 53 | 54 | get_process_info() -> 55 | [{pid_port_fun_to_atom(Pid), get_process_info(Pid)} || Pid <- processes()]. 56 | 57 | get_port_info() -> 58 | [{pid_port_fun_to_atom(Port), get_port_info(Port)} || Port <- erlang:ports()]. 59 | 60 | get_ets_info() -> 61 | [{Tab, get_ets_dets_info(ets, Tab)} || Tab <- ets:all()]. 62 | 63 | get_dets_info() -> 64 | [{Tab, get_ets_dets_info(dets, Tab)} || Tab <- dets:all()]. 65 | 66 | % internal functions 67 | 68 | % wrap system_info and statistics in a try/catch in case keys are missing 69 | % in old/new versions of erlang 70 | 71 | get_system_info(Key) -> 72 | try erlang:system_info(Key) catch 73 | error:badarg->undefined 74 | end. 75 | 76 | get_statistics(Key) -> 77 | try erlang:statistics(Key) catch 78 | error:badarg->undefined 79 | end. 80 | 81 | %% conversion functions for erlang:statistics(Key) 82 | 83 | convert_statistics(context_switches, {ContextSwitches, 0}) -> 84 | ContextSwitches; 85 | convert_statistics(garbage_collection, {NumberofGCs, WordsReclaimed, 0}) -> 86 | [{number_of_gcs, NumberofGCs}, {words_reclaimed, WordsReclaimed}]; 87 | convert_statistics(io, {Input, Output}) -> 88 | [Input, Output]; 89 | convert_statistics(reductions, {TotalReductions, ReductionsSinceLastCall}) -> 90 | [{total_reductions, TotalReductions}, 91 | {reductions_since_last_call, ReductionsSinceLastCall}]; 92 | convert_statistics(runtime, {TotalRunTime, TimeSinceLastCall}) -> 93 | [{total_run_time, TotalRunTime}, {time_since_last_call, TimeSinceLastCall}]; 94 | convert_statistics(wall_clock, {TotalWallclockTime, WallclockTimeSinceLastCall}) -> 95 | [{total_wall_clock_time, TotalWallclockTime}, 96 | {wall_clock_time_since_last_call, WallclockTimeSinceLastCall}]; 97 | convert_statistics(_, Value) -> 98 | Value. 99 | 100 | %% conversion functions for erlang:system_info(Key) 101 | 102 | convert_system_info(allocated_areas, List) -> 103 | [convert_allocated_areas(Value) || Value <- List]; 104 | convert_system_info(allocator, {_,_,_,List}) -> 105 | List; 106 | convert_system_info(c_compiler_used, {Compiler, Version}) -> 107 | [{compiler, Compiler}, {version, convert_c_compiler_version(Version)}]; 108 | convert_system_info(cpu_topology, undefined) -> 109 | undefined; 110 | convert_system_info(cpu_topology, List) when is_list(List) -> 111 | [{Type, convert_cpu_topology(Item, [])} || {Type, Item} <- List]; 112 | convert_system_info(cpu_topology, {logical,Item}) -> 113 | convert_system_info(cpu_topology, [{processor,[{core,{logical,Item}}]}]); 114 | convert_system_info(dist_ctrl, List) -> 115 | lists:map(fun({Node, Socket}) -> 116 | {ok, Stats} = inet:getstat(Socket), 117 | {Node, Stats} 118 | end, List); 119 | convert_system_info(driver_version, Value) -> 120 | list_to_binary(Value); 121 | convert_system_info(machine, Value) -> 122 | list_to_binary(Value); 123 | convert_system_info(otp_release, Value) -> 124 | list_to_binary(Value); 125 | convert_system_info(scheduler_bindings, Value) -> 126 | tuple_to_list(Value); 127 | convert_system_info(system_version, Value) -> 128 | list_to_binary(Value); 129 | convert_system_info(system_architecture, Value) -> 130 | list_to_binary(Value); 131 | convert_system_info(version, Value) -> 132 | list_to_binary(Value); 133 | convert_system_info(_, Value) -> 134 | Value. 135 | 136 | convert_allocated_areas({Key, Value1, Value2}) -> 137 | {Key, [Value1, Value2]}; 138 | convert_allocated_areas({Key, Value}) -> 139 | {Key, Value}. 140 | 141 | convert_c_compiler_version({A, B, C}) -> 142 | list_to_binary(io_lib:format("~p.~p.~p", [A, B, C])); 143 | convert_c_compiler_version({A, B}) -> 144 | list_to_binary(io_lib:format("~p.~p", [A, B])); 145 | convert_c_compiler_version(A) -> 146 | list_to_binary(io_lib:format("~p", [A])). 147 | 148 | convert_cpu_topology([{core, Value}| Tail], Acc) when is_tuple(Value) -> 149 | convert_cpu_topology(Tail, lists:append(Acc, [{core, tuple_to_list(Value)}])); 150 | convert_cpu_topology([{core, Value}| Tail], Acc) when is_list(Value) -> 151 | convert_cpu_topology(Tail, lists:append(Acc, [{core, convert_cpu_topology(Value, [])}])); 152 | convert_cpu_topology([{thread, Value}| Tail], Acc) -> 153 | convert_cpu_topology(Tail, lists:append(Acc, [{thread, tuple_to_list(Value)}])); 154 | convert_cpu_topology([{node, Value}| Tail], Acc) -> 155 | convert_cpu_topology(Tail, lists:append(Acc, [{node, convert_cpu_topology(Value, [])}])); 156 | convert_cpu_topology([{processor, Value}| Tail], Acc) -> 157 | convert_cpu_topology(Tail, lists:append(Acc, [{processor, convert_cpu_topology(Value, [])}])); 158 | convert_cpu_topology({Key, Value}, _) -> 159 | [{Key, Value}]; 160 | convert_cpu_topology([], Acc) -> 161 | Acc. 162 | 163 | get_process_info(Pid) -> 164 | Info = [process_info(Pid, Key) || Key <- ?PROCESS_INFO], 165 | lists:flatten([convert_pid_info(Item) || Item <- Info]). 166 | 167 | get_port_info(Port) -> 168 | Stat = get_socket_getstat(Port), 169 | SockName = get_socket_sockname(Port), 170 | Opts = get_socket_opts(Port), 171 | Info = get_erlang_port_info(Port), 172 | Protocol = get_socket_protocol(Port), 173 | Status = get_socket_status(Port), 174 | Type = get_socket_type(Port), 175 | 176 | lists:flatten(lists:append([ 177 | Stat, 178 | SockName, 179 | Opts, 180 | Info, 181 | Protocol, 182 | Status, 183 | Type 184 | ])). 185 | 186 | get_socket_getstat(Socket) -> 187 | case catch inet:getstat(Socket) of 188 | {ok, Info} -> 189 | Info; 190 | _ -> 191 | [] 192 | end. 193 | 194 | get_socket_status(Socket) -> 195 | case catch prim_inet:getstatus(Socket) of 196 | {ok, Status} -> 197 | [{status, Status}]; 198 | _ -> 199 | [] 200 | end. 201 | 202 | get_erlang_port_info(Port) -> 203 | Info = erlang:port_info(Port), 204 | [convert_port_info(Item) || Item <- Info]. 205 | 206 | get_socket_type(Socket) -> 207 | case catch prim_inet:gettype(Socket) of 208 | {ok, Type} -> 209 | [{type, tuple_to_list(Type)}]; 210 | _ -> 211 | [] 212 | end. 213 | 214 | get_socket_opts(Socket) -> 215 | [get_socket_opts(Socket, Key) || Key <- ?SOCKET_OPTS]. 216 | 217 | get_socket_opts(Socket, Key) -> 218 | case catch inet:getopts(Socket, [Key]) of 219 | {ok, Opt} -> 220 | Opt; 221 | _ -> 222 | [] 223 | end. 224 | 225 | get_socket_protocol(Socket) -> 226 | case erlang:port_info(Socket, name) of 227 | {name, "tcp_inet"} -> 228 | [{protocol, tcp}]; 229 | {name, "udp_inet"} -> 230 | [{protocol, udp}]; 231 | {name,"sctp_inet"} -> 232 | [{protocol, sctp}]; 233 | _ -> 234 | [] 235 | end. 236 | 237 | get_socket_sockname(Socket) -> 238 | case catch inet:sockname(Socket) of 239 | {ok, {Ip, Port}} -> 240 | [{ip, ip_to_binary(Ip)}, {port, Port}]; 241 | _ -> 242 | [] 243 | end. 244 | 245 | get_ets_dets_info(Type, Tab) -> 246 | case Type:info(Tab) of 247 | undefined -> []; 248 | Entries when is_list(Entries) -> 249 | [{Key, pid_port_fun_to_atom(Value)} || {Key, Value} <- Entries] 250 | end. 251 | 252 | ip_to_binary(Tuple) -> 253 | iolist_to_binary(string:join(lists:map(fun integer_to_list/1, tuple_to_list(Tuple)), ".")). 254 | 255 | convert_port_info({name, Name}) -> 256 | {name, list_to_binary(Name)}; 257 | convert_port_info({links, List}) -> 258 | {links, [pid_port_fun_to_atom(Item) || Item <- List]}; 259 | convert_port_info({connected, Pid}) -> 260 | {connected, pid_port_fun_to_atom(Pid)}; 261 | convert_port_info(Item) -> 262 | Item. 263 | 264 | convert_pid_info({current_function, MFA}) -> 265 | {current_function, tuple_to_list(MFA)}; 266 | convert_pid_info({Key, Term}) when is_pid(Term) or is_port(Term) or is_function(Term) -> 267 | {Key, pid_port_fun_to_atom(Term)}; 268 | convert_pid_info({links, List}) -> 269 | {links, [pid_port_fun_to_atom(Item) || Item <- List]}; 270 | convert_pid_info({suspending, List}) -> 271 | {suspending, [pid_port_fun_to_atom(Item) || Item <- List]}; 272 | convert_pid_info({monitors, List}) -> 273 | {monitors, [{Key, pid_port_fun_to_atom(Value)} || {Key, Value} <- List]}; 274 | convert_pid_info({monitored_by, List}) -> 275 | {monitored_by, [pid_port_fun_to_atom(Item) || Item <- List]}; 276 | convert_pid_info({binary, List}) -> 277 | {binary, [tuple_to_list(Item) || Item <- List]}; 278 | convert_pid_info({initial_call, MFA}) -> 279 | {inital_call, tuple_to_list(MFA)}; 280 | convert_pid_info(Item) -> 281 | Item. 282 | 283 | pid_port_fun_to_atom(Term) when is_pid(Term) -> 284 | erlang:list_to_atom(pid_to_list(Term)); 285 | pid_port_fun_to_atom(Term) when is_port(Term) -> 286 | erlang:list_to_atom(erlang:port_to_list(Term)); 287 | pid_port_fun_to_atom(Term) when is_function(Term) -> 288 | erlang:list_to_atom(erlang:fun_to_list(Term)); 289 | pid_port_fun_to_atom(Term) -> 290 | Term. 291 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /test/mochinum.erl: -------------------------------------------------------------------------------- 1 | %% @copyright 2007 Mochi Media, Inc. 2 | %% @author Bob Ippolito 3 | 4 | %% @doc Useful numeric algorithms for floats that cover some deficiencies 5 | %% in the math module. More interesting is digits/1, which implements 6 | %% the algorithm from: 7 | %% http://www.cs.indiana.edu/~burger/fp/index.html 8 | %% See also "Printing Floating-Point Numbers Quickly and Accurately" 9 | %% in Proceedings of the SIGPLAN '96 Conference on Programming Language 10 | %% Design and Implementation. 11 | 12 | -module(mochinum). 13 | -author("Bob Ippolito "). 14 | -export([digits/1, frexp/1, int_pow/2, int_ceil/1]). 15 | 16 | %% IEEE 754 Float exponent bias 17 | -define(FLOAT_BIAS, 1022). 18 | -define(MIN_EXP, -1074). 19 | -define(BIG_POW, 4503599627370496). 20 | 21 | %% External API 22 | 23 | %% @spec digits(number()) -> string() 24 | %% @doc Returns a string that accurately represents the given integer or float 25 | %% using a conservative amount of digits. Great for generating 26 | %% human-readable output, or compact ASCII serializations for floats. 27 | digits(N) when is_integer(N) -> 28 | integer_to_list(N); 29 | digits(0.0) -> 30 | "0.0"; 31 | digits(Float) -> 32 | {Frac1, Exp1} = frexp_int(Float), 33 | [Place0 | Digits0] = digits1(Float, Exp1, Frac1), 34 | {Place, Digits} = transform_digits(Place0, Digits0), 35 | R = insert_decimal(Place, Digits), 36 | case Float < 0 of 37 | true -> 38 | [$- | R]; 39 | _ -> 40 | R 41 | end. 42 | 43 | %% @spec frexp(F::float()) -> {Frac::float(), Exp::float()} 44 | %% @doc Return the fractional and exponent part of an IEEE 754 double, 45 | %% equivalent to the libc function of the same name. 46 | %% F = Frac * pow(2, Exp). 47 | frexp(F) -> 48 | frexp1(unpack(F)). 49 | 50 | %% @spec int_pow(X::integer(), N::integer()) -> Y::integer() 51 | %% @doc Moderately efficient way to exponentiate integers. 52 | %% int_pow(10, 2) = 100. 53 | int_pow(_X, 0) -> 54 | 1; 55 | int_pow(X, N) when N > 0 -> 56 | int_pow(X, N, 1). 57 | 58 | %% @spec int_ceil(F::float()) -> integer() 59 | %% @doc Return the ceiling of F as an integer. The ceiling is defined as 60 | %% F when F == trunc(F); 61 | %% trunc(F) when F < 0; 62 | %% trunc(F) + 1 when F > 0. 63 | int_ceil(X) -> 64 | T = trunc(X), 65 | case (X - T) of 66 | Pos when Pos > 0 -> T + 1; 67 | _ -> T 68 | end. 69 | 70 | 71 | %% Internal API 72 | 73 | int_pow(X, N, R) when N < 2 -> 74 | R * X; 75 | int_pow(X, N, R) -> 76 | int_pow(X * X, N bsr 1, case N band 1 of 1 -> R * X; 0 -> R end). 77 | 78 | insert_decimal(0, S) -> 79 | "0." ++ S; 80 | insert_decimal(Place, S) when Place > 0 -> 81 | L = length(S), 82 | case Place - L of 83 | 0 -> 84 | S ++ ".0"; 85 | N when N < 0 -> 86 | {S0, S1} = lists:split(L + N, S), 87 | S0 ++ "." ++ S1; 88 | N when N < 6 -> 89 | %% More places than digits 90 | S ++ lists:duplicate(N, $0) ++ ".0"; 91 | _ -> 92 | insert_decimal_exp(Place, S) 93 | end; 94 | insert_decimal(Place, S) when Place > -6 -> 95 | "0." ++ lists:duplicate(abs(Place), $0) ++ S; 96 | insert_decimal(Place, S) -> 97 | insert_decimal_exp(Place, S). 98 | 99 | insert_decimal_exp(Place, S) -> 100 | [C | S0] = S, 101 | S1 = case S0 of 102 | [] -> 103 | "0"; 104 | _ -> 105 | S0 106 | end, 107 | Exp = case Place < 0 of 108 | true -> 109 | "e-"; 110 | false -> 111 | "e+" 112 | end, 113 | [C] ++ "." ++ S1 ++ Exp ++ integer_to_list(abs(Place - 1)). 114 | 115 | 116 | digits1(Float, Exp, Frac) -> 117 | Round = ((Frac band 1) =:= 0), 118 | case Exp >= 0 of 119 | true -> 120 | BExp = 1 bsl Exp, 121 | case (Frac =/= ?BIG_POW) of 122 | true -> 123 | scale((Frac * BExp * 2), 2, BExp, BExp, 124 | Round, Round, Float); 125 | false -> 126 | scale((Frac * BExp * 4), 4, (BExp * 2), BExp, 127 | Round, Round, Float) 128 | end; 129 | false -> 130 | case (Exp =:= ?MIN_EXP) orelse (Frac =/= ?BIG_POW) of 131 | true -> 132 | scale((Frac * 2), 1 bsl (1 - Exp), 1, 1, 133 | Round, Round, Float); 134 | false -> 135 | scale((Frac * 4), 1 bsl (2 - Exp), 2, 1, 136 | Round, Round, Float) 137 | end 138 | end. 139 | 140 | scale(R, S, MPlus, MMinus, LowOk, HighOk, Float) -> 141 | Est = int_ceil(math:log10(abs(Float)) - 1.0e-10), 142 | %% Note that the scheme implementation uses a 326 element look-up table 143 | %% for int_pow(10, N) where we do not. 144 | case Est >= 0 of 145 | true -> 146 | fixup(R, S * int_pow(10, Est), MPlus, MMinus, Est, 147 | LowOk, HighOk); 148 | false -> 149 | Scale = int_pow(10, -Est), 150 | fixup(R * Scale, S, MPlus * Scale, MMinus * Scale, Est, 151 | LowOk, HighOk) 152 | end. 153 | 154 | fixup(R, S, MPlus, MMinus, K, LowOk, HighOk) -> 155 | TooLow = case HighOk of 156 | true -> 157 | (R + MPlus) >= S; 158 | false -> 159 | (R + MPlus) > S 160 | end, 161 | case TooLow of 162 | true -> 163 | [(K + 1) | generate(R, S, MPlus, MMinus, LowOk, HighOk)]; 164 | false -> 165 | [K | generate(R * 10, S, MPlus * 10, MMinus * 10, LowOk, HighOk)] 166 | end. 167 | 168 | generate(R0, S, MPlus, MMinus, LowOk, HighOk) -> 169 | D = R0 div S, 170 | R = R0 rem S, 171 | TC1 = case LowOk of 172 | true -> 173 | R =< MMinus; 174 | false -> 175 | R < MMinus 176 | end, 177 | TC2 = case HighOk of 178 | true -> 179 | (R + MPlus) >= S; 180 | false -> 181 | (R + MPlus) > S 182 | end, 183 | case TC1 of 184 | false -> 185 | case TC2 of 186 | false -> 187 | [D | generate(R * 10, S, MPlus * 10, MMinus * 10, 188 | LowOk, HighOk)]; 189 | true -> 190 | [D + 1] 191 | end; 192 | true -> 193 | case TC2 of 194 | false -> 195 | [D]; 196 | true -> 197 | case R * 2 < S of 198 | true -> 199 | [D]; 200 | false -> 201 | [D + 1] 202 | end 203 | end 204 | end. 205 | 206 | unpack(Float) -> 207 | <> = <>, 208 | {Sign, Exp, Frac}. 209 | 210 | frexp1({_Sign, 0, 0}) -> 211 | {0.0, 0}; 212 | frexp1({Sign, 0, Frac}) -> 213 | Exp = log2floor(Frac), 214 | <> = <>, 215 | {Frac1, -(?FLOAT_BIAS) - 52 + Exp}; 216 | frexp1({Sign, Exp, Frac}) -> 217 | <> = <>, 218 | {Frac1, Exp - ?FLOAT_BIAS}. 219 | 220 | log2floor(Int) -> 221 | log2floor(Int, 0). 222 | 223 | log2floor(0, N) -> 224 | N; 225 | log2floor(Int, N) -> 226 | log2floor(Int bsr 1, 1 + N). 227 | 228 | 229 | transform_digits(Place, [0 | Rest]) -> 230 | transform_digits(Place, Rest); 231 | transform_digits(Place, Digits) -> 232 | {Place, [$0 + D || D <- Digits]}. 233 | 234 | 235 | frexp_int(F) -> 236 | case unpack(F) of 237 | {_Sign, 0, Frac} -> 238 | {Frac, ?MIN_EXP}; 239 | {_Sign, Exp, Frac} -> 240 | {Frac + (1 bsl 52), Exp - 53 - ?FLOAT_BIAS} 241 | end. 242 | 243 | %% 244 | %% Tests 245 | %% 246 | -ifdef(TEST). 247 | -include_lib("eunit/include/eunit.hrl"). 248 | 249 | int_ceil_test() -> 250 | ?assertEqual(1, int_ceil(0.0001)), 251 | ?assertEqual(0, int_ceil(0.0)), 252 | ?assertEqual(1, int_ceil(0.99)), 253 | ?assertEqual(1, int_ceil(1.0)), 254 | ?assertEqual(-1, int_ceil(-1.5)), 255 | ?assertEqual(-2, int_ceil(-2.0)), 256 | ok. 257 | 258 | int_pow_test() -> 259 | ?assertEqual(1, int_pow(1, 1)), 260 | ?assertEqual(1, int_pow(1, 0)), 261 | ?assertEqual(1, int_pow(10, 0)), 262 | ?assertEqual(10, int_pow(10, 1)), 263 | ?assertEqual(100, int_pow(10, 2)), 264 | ?assertEqual(1000, int_pow(10, 3)), 265 | ok. 266 | 267 | digits_test() -> 268 | ?assertEqual("0", 269 | digits(0)), 270 | ?assertEqual("0.0", 271 | digits(0.0)), 272 | ?assertEqual("1.0", 273 | digits(1.0)), 274 | ?assertEqual("-1.0", 275 | digits(-1.0)), 276 | ?assertEqual("0.1", 277 | digits(0.1)), 278 | ?assertEqual("0.01", 279 | digits(0.01)), 280 | ?assertEqual("0.001", 281 | digits(0.001)), 282 | ?assertEqual("1.0e+6", 283 | digits(1000000.0)), 284 | ?assertEqual("0.5", 285 | digits(0.5)), 286 | ?assertEqual("4503599627370496.0", 287 | digits(4503599627370496.0)), 288 | %% small denormalized number 289 | %% 4.94065645841246544177e-324 =:= 5.0e-324 290 | <> = <<0,0,0,0,0,0,0,1>>, 291 | ?assertEqual("5.0e-324", 292 | digits(SmallDenorm)), 293 | ?assertEqual(SmallDenorm, 294 | list_to_float(digits(SmallDenorm))), 295 | %% large denormalized number 296 | %% 2.22507385850720088902e-308 297 | <> = <<0,15,255,255,255,255,255,255>>, 298 | ?assertEqual("2.225073858507201e-308", 299 | digits(BigDenorm)), 300 | ?assertEqual(BigDenorm, 301 | list_to_float(digits(BigDenorm))), 302 | %% small normalized number 303 | %% 2.22507385850720138309e-308 304 | <> = <<0,16,0,0,0,0,0,0>>, 305 | ?assertEqual("2.2250738585072014e-308", 306 | digits(SmallNorm)), 307 | ?assertEqual(SmallNorm, 308 | list_to_float(digits(SmallNorm))), 309 | %% large normalized number 310 | %% 1.79769313486231570815e+308 311 | <> = <<127,239,255,255,255,255,255,255>>, 312 | ?assertEqual("1.7976931348623157e+308", 313 | digits(LargeNorm)), 314 | ?assertEqual(LargeNorm, 315 | list_to_float(digits(LargeNorm))), 316 | %% issue #10 - mochinum:frexp(math:pow(2, -1074)). 317 | ?assertEqual("5.0e-324", 318 | digits(math:pow(2, -1074))), 319 | ok. 320 | 321 | frexp_test() -> 322 | %% zero 323 | ?assertEqual({0.0, 0}, frexp(0.0)), 324 | %% one 325 | ?assertEqual({0.5, 1}, frexp(1.0)), 326 | %% negative one 327 | ?assertEqual({-0.5, 1}, frexp(-1.0)), 328 | %% small denormalized number 329 | %% 4.94065645841246544177e-324 330 | <> = <<0,0,0,0,0,0,0,1>>, 331 | ?assertEqual({0.5, -1073}, frexp(SmallDenorm)), 332 | %% large denormalized number 333 | %% 2.22507385850720088902e-308 334 | <> = <<0,15,255,255,255,255,255,255>>, 335 | ?assertEqual( 336 | {0.99999999999999978, -1022}, 337 | frexp(BigDenorm)), 338 | %% small normalized number 339 | %% 2.22507385850720138309e-308 340 | <> = <<0,16,0,0,0,0,0,0>>, 341 | ?assertEqual({0.5, -1021}, frexp(SmallNorm)), 342 | %% large normalized number 343 | %% 1.79769313486231570815e+308 344 | <> = <<127,239,255,255,255,255,255,255>>, 345 | ?assertEqual( 346 | {0.99999999999999989, 1024}, 347 | frexp(LargeNorm)), 348 | %% issue #10 - mochinum:frexp(math:pow(2, -1074)). 349 | ?assertEqual( 350 | {0.5, -1073}, 351 | frexp(math:pow(2, -1074))), 352 | ok. 353 | 354 | -endif. 355 | -------------------------------------------------------------------------------- /src/folsom_ets.erl: -------------------------------------------------------------------------------- 1 | %%% 2 | %%% Copyright 2011, Boundary 3 | %%% 4 | %%% Licensed under the Apache License, Version 2.0 (the "License"); 5 | %%% you may not use this file except in compliance with the License. 6 | %%% You may obtain a copy of the License at 7 | %%% 8 | %%% http://www.apache.org/licenses/LICENSE-2.0 9 | %%% 10 | %%% Unless required by applicable law or agreed to in writing, software 11 | %%% distributed under the License is distributed on an "AS IS" BASIS, 12 | %%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | %%% See the License for the specific language governing permissions and 14 | %%% limitations under the License. 15 | %%% 16 | 17 | %%%------------------------------------------------------------------- 18 | %%% File: folsom_ets.erl 19 | %%% @author joe williams 20 | %%% @doc 21 | %%% @end 22 | %%%------------------------------------------------------------------ 23 | 24 | -module(folsom_ets). 25 | 26 | %% API 27 | -export([ 28 | add_handler/2, 29 | add_handler/3, 30 | add_handler/4, 31 | add_handler/5, 32 | tag_handler/2, 33 | untag_handler/2, 34 | delete_handler/1, 35 | handler_exists/1, 36 | notify/1, 37 | notify/2, 38 | notify/3, 39 | tagged_notify/4, 40 | notify_existing_metric/3, 41 | get_handlers/0, 42 | get_handlers_info/0, 43 | get_info/1, 44 | get_values/1, 45 | get_history_values/2, 46 | get_group_values/1, 47 | get_group_values/2, 48 | get_tags/1 49 | ]). 50 | 51 | -record(metric, { 52 | tags = sets:new(), 53 | type, 54 | history_size 55 | }). 56 | 57 | -include("folsom.hrl"). 58 | 59 | %%%=================================================================== 60 | %%% API 61 | %%%=================================================================== 62 | 63 | add_handler(Type, Name) -> 64 | maybe_add_handler(Type, Name, handler_exists(Name)). 65 | 66 | add_handler(Type, Name, SampleSize) -> 67 | maybe_add_handler(Type, Name, SampleSize, handler_exists(Name)). 68 | 69 | add_handler(Type, Name, SampleType, SampleSize) -> 70 | maybe_add_handler(Type, Name, SampleType, SampleSize, handler_exists(Name)). 71 | 72 | add_handler(Type, Name, SampleType, SampleSize, Alpha) -> 73 | maybe_add_handler(Type, Name, SampleType, SampleSize, Alpha, handler_exists(Name)). 74 | 75 | tag_handler(Name, Tag) -> 76 | case handler_exists(Name) of 77 | true -> 78 | add_tag(Name, Tag); 79 | false -> 80 | {error, Name, nonexistent_metric} 81 | end. 82 | 83 | untag_handler(Name, Tag) -> 84 | case handler_exists(Name) of 85 | true -> 86 | rm_tag(Name, Tag); 87 | false -> 88 | {error, Name, nonexistent_metric} 89 | end. 90 | 91 | delete_handler(Name) -> 92 | {_, Info} = get_info(Name), 93 | ok = delete_metric(Name, proplists:get_value(type, Info)). 94 | 95 | handler_exists(Name) -> 96 | ets:member(?FOLSOM_TABLE, Name). 97 | 98 | %% old tuple style notifications 99 | notify({Name, Event}) -> 100 | notify(Name, Event). 101 | 102 | %% notify/2, checks metric type and makes sure metric exists 103 | %% before notifying, returning error if not 104 | notify(Name, Event) -> 105 | case handler_exists(Name) of 106 | true -> 107 | {_, Info} = get_info(Name), 108 | Type = proplists:get_value(type, Info), 109 | notify(Name, Event, Type, true); 110 | false -> 111 | {error, Name, nonexistent_metric} 112 | end. 113 | 114 | %% notify/3, makes sure metric exist, if not creates metric 115 | notify(Name, Event, Type) -> 116 | notify(Name, Event, Type, handler_exists(Name)). 117 | 118 | tagged_notify(Name, Event, Type, Tags) -> 119 | R = notify(Name, Event, Type), 120 | case get_tags(Name) of 121 | {error, _, _} -> skip; 122 | CurrentTags -> 123 | [add_tag(Name, T) || T <- Tags, not sets:is_element(T, CurrentTags)] 124 | end, 125 | R. 126 | 127 | %% assumes metric already exists, bypasses above checks 128 | notify_existing_metric(Name, Event, Type) -> 129 | notify(Name, Event, Type, true). 130 | 131 | get_handlers() -> 132 | proplists:get_keys(ets:tab2list(?FOLSOM_TABLE)). 133 | 134 | get_handlers_info() -> 135 | [get_info(Id) || Id <- get_handlers()]. 136 | 137 | get_info(Name) -> 138 | case handler_exists(Name) of 139 | true -> 140 | [{_, #metric{type = Type, tags = Tags}}] = ets:lookup(?FOLSOM_TABLE, Name), 141 | {Name, [{type, Type}, {tags, Tags}]}; 142 | false -> 143 | {error, Name, nonexistent_metric} 144 | end. 145 | 146 | get_values(Name) -> 147 | case handler_exists(Name) of 148 | true -> 149 | {_, Info} = get_info(Name), 150 | get_values(Name, proplists:get_value(type, Info)); 151 | false -> 152 | {error, Name, nonexistent_metric} 153 | end. 154 | 155 | get_values(Name, counter) -> 156 | folsom_metrics_counter:get_value(Name); 157 | get_values(Name, gauge) -> 158 | folsom_metrics_gauge:get_value(Name); 159 | get_values(Name, histogram) -> 160 | folsom_metrics_histogram:get_values(Name); 161 | get_values(Name, history) -> 162 | folsom_metrics_history:get_events(Name); 163 | get_values(Name, meter) -> 164 | folsom_metrics_meter:get_values(Name); 165 | get_values(Name, meter_reader) -> 166 | folsom_metrics_meter_reader:get_values(Name); 167 | get_values(Name, duration) -> 168 | folsom_metrics_duration:get_values(Name); 169 | get_values(Name, spiral) -> 170 | folsom_metrics_spiral:get_values(Name); 171 | get_values(_, Type) -> 172 | {error, Type, unsupported_metric_type}. 173 | 174 | get_history_values(Name, Count) -> 175 | folsom_metrics_history:get_events(Name, Count). 176 | 177 | get_group_values(Tag) -> 178 | folsom_ets:get_group_values(Tag, '_'). 179 | 180 | get_group_values(Tag, Type) -> 181 | Metrics = ets:match(?FOLSOM_TABLE, {'$1', {metric, '$2', Type, '_'}}), 182 | [{Name, get_values(Name)} || [Name, Tags] <- Metrics, sets:is_element(Tag, Tags)]. 183 | 184 | get_tags(Name) -> 185 | case handler_exists(Name) of 186 | true -> 187 | {_, Info} = get_info(Name), 188 | proplists:get_value(tags, Info); 189 | false -> 190 | {error, Name, nonexistent_metric} 191 | end. 192 | 193 | %%%=================================================================== 194 | %%% Internal functions 195 | %%%=================================================================== 196 | 197 | maybe_add_handler(counter, Name, false) -> 198 | true = folsom_metrics_counter:new(Name), 199 | true = ets:insert(?FOLSOM_TABLE, {Name, #metric{type = counter}}), 200 | ok; 201 | maybe_add_handler(gauge, Name, false) -> 202 | true = folsom_metrics_gauge:new(Name), 203 | true = ets:insert(?FOLSOM_TABLE, {Name, #metric{type = gauge}}), 204 | ok; 205 | maybe_add_handler(histogram, Name, false) -> 206 | true = folsom_metrics_histogram:new(Name), 207 | true = ets:insert(?FOLSOM_TABLE, {Name, #metric{type = histogram}}), 208 | ok; 209 | maybe_add_handler(duration, Name, false) -> 210 | true = folsom_metrics_histogram:new(Name), 211 | true = folsom_metrics_duration:new(Name), 212 | true = ets:insert(?FOLSOM_TABLE, {Name, #metric{type = duration}}), 213 | ok; 214 | maybe_add_handler(history, Name, false) -> 215 | ok = folsom_metrics_history:new(Name), 216 | true = ets:insert(?FOLSOM_TABLE, {Name, #metric{type = history, history_size = ?DEFAULT_SIZE}}), 217 | ok; 218 | maybe_add_handler(meter, Name, false) -> 219 | ok = folsom_meter_timer_server:register(Name, folsom_metrics_meter), 220 | true = folsom_metrics_meter:new(Name), 221 | true = ets:insert(?FOLSOM_TABLE, {Name, #metric{type = meter}}), 222 | ok; 223 | maybe_add_handler(meter_reader, Name, false) -> 224 | ok = folsom_meter_timer_server:register(Name, folsom_metrics_meter_reader), 225 | true = folsom_metrics_meter_reader:new(Name), 226 | true = ets:insert(?FOLSOM_TABLE, {Name, #metric{type = meter_reader}}), 227 | ok; 228 | maybe_add_handler(spiral, Name, false) -> 229 | true = folsom_metrics_spiral:new(Name), 230 | true = ets:insert(?FOLSOM_TABLE, {Name, #metric{type = spiral}}), 231 | ok; 232 | maybe_add_handler(Type, _, false) -> 233 | {error, Type, unsupported_metric_type}; 234 | maybe_add_handler(_, Name, true) -> 235 | {error, Name, metric_already_exists}. 236 | 237 | maybe_add_handler(histogram, Name, SampleType, false) -> 238 | true = folsom_metrics_histogram:new(Name, SampleType), 239 | true = ets:insert(?FOLSOM_TABLE, {Name, #metric{type = histogram}}), 240 | ok; 241 | maybe_add_handler(history, Name, SampleSize, false) -> 242 | ok = folsom_metrics_history:new(Name), 243 | true = ets:insert(?FOLSOM_TABLE, {Name, #metric{type = history, history_size = SampleSize}}), 244 | ok; 245 | maybe_add_handler(spiral, Name, Update, false) -> 246 | true = folsom_metrics_spiral:new(Name, Update), 247 | true = ets:insert(?FOLSOM_TABLE, {Name, #metric{type = spiral}}), 248 | ok; 249 | maybe_add_handler(Type, _, _, false) -> 250 | {error, Type, unsupported_metric_type}; 251 | maybe_add_handler(_, Name, _, true) -> 252 | {error, Name, metric_already_exists}. 253 | 254 | maybe_add_handler(histogram, Name, SampleType, SampleSize, false) -> 255 | true = folsom_metrics_histogram:new(Name, SampleType, SampleSize), 256 | true = ets:insert(?FOLSOM_TABLE, {Name, #metric{type = histogram}}), 257 | ok; 258 | maybe_add_handler(Type, _, _, _, false) -> 259 | {error, Type, unsupported_metric_type}; 260 | maybe_add_handler(_, Name, _, _, true) -> 261 | {error, Name, metric_already_exists}. 262 | 263 | maybe_add_handler(histogram, Name, SampleType, SampleSize, Alpha, false) -> 264 | true = folsom_metrics_histogram:new(Name, SampleType, SampleSize, Alpha), 265 | true = ets:insert(?FOLSOM_TABLE, {Name, #metric{type = histogram}}), 266 | ok; 267 | maybe_add_handler(duration, Name, SampleType, SampleSize, Alpha, false) -> 268 | true = folsom_metrics_histogram:new(Name, SampleType, SampleSize, Alpha), 269 | true = folsom_metrics_duration:new(Name), 270 | true = ets:insert(?FOLSOM_TABLE, {Name, #metric{type = duration}}), 271 | ok; 272 | maybe_add_handler(Type, _, _, _, _, false) -> 273 | {error, Type, unsupported_metric_type}; 274 | maybe_add_handler(_, Name, _, _, _, true) -> 275 | {error, Name, metric_already_exists}. 276 | 277 | add_tag(Name, Tag) -> 278 | M = #metric{tags=Tags} = ets:lookup_element(?FOLSOM_TABLE, Name, 2), 279 | true = ets:update_element(?FOLSOM_TABLE, Name, {2, M#metric{tags=sets:add_element(Tag, Tags)}}), 280 | ok. 281 | 282 | rm_tag(Name, Tag) -> 283 | M = #metric{tags=Tags} = ets:lookup_element(?FOLSOM_TABLE, Name, 2), 284 | true = ets:update_element(?FOLSOM_TABLE, Name, {2, M#metric{tags=sets:del_element(Tag, Tags)}}), 285 | ok. 286 | 287 | delete_metric(Name, history) -> 288 | History = folsom_metrics_history:get_value(Name), 289 | ok = delete_history(Name, History), 290 | ok; 291 | delete_metric(Name, histogram) -> 292 | Metric = folsom_metrics_histogram:get_value(Name), 293 | ok = delete_histogram(Name, Metric), 294 | ok; 295 | delete_metric(Name, duration) -> 296 | Histo = folsom_metrics_histogram:get_value(Name), 297 | ok = delete_histogram(Name, Histo), 298 | true = ets:delete(?DURATION_TABLE, Name), 299 | true = ets:delete(?FOLSOM_TABLE, Name), 300 | ok; 301 | delete_metric(Name, counter) -> 302 | ok = folsom_metrics_counter:delete(Name), 303 | true = ets:delete(?FOLSOM_TABLE, Name), 304 | ok; 305 | delete_metric(Name, gauge) -> 306 | true = ets:delete(?GAUGE_TABLE, Name), 307 | true = ets:delete(?FOLSOM_TABLE, Name), 308 | ok; 309 | delete_metric(Name, meter) -> 310 | ok = folsom_meter_timer_server:unregister(Name), 311 | true = ets:delete(?METER_TABLE, Name), 312 | true = ets:delete(?FOLSOM_TABLE, Name), 313 | ok; 314 | delete_metric(Name, meter_reader) -> 315 | ok = folsom_meter_timer_server:unregister(Name), 316 | true = ets:delete(?METER_READER_TABLE, Name), 317 | true = ets:delete(?FOLSOM_TABLE, Name), 318 | ok; 319 | delete_metric(Name, spiral) -> 320 | #spiral{tid=Tid, server=Pid} = folsom_metrics_spiral:get_value(Name), 321 | folsom_sample_slide_server:stop(Pid), 322 | ets:delete(?SPIRAL_TABLE, Name), 323 | ets:delete(?FOLSOM_TABLE, Name), 324 | ets:delete(Tid), 325 | ok. 326 | 327 | delete_histogram(Name, #histogram{type = uniform, sample = #uniform{reservoir = Reservoir}}) -> 328 | true = ets:delete(?HISTOGRAM_TABLE, Name), 329 | true = ets:delete(?FOLSOM_TABLE, Name), 330 | true = ets:delete(Reservoir), 331 | ok; 332 | delete_histogram(Name, #histogram{type = none, sample = #none{reservoir = Reservoir}}) -> 333 | true = ets:delete(?HISTOGRAM_TABLE, Name), 334 | true = ets:delete(?FOLSOM_TABLE, Name), 335 | true = ets:delete(Reservoir), 336 | ok; 337 | delete_histogram(Name, #histogram{type = slide_sorted, sample = #slide_sorted{reservoir = Reservoir}}) -> 338 | true = ets:delete(?HISTOGRAM_TABLE, Name), 339 | true = ets:delete(?FOLSOM_TABLE, Name), 340 | true = ets:delete(Reservoir), 341 | ok; 342 | delete_histogram(Name, #histogram{type = exdec}) -> 343 | true = ets:delete(?HISTOGRAM_TABLE, Name), 344 | true = ets:delete(?FOLSOM_TABLE, Name), 345 | ok; 346 | delete_histogram(Name, #histogram{type = slide, sample = #slide{reservoir = Reservoir, server=Pid}}) -> 347 | folsom_sample_slide_server:stop(Pid), 348 | true = ets:delete(?HISTOGRAM_TABLE, Name), 349 | true = ets:delete(?FOLSOM_TABLE, Name), 350 | true = ets:delete(Reservoir), 351 | ok; 352 | delete_histogram(Name, #histogram{type = slide_uniform, sample = #slide_uniform{reservoir = Reservoir, server=Pid}}) -> 353 | folsom_sample_slide_server:stop(Pid), 354 | true = ets:delete(?HISTOGRAM_TABLE, Name), 355 | true = ets:delete(?FOLSOM_TABLE, Name), 356 | true = ets:delete(Reservoir), 357 | ok. 358 | 359 | delete_history(Name, #history{tid = Tid}) -> 360 | true = ets:delete(?HISTORY_TABLE, Name), 361 | true = ets:delete(?FOLSOM_TABLE, Name), 362 | true = ets:delete(Tid), 363 | ok. 364 | 365 | notify(Name, {inc, Value}, counter, true) -> 366 | folsom_metrics_counter:inc(Name, Value), 367 | ok; 368 | notify(Name, {inc, Value}, counter, false) -> 369 | add_handler(counter, Name), 370 | folsom_metrics_counter:inc(Name, Value), 371 | ok; 372 | notify(Name, {dec, Value}, counter, true) -> 373 | folsom_metrics_counter:dec(Name, Value), 374 | ok; 375 | notify(Name, {dec, Value}, counter, false) -> 376 | add_handler(counter, Name), 377 | folsom_metrics_counter:dec(Name, Value), 378 | ok; 379 | notify(Name, clear, counter, true) -> 380 | folsom_metrics_counter:clear(Name), 381 | ok; 382 | notify(Name, clear, counter, false) -> 383 | add_handler(counter, Name), 384 | folsom_metrics_counter:clear(Name), 385 | ok; 386 | notify(Name, Value, gauge, true) -> 387 | folsom_metrics_gauge:update(Name, Value), 388 | ok; 389 | notify(Name, Value, gauge, false) -> 390 | add_handler(gauge, Name), 391 | folsom_metrics_gauge:update(Name, Value), 392 | ok; 393 | notify(Name, Value, histogram, true) -> 394 | folsom_metrics_histogram:update(Name, Value), 395 | ok; 396 | notify(Name, Value, histogram, false) -> 397 | add_handler(histogram, Name), 398 | folsom_metrics_histogram:update(Name, Value), 399 | ok; 400 | notify(Name, Value, history, true) -> 401 | [{_, #metric{history_size = HistorySize}}] = ets:lookup(?FOLSOM_TABLE, Name), 402 | folsom_metrics_history:update(Name, HistorySize, Value), 403 | ok; 404 | notify(Name, Value, history, false) -> 405 | add_handler(history, Name), 406 | [{_, #metric{history_size = HistorySize}}] = ets:lookup(?FOLSOM_TABLE, Name), 407 | folsom_metrics_history:update(Name, HistorySize, Value), 408 | ok; 409 | notify(Name, Value, meter, true) -> 410 | folsom_metrics_meter:mark(Name, Value), 411 | ok; 412 | notify(Name, Value, meter, false) -> 413 | add_handler(meter, Name), 414 | folsom_metrics_meter:mark(Name, Value), 415 | ok; 416 | notify(Name, Value, meter_reader, true) -> 417 | folsom_metrics_meter_reader:mark(Name, Value), 418 | ok; 419 | notify(Name, Value, meter_reader, false) -> 420 | add_handler(meter_reader, Name), 421 | folsom_metrics_meter_reader:mark(Name, Value), 422 | ok; 423 | notify(Name, Value, duration, true) -> 424 | folsom_metrics_duration:update(Name, Value), 425 | ok; 426 | notify(Name, Value, duration, false) -> 427 | add_handler(duration, Name), 428 | folsom_metrics_duration:update(Name, Value), 429 | ok; 430 | notify(Name, Value, spiral, true) -> 431 | folsom_metrics_spiral:update(Name, Value), 432 | ok; 433 | notify(Name, Value, spiral, false) -> 434 | add_handler(spiral, Name), 435 | folsom_metrics_spiral:update(Name, Value), 436 | ok; 437 | notify(_, _, Type, _) -> 438 | {error, Type, unsupported_metric_type}. 439 | 440 | -------------------------------------------------------------------------------- /test/folsom_erlang_checks.erl: -------------------------------------------------------------------------------- 1 | %%% 2 | %%% Copyright 2011, Boundary 3 | %%% 4 | %%% Licensed under the Apache License, Version 2.0 (the "License"); 5 | %%% you may not use this file except in compliance with the License. 6 | %%% You may obtain a copy of the License at 7 | %%% 8 | %%% http://www.apache.org/licenses/LICENSE-2.0 9 | %%% 10 | %%% Unless required by applicable law or agreed to in writing, software 11 | %%% distributed under the License is distributed on an "AS IS" BASIS, 12 | %%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | %%% See the License for the specific language governing permissions and 14 | %%% limitations under the License. 15 | %%% 16 | 17 | 18 | %%%------------------------------------------------------------------- 19 | %%% File: folsom_erlang_checks.erl 20 | %%% @author joe williams 21 | %%% @doc 22 | %%% @end 23 | %%%------------------------------------------------------------------ 24 | 25 | -module(folsom_erlang_checks). 26 | 27 | -include_lib("eunit/include/eunit.hrl"). 28 | 29 | -export([ 30 | create_metrics/0, 31 | populate_metrics/0, 32 | tag_metrics/0, 33 | check_metrics/0, 34 | check_group_metrics/0, 35 | delete_metrics/0, 36 | vm_metrics/0, 37 | counter_metric/2, 38 | cpu_topology/0, 39 | c_compiler_used/0, 40 | create_delete_metrics/0 41 | ]). 42 | 43 | -define(DATA, [0, 1, 5, 10, 100, 200, 500, 750, 1000, 2000, 5000]). 44 | -define(HUGEDATA, lists:seq(1,10000)). 45 | 46 | -define(DATA1, [0, 5, 10, 15, 20, 25, 30, 35, 40, 45, 50]). 47 | -define(DATA2, [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]). 48 | 49 | -include("folsom.hrl"). 50 | 51 | create_metrics() -> 52 | ok = folsom_metrics:new_counter(counter), 53 | ok = folsom_metrics:new_counter(counter2), 54 | ok = folsom_metrics:new_gauge(<<"gauge">>), 55 | 56 | ok = folsom_metrics:new_histogram(<<"uniform">>, uniform, 5000), 57 | ok = folsom_metrics:new_histogram(<<"hugedata">>, uniform, 5000), 58 | ok = folsom_metrics:new_histogram(exdec, exdec), 59 | ok = folsom_metrics:new_histogram(none, none, 5000), 60 | 61 | ok = folsom_metrics:new_histogram(nonea, none, 5000), 62 | 63 | ok = folsom_metrics:new_histogram(noneb, none, 10), 64 | ok = folsom_metrics:new_histogram(nonec, none, 5), 65 | 66 | ok = folsom_metrics:new_histogram(slide_sorted_a, slide_sorted, 10), 67 | 68 | ok = folsom_metrics:new_histogram(timed, none, 5000), 69 | ok = folsom_metrics:new_histogram(timed2, none, 5000), 70 | 71 | ok = folsom_metrics:new_history(<<"history">>), 72 | ok = folsom_metrics:new_meter(meter), 73 | 74 | ok = folsom_metrics:new_meter_reader(meter_reader), 75 | 76 | ok = folsom_metrics:new_duration(duration), 77 | 78 | ok = folsom_metrics:new_spiral(spiral), 79 | ok = folsom_metrics:new_spiral(spiral_no_exceptions, no_exceptions), 80 | 81 | ?debugFmt("ensuring meter tick is registered with gen_server~n", []), 82 | ok = ensure_meter_tick_exists(2), 83 | 84 | ?debugFmt("ensuring multiple timer registrations dont cause issues", []), 85 | ok = folsom_meter_timer_server:register(meter, folsom_metrics_meter), 86 | ok = folsom_meter_timer_server:register(meter, folsom_metrics_meter), 87 | ok = folsom_meter_timer_server:register(meter, folsom_metrics_meter), 88 | 89 | ?debugFmt("~p", [folsom_meter_timer_server:dump()]), 90 | {state, List} = folsom_meter_timer_server:dump(), 91 | 2 = length(List), 92 | 93 | %% check two servers got started for the spiral metrics 94 | 2 = length(supervisor:which_children(folsom_sample_slide_sup)), 95 | 96 | 19 = length(folsom_metrics:get_metrics()), 97 | 98 | ?debugFmt("~n~nmetrics: ~p~n", [folsom_metrics:get_metrics()]). 99 | 100 | tag_metrics() -> 101 | Group = "mygroup", 102 | ok = folsom_metrics:tag_metric(counter, Group), 103 | ok = folsom_metrics:tag_metric(counter2, Group), 104 | ok = folsom_metrics:tag_metric(<<"gauge">>, Group), 105 | ok = folsom_metrics:tag_metric(meter, Group), 106 | ok = folsom_metrics:tag_metric(spiral, Group), 107 | ok = folsom_metrics:tag_metric(spiral_no_exceptions, Group), 108 | ?debugFmt("~n~ntagged metrics: ~p, ~p, ~p, ~p, ~p and ~p in group ~p~n", [counter,counter2,<<"gauge">>,meter,spiral,spiral_no_exceptions,Group]). 109 | 110 | populate_metrics() -> 111 | ok = folsom_metrics:notify({counter, {inc, 1}}), 112 | ok = folsom_metrics:notify({counter, {dec, 1}}), 113 | 114 | ok = folsom_metrics:notify({counter2, {inc, 10}}), 115 | ok = folsom_metrics:notify({counter2, {dec, 7}}), 116 | 117 | meck:new(folsom_ets), 118 | meck:expect(folsom_ets, notify, fun(_Event) -> meck:exception(error, something_wrong_with_ets) end), 119 | {'EXIT', {something_wrong_with_ets, _}} = folsom_metrics:safely_notify({unknown_counter, {inc, 1}}), 120 | meck:unload(folsom_ets), 121 | ok = folsom_metrics:safely_histogram_timed_update(unknown_histogram, fun() -> ok end), 122 | ok = folsom_metrics:safely_histogram_timed_update(unknown_histogram, fun(ok) -> ok end, [ok]), 123 | 3.141592653589793 = folsom_metrics:safely_histogram_timed_update(unknown_histogram, math, pi, []), 124 | UnknownHistogramBegin = folsom_metrics:histogram_timed_begin(unknown_histogram), 125 | {error, unknown_histogram, nonexistent_metric} = folsom_metrics:safely_histogram_timed_notify(UnknownHistogramBegin), 126 | 127 | ok = folsom_metrics:notify({<<"gauge">>, 2}), 128 | 129 | [ok = folsom_metrics:notify({<<"uniform">>, Value}) || Value <- ?DATA], 130 | 131 | [ok = folsom_metrics:notify({<<"hugedata">>, Value}) || Value <- ?HUGEDATA], 132 | 133 | [ok = folsom_metrics:notify({exdec, Value}) || Value <- lists:seq(1, 100000)], 134 | 135 | [ok = folsom_metrics:notify({none, Value}) || Value <- ?DATA], 136 | 137 | [ok = folsom_metrics:notify({nonea, Value}) || Value <- ?DATA1], 138 | 139 | [ok = folsom_metrics:notify({noneb, Value}) || Value <- ?DATA2], 140 | 141 | [ok = folsom_metrics:notify({nonec, Value}) || Value <- ?DATA2], 142 | 143 | [ok = folsom_metrics:notify({slide_sorted_a, Value}) || Value <- ?DATA2], 144 | 145 | ok = folsom_metrics:notify(tagged_metric, 1, meter, [a, b]), 146 | ok = folsom_metrics:notify(tagged_metric, 1, meter, [c]), 147 | 148 | {error, _, unsupported_metric_type} = folsom_metrics:notify(tagged_unknown_metric, 1, unknown_metric, [tag]), 149 | 150 | 3.141592653589793 = folsom_metrics:histogram_timed_update(timed, math, pi, []), 151 | 152 | Begin = folsom_metrics:histogram_timed_begin(timed2), 153 | folsom_metrics:histogram_timed_notify(Begin), 154 | 155 | PopulateDuration = fun() -> 156 | ok = folsom_metrics:notify_existing_metric(duration, timer_start, duration), 157 | timer:sleep(10), 158 | ok = folsom_metrics:notify_existing_metric(duration, timer_end, duration) end, 159 | 160 | [PopulateDuration() || _ <- lists:seq(1, 10)], 161 | 162 | ok = folsom_metrics:notify({<<"history">>, "string"}), 163 | 164 | {error, _, nonexistent_metric} = folsom_metrics:notify({historya, "5"}), 165 | ok = folsom_metrics:notify(historya, <<"binary">>, history), 166 | 167 | ?debugFmt("testing meter ...", []), 168 | 169 | % simulate an interval tick 170 | folsom_metrics_meter:tick(meter), 171 | 172 | [ok,ok,ok,ok,ok] = 173 | [ folsom_metrics:notify({meter, Item}) || Item <- [100, 100, 100, 100, 100]], 174 | 175 | % simulate an interval tick 176 | folsom_metrics_meter:tick(meter), 177 | 178 | ?debugFmt("testing meter reader ...", []), 179 | 180 | % simulate an interval tick 181 | folsom_metrics_meter_reader:tick(meter_reader), 182 | 183 | [ok,ok,ok,ok,ok] = 184 | [ folsom_metrics:notify({meter_reader, Item}) || Item <- [1, 10, 100, 1000, 10000]], 185 | 186 | % simulate an interval tick 187 | folsom_metrics_meter_reader:tick(meter_reader), 188 | 189 | folsom_metrics:notify_existing_metric(spiral, 100, spiral), 190 | folsom_metrics:notify_existing_metric(spiral_no_exceptions, 200, spiral). 191 | 192 | check_metrics() -> 193 | 0 = folsom_metrics:get_metric_value(counter), 194 | 195 | 3 = folsom_metrics:get_metric_value(counter2), 196 | 197 | ok = folsom_metrics:notify_existing_metric(counter2, clear, counter), 198 | 199 | 0 = folsom_metrics:get_metric_value(counter2), 200 | 201 | 2 = folsom_metrics:get_metric_value(<<"gauge">>), 202 | 203 | true = sets:is_subset(sets:from_list([a,b,c]), folsom_metrics:get_tags(tagged_metric)), 204 | 205 | [11,12,13,14,15,6,7,8,9,10] = folsom_metrics:get_metric_value(noneb), 206 | 207 | [11,12,13,14,15] = folsom_metrics:get_metric_value(nonec), 208 | 209 | [6,7,8,9,10,11,12,13,14,15] = folsom_metrics:get_metric_value(slide_sorted_a), 210 | 211 | Histogram1 = folsom_metrics:get_histogram_statistics(<<"uniform">>), 212 | histogram_checks(Histogram1), 213 | 214 | MetricsSubset = [min, max], 215 | 216 | ok = set_enabled_metrics(MetricsSubset), 217 | Histogram2 = folsom_metrics:get_histogram_statistics(<<"uniform">>), 218 | subset_checks(Histogram2, MetricsSubset), 219 | ok = set_enabled_metrics(?DEFAULT_METRICS), 220 | 221 | HugeHistogram = folsom_metrics:get_histogram_statistics(<<"hugedata">>), 222 | huge_histogram_checks(HugeHistogram), 223 | 224 | % just check exdec for non-zero values 225 | Exdec = folsom_metrics:get_histogram_statistics(exdec), 226 | 227 | ?debugFmt("checking exdec sample~n~p~n", [Exdec]), 228 | 229 | ok = case proplists:get_value(median, Exdec) of 230 | Median when Median > 0 -> 231 | ok; 232 | _ -> 233 | error 234 | end, 235 | 236 | Histogram3 = folsom_metrics:get_histogram_statistics(none), 237 | histogram_checks(Histogram3), 238 | 239 | CoValues = folsom_metrics:get_histogram_statistics(none, nonea), 240 | histogram_co_checks(CoValues), 241 | 242 | List = folsom_metrics:get_metric_value(timed), 243 | ?debugFmt("timed update value: ~p", [List]), 244 | 245 | List2 = folsom_metrics:get_metric_value(timed2), 246 | ?debugFmt("timed update value begin/end: ~p", [List2]), 247 | 248 | 1 = length(folsom_metrics:get_metric_value(<<"history">>)), 249 | 1 = length(folsom_metrics:get_metric_value(historya)), 250 | 251 | ?debugFmt("checking meter~n", []), 252 | Meter = folsom_metrics:get_metric_value(meter), 253 | ?debugFmt("~p", [Meter]), 254 | ok = case proplists:get_value(one, Meter) of 255 | Value when Value > 1 -> 256 | ok; 257 | _ -> 258 | error 259 | end, 260 | ok = case proplists:get_value(day, Meter) of 261 | Value1 when Value1 > 0.005 -> 262 | ok; 263 | _ -> 264 | error 265 | end, 266 | 267 | ?debugFmt("checking meter reader~n", []), 268 | MeterReader = folsom_metrics:get_metric_value(meter_reader), 269 | ?debugFmt("~p~n", [MeterReader]), 270 | ok = case proplists:get_value(one, MeterReader) of 271 | Value2 when Value2 > 1 -> 272 | ok; 273 | _ -> 274 | error 275 | end, 276 | 277 | %% check duration 278 | Dur = folsom_metrics:get_metric_value(duration), 279 | duration_check(Dur), 280 | 281 | ok = set_enabled_metrics(MetricsSubset), 282 | Dur2 = folsom_metrics:get_metric_value(duration), 283 | subset_checks(Dur2, MetricsSubset), 284 | ok = set_enabled_metrics(?DEFAULT_METRICS), 285 | 286 | %% check spiral 287 | [{count, 100}, {one, 100}] = folsom_metrics:get_metric_value(spiral), 288 | 289 | [{count, 200}, {one, 200}] = folsom_metrics:get_metric_value(spiral_no_exceptions). 290 | 291 | check_group_metrics() -> 292 | Group = "mygroup", 293 | Metrics = folsom_metrics:get_metrics_value(Group), 294 | 6 = length(Metrics), 295 | {counter, 0} = lists:keyfind(counter,1,Metrics), 296 | {counter2, 0} = lists:keyfind(counter2,1,Metrics), 297 | {<<"gauge">>, 2} = lists:keyfind(<<"gauge">>,1,Metrics), 298 | 299 | {meter, Meter} = lists:keyfind(meter,1,Metrics), 300 | ok = case proplists:get_value(one, Meter) of 301 | Value when Value > 1 -> 302 | ok; 303 | _ -> 304 | error 305 | end, 306 | ok = case proplists:get_value(day, Meter) of 307 | Value1 when Value1 > 0.005 -> 308 | ok; 309 | _ -> 310 | error 311 | end, 312 | 313 | {spiral, [{count, 100}, {one, 100}]} = lists:keyfind(spiral,1,Metrics), 314 | {spiral_no_exceptions, [{count, 200}, {one, 200}]} = lists:keyfind(spiral_no_exceptions,1,Metrics), 315 | 316 | Counters = folsom_metrics:get_metrics_value(Group,counter), 317 | {counter, 0} = lists:keyfind(counter,1,Counters), 318 | {counter2, 0} = lists:keyfind(counter2,1,Counters), 319 | 320 | ok = folsom_metrics:untag_metric(counter2, Group), 321 | ok = folsom_metrics:untag_metric(<<"gauge">>, Group), 322 | ok = folsom_metrics:untag_metric(meter, Group), 323 | ok = folsom_metrics:untag_metric(spiral, Group), 324 | ok = folsom_metrics:untag_metric(spiral_no_exceptions, Group), 325 | ?debugFmt("~n~nuntagged metrics: ~p, ~p, ~p, ~p and ~p in group ~p~n", [counter2,<<"gauge">>,meter,spiral,spiral_no_exceptions,Group]), 326 | RemainingMetrics = folsom_metrics:get_metrics_value(Group), 327 | 1 = length(RemainingMetrics), 328 | {counter, 0} = lists:keyfind(counter,1,Metrics). 329 | 330 | delete_metrics() -> 331 | 22 = length(ets:tab2list(?FOLSOM_TABLE)), 332 | 333 | ok = folsom_metrics:delete_metric(counter), 334 | ok = folsom_metrics:delete_metric(counter2), 335 | ok = folsom_metrics:delete_metric(<<"gauge">>), 336 | 337 | ok = folsom_metrics:delete_metric(<<"hugedata">>), 338 | ok = folsom_metrics:delete_metric(<<"uniform">>), 339 | ok = folsom_metrics:delete_metric(exdec), 340 | ok = folsom_metrics:delete_metric(none), 341 | 342 | ok = folsom_metrics:delete_metric(<<"history">>), 343 | ok = folsom_metrics:delete_metric(historya), 344 | 345 | ok = folsom_metrics:delete_metric(nonea), 346 | ok = folsom_metrics:delete_metric(noneb), 347 | ok = folsom_metrics:delete_metric(nonec), 348 | 349 | ok = folsom_metrics:delete_metric(tagged_metric), 350 | 351 | ok = folsom_metrics:delete_metric(slide_sorted_a), 352 | 353 | ok = folsom_metrics:delete_metric(timed), 354 | ok = folsom_metrics:delete_metric(timed2), 355 | ok = folsom_metrics:delete_metric(testcounter), 356 | 357 | ok = ensure_meter_tick_exists(2), 358 | 359 | 1 = length(ets:tab2list(?METER_TABLE)), 360 | ok = folsom_metrics:delete_metric(meter), 361 | 0 = length(ets:tab2list(?METER_TABLE)), 362 | 363 | 1 = length(ets:tab2list(?METER_READER_TABLE)), 364 | ok = folsom_metrics:delete_metric(meter_reader), 365 | 0 = length(ets:tab2list(?METER_READER_TABLE)), 366 | 367 | ok = ensure_meter_tick_exists(0), 368 | 369 | ok = folsom_metrics:delete_metric(duration), 370 | ok = folsom_metrics:delete_metric(spiral), 371 | ok = folsom_metrics:delete_metric(spiral_no_exceptions), 372 | 373 | 0 = length(ets:tab2list(?FOLSOM_TABLE)). 374 | 375 | vm_metrics() -> 376 | List1 = folsom_vm_metrics:get_memory(), 377 | true = lists:keymember(total, 1, List1), 378 | 379 | List2 = folsom_vm_metrics:get_statistics(), 380 | true = lists:keymember(context_switches, 1, List2), 381 | 382 | List3 = folsom_vm_metrics:get_system_info(), 383 | true = lists:keymember(allocated_areas, 1, List3), 384 | true = lists:keymember(port_count, 1, List3), 385 | 386 | [{_, [{backtrace, _}| _]} | _] = folsom_vm_metrics:get_process_info(), 387 | 388 | [{_, [{name, _}| _]} | _] = folsom_vm_metrics:get_port_info(). 389 | 390 | 391 | counter_metric(Count, Counter) -> 392 | ok = folsom_metrics:new_counter(Counter), 393 | 394 | ?debugFmt("running ~p counter inc/dec rounds~n", [Count]), 395 | for(Count, Counter), 396 | 397 | Result = folsom_metrics:get_metric_value(Counter), 398 | ?debugFmt("counter result: ~p~n", [Result]), 399 | 400 | 0 = Result. 401 | 402 | ensure_meter_tick_exists(MeterCnt) -> 403 | {state, State} = folsom_meter_timer_server:dump(), 404 | MeterCnt = length(State), 405 | ok. 406 | 407 | %% internal function 408 | 409 | histogram_checks(List) -> 410 | ?debugFmt("checking histogram statistics", []), 411 | ?debugFmt("~p~n", [List]), 412 | 0 = proplists:get_value(min, List), 413 | 5000 = proplists:get_value(max, List), 414 | 869.6363636363636 = proplists:get_value(arithmetic_mean, List), 415 | 416 | GeoMean = proplists:get_value(geometric_mean, List), 417 | ok = case GeoMean - 100.17443147308997 of 418 | GeoDiff when GeoDiff < 0.00000001 -> 419 | ok; 420 | _ -> 421 | error 422 | end, 423 | 424 | Value = proplists:get_value(harmonic_mean, List), 425 | %?debugFmt("~p~n", [Value]), 426 | ok = case Value - 8.333122900936845 of 427 | Diff when Diff < 0.00000001 -> 428 | ok; 429 | _ -> 430 | error 431 | end, 432 | 433 | 200 = proplists:get_value(median, List), 434 | 2254368.454545454 = proplists:get_value(variance, List), 435 | 1501.4554454080394 = proplists:get_value(standard_deviation, List), 436 | 1.8399452806806476 = proplists:get_value(skewness, List), 437 | 2.2856772911293204 = proplists:get_value(kurtosis, List), 438 | List1 = proplists:get_value(percentile, List), 439 | percentile_check(List1), 440 | List2 = proplists:get_value(histogram, List), 441 | histogram_check(List2). 442 | 443 | huge_histogram_checks(List) -> 444 | Skew = erlang:abs(proplists:get_value(skewness, List)), 445 | A = skewness_is_too_high_for_sample_of_this_size, 446 | B = this_event_is_very_unprobable, 447 | C = please_rerun_this_test__if_it_fails_again_your_code_is_bugged, 448 | {A, B, C, true} = {A, B, C, Skew < 0.2}. 449 | 450 | histogram_co_checks(List) -> 451 | ?debugFmt("checking histogram covariance and etc statistics", []), 452 | ?debugFmt("~p~n", [List]), 453 | [ 454 | {covariance,17209.545454545456}, 455 | {tau,1.0}, 456 | {rho,0.760297020598996}, 457 | {r,1.0} 458 | ] = List. 459 | 460 | percentile_check(List) -> 461 | 750 = proplists:get_value(75, List), 462 | 2000 = proplists:get_value(95, List), 463 | 5000 = proplists:get_value(99, List), 464 | 5000 = proplists:get_value(999, List). 465 | 466 | histogram_check(List) -> 467 | [{2400,10},{5000,1},{8000,0}] = List. 468 | 469 | counter_inc_dec(Counter) -> 470 | ok = folsom_metrics:notify({Counter, {inc, 1}}), 471 | ok = folsom_metrics:notify({Counter, {dec, 1}}). 472 | 473 | for(N, Counter) -> 474 | for(N, 0, Counter). 475 | for(N, Count, _Counter) when N == Count -> 476 | ok; 477 | for(N, LoopCount, Counter) -> 478 | counter_inc_dec(Counter), 479 | for(N, LoopCount + 1, Counter). 480 | 481 | cpu_topology() -> 482 | ?debugFmt("Testing various CPU topologies ...~n", []), 483 | {ok, [Data]} = file:consult("../test/cpu_topo_data"), 484 | [run_convert_and_jsonify(Item) || Item <- Data]. 485 | 486 | 487 | run_convert_and_jsonify(Item) -> 488 | ?debugFmt("Converting ... ~n~p~n", [Item]), 489 | Result = folsom_vm_metrics:convert_system_info(cpu_topology, Item), 490 | %?debugFmt("~p~n", [mochijson2:encode(Result)]). 491 | mochijson2:encode(Result). 492 | 493 | c_compiler_used() -> 494 | Test = [{gnuc, {4,4,5}}, 495 | {gnuc, {4,4}}, 496 | {msc, 1600}], 497 | 498 | Expected = [[{compiler, gnuc}, {version, <<"4.4.5">>}], 499 | [{compiler, gnuc}, {version, <<"4.4">>}], 500 | [{compiler, msc}, {version, <<"1600">>}]], 501 | 502 | ?assertEqual(Expected, [folsom_vm_metrics:convert_system_info(c_compiler_used, {Compiler, Version}) 503 | || {Compiler, Version} <- Test]). 504 | 505 | 506 | duration_check(Duration) -> 507 | [?assert(lists:keymember(Key, 1, Duration)) || Key <- 508 | [count, last, min, max, arithmetic_mean, 509 | geometric_mean, harmonic_mean, median, 510 | variance, standard_deviation, skewness, 511 | kurtosis, percentile, histogram]], 512 | ?assertEqual(10, proplists:get_value(count, Duration)), 513 | Last = proplists:get_value(last, Duration), 514 | ?assert(Last > 10000). 515 | 516 | create_delete_metrics() -> 517 | ?assertMatch(ok, folsom_metrics:new_counter(counter)), 518 | ?assertMatch(ok, folsom_metrics:notify_existing_metric(counter, {inc, 1}, counter)), 519 | ?assertMatch(1, folsom_metrics:get_metric_value(counter)), 520 | ?assertMatch(ok, folsom_metrics:delete_metric(counter)), 521 | ?assertError(badarg, folsom_metrics:notify_existing_metric(counter, {inc, 1}, counter)), 522 | ?assertMatch(ok, folsom_metrics:new_counter(counter)), 523 | ?assertMatch(ok, folsom_metrics:notify_existing_metric(counter, {inc, 1}, counter)), 524 | ?assertMatch(1, folsom_metrics:get_metric_value(counter)). 525 | 526 | set_enabled_metrics(Enabled) -> 527 | application:set_env(folsom, enabled_metrics, Enabled). 528 | 529 | subset_checks(List, Enabled) -> 530 | ?debugFmt("checking subset statistics", []), 531 | ?debugFmt("~p, ~p~n", [List, Enabled]), 532 | Disabled = ?DEFAULT_METRICS -- Enabled, 533 | true = lists:all(fun(K) -> 534 | proplists:get_value(K, List) == undefined 535 | end, 536 | Disabled), 537 | true = lists:all(fun(K) -> 538 | proplists:get_value(K, List) /= undefined 539 | end, 540 | Enabled). 541 | --------------------------------------------------------------------------------