release 0.8.0 - re-factored cache bucket structure. The application uses segmented cache approach vs B-tree index for TTL handling

This commit is contained in:
Dmitry Kolesnikov 2013-07-27 18:28:26 +03:00
parent 699865d890
commit 44c8f92a8c
14 changed files with 521 additions and 184 deletions

202
LICENSE Normal file
View File

@ -0,0 +1,202 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

View File

@ -1,5 +1,17 @@
.PHONY: deps test
ifeq ($(id),)
export id=cache
endif
FLAGS=\
-name ${id}@127.0.0.1 \
-setcookie nocookie \
-pa ./deps/*/ebin \
-pa ./examples/*/ebin \
-pa ./ebin \
+K true +A 160 -sbt ts
BB=../basho_bench
all: rebar deps compile
@ -27,15 +39,19 @@ dialyzer: compile
@dialyzer -Wno_return -c ./ebin
run:
erl -name cache@127.0.0.1 -setcookie nocookie -pa ./deps/*/ebin -pa ./ebin
erl ${FLAGS}
rebar:
curl -O http://cloud.github.com/downloads/basho/rebar/rebar
chmod ugo+x rebar
benchmark:
$(BB)/basho_bench priv/cache.benchmark
$(BB)/basho_bench -N bb@127.0.0.0 -C nocookie -J ${id}@127.0.0.1 priv/${id}.benchmark
$(BB)/priv/summary.r -i tests/current
open tests/current/summary.png
# benchmark:
# $(BB)/basho_bench -N bb@127.0.0.0 -C nocookie -J ${id}@127.0.0.1 priv/${id}.benchmark
# $(BB)/priv/summary.r -i tests/current
# open tests/current/summary.png

80
README.md Normal file
View File

@ -0,0 +1,80 @@
# Segmented in-memory cache
Cache uses N disposable ETS tables instead of single one. The cache applies eviction and quota
policies at segment level. The oldest ETS table is destroyed and new one is created when
quota or TTL criteria are exceeded.
The write operation always uses youngest segment. The read operation lookup key from youngest to oldest table
until it is found same time key is moved to youngest segment to prolong TTL. If none of ETS table contains key
then cache-miss occurs.
The downside is inability to assign precise TTL per single cache entry. TTL is always approximated to nearest segment. (e.g. cache with 60 sec TTL and 10 segments has 6 sec accuracy on TTL)
## Usage
```erlang
application:start(cache).
{ok, _} = cache:start_link(my_cache, [{n, 10}, {ttl, 60}]).
ok = cache:put(my_cache, <<"my key">>, <<"my value">>).
Val = cache:get(my_cache, <<"my key">>).
```
### configuration via Erlang `sys.config`
The cache instances are configurable via `sys.config`. Theses cache instances are supervised by application
supervisor.
```erlang
{cache, [
{my_cache, [{n, 10}, {ttl, 60}]}
]}
```
### distributed environment
The cache application uses standard Erlang distribution model.
Please node that Erlang distribution uses single tcp/ip connection for message passing between nodes.
Therefore, frequent read/write of large entries might impact on overall Erlang performance.
The global cache instance is visible to all Erlang nodes in the cluster.
```erlang
%% at a@example.com
{ok, _} = cache:start_link({global, my_cache}, [{n, 10}, {ttl, 60}]).
Val = cache:get({global, my_cache}, <<"my key">>).
%% at b@example.com
ok = cache:put({global, my_cache}, <<"my key">>, <<"my value">>).
Val = cache:get({global, my_cache}, <<"my key">>).
```
The local cache instance is accessible for any Erlang nodes in the cluster.
```erlang
%% a@example.com
{ok, _} = cache:start_link(my_cache, [{n, 10}, {ttl, 60}]).
Val = cache:get(my_cache, <<"my key">>).
%% b@example.com
ok = cache:put({my_cache, 'a@example.com'}, <<"my key">>, <<"my value">>).
Val = cache:get({my_cache, 'a@example.com'}, <<"my key">>).
```
## Performance
MacBook Pro, Intel Core i5, 2.5GHz, 8GB 1600 MHz DDR3, 256 SSD
LRU Cache, 10 segments, 20 sec ttl (~2 sec per segment)
![Local cache (application and cache within same VM)](local.png)
![Distributed cache (application and cache runs in different VMs)](distributed.png)
## Contributors
* Jose Luis Navarro https://github.com/artefactop
* Valentin Micic

BIN
distributed.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 100 KiB

BIN
local.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 107 KiB

View File

@ -6,7 +6,7 @@
%%
%% workload
{mode, max}.
{duration, 1}.
{duration, 5}.
{concurrent, 10}.
{key_generator, {uniform_int, 1000000}}.
{value_generator, {fixed_bin, 1000}}.
@ -14,7 +14,6 @@
{operations, [
{put, 5}
,{get, 5}
%,{remove, 1}
]}.
%{cache, {mycache, 'cache@127.0.0.1'}}.
@ -22,6 +21,4 @@
{ttl, 20}
,{n, 10}
,{policy, lru}
%,{size, 500000}
%,{memory, 400000000}
]}.

View File

@ -1,9 +1,10 @@
{application, cache,
[
{description, "in-memory cache"},
{vsn, "0.3.0"},
{vsn, "0.8.0"},
{modules, [
cache,
cache_bucket,
cache_sup,
cache_app
]},

View File

@ -1,32 +1,41 @@
%%
%% Copyright (c) 2012, Dmitry Kolesnikov
%% All Rights Reserved.
%% Copyright 2012 Dmitry Kolesnikov, All Rights Reserved
%%
%% This library is free software; you can redistribute it and/or modify
%% it under the terms of the GNU Lesser General Public License, version 3.0
%% as published by the Free Software Foundation (the "License").
%% Licensed under the Apache License, Version 2.0 (the "License");
%% you may not use this file except in compliance with the License.
%% You may obtain a copy of the License at
%%
%% Software distributed under the License is distributed on an "AS IS"
%% basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See
%% the License for the specific language governing rights and limitations
%% under the License.
%% http://www.apache.org/licenses/LICENSE-2.0
%%
%% You should have received a copy of the GNU Lesser General Public
%% License along with this library; if not, write to the Free Software
%% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
%% USA or retrieve online http://www.opensource.org/licenses/lgpl-3.0.html
%% Unless required by applicable law or agreed to in writing, software
%% distributed under the License is distributed on an "AS IS" BASIS,
%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
%% See the License for the specific language governing permissions and
%% limitations under the License.
%%
%% @description
%% segmented in-memory cache, cache memory is split into N segments,
%% each segment is associated with quota and ttl, eviction policy applied
%% at segment level.
%% segmented in-memory cache
%% * cache memory is split into N segments
%% * cache applies eviction and quota policies at segment level
%% (e.g. whole segments is destroyed at time)
%% * cache add new items to youngest segment
%% * cache lookup items from youngest to oldest segment
%%
%% @todo
%% * unit tests (improve coverage)
%% * cache read/write through handler
%% * cache atomic update (in-place update)
%% * memcached protocol
-module(cache).
-author('Dmitry Kolesnikov <dmkolesnikov@gmail.com>').
-include("cache.hrl").
-export([
start_link/2,
drop/1,
i/1,
i/2,
heap/2,
put/3,
put/4,
@ -40,45 +49,72 @@
remove_/2
]).
-export_type([cache/0]).
-type(cache() :: atom() | {atom(), atom()} | {global, atom()} | pid()).
-type(name() :: atom() | {global, atom()}).
-type(key() :: any()).
-type(entity() :: any()).
-type(ttl() :: integer()).
%%
%% start new cache
-spec(start_link/2 :: (atom(), list()) -> {ok, pid()} | {error, any()}).
%% start new cache bucket, accepted options:
%% {policy, lru | mru} - cache eviction policy
%% {memory, integer()} - cache memory quota in bytes
%% {size, integer()} - cache cardinality quota
%% {n, integer()} - number of cache segments
%% {ttl, integer()} - default time-to-live in seconds
%% {quota, integer()} - frequency of quota check in seconds
%% {stats, function() | {Mod, Fun}} - cache statistic aggregate functor
-spec(start_link/2 :: (name(), list()) -> {ok, pid()} | {error, any()}).
start_link(Cache, Opts) ->
cache_bucket:start_link(Cache, Opts).
%%
%% drop cache
-spec(drop/1 :: (atom()) -> ok).
-spec(drop/1 :: (cache()) -> ok).
drop(Cache) ->
erlang:exit(whereis(Cache), shutdown).
drop(undefined) ->
ok;
drop({global, Cache}) ->
drop(global:whereis_name(Cache));
drop({Cache, Node}) ->
drop(rpc:call(Node, cache, drop, [Cache]));
drop(Cache)
when is_atom(Cache) ->
drop(whereis(Cache));
drop(Cache)
when is_pid(Cache) ->
erlang:exit(Cache, shutdown).
%%
%% return cache meta data
-spec(i/1 :: (atom()) -> list()).
%% {heap, [integer()]} - cache segments references
%% {expire, [integer()]} - cache segments expire times
%% {size, [integer()]} - cardinality of cache segments
%% {memory, [integer()]} - memory occupied by each cache segment
-spec(i/1 :: (cache()) -> list()).
-spec(i/2 :: (cache(), atom()) -> list()).
i(Cache) ->
gen_server:call(Cache, i).
i(Cache, Name) ->
proplists:get_value(Name, i(Cache)).
%%
%% return nth cache heap
-spec(heap/2 :: (atom(), integer()) -> integer() | badarg).
%% return nth cache segment (e.g. heap(..., 1) returns youngest segment)
-spec(heap/2 :: (cache(), integer()) -> integer() | badarg).
heap(Cache, N) ->
gen_server:call(Cache, {heap, N}).
%%
%% put entity to cache
-spec(put/3 :: (atom(), key(), entity()) -> ok).
-spec(put_/3 :: (atom(), key(), entity()) -> ok).
-spec(put/4 :: (atom(), key(), entity(), ttl()) -> ok).
-spec(put_/4 :: (atom(), key(), entity(), ttl()) -> ok).
%% synchronous cache put
-spec(put/3 :: (cache(), key(), entity()) -> ok).
-spec(put/4 :: (cache(), key(), entity(), ttl()) -> ok).
put(Cache, Key, Val) ->
gen_server:call(Cache, {put, Key, Val}, ?DEF_CACHE_TIMEOUT).
@ -86,6 +122,11 @@ put(Cache, Key, Val) ->
put(Cache, Key, Val, TTL) ->
gen_server:call(Cache, {put, Key, Val, TTL}, ?DEF_CACHE_TIMEOUT).
%%
%% asynchronous cache put
-spec(put_/3 :: (cache(), key(), entity()) -> ok).
-spec(put_/4 :: (cache(), key(), entity(), ttl()) -> ok).
put_(Cache, Key, Val) ->
gen_server:cast(Cache, {put, Key, Val}).
@ -93,41 +134,44 @@ put_(Cache, Key, Val, TTL) ->
gen_server:cast(Cache, {put, Key, Val, TTL}).
%%
%% get entity from cache, prolong ttl
-spec(get/2 :: (atom(), key()) -> entity() | undefined).
%% synchronous get cache entry, the operation prolongs entry ttl
-spec(get/2 :: (cache(), key()) -> entity() | undefined).
get(Cache, Key) ->
gen_server:call(Cache, {get, Key}, ?DEF_CACHE_TIMEOUT).
%%
%% lookup entity at cache do not prolong ttl
-spec(lookup/2 :: (atom(), key()) -> entity() | undefined).
%% synchronous lookup cache entry, the operation do not prolong entry ttl
-spec(lookup/2 :: (cache(), key()) -> entity() | undefined).
lookup(Cache, Key) ->
gen_server:call(Cache, {lookup, Key}, ?DEF_CACHE_TIMEOUT).
%%
%% check entity at cache
-spec(has/2 :: (atom(), key()) -> true | false).
%% check if cache key exists,
-spec(has/2 :: (cache(), key()) -> true | false).
has(Cache, Key) ->
gen_server:call(Cache, {has, Key}, ?DEF_CACHE_TIMEOUT).
%%
%% check entity at cache and return estimated ttl
-spec(ttl/2 :: (atom(), key()) -> ttl() | false).
-spec(ttl/2 :: (cache(), key()) -> ttl() | false).
ttl(Cache, Key) ->
gen_server:call(Cache, {ttl, Key}, ?DEF_CACHE_TIMEOUT).
%%
%% remove entity from cache
-spec(remove/2 :: (atom(), key()) -> ok).
-spec(remove_/2 :: (atom(), key()) -> ok).
%% synchronous remove entry from cache
-spec(remove/2 :: (cache(), key()) -> ok).
remove(Cache, Key) ->
gen_server:call(Cache, {remove, Key}, ?DEF_CACHE_TIMEOUT).
%%
%% asynchronous remove entry from cache
-spec(remove_/2 :: (cache(), key()) -> ok).
remove_(Cache, Key) ->
gen_server:cast(Cache, {remove, Key}).

View File

@ -1,4 +1,18 @@
%%
%% Copyright 2012 Dmitry Kolesnikov, All Rights Reserved
%%
%% Licensed under the Apache License, Version 2.0 (the "License");
%% you may not use this file except in compliance with the License.
%% You may obtain a copy of the License at
%%
%% http://www.apache.org/licenses/LICENSE-2.0
%%
%% Unless required by applicable law or agreed to in writing, software
%% distributed under the License is distributed on an "AS IS" BASIS,
%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
%% See the License for the specific language governing permissions and
%% limitations under the License.
%%
%-define(VERBOSE, true).
-ifdef(VERBOSE).

View File

@ -1,22 +1,20 @@
%%
%% Copyright (c) 2012, Dmitry Kolesnikov
%% All Rights Reserved.
%% Copyright 2012 Dmitry Kolesnikov, All Rights Reserved
%%
%% This library is free software; you can redistribute it and/or modify
%% it under the terms of the GNU Lesser General Public License, version 3.0
%% as published by the Free Software Foundation (the "License").
%% Licensed under the Apache License, Version 2.0 (the "License");
%% you may not use this file except in compliance with the License.
%% You may obtain a copy of the License at
%%
%% Software distributed under the License is distributed on an "AS IS"
%% basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See
%% the License for the specific language governing rights and limitations
%% under the License.
%% http://www.apache.org/licenses/LICENSE-2.0
%%
%% You should have received a copy of the GNU Lesser General Public
%% License along with this library; if not, write to the Free Software
%% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
%% USA or retrieve online http://www.opensource.org/licenses/lgpl-3.0.html
%% Unless required by applicable law or agreed to in writing, software
%% distributed under the License is distributed on an "AS IS" BASIS,
%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
%% See the License for the specific language governing permissions and
%% limitations under the License.
%%
%% @description
%% cache application
-module(cache_app).
-behaviour(application).
-author('Dmitry Kolesnikov <dmkolesnikov@gmail.com>').

View File

@ -1,28 +1,24 @@
%%
%% Copyright (c) 2012, Dmitry Kolesnikov
%% All Rights Reserved.
%% Copyright 2012 Dmitry Kolesnikov, All Rights Reserved
%%
%% This library is free software; you can redistribute it and/or modify
%% it under the terms of the GNU Lesser General Public License, version 3.0
%% as published by the Free Software Foundation (the "License").
%% Licensed under the Apache License, Version 2.0 (the "License");
%% you may not use this file except in compliance with the License.
%% You may obtain a copy of the License at
%%
%% Software distributed under the License is distributed on an "AS IS"
%% basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See
%% the License for the specific language governing rights and limitations
%% under the License.
%% http://www.apache.org/licenses/LICENSE-2.0
%%
%% You should have received a copy of the GNU Lesser General Public
%% License along with this library; if not, write to the Free Software
%% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
%% USA or retrieve online http://www.opensource.org/licenses/lgpl-3.0.html
%% Unless required by applicable law or agreed to in writing, software
%% distributed under the License is distributed on an "AS IS" BASIS,
%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
%% See the License for the specific language governing permissions and
%% limitations under the License.
%%
%% @description
%% basho_bench driver
%% cache basho_bench driver
-module(cache_benchmark).
-author('Dmitry Kolesnikov <dmkolesnikov@gmail.com>').
-export([
new/1, run/4
]).
-export([new/1, run/4]).
%%
%%
@ -76,7 +72,6 @@ local_init() ->
%%
%%
failure(Tag, _Key, E) ->
%io:format("----> ~p~n", [process_info(pns:whereis(kv, Key))]),
io:format("~s -> ~p~n", [Tag, E]),
failure(_Tag, _Key, _E) ->
%io:format("~s -> ~p~n", [Tag, E]),
failed.

View File

@ -1,52 +1,55 @@
%%
%% Copyright (c) 2012, Dmitry Kolesnikov
%% All Rights Reserved.
%% Copyright 2012 Dmitry Kolesnikov, All Rights Reserved
%%
%% This library is free software; you can redistribute it and/or modify
%% it under the terms of the GNU Lesser General Public License, version 3.0
%% as published by the Free Software Foundation (the "License").
%% Licensed under the Apache License, Version 2.0 (the "License");
%% you may not use this file except in compliance with the License.
%% You may obtain a copy of the License at
%%
%% Software distributed under the License is distributed on an "AS IS"
%% basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See
%% the License for the specific language governing rights and limitations
%% under the License.
%% http://www.apache.org/licenses/LICENSE-2.0
%%
%% You should have received a copy of the GNU Lesser General Public
%% License along with this library; if not, write to the Free Software
%% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
%% USA or retrieve online http://www.opensource.org/licenses/lgpl-3.0.html
%% Unless required by applicable law or agreed to in writing, software
%% distributed under the License is distributed on an "AS IS" BASIS,
%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
%% See the License for the specific language governing permissions and
%% limitations under the License.
%%
%% @description
%%
%% cache bucket process
-module(cache_bucket).
-behaviour(gen_server).
-author('Dmitry Kolesnikov <dmkolesnikov@gmail.com>').
-include("cache.hrl").
-export([
start_link/2,
init/1, handle_call/3, handle_cast/2, handle_info/2, terminate/2, code_change/3
init/1,
terminate/2,
handle_call/3,
handle_cast/2,
handle_info/2,
code_change/3
]).
%%
%%
%% internal bucket state
-record(cache, {
name :: atom(), %% name of cache bucket
name = undefined :: atom(), %% name of cache bucket
heap = [] :: list(), %% cache heap segments
n = ?DEF_CACHE_N :: integer(), %% number of segments
ttl = ?DEF_CACHE_TTL :: integer(), %% chunk time to live
ttl = ?DEF_CACHE_TTL :: integer(), %% cache time to live
policy = ?DEF_CACHE_POLICY :: integer(), %% eviction policy
cardinality :: integer(), %% cache cardinality
memory :: integer(), %% cache memory limit
cardinality = undefined :: integer(), %% cache cardinality
memory = undefined :: integer(), %% cache memory limit
quota = ?DEF_CACHE_QUOTA :: integer(), %% quota enforcement timer
evict = undefined, %% evict timer
stats :: any() %% stats functor
stats = undefined :: any() %% stats aggregation functor
}).
%% cache segment
-record(heap, {
id :: integer(), %% segment heap
expire :: integer(), %% segment expire time
@ -54,8 +57,12 @@
memory :: integer() %% segment memory quota
}).
%%
%%
%%%----------------------------------------------------------------------------
%%%
%%% Factory
%%%
%%%----------------------------------------------------------------------------
start_link({global, Name}, Opts) ->
gen_server:start_link({global, Name}, ?MODULE, [Name, Opts], []);
@ -90,7 +97,7 @@ init([_ | Opts], S) ->
init(Opts, S);
init([], S) ->
random:seed(erlang:now()),
random:seed(os:timestamp()),
Evict = cache_util:mdiv(S#cache.ttl, S#cache.n),
init_heap(
S#cache{
@ -102,7 +109,6 @@ init([], S) ->
%%
%%
terminate(_Reason, _S) ->
%cache_heap:free(S#cache.heap),
ok.
%%%----------------------------------------------------------------------------
@ -164,6 +170,8 @@ handle_cast({remove, Key}, S) ->
handle_cast(_, S) ->
{noreply, S}.
%%
%%
handle_info(evict, S) ->
Now = cache_util:now(),
case lists:last(S#cache.heap) of
@ -188,13 +196,13 @@ handle_info(quota, S) ->
N when N =:= S#cache.n ->
{noreply,
free_heap(
S#cache{quota = cache_util:timeout(S#cache.evict, quota)}
S#cache{quota = cache_util:timeout(S#cache.quota, quota)}
)
};
_ ->
{noreply,
init_heap(
S#cache{quota = cache_util:timeout(S#cache.evict, quota)}
S#cache{quota = cache_util:timeout(S#cache.quota, quota)}
)
}
end;
@ -234,8 +242,8 @@ cache_put(Key, Val, #cache{}=S) ->
?DEBUG("cache ~p: put ~p to heap ~p~n", [S#cache.name, Key, Head#heap.id]),
S.
cache_put(Key, Val, Time, #cache{}=S) ->
case lists:splitwith(fun(X) -> X#heap.expire > Time end, S#cache.heap) of
cache_put(Key, Val, Expire, #cache{}=S) ->
case lists:splitwith(fun(X) -> X#heap.expire > Expire end, S#cache.heap) of
{[], _Tail} ->
cache_put(Key, Val, S);
{Head, Tail} ->
@ -250,18 +258,13 @@ cache_put(Key, Val, Time, #cache{}=S) ->
S
end.
%%
%% get cache value
cache_get(Key, #cache{policy=mru}=S) ->
% cache MRU should not move key anywhere because
% cache always evicts last generation
% MRU caches do not prolong recently used entity
case heap_lookup(Key, S#cache.heap) of
undefined ->
cache_util:stats(S#cache.stats, {cache, S#cache.name, miss}),
undefined;
{_Heap, Val} ->
?DEBUG("cache ~p: get ~p at cell ~p~n", [S#cache.name, Key, Heap#heap.id]),
cache_util:stats(S#cache.stats, {cache, S#cache.name, hit}),
Val
end;
% fall-back to cache lookup
cache_lookup(Key, S);
cache_get(Key, #cache{}=S) ->
Head = hd(S#cache.heap),
@ -281,6 +284,8 @@ cache_get(Key, #cache{}=S) ->
Val
end.
%%
%% lookup cache value
cache_lookup(Key, #cache{}=S) ->
case heap_lookup(Key, S#cache.heap) of
undefined ->
@ -292,6 +297,8 @@ cache_lookup(Key, #cache{}=S) ->
Val
end.
%%
%% check if key exists
cache_has(Key, #cache{}=S) ->
case heap_has(Key, S#cache.heap) of
false ->
@ -301,6 +308,8 @@ cache_has(Key, #cache{}=S) ->
true
end.
%%
%% check key ttl
cache_ttl(Key, #cache{}=S) ->
case heap_has(Key, S#cache.heap) of
false ->
@ -309,6 +318,8 @@ cache_ttl(Key, #cache{}=S) ->
Heap#heap.expire - cache_util:now()
end.
%%
%%
cache_remove(Key, #cache{}=S) ->
lists:foreach(
fun(X) -> ets:delete(X#heap.id, Key) end,
@ -341,22 +352,6 @@ heap_has(_Key, []) ->
false.
% %%
% %%
% remove(Key, S) ->
% Cell = evict_key(Key, cache_heap:cells(S#cache.heap)),
% ?DEBUG("cache ~p: remove ~p in cell ~p~n", [S#cache.name, Key, Cell]),
% S.
% %%
% %%
% member(Key, S) ->
% dowhile(
% fun(X) -> ets:member(X, Key) end,
% cache_heap:cells(S#cache.heap)
% ).
%%
%% init cache heap
init_heap(#cache{}=S) ->
@ -387,7 +382,7 @@ free_heap(#cache{}=S) ->
).
%%
%%
%% heap policy check
is_heap_out_of_quota(#heap{}=H) ->
is_out_of_memory(H) orelse is_out_of_capacity(H).

View File

@ -1,25 +1,23 @@
%%
%% Copyright (c) 2012, Dmitry Kolesnikov
%% All Rights Reserved.
%% Copyright 2012 Dmitry Kolesnikov, All Rights Reserved
%%
%% This library is free software; you can redistribute it and/or modify
%% it under the terms of the GNU Lesser General Public License, version 3.0
%% as published by the Free Software Foundation (the "License").
%% Licensed under the Apache License, Version 2.0 (the "License");
%% you may not use this file except in compliance with the License.
%% You may obtain a copy of the License at
%%
%% Software distributed under the License is distributed on an "AS IS"
%% basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See
%% the License for the specific language governing rights and limitations
%% under the License.
%% http://www.apache.org/licenses/LICENSE-2.0
%%
%% You should have received a copy of the GNU Lesser General Public
%% License along with this library; if not, write to the Free Software
%% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
%% USA or retrieve online http://www.opensource.org/licenses/lgpl-3.0.html
%% Unless required by applicable law or agreed to in writing, software
%% distributed under the License is distributed on an "AS IS" BASIS,
%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
%% See the License for the specific language governing permissions and
%% limitations under the License.
%%
%% @description
%% root cache supervisor
-module(cache_sup).
-behaviour(supervisor).
-author('Dmitry Kolesnikov <dmkolesnikov@gmail.com>').
-export([start_link/0, init/1]).

View File

@ -1,23 +1,20 @@
%%
%% Copyright (c) 2012, Dmitry Kolesnikov
%% All Rights Reserved.
%% Copyright 2012 Dmitry Kolesnikov, All Rights Reserved
%%
%% This library is free software; you can redistribute it and/or modify
%% it under the terms of the GNU Lesser General Public License, version 3.0
%% as published by the Free Software Foundation (the "License").
%% Licensed under the Apache License, Version 2.0 (the "License");
%% you may not use this file except in compliance with the License.
%% You may obtain a copy of the License at
%%
%% Software distributed under the License is distributed on an "AS IS"
%% basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See
%% the License for the specific language governing rights and limitations
%% under the License.
%% http://www.apache.org/licenses/LICENSE-2.0
%%
%% You should have received a copy of the GNU Lesser General Public
%% License along with this library; if not, write to the Free Software
%% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
%% USA or retrieve online http://www.opensource.org/licenses/lgpl-3.0.html
%% Unless required by applicable law or agreed to in writing, software
%% distributed under the License is distributed on an "AS IS" BASIS,
%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
%% See the License for the specific language governing permissions and
%% limitations under the License.
%%
%% @description
%%
%% cache utility
-module(cache_util).
-export([
@ -25,31 +22,33 @@
]).
%%
%%
mdiv(undefined, _) ->
%% maybe div
mdiv(X, Y)
when X =:= undefined orelse Y =:= undefined ->
undefined;
mdiv(X, Y) ->
X div Y.
%%
%%
madd(undefined, _) ->
%% maybe add
madd(X, Y)
when X =:= undefined orelse Y =:= undefined ->
undefined;
madd(X, Y) ->
X + Y.
%%
%%
mmul(undefined, _) ->
%% maybe multiply
mmul(X, Y)
when X =:= undefined orelse Y =:= undefined ->
undefined;
mmul(X, Y) ->
X * Y.
%%
%%
now() ->
{Mega, Sec, _} = erlang:now(),
{Mega, Sec, _} = os:timestamp(),
Mega * 1000000 + Sec.
%%
@ -71,9 +70,7 @@ stats(Fun, Counter, Val)
Fun(Counter, Val).
%%
%%
%%
%% re-set alarm after time
%% set / reset timeout
timeout(T, Msg)
when is_integer(T) ->
{clock, T, erlang:send_after(T, self(), Msg)};