From ff74707768fc338e5b4240790a76b58e4075207a Mon Sep 17 00:00:00 2001 From: Damien Levin Date: Sun, 29 Mar 2015 22:36:16 -0400 Subject: [PATCH 1/3] Added Sentinel support Connection is now in a separate file Config is pulled from the companion objects Apply methods now takes null as default instead of None --- .travis.yml | 13 +- README.md | 89 ++- build.sbt | 6 +- redis-config/redis-slave.conf | 707 ++++++++++++++++++++++ redis-config/redis.conf | 707 ++++++++++++++++++++++ redis-config/sentinel.conf | 144 +++++ src/main/resources/reference.conf | 15 +- src/main/scala/Brando.scala | 265 ++------ src/main/scala/BrandoSentinel.scala | 101 ++++ src/main/scala/Connection.scala | 137 +++++ src/main/scala/ConnectionSupervisor.scala | 97 +++ src/main/scala/HealthMonitor.scala | 41 -- src/main/scala/Request.scala | 2 +- src/main/scala/Response.scala | 6 + src/main/scala/SentinelClient.scala | 108 ++++ src/main/scala/ShardManager.scala | 98 +-- src/test/resources/application.conf | 5 +- src/test/scala/BrandoSentinelTest.scala | 102 ++++ src/test/scala/BrandoTest.scala | 107 ++-- src/test/scala/HealthMonitorTest.scala | 66 -- src/test/scala/SentinelClientTest.scala | 122 ++++ src/test/scala/ShardManagerTest.scala | 123 ++-- 22 files changed, 2602 insertions(+), 459 deletions(-) create mode 100755 redis-config/redis-slave.conf create mode 100644 redis-config/redis.conf create mode 100755 redis-config/sentinel.conf create mode 100644 src/main/scala/BrandoSentinel.scala create mode 100644 src/main/scala/Connection.scala create mode 100644 src/main/scala/ConnectionSupervisor.scala delete mode 100644 src/main/scala/HealthMonitor.scala create mode 100644 src/main/scala/SentinelClient.scala create mode 100644 src/test/scala/BrandoSentinelTest.scala delete mode 100644 src/test/scala/HealthMonitorTest.scala create mode 100644 src/test/scala/SentinelClientTest.scala diff --git a/.travis.yml b/.travis.yml index 83035aa..dfda515 100644 --- a/.travis.yml +++ b/.travis.yml @@ -2,8 +2,17 @@ language: scala scala: - "2.10.4" - "2.11.0" -services: - - redis-server cache: directories: - $HOME/.ivy2 +before_script: + - sudo redis-server `pwd`/redis-config/sentinel.conf --sentinel & + - sleep 15 + - sudo redis-server `pwd`/redis-config/redis.conf --loglevel verbose + - sleep 15 + - sudo mkdir /var/lib/redis-slave + - sudo redis-server `pwd`/redis-config/redis-slave.conf --loglevel verbose + - sleep 15 + - cat /var/log/redis/redis-slave-server.log + - cat /var/log/redis/redis-server.log + diff --git a/README.md b/README.md index e162b6a..0e7d53e 100644 --- a/README.md +++ b/README.md @@ -11,7 +11,7 @@ In your build.sbt resolvers += "http://chrisdinn.github.io/releases/" - libraryDependencies += "com.digital-achiever" %% "brando" % "2.1.2" + libraryDependencies += "com.digital-achiever" %% "brando" % "3.0.0-SNAPSHOT" ### Getting started @@ -25,7 +25,7 @@ Create a Brando actor with your server host and port. You should specify a database and password if you intend to use them. - val redis = system.actorOf(Brando("localhost", 6379, database = Some(5), auth = Some("password"))) + val redis = system.actorOf(Brando("localhost", 6379, database = 5, auth = "password")) This is important; if your Brando actor restarts you want be sure it reconnects successfully and to the same database. @@ -112,12 +112,49 @@ If a set of listeners is provided to the Brando actor when it is created , it wi Currently, the possible messages sent to each listener include the following: + * `Connecting`: When creating a TCP connection. * `Connected`: When a TCP connection has been created, and Authentication (if applicable) has succeeded. * `Disconnected`: The connection has been lost. Brando transparently handles disconnects and will automatically reconnect, so typically no user action at all is needed here. During the time that Brando is disconnected, Redis commands sent to Brando will be queued, and will be processed when a connection is established. * `AuthenticationFailed`: The TCP connected was made, but Redis auth failed. * `ConnectionFailed`: A connection could not be (re-) established after three attempts. Brando will not attempt to recover from this state; the user should take action. -All these messages inherit from the `BrandoStateChange` trait. +All these messages inherit from the `Connection.StateChange` trait. + + +### Sentinel + +#### SentinelClient + +Brando provides support for `monitoring`, `notification` and `automatic failover` using [sentinel](http://redis.io/topics/sentinel). It is implemented based on the following [guidelines](http://redis.io/topics/sentinel-clients) + +A sentinel client can be created like this. Here, we are using two instances and we provide a listener to receive `Connection.StateChange` events. + + val sentinel = system.actorOf(SentinelClient(Seq( + Instance("localhost", 26380), + Instance("localhost", 26379)), Set(probe.ref))) + +You can listen for events using the following: + + sentinel ! Request("SENTINEL","SUBSCRIBE", "failover-end") + +You can also send commands such as + + sentinel ! Request("SENTINEL", "MASTERS") + + +#### BrandoSentinel + +Brando can be used with Sentinel to provide automatic failover and discovery. To do so you need to create a `SentinelClient` and `BrandoSentinel`. In this example we are connecting to the master `mymaster` + + val sentinel = system.actorOf(SentinelClient(Seq( + Instance("localhost", 26380), + Instance("localhost", 26379)))) + + val redis = system.actorOf(BrandoSentinel("mymaster", sentinel)) + + redis ! Request("PING") + +For reliability we encourage to pass `connectionHeartbeatDelay` when using BrandoSentinel, this will generate a heartbeat to Redis and will improve failures detections in the case of network partitions. ### Sharding @@ -125,9 +162,9 @@ Brando provides support for sharding, as outlined [in the Redis documentation](h To use it, simply create an instance of `ShardManager`, passing it a list of Redis shards you'd like it to connect to. From there, we create a pool of `Brando` instances - one for each shard. - val shards = Seq(Shard("redis1", "10.0.0.1", 6379), - Shard("redis2", "10.0.0.2", 6379), - Shard("redis3", "10.0.0.3", 6379)) + val shards = Seq(RedisShard("redis1", "10.0.0.1", 6379), + RedisShard("redis2", "10.0.0.2", 6379), + RedisShard("redis3", "10.0.0.3", 6379)) val shardManager = context.actorOf(ShardManager(shards)) @@ -147,19 +184,47 @@ Note that the `ShardManager` explicitly requires a key for all operations except Individual shards can have their configuration updated on the fly. To do this, send a `Shard` message to `ShardManager`. - shardManager ! Shard("redis1", "10.0.0.4", 6379) + shardManager ! RedisShard("redis1", "10.0.0.4", 6379) + + +val shardManager = context.actorOf(ShardManager(shards, listeners = Set(self))) + +The `ShardManager` will forward all `Connection.StateChange` messages when a shard changes state. + + +#### Sharding with sentinel + +It's possible to use sharding with Sentinel, to do so you need to use `SentinelShard` instead of `RedisShard` + + val shards = Seq( + SentinelShard("mymaster1"), + SentinelShard("mymaster2")) + + val sentinel = system.actorOf(SentinelClient()) + + val shardManager = context.actorOf(ShardManager(shards,sentinel)) + + +## Run the tests + +* Start sentinel + + sudo redis-sentinel redis-config/sentinel.conf --sentinel + +* Start a Redis master and slave -This is intended to support failover via [Redis Sentinel](http://redis.io/topics/sentinel). Note that the id of the shard __MUST__ match one of the original shards configured when the `ShardManager` instance was created. Adding new shards is not supported. + sudo redis-server redis-config/redis.conf --loglevel verbose + sudo mkdir /var/lib/redis-slave + sudo redis-server redis-config/redis-slave.conf --loglevel verbose -State changes such as disconnects and connection failures can be monitored by providing a set of listeners to the `ShardManager`: +* Run the tests - val shardManager = context.actorOf(ShardManager(shards, listeners = Set(self))) + sbt test -The `ShardManager` will send a `ShardStateChange(shard, state)` message when a shard changes state; here `shard` is a shard object indicating which shard has changed state, and `state` is a `BrandoStateChange` object, documented above, indicating which new state the shard has entered. ## Documentation -Read the API documentation here: [http://chrisdinn.github.io/api/brando-2.1.2/](http://chrisdinn.github.io/api/brando-2.1.2/) +Read the API documentation here: [http://chrisdinn.github.io/api/brando-3.0.0-SNAPSHOT/](http://chrisdinn.github.io/api/brando-3.0.0-SNAPSHOT/) ## Mailing list diff --git a/build.sbt b/build.sbt index 6a96c1a..4ca13f5 100644 --- a/build.sbt +++ b/build.sbt @@ -2,7 +2,7 @@ name := "brando" organization := "com.digital-achiever" -version := "2.1.2" +version := "3.0.0-SNAPSHOT" scalaVersion := "2.11.4" @@ -11,9 +11,9 @@ crossScalaVersions := Seq("2.10.4", "2.11.4") scalacOptions ++= Seq("-unchecked", "-deprecation", "-feature") libraryDependencies ++= Seq( - "com.typesafe.akka" %% "akka-actor" % "2.3.4", + "com.typesafe.akka" %% "akka-actor" % "2.3.9", "org.scalatest" %% "scalatest" % "2.1.3" % "test", - "com.typesafe.akka" %% "akka-testkit" % "2.3.4" % "test" + "com.typesafe.akka" %% "akka-testkit" % "2.3.9" % "test" ) resolvers += "Typesafe Repository" at "http://repo.typesafe.com/typesafe/releases/" diff --git a/redis-config/redis-slave.conf b/redis-config/redis-slave.conf new file mode 100755 index 0000000..8faf54b --- /dev/null +++ b/redis-config/redis-slave.conf @@ -0,0 +1,707 @@ +# Redis configuration file example + +# Note on units: when memory size is needed, it is possible to specify +# it in the usual form of 1k 5GB 4M and so forth: +# +# 1k => 1000 bytes +# 1kb => 1024 bytes +# 1m => 1000000 bytes +# 1mb => 1024*1024 bytes +# 1g => 1000000000 bytes +# 1gb => 1024*1024*1024 bytes +# +# units are case insensitive so 1GB 1Gb 1gB are all the same. + +################################## INCLUDES ################################### + +# Include one or more other config files here. This is useful if you +# have a standard template that goes to all Redis server but also need +# to customize a few per-server settings. Include files can include +# other files, so use this wisely. +# +# Notice option "include" won't be rewritten by command "CONFIG REWRITE" +# from admin or Redis Sentinel. Since Redis always uses the last processed +# line as value of a configuration directive, you'd better put includes +# at the beginning of this file to avoid overwriting config change at runtime. +# +# If instead you are interested in using includes to override configuration +# options, it is better to use include as the last line. +# +# include /path/to/local.conf +# include /path/to/other.conf + +################################ GENERAL ##################################### + +# By default Redis does not run as a daemon. Use 'yes' if you need it. +# Note that Redis will write a pid file in /var/run/redis.pid when daemonized. +daemonize yes + +# When running daemonized, Redis writes a pid file in /var/run/redis.pid by +# default. You can specify a custom pid file location here. +pidfile "/var/run/redis/redis-slave-server.pid" + +# Accept connections on the specified port, default is 6379. +# If port 0 is specified Redis will not listen on a TCP socket. +port 6380 + +# By default Redis listens for connections from all the network interfaces +# available on the server. It is possible to listen to just one or multiple +# interfaces using the "bind" configuration directive, followed by one or +# more IP addresses. +# +# Examples: +# +# bind 192.168.1.100 10.0.0.1 +bind 127.0.0.1 + +# Specify the path for the unix socket that will be used to listen for +# incoming connections. There is no default, so Redis will not listen +# on a unix socket when not specified. +# +# unixsocket /var/run/redis/redis.sock +# unixsocketperm 755 + +# Close the connection after a client is idle for N seconds (0 to disable) +timeout 0 + +# TCP keepalive. +# +# If non-zero, use SO_KEEPALIVE to send TCP ACKs to clients in absence +# of communication. This is useful for two reasons: +# +# 1) Detect dead peers. +# 2) Take the connection alive from the point of view of network +# equipment in the middle. +# +# On Linux, the specified value (in seconds) is the period used to send ACKs. +# Note that to close the connection the double of the time is needed. +# On other kernels the period depends on the kernel configuration. +# +# A reasonable value for this option is 60 seconds. +tcp-keepalive 0 + +# Specify the server verbosity level. +# This can be one of: +# debug (a lot of information, useful for development/testing) +# verbose (many rarely useful info, but not a mess like the debug level) +# notice (moderately verbose, what you want in production probably) +# warning (only very important / critical messages are logged) +loglevel verbose + +# Specify the log file name. Also the empty string can be used to force +# Redis to log on the standard output. Note that if you use standard +# output for logging but daemonize, logs will be sent to /dev/null +logfile "/var/log/redis/redis-slave-server.log" + +# To enable logging to the system logger, just set 'syslog-enabled' to yes, +# and optionally update the other syslog parameters to suit your needs. +# syslog-enabled no + +# Specify the syslog identity. +# syslog-ident redis + +# Specify the syslog facility. Must be USER or between LOCAL0-LOCAL7. +# syslog-facility local0 + +# Set the number of databases. The default database is DB 0, you can select +# a different one on a per-connection basis using SELECT where +# dbid is a number between 0 and 'databases'-1 +databases 16 + +################################ SNAPSHOTTING ################################ +# +# Save the DB on disk: +# +# save +# +# Will save the DB if both the given number of seconds and the given +# number of write operations against the DB occurred. +# +# In the example below the behaviour will be to save: +# after 900 sec (15 min) if at least 1 key changed +# after 300 sec (5 min) if at least 10 keys changed +# after 60 sec if at least 10000 keys changed +# +# Note: you can disable saving at all commenting all the "save" lines. +# +# It is also possible to remove all the previously configured save +# points by adding a save directive with a single empty string argument +# like in the following example: +# +# save "" + +save 900 1 +save 300 10 +save 60 10000 + +# By default Redis will stop accepting writes if RDB snapshots are enabled +# (at least one save point) and the latest background save failed. +# This will make the user aware (in a hard way) that data is not persisting +# on disk properly, otherwise chances are that no one will notice and some +# disaster will happen. +# +# If the background saving process will start working again Redis will +# automatically allow writes again. +# +# However if you have setup your proper monitoring of the Redis server +# and persistence, you may want to disable this feature so that Redis will +# continue to work as usual even if there are problems with disk, +# permissions, and so forth. +stop-writes-on-bgsave-error yes + +# Compress string objects using LZF when dump .rdb databases? +# For default that's set to 'yes' as it's almost always a win. +# If you want to save some CPU in the saving child set it to 'no' but +# the dataset will likely be bigger if you have compressible values or keys. +rdbcompression yes + +# Since version 5 of RDB a CRC64 checksum is placed at the end of the file. +# This makes the format more resistant to corruption but there is a performance +# hit to pay (around 10%) when saving and loading RDB files, so you can disable it +# for maximum performances. +# +# RDB files created with checksum disabled have a checksum of zero that will +# tell the loading code to skip the check. +rdbchecksum yes + +# The filename where to dump the DB +dbfilename "dump.rdb" + +# The working directory. +# +# The DB will be written inside this directory, with the filename specified +# above using the 'dbfilename' configuration directive. +# +# The Append Only File will also be created inside this directory. +# +# Note that you must specify a directory here, not a file name. +dir "/var/lib/redis-slave" + +################################# REPLICATION ################################# + +# Master-Slave replication. Use slaveof to make a Redis instance a copy of +# another Redis server. Note that the configuration is local to the slave +# so for example it is possible to configure the slave to save the DB with a +# different interval, or to listen to another port, and so on. +# + +# If the master is password protected (using the "requirepass" configuration +# directive below) it is possible to tell the slave to authenticate before +# starting the replication synchronization process, otherwise the master will +# refuse the slave request. +# +# masterauth + +# When a slave loses its connection with the master, or when the replication +# is still in progress, the slave can act in two different ways: +# +# 1) if slave-serve-stale-data is set to 'yes' (the default) the slave will +# still reply to client requests, possibly with out of date data, or the +# data set may just be empty if this is the first synchronization. +# +# 2) if slave-serve-stale-data is set to 'no' the slave will reply with +# an error "SYNC with master in progress" to all the kind of commands +# but to INFO and SLAVEOF. +# +slave-serve-stale-data yes + +# You can configure a slave instance to accept writes or not. Writing against +# a slave instance may be useful to store some ephemeral data (because data +# written on a slave will be easily deleted after resync with the master) but +# may also cause problems if clients are writing to it because of a +# misconfiguration. +# +# Since Redis 2.6 by default slaves are read-only. +# +# Note: read only slaves are not designed to be exposed to untrusted clients +# on the internet. It's just a protection layer against misuse of the instance. +# Still a read only slave exports by default all the administrative commands +# such as CONFIG, DEBUG, and so forth. To a limited extent you can improve +# security of read only slaves using 'rename-command' to shadow all the +# administrative / dangerous commands. +slave-read-only yes + +# Slaves send PINGs to server in a predefined interval. It's possible to change +# this interval with the repl_ping_slave_period option. The default value is 10 +# seconds. +# +# repl-ping-slave-period 10 + +# The following option sets the replication timeout for: +# +# 1) Bulk transfer I/O during SYNC, from the point of view of slave. +# 2) Master timeout from the point of view of slaves (data, pings). +# 3) Slave timeout from the point of view of masters (REPLCONF ACK pings). +# +# It is important to make sure that this value is greater than the value +# specified for repl-ping-slave-period otherwise a timeout will be detected +# every time there is low traffic between the master and the slave. +# +# repl-timeout 60 + +# Disable TCP_NODELAY on the slave socket after SYNC? +# +# If you select "yes" Redis will use a smaller number of TCP packets and +# less bandwidth to send data to slaves. But this can add a delay for +# the data to appear on the slave side, up to 40 milliseconds with +# Linux kernels using a default configuration. +# +# If you select "no" the delay for data to appear on the slave side will +# be reduced but more bandwidth will be used for replication. +# +# By default we optimize for low latency, but in very high traffic conditions +# or when the master and slaves are many hops away, turning this to "yes" may +# be a good idea. +repl-disable-tcp-nodelay no + +# Set the replication backlog size. The backlog is a buffer that accumulates +# slave data when slaves are disconnected for some time, so that when a slave +# wants to reconnect again, often a full resync is not needed, but a partial +# resync is enough, just passing the portion of data the slave missed while +# disconnected. +# +# The biggest the replication backlog, the longer the time the slave can be +# disconnected and later be able to perform a partial resynchronization. +# +# The backlog is only allocated once there is at least a slave connected. +# +# repl-backlog-size 1mb + +# After a master has no longer connected slaves for some time, the backlog +# will be freed. The following option configures the amount of seconds that +# need to elapse, starting from the time the last slave disconnected, for +# the backlog buffer to be freed. +# +# A value of 0 means to never release the backlog. +# +# repl-backlog-ttl 3600 + +# The slave priority is an integer number published by Redis in the INFO output. +# It is used by Redis Sentinel in order to select a slave to promote into a +# master if the master is no longer working correctly. +# +# A slave with a low priority number is considered better for promotion, so +# for instance if there are three slaves with priority 10, 100, 25 Sentinel will +# pick the one with priority 10, that is the lowest. +# +# However a special priority of 0 marks the slave as not able to perform the +# role of master, so a slave with priority of 0 will never be selected by +# Redis Sentinel for promotion. +# +# By default the priority is 100. +slave-priority 100 + +# It is possible for a master to stop accepting writes if there are less than +# N slaves connected, having a lag less or equal than M seconds. +# +# The N slaves need to be in "online" state. +# +# The lag in seconds, that must be <= the specified value, is calculated from +# the last ping received from the slave, that is usually sent every second. +# +# This option does not GUARANTEES that N replicas will accept the write, but +# will limit the window of exposure for lost writes in case not enough slaves +# are available, to the specified number of seconds. +# +# For example to require at least 3 slaves with a lag <= 10 seconds use: +# +# min-slaves-to-write 3 +# min-slaves-max-lag 10 +# +# Setting one or the other to 0 disables the feature. +# +# By default min-slaves-to-write is set to 0 (feature disabled) and +# min-slaves-max-lag is set to 10. + +################################## SECURITY ################################### + +# Require clients to issue AUTH before processing any other +# commands. This might be useful in environments in which you do not trust +# others with access to the host running redis-server. +# +# This should stay commented out for backward compatibility and because most +# people do not need auth (e.g. they run their own servers). +# +# Warning: since Redis is pretty fast an outside user can try up to +# 150k passwords per second against a good box. This means that you should +# use a very strong password otherwise it will be very easy to break. +# +# requirepass foobared + +# Command renaming. +# +# It is possible to change the name of dangerous commands in a shared +# environment. For instance the CONFIG command may be renamed into something +# hard to guess so that it will still be available for internal-use tools +# but not available for general clients. +# +# Example: +# +# rename-command CONFIG b840fc02d524045429941cc15f59e41cb7be6c52 +# +# It is also possible to completely kill a command by renaming it into +# an empty string: +# +# rename-command CONFIG "" +# +# Please note that changing the name of commands that are logged into the +# AOF file or transmitted to slaves may cause problems. + +################################### LIMITS #################################### + +# Set the max number of connected clients at the same time. By default +# this limit is set to 10000 clients, however if the Redis server is not +# able to configure the process file limit to allow for the specified limit +# the max number of allowed clients is set to the current file limit +# minus 32 (as Redis reserves a few file descriptors for internal uses). +# +# Once the limit is reached Redis will close all the new connections sending +# an error 'max number of clients reached'. +# +# maxclients 10000 + +# Don't use more memory than the specified amount of bytes. +# When the memory limit is reached Redis will try to remove keys +# according to the eviction policy selected (see maxmemory-policy). +# +# If Redis can't remove keys according to the policy, or if the policy is +# set to 'noeviction', Redis will start to reply with errors to commands +# that would use more memory, like SET, LPUSH, and so on, and will continue +# to reply to read-only commands like GET. +# +# This option is usually useful when using Redis as an LRU cache, or to set +# a hard memory limit for an instance (using the 'noeviction' policy). +# +# WARNING: If you have slaves attached to an instance with maxmemory on, +# the size of the output buffers needed to feed the slaves are subtracted +# from the used memory count, so that network problems / resyncs will +# not trigger a loop where keys are evicted, and in turn the output +# buffer of slaves is full with DELs of keys evicted triggering the deletion +# of more keys, and so forth until the database is completely emptied. +# +# In short... if you have slaves attached it is suggested that you set a lower +# limit for maxmemory so that there is some free RAM on the system for slave +# output buffers (but this is not needed if the policy is 'noeviction'). +# +# maxmemory + +# MAXMEMORY POLICY: how Redis will select what to remove when maxmemory +# is reached. You can select among five behaviors: +# +# volatile-lru -> remove the key with an expire set using an LRU algorithm +# allkeys-lru -> remove any key accordingly to the LRU algorithm +# volatile-random -> remove a random key with an expire set +# allkeys-random -> remove a random key, any key +# volatile-ttl -> remove the key with the nearest expire time (minor TTL) +# noeviction -> don't expire at all, just return an error on write operations +# +# Note: with any of the above policies, Redis will return an error on write +# operations, when there are not suitable keys for eviction. +# +# At the date of writing this commands are: set setnx setex append +# incr decr rpush lpush rpushx lpushx linsert lset rpoplpush sadd +# sinter sinterstore sunion sunionstore sdiff sdiffstore zadd zincrby +# zunionstore zinterstore hset hsetnx hmset hincrby incrby decrby +# getset mset msetnx exec sort +# +# The default is: +# +# maxmemory-policy volatile-lru + +# LRU and minimal TTL algorithms are not precise algorithms but approximated +# algorithms (in order to save memory), so you can select as well the sample +# size to check. For instance for default Redis will check three keys and +# pick the one that was used less recently, you can change the sample size +# using the following configuration directive. +# +# maxmemory-samples 3 + +############################## APPEND ONLY MODE ############################### + +# By default Redis asynchronously dumps the dataset on disk. This mode is +# good enough in many applications, but an issue with the Redis process or +# a power outage may result into a few minutes of writes lost (depending on +# the configured save points). +# +# The Append Only File is an alternative persistence mode that provides +# much better durability. For instance using the default data fsync policy +# (see later in the config file) Redis can lose just one second of writes in a +# dramatic event like a server power outage, or a single write if something +# wrong with the Redis process itself happens, but the operating system is +# still running correctly. +# +# AOF and RDB persistence can be enabled at the same time without problems. +# If the AOF is enabled on startup Redis will load the AOF, that is the file +# with the better durability guarantees. +# +# Please check http://redis.io/topics/persistence for more information. + +appendonly no + +# The name of the append only file (default: "appendonly.aof") + +appendfilename "appendonly.aof" + +# The fsync() call tells the Operating System to actually write data on disk +# instead to wait for more data in the output buffer. Some OS will really flush +# data on disk, some other OS will just try to do it ASAP. +# +# Redis supports three different modes: +# +# no: don't fsync, just let the OS flush the data when it wants. Faster. +# always: fsync after every write to the append only log . Slow, Safest. +# everysec: fsync only one time every second. Compromise. +# +# The default is "everysec", as that's usually the right compromise between +# speed and data safety. It's up to you to understand if you can relax this to +# "no" that will let the operating system flush the output buffer when +# it wants, for better performances (but if you can live with the idea of +# some data loss consider the default persistence mode that's snapshotting), +# or on the contrary, use "always" that's very slow but a bit safer than +# everysec. +# +# More details please check the following article: +# http://antirez.com/post/redis-persistence-demystified.html +# +# If unsure, use "everysec". + +# appendfsync always +appendfsync everysec +# appendfsync no + +# When the AOF fsync policy is set to always or everysec, and a background +# saving process (a background save or AOF log background rewriting) is +# performing a lot of I/O against the disk, in some Linux configurations +# Redis may block too long on the fsync() call. Note that there is no fix for +# this currently, as even performing fsync in a different thread will block +# our synchronous write(2) call. +# +# In order to mitigate this problem it's possible to use the following option +# that will prevent fsync() from being called in the main process while a +# BGSAVE or BGREWRITEAOF is in progress. +# +# This means that while another child is saving, the durability of Redis is +# the same as "appendfsync none". In practical terms, this means that it is +# possible to lose up to 30 seconds of log in the worst scenario (with the +# default Linux settings). +# +# If you have latency problems turn this to "yes". Otherwise leave it as +# "no" that is the safest pick from the point of view of durability. + +no-appendfsync-on-rewrite no + +# Automatic rewrite of the append only file. +# Redis is able to automatically rewrite the log file implicitly calling +# BGREWRITEAOF when the AOF log size grows by the specified percentage. +# +# This is how it works: Redis remembers the size of the AOF file after the +# latest rewrite (if no rewrite has happened since the restart, the size of +# the AOF at startup is used). +# +# This base size is compared to the current size. If the current size is +# bigger than the specified percentage, the rewrite is triggered. Also +# you need to specify a minimal size for the AOF file to be rewritten, this +# is useful to avoid rewriting the AOF file even if the percentage increase +# is reached but it is still pretty small. +# +# Specify a percentage of zero in order to disable the automatic AOF +# rewrite feature. + +auto-aof-rewrite-percentage 100 +auto-aof-rewrite-min-size 64mb + +################################ LUA SCRIPTING ############################### + +# Max execution time of a Lua script in milliseconds. +# +# If the maximum execution time is reached Redis will log that a script is +# still in execution after the maximum allowed time and will start to +# reply to queries with an error. +# +# When a long running script exceed the maximum execution time only the +# SCRIPT KILL and SHUTDOWN NOSAVE commands are available. The first can be +# used to stop a script that did not yet called write commands. The second +# is the only way to shut down the server in the case a write commands was +# already issue by the script but the user don't want to wait for the natural +# termination of the script. +# +# Set it to 0 or a negative value for unlimited execution without warnings. +lua-time-limit 5000 + +################################## SLOW LOG ################################### + +# The Redis Slow Log is a system to log queries that exceeded a specified +# execution time. The execution time does not include the I/O operations +# like talking with the client, sending the reply and so forth, +# but just the time needed to actually execute the command (this is the only +# stage of command execution where the thread is blocked and can not serve +# other requests in the meantime). +# +# You can configure the slow log with two parameters: one tells Redis +# what is the execution time, in microseconds, to exceed in order for the +# command to get logged, and the other parameter is the length of the +# slow log. When a new command is logged the oldest one is removed from the +# queue of logged commands. + +# The following time is expressed in microseconds, so 1000000 is equivalent +# to one second. Note that a negative number disables the slow log, while +# a value of zero forces the logging of every command. +slowlog-log-slower-than 10000 + +# There is no limit to this length. Just be aware that it will consume memory. +# You can reclaim memory used by the slow log with SLOWLOG RESET. +slowlog-max-len 128 + +############################# Event notification ############################## + +# Redis can notify Pub/Sub clients about events happening in the key space. +# This feature is documented at http://redis.io/topics/keyspace-events +# +# For instance if keyspace events notification is enabled, and a client +# performs a DEL operation on key "foo" stored in the Database 0, two +# messages will be published via Pub/Sub: +# +# PUBLISH __keyspace@0__:foo del +# PUBLISH __keyevent@0__:del foo +# +# It is possible to select the events that Redis will notify among a set +# of classes. Every class is identified by a single character: +# +# K Keyspace events, published with __keyspace@__ prefix. +# E Keyevent events, published with __keyevent@__ prefix. +# g Generic commands (non-type specific) like DEL, EXPIRE, RENAME, ... +# $ String commands +# l List commands +# s Set commands +# h Hash commands +# z Sorted set commands +# x Expired events (events generated every time a key expires) +# e Evicted events (events generated when a key is evicted for maxmemory) +# A Alias for g$lshzxe, so that the "AKE" string means all the events. +# +# The "notify-keyspace-events" takes as argument a string that is composed +# by zero or multiple characters. The empty string means that notifications +# are disabled at all. +# +# Example: to enable list and generic events, from the point of view of the +# event name, use: +# +# notify-keyspace-events Elg +# +# Example 2: to get the stream of the expired keys subscribing to channel +# name __keyevent@0__:expired use: +# +# notify-keyspace-events Ex +# +# By default all notifications are disabled because most users don't need +# this feature and the feature has some overhead. Note that if you don't +# specify at least one of K or E, no events will be delivered. +notify-keyspace-events "" + +############################### ADVANCED CONFIG ############################### + +# Hashes are encoded using a memory efficient data structure when they have a +# small number of entries, and the biggest entry does not exceed a given +# threshold. These thresholds can be configured using the following directives. +hash-max-ziplist-entries 512 +hash-max-ziplist-value 64 + +# Similarly to hashes, small lists are also encoded in a special way in order +# to save a lot of space. The special representation is only used when +# you are under the following limits: +list-max-ziplist-entries 512 +list-max-ziplist-value 64 + +# Sets have a special encoding in just one case: when a set is composed +# of just strings that happens to be integers in radix 10 in the range +# of 64 bit signed integers. +# The following configuration setting sets the limit in the size of the +# set in order to use this special memory saving encoding. +set-max-intset-entries 512 + +# Similarly to hashes and lists, sorted sets are also specially encoded in +# order to save a lot of space. This encoding is only used when the length and +# elements of a sorted set are below the following limits: +zset-max-ziplist-entries 128 +zset-max-ziplist-value 64 + +# Active rehashing uses 1 millisecond every 100 milliseconds of CPU time in +# order to help rehashing the main Redis hash table (the one mapping top-level +# keys to values). The hash table implementation Redis uses (see dict.c) +# performs a lazy rehashing: the more operation you run into a hash table +# that is rehashing, the more rehashing "steps" are performed, so if the +# server is idle the rehashing is never complete and some more memory is used +# by the hash table. +# +# The default is to use this millisecond 10 times every second in order to +# active rehashing the main dictionaries, freeing memory when possible. +# +# If unsure: +# use "activerehashing no" if you have hard latency requirements and it is +# not a good thing in your environment that Redis can reply form time to time +# to queries with 2 milliseconds delay. +# +# use "activerehashing yes" if you don't have such hard requirements but +# want to free memory asap when possible. +activerehashing yes + +# The client output buffer limits can be used to force disconnection of clients +# that are not reading data from the server fast enough for some reason (a +# common reason is that a Pub/Sub client can't consume messages as fast as the +# publisher can produce them). +# +# The limit can be set differently for the three different classes of clients: +# +# normal -> normal clients +# slave -> slave clients and MONITOR clients +# pubsub -> clients subscribed to at least one pubsub channel or pattern +# +# The syntax of every client-output-buffer-limit directive is the following: +# +# client-output-buffer-limit +# +# A client is immediately disconnected once the hard limit is reached, or if +# the soft limit is reached and remains reached for the specified number of +# seconds (continuously). +# So for instance if the hard limit is 32 megabytes and the soft limit is +# 16 megabytes / 10 seconds, the client will get disconnected immediately +# if the size of the output buffers reach 32 megabytes, but will also get +# disconnected if the client reaches 16 megabytes and continuously overcomes +# the limit for 10 seconds. +# +# By default normal clients are not limited because they don't receive data +# without asking (in a push way), but just after a request, so only +# asynchronous clients may create a scenario where data is requested faster +# than it can read. +# +# Instead there is a default limit for pubsub and slave clients, since +# subscribers and slaves receive data in a push fashion. +# +# Both the hard or the soft limit can be disabled by setting them to zero. +client-output-buffer-limit normal 0 0 0 +client-output-buffer-limit slave 256mb 64mb 60 +client-output-buffer-limit pubsub 32mb 8mb 60 + +# Redis calls an internal function to perform many background tasks, like +# closing connections of clients in timeout, purging expired keys that are +# never requested, and so forth. +# +# Not all tasks are performed with the same frequency, but Redis checks for +# tasks to perform accordingly to the specified "hz" value. +# +# By default "hz" is set to 10. Raising the value will use more CPU when +# Redis is idle, but at the same time will make Redis more responsive when +# there are many keys expiring at the same time, and timeouts may be +# handled with more precision. +# +# The range is between 1 and 500, however a value over 100 is usually not +# a good idea. Most users should use the default of 10 and raise this up to +# 100 only in environments where very low latency is required. +hz 10 + +# When a child rewrites the AOF file, if the following option is enabled +# the file will be fsync-ed every 32 MB of data generated. This is useful +# in order to commit the file to the disk more incrementally and avoid +# big latency spikes. +aof-rewrite-incremental-fsync yes + diff --git a/redis-config/redis.conf b/redis-config/redis.conf new file mode 100644 index 0000000..cefba6f --- /dev/null +++ b/redis-config/redis.conf @@ -0,0 +1,707 @@ +# Redis configuration file example + +# Note on units: when memory size is needed, it is possible to specify +# it in the usual form of 1k 5GB 4M and so forth: +# +# 1k => 1000 bytes +# 1kb => 1024 bytes +# 1m => 1000000 bytes +# 1mb => 1024*1024 bytes +# 1g => 1000000000 bytes +# 1gb => 1024*1024*1024 bytes +# +# units are case insensitive so 1GB 1Gb 1gB are all the same. + +################################## INCLUDES ################################### + +# Include one or more other config files here. This is useful if you +# have a standard template that goes to all Redis server but also need +# to customize a few per-server settings. Include files can include +# other files, so use this wisely. +# +# Notice option "include" won't be rewritten by command "CONFIG REWRITE" +# from admin or Redis Sentinel. Since Redis always uses the last processed +# line as value of a configuration directive, you'd better put includes +# at the beginning of this file to avoid overwriting config change at runtime. +# +# If instead you are interested in using includes to override configuration +# options, it is better to use include as the last line. +# +# include /path/to/local.conf +# include /path/to/other.conf + +################################ GENERAL ##################################### + +# By default Redis does not run as a daemon. Use 'yes' if you need it. +# Note that Redis will write a pid file in /var/run/redis.pid when daemonized. +daemonize yes + +# When running daemonized, Redis writes a pid file in /var/run/redis.pid by +# default. You can specify a custom pid file location here. +pidfile "/var/run/redis/redis-server.pid" + +# Accept connections on the specified port, default is 6379. +# If port 0 is specified Redis will not listen on a TCP socket. +port 6379 + +# By default Redis listens for connections from all the network interfaces +# available on the server. It is possible to listen to just one or multiple +# interfaces using the "bind" configuration directive, followed by one or +# more IP addresses. +# +# Examples: +# +# bind 192.168.1.100 10.0.0.1 +bind 127.0.0.1 + +# Specify the path for the unix socket that will be used to listen for +# incoming connections. There is no default, so Redis will not listen +# on a unix socket when not specified. +# +# unixsocket /var/run/redis/redis.sock +# unixsocketperm 755 + +# Close the connection after a client is idle for N seconds (0 to disable) +timeout 0 + +# TCP keepalive. +# +# If non-zero, use SO_KEEPALIVE to send TCP ACKs to clients in absence +# of communication. This is useful for two reasons: +# +# 1) Detect dead peers. +# 2) Take the connection alive from the point of view of network +# equipment in the middle. +# +# On Linux, the specified value (in seconds) is the period used to send ACKs. +# Note that to close the connection the double of the time is needed. +# On other kernels the period depends on the kernel configuration. +# +# A reasonable value for this option is 60 seconds. +tcp-keepalive 0 + +# Specify the server verbosity level. +# This can be one of: +# debug (a lot of information, useful for development/testing) +# verbose (many rarely useful info, but not a mess like the debug level) +# notice (moderately verbose, what you want in production probably) +# warning (only very important / critical messages are logged) +loglevel verbose + +# Specify the log file name. Also the empty string can be used to force +# Redis to log on the standard output. Note that if you use standard +# output for logging but daemonize, logs will be sent to /dev/null +logfile "/var/log/redis/redis-server.log" + +# To enable logging to the system logger, just set 'syslog-enabled' to yes, +# and optionally update the other syslog parameters to suit your needs. +# syslog-enabled no + +# Specify the syslog identity. +# syslog-ident redis + +# Specify the syslog facility. Must be USER or between LOCAL0-LOCAL7. +# syslog-facility local0 + +# Set the number of databases. The default database is DB 0, you can select +# a different one on a per-connection basis using SELECT where +# dbid is a number between 0 and 'databases'-1 +databases 16 + +################################ SNAPSHOTTING ################################ +# +# Save the DB on disk: +# +# save +# +# Will save the DB if both the given number of seconds and the given +# number of write operations against the DB occurred. +# +# In the example below the behaviour will be to save: +# after 900 sec (15 min) if at least 1 key changed +# after 300 sec (5 min) if at least 10 keys changed +# after 60 sec if at least 10000 keys changed +# +# Note: you can disable saving at all commenting all the "save" lines. +# +# It is also possible to remove all the previously configured save +# points by adding a save directive with a single empty string argument +# like in the following example: +# +# save "" + +save 900 1 +save 300 10 +save 60 10000 + +# By default Redis will stop accepting writes if RDB snapshots are enabled +# (at least one save point) and the latest background save failed. +# This will make the user aware (in a hard way) that data is not persisting +# on disk properly, otherwise chances are that no one will notice and some +# disaster will happen. +# +# If the background saving process will start working again Redis will +# automatically allow writes again. +# +# However if you have setup your proper monitoring of the Redis server +# and persistence, you may want to disable this feature so that Redis will +# continue to work as usual even if there are problems with disk, +# permissions, and so forth. +stop-writes-on-bgsave-error yes + +# Compress string objects using LZF when dump .rdb databases? +# For default that's set to 'yes' as it's almost always a win. +# If you want to save some CPU in the saving child set it to 'no' but +# the dataset will likely be bigger if you have compressible values or keys. +rdbcompression yes + +# Since version 5 of RDB a CRC64 checksum is placed at the end of the file. +# This makes the format more resistant to corruption but there is a performance +# hit to pay (around 10%) when saving and loading RDB files, so you can disable it +# for maximum performances. +# +# RDB files created with checksum disabled have a checksum of zero that will +# tell the loading code to skip the check. +rdbchecksum yes + +# The filename where to dump the DB +dbfilename "dump.rdb" + +# The working directory. +# +# The DB will be written inside this directory, with the filename specified +# above using the 'dbfilename' configuration directive. +# +# The Append Only File will also be created inside this directory. +# +# Note that you must specify a directory here, not a file name. +dir "/var/lib/redis" + +################################# REPLICATION ################################# + +# Master-Slave replication. Use slaveof to make a Redis instance a copy of +# another Redis server. Note that the configuration is local to the slave +# so for example it is possible to configure the slave to save the DB with a +# different interval, or to listen to another port, and so on. +# +# slaveof + +# If the master is password protected (using the "requirepass" configuration +# directive below) it is possible to tell the slave to authenticate before +# starting the replication synchronization process, otherwise the master will +# refuse the slave request. +# +# masterauth + +# When a slave loses its connection with the master, or when the replication +# is still in progress, the slave can act in two different ways: +# +# 1) if slave-serve-stale-data is set to 'yes' (the default) the slave will +# still reply to client requests, possibly with out of date data, or the +# data set may just be empty if this is the first synchronization. +# +# 2) if slave-serve-stale-data is set to 'no' the slave will reply with +# an error "SYNC with master in progress" to all the kind of commands +# but to INFO and SLAVEOF. +# +slave-serve-stale-data yes + +# You can configure a slave instance to accept writes or not. Writing against +# a slave instance may be useful to store some ephemeral data (because data +# written on a slave will be easily deleted after resync with the master) but +# may also cause problems if clients are writing to it because of a +# misconfiguration. +# +# Since Redis 2.6 by default slaves are read-only. +# +# Note: read only slaves are not designed to be exposed to untrusted clients +# on the internet. It's just a protection layer against misuse of the instance. +# Still a read only slave exports by default all the administrative commands +# such as CONFIG, DEBUG, and so forth. To a limited extent you can improve +# security of read only slaves using 'rename-command' to shadow all the +# administrative / dangerous commands. +slave-read-only yes + +# Slaves send PINGs to server in a predefined interval. It's possible to change +# this interval with the repl_ping_slave_period option. The default value is 10 +# seconds. +# +# repl-ping-slave-period 10 + +# The following option sets the replication timeout for: +# +# 1) Bulk transfer I/O during SYNC, from the point of view of slave. +# 2) Master timeout from the point of view of slaves (data, pings). +# 3) Slave timeout from the point of view of masters (REPLCONF ACK pings). +# +# It is important to make sure that this value is greater than the value +# specified for repl-ping-slave-period otherwise a timeout will be detected +# every time there is low traffic between the master and the slave. +# +# repl-timeout 60 + +# Disable TCP_NODELAY on the slave socket after SYNC? +# +# If you select "yes" Redis will use a smaller number of TCP packets and +# less bandwidth to send data to slaves. But this can add a delay for +# the data to appear on the slave side, up to 40 milliseconds with +# Linux kernels using a default configuration. +# +# If you select "no" the delay for data to appear on the slave side will +# be reduced but more bandwidth will be used for replication. +# +# By default we optimize for low latency, but in very high traffic conditions +# or when the master and slaves are many hops away, turning this to "yes" may +# be a good idea. +repl-disable-tcp-nodelay no + +# Set the replication backlog size. The backlog is a buffer that accumulates +# slave data when slaves are disconnected for some time, so that when a slave +# wants to reconnect again, often a full resync is not needed, but a partial +# resync is enough, just passing the portion of data the slave missed while +# disconnected. +# +# The biggest the replication backlog, the longer the time the slave can be +# disconnected and later be able to perform a partial resynchronization. +# +# The backlog is only allocated once there is at least a slave connected. +# +# repl-backlog-size 1mb + +# After a master has no longer connected slaves for some time, the backlog +# will be freed. The following option configures the amount of seconds that +# need to elapse, starting from the time the last slave disconnected, for +# the backlog buffer to be freed. +# +# A value of 0 means to never release the backlog. +# +# repl-backlog-ttl 3600 + +# The slave priority is an integer number published by Redis in the INFO output. +# It is used by Redis Sentinel in order to select a slave to promote into a +# master if the master is no longer working correctly. +# +# A slave with a low priority number is considered better for promotion, so +# for instance if there are three slaves with priority 10, 100, 25 Sentinel will +# pick the one with priority 10, that is the lowest. +# +# However a special priority of 0 marks the slave as not able to perform the +# role of master, so a slave with priority of 0 will never be selected by +# Redis Sentinel for promotion. +# +# By default the priority is 100. +slave-priority 100 + +# It is possible for a master to stop accepting writes if there are less than +# N slaves connected, having a lag less or equal than M seconds. +# +# The N slaves need to be in "online" state. +# +# The lag in seconds, that must be <= the specified value, is calculated from +# the last ping received from the slave, that is usually sent every second. +# +# This option does not GUARANTEES that N replicas will accept the write, but +# will limit the window of exposure for lost writes in case not enough slaves +# are available, to the specified number of seconds. +# +# For example to require at least 3 slaves with a lag <= 10 seconds use: +# +# min-slaves-to-write 3 +# min-slaves-max-lag 10 +# +# Setting one or the other to 0 disables the feature. +# +# By default min-slaves-to-write is set to 0 (feature disabled) and +# min-slaves-max-lag is set to 10. + +################################## SECURITY ################################### + +# Require clients to issue AUTH before processing any other +# commands. This might be useful in environments in which you do not trust +# others with access to the host running redis-server. +# +# This should stay commented out for backward compatibility and because most +# people do not need auth (e.g. they run their own servers). +# +# Warning: since Redis is pretty fast an outside user can try up to +# 150k passwords per second against a good box. This means that you should +# use a very strong password otherwise it will be very easy to break. +# +# requirepass foobared + +# Command renaming. +# +# It is possible to change the name of dangerous commands in a shared +# environment. For instance the CONFIG command may be renamed into something +# hard to guess so that it will still be available for internal-use tools +# but not available for general clients. +# +# Example: +# +# rename-command CONFIG b840fc02d524045429941cc15f59e41cb7be6c52 +# +# It is also possible to completely kill a command by renaming it into +# an empty string: +# +# rename-command CONFIG "" +# +# Please note that changing the name of commands that are logged into the +# AOF file or transmitted to slaves may cause problems. + +################################### LIMITS #################################### + +# Set the max number of connected clients at the same time. By default +# this limit is set to 10000 clients, however if the Redis server is not +# able to configure the process file limit to allow for the specified limit +# the max number of allowed clients is set to the current file limit +# minus 32 (as Redis reserves a few file descriptors for internal uses). +# +# Once the limit is reached Redis will close all the new connections sending +# an error 'max number of clients reached'. +# +# maxclients 10000 + +# Don't use more memory than the specified amount of bytes. +# When the memory limit is reached Redis will try to remove keys +# according to the eviction policy selected (see maxmemory-policy). +# +# If Redis can't remove keys according to the policy, or if the policy is +# set to 'noeviction', Redis will start to reply with errors to commands +# that would use more memory, like SET, LPUSH, and so on, and will continue +# to reply to read-only commands like GET. +# +# This option is usually useful when using Redis as an LRU cache, or to set +# a hard memory limit for an instance (using the 'noeviction' policy). +# +# WARNING: If you have slaves attached to an instance with maxmemory on, +# the size of the output buffers needed to feed the slaves are subtracted +# from the used memory count, so that network problems / resyncs will +# not trigger a loop where keys are evicted, and in turn the output +# buffer of slaves is full with DELs of keys evicted triggering the deletion +# of more keys, and so forth until the database is completely emptied. +# +# In short... if you have slaves attached it is suggested that you set a lower +# limit for maxmemory so that there is some free RAM on the system for slave +# output buffers (but this is not needed if the policy is 'noeviction'). +# +# maxmemory + +# MAXMEMORY POLICY: how Redis will select what to remove when maxmemory +# is reached. You can select among five behaviors: +# +# volatile-lru -> remove the key with an expire set using an LRU algorithm +# allkeys-lru -> remove any key accordingly to the LRU algorithm +# volatile-random -> remove a random key with an expire set +# allkeys-random -> remove a random key, any key +# volatile-ttl -> remove the key with the nearest expire time (minor TTL) +# noeviction -> don't expire at all, just return an error on write operations +# +# Note: with any of the above policies, Redis will return an error on write +# operations, when there are not suitable keys for eviction. +# +# At the date of writing this commands are: set setnx setex append +# incr decr rpush lpush rpushx lpushx linsert lset rpoplpush sadd +# sinter sinterstore sunion sunionstore sdiff sdiffstore zadd zincrby +# zunionstore zinterstore hset hsetnx hmset hincrby incrby decrby +# getset mset msetnx exec sort +# +# The default is: +# +# maxmemory-policy volatile-lru + +# LRU and minimal TTL algorithms are not precise algorithms but approximated +# algorithms (in order to save memory), so you can select as well the sample +# size to check. For instance for default Redis will check three keys and +# pick the one that was used less recently, you can change the sample size +# using the following configuration directive. +# +# maxmemory-samples 3 + +############################## APPEND ONLY MODE ############################### + +# By default Redis asynchronously dumps the dataset on disk. This mode is +# good enough in many applications, but an issue with the Redis process or +# a power outage may result into a few minutes of writes lost (depending on +# the configured save points). +# +# The Append Only File is an alternative persistence mode that provides +# much better durability. For instance using the default data fsync policy +# (see later in the config file) Redis can lose just one second of writes in a +# dramatic event like a server power outage, or a single write if something +# wrong with the Redis process itself happens, but the operating system is +# still running correctly. +# +# AOF and RDB persistence can be enabled at the same time without problems. +# If the AOF is enabled on startup Redis will load the AOF, that is the file +# with the better durability guarantees. +# +# Please check http://redis.io/topics/persistence for more information. + +appendonly no + +# The name of the append only file (default: "appendonly.aof") + +appendfilename "appendonly.aof" + +# The fsync() call tells the Operating System to actually write data on disk +# instead to wait for more data in the output buffer. Some OS will really flush +# data on disk, some other OS will just try to do it ASAP. +# +# Redis supports three different modes: +# +# no: don't fsync, just let the OS flush the data when it wants. Faster. +# always: fsync after every write to the append only log . Slow, Safest. +# everysec: fsync only one time every second. Compromise. +# +# The default is "everysec", as that's usually the right compromise between +# speed and data safety. It's up to you to understand if you can relax this to +# "no" that will let the operating system flush the output buffer when +# it wants, for better performances (but if you can live with the idea of +# some data loss consider the default persistence mode that's snapshotting), +# or on the contrary, use "always" that's very slow but a bit safer than +# everysec. +# +# More details please check the following article: +# http://antirez.com/post/redis-persistence-demystified.html +# +# If unsure, use "everysec". + +# appendfsync always +appendfsync everysec +# appendfsync no + +# When the AOF fsync policy is set to always or everysec, and a background +# saving process (a background save or AOF log background rewriting) is +# performing a lot of I/O against the disk, in some Linux configurations +# Redis may block too long on the fsync() call. Note that there is no fix for +# this currently, as even performing fsync in a different thread will block +# our synchronous write(2) call. +# +# In order to mitigate this problem it's possible to use the following option +# that will prevent fsync() from being called in the main process while a +# BGSAVE or BGREWRITEAOF is in progress. +# +# This means that while another child is saving, the durability of Redis is +# the same as "appendfsync none". In practical terms, this means that it is +# possible to lose up to 30 seconds of log in the worst scenario (with the +# default Linux settings). +# +# If you have latency problems turn this to "yes". Otherwise leave it as +# "no" that is the safest pick from the point of view of durability. + +no-appendfsync-on-rewrite no + +# Automatic rewrite of the append only file. +# Redis is able to automatically rewrite the log file implicitly calling +# BGREWRITEAOF when the AOF log size grows by the specified percentage. +# +# This is how it works: Redis remembers the size of the AOF file after the +# latest rewrite (if no rewrite has happened since the restart, the size of +# the AOF at startup is used). +# +# This base size is compared to the current size. If the current size is +# bigger than the specified percentage, the rewrite is triggered. Also +# you need to specify a minimal size for the AOF file to be rewritten, this +# is useful to avoid rewriting the AOF file even if the percentage increase +# is reached but it is still pretty small. +# +# Specify a percentage of zero in order to disable the automatic AOF +# rewrite feature. + +auto-aof-rewrite-percentage 100 +auto-aof-rewrite-min-size 64mb + +################################ LUA SCRIPTING ############################### + +# Max execution time of a Lua script in milliseconds. +# +# If the maximum execution time is reached Redis will log that a script is +# still in execution after the maximum allowed time and will start to +# reply to queries with an error. +# +# When a long running script exceed the maximum execution time only the +# SCRIPT KILL and SHUTDOWN NOSAVE commands are available. The first can be +# used to stop a script that did not yet called write commands. The second +# is the only way to shut down the server in the case a write commands was +# already issue by the script but the user don't want to wait for the natural +# termination of the script. +# +# Set it to 0 or a negative value for unlimited execution without warnings. +lua-time-limit 5000 + +################################## SLOW LOG ################################### + +# The Redis Slow Log is a system to log queries that exceeded a specified +# execution time. The execution time does not include the I/O operations +# like talking with the client, sending the reply and so forth, +# but just the time needed to actually execute the command (this is the only +# stage of command execution where the thread is blocked and can not serve +# other requests in the meantime). +# +# You can configure the slow log with two parameters: one tells Redis +# what is the execution time, in microseconds, to exceed in order for the +# command to get logged, and the other parameter is the length of the +# slow log. When a new command is logged the oldest one is removed from the +# queue of logged commands. + +# The following time is expressed in microseconds, so 1000000 is equivalent +# to one second. Note that a negative number disables the slow log, while +# a value of zero forces the logging of every command. +slowlog-log-slower-than 10000 + +# There is no limit to this length. Just be aware that it will consume memory. +# You can reclaim memory used by the slow log with SLOWLOG RESET. +slowlog-max-len 128 + +############################# Event notification ############################## + +# Redis can notify Pub/Sub clients about events happening in the key space. +# This feature is documented at http://redis.io/topics/keyspace-events +# +# For instance if keyspace events notification is enabled, and a client +# performs a DEL operation on key "foo" stored in the Database 0, two +# messages will be published via Pub/Sub: +# +# PUBLISH __keyspace@0__:foo del +# PUBLISH __keyevent@0__:del foo +# +# It is possible to select the events that Redis will notify among a set +# of classes. Every class is identified by a single character: +# +# K Keyspace events, published with __keyspace@__ prefix. +# E Keyevent events, published with __keyevent@__ prefix. +# g Generic commands (non-type specific) like DEL, EXPIRE, RENAME, ... +# $ String commands +# l List commands +# s Set commands +# h Hash commands +# z Sorted set commands +# x Expired events (events generated every time a key expires) +# e Evicted events (events generated when a key is evicted for maxmemory) +# A Alias for g$lshzxe, so that the "AKE" string means all the events. +# +# The "notify-keyspace-events" takes as argument a string that is composed +# by zero or multiple characters. The empty string means that notifications +# are disabled at all. +# +# Example: to enable list and generic events, from the point of view of the +# event name, use: +# +# notify-keyspace-events Elg +# +# Example 2: to get the stream of the expired keys subscribing to channel +# name __keyevent@0__:expired use: +# +# notify-keyspace-events Ex +# +# By default all notifications are disabled because most users don't need +# this feature and the feature has some overhead. Note that if you don't +# specify at least one of K or E, no events will be delivered. +notify-keyspace-events "" + +############################### ADVANCED CONFIG ############################### + +# Hashes are encoded using a memory efficient data structure when they have a +# small number of entries, and the biggest entry does not exceed a given +# threshold. These thresholds can be configured using the following directives. +hash-max-ziplist-entries 512 +hash-max-ziplist-value 64 + +# Similarly to hashes, small lists are also encoded in a special way in order +# to save a lot of space. The special representation is only used when +# you are under the following limits: +list-max-ziplist-entries 512 +list-max-ziplist-value 64 + +# Sets have a special encoding in just one case: when a set is composed +# of just strings that happens to be integers in radix 10 in the range +# of 64 bit signed integers. +# The following configuration setting sets the limit in the size of the +# set in order to use this special memory saving encoding. +set-max-intset-entries 512 + +# Similarly to hashes and lists, sorted sets are also specially encoded in +# order to save a lot of space. This encoding is only used when the length and +# elements of a sorted set are below the following limits: +zset-max-ziplist-entries 128 +zset-max-ziplist-value 64 + +# Active rehashing uses 1 millisecond every 100 milliseconds of CPU time in +# order to help rehashing the main Redis hash table (the one mapping top-level +# keys to values). The hash table implementation Redis uses (see dict.c) +# performs a lazy rehashing: the more operation you run into a hash table +# that is rehashing, the more rehashing "steps" are performed, so if the +# server is idle the rehashing is never complete and some more memory is used +# by the hash table. +# +# The default is to use this millisecond 10 times every second in order to +# active rehashing the main dictionaries, freeing memory when possible. +# +# If unsure: +# use "activerehashing no" if you have hard latency requirements and it is +# not a good thing in your environment that Redis can reply form time to time +# to queries with 2 milliseconds delay. +# +# use "activerehashing yes" if you don't have such hard requirements but +# want to free memory asap when possible. +activerehashing yes + +# The client output buffer limits can be used to force disconnection of clients +# that are not reading data from the server fast enough for some reason (a +# common reason is that a Pub/Sub client can't consume messages as fast as the +# publisher can produce them). +# +# The limit can be set differently for the three different classes of clients: +# +# normal -> normal clients +# slave -> slave clients and MONITOR clients +# pubsub -> clients subscribed to at least one pubsub channel or pattern +# +# The syntax of every client-output-buffer-limit directive is the following: +# +# client-output-buffer-limit +# +# A client is immediately disconnected once the hard limit is reached, or if +# the soft limit is reached and remains reached for the specified number of +# seconds (continuously). +# So for instance if the hard limit is 32 megabytes and the soft limit is +# 16 megabytes / 10 seconds, the client will get disconnected immediately +# if the size of the output buffers reach 32 megabytes, but will also get +# disconnected if the client reaches 16 megabytes and continuously overcomes +# the limit for 10 seconds. +# +# By default normal clients are not limited because they don't receive data +# without asking (in a push way), but just after a request, so only +# asynchronous clients may create a scenario where data is requested faster +# than it can read. +# +# Instead there is a default limit for pubsub and slave clients, since +# subscribers and slaves receive data in a push fashion. +# +# Both the hard or the soft limit can be disabled by setting them to zero. +client-output-buffer-limit normal 0 0 0 +client-output-buffer-limit slave 256mb 64mb 60 +client-output-buffer-limit pubsub 32mb 8mb 60 + +# Redis calls an internal function to perform many background tasks, like +# closing connections of clients in timeout, purging expired keys that are +# never requested, and so forth. +# +# Not all tasks are performed with the same frequency, but Redis checks for +# tasks to perform accordingly to the specified "hz" value. +# +# By default "hz" is set to 10. Raising the value will use more CPU when +# Redis is idle, but at the same time will make Redis more responsive when +# there are many keys expiring at the same time, and timeouts may be +# handled with more precision. +# +# The range is between 1 and 500, however a value over 100 is usually not +# a good idea. Most users should use the default of 10 and raise this up to +# 100 only in environments where very low latency is required. +hz 10 + +# When a child rewrites the AOF file, if the following option is enabled +# the file will be fsync-ed every 32 MB of data generated. This is useful +# in order to commit the file to the disk more incrementally and avoid +# big latency spikes. +aof-rewrite-incremental-fsync yes diff --git a/redis-config/sentinel.conf b/redis-config/sentinel.conf new file mode 100755 index 0000000..ac4557d --- /dev/null +++ b/redis-config/sentinel.conf @@ -0,0 +1,144 @@ +# Example sentinel.conf + +# port +# The port that this sentinel instance will run on +port 26379 + +#sentinel monitor test 127.0.0.1 6379 1 +# +# Tells Sentinel to monitor this master, and to consider it in O_DOWN +# (Objectively Down) state only if at least sentinels agree. +# +# Note that whatever is the ODOWN quorum, a Sentinel will require to +# be elected by the majority of the known Sentinels in order to +# start a failover, so no failover can be performed in minority. +# +# Note: master name should not include special characters or spaces. +# The valid charset is A-z 0-9 and the three characters ".-_". +sentinel monitor mymaster 127.0.0.1 6379 1 + +# sentinel auth-pass +# +# Set the password to use to authenticate with the master and slaves. +# Useful if there is a password set in the Redis instances to monitor. +# +# Note that the master password is also used for slaves, so it is not +# possible to set a different password in masters and slaves instances +# if you want to be able to monitor these instances with Sentinel. +# +# However you can have Redis instances without the authentication enabled +# mixed with Redis instances requiring the authentication (as long as the +# password set is the same for all the instances requiring the password) as +# the AUTH command will have no effect in Redis instances with authentication +# switched off. +# +# Example: +# +# sentinel auth-pass mymaster MySUPER--secret-0123passw0rd + +# sentinel down-after-milliseconds +# +# Number of milliseconds the master (or any attached slave or sentinel) should +# be unreachable (as in, not acceptable reply to PING, continuously, for the +# specified period) in order to consider it in S_DOWN state (Subjectively +# Down). +# +# Default is 30 seconds. +sentinel failover-timeout mymaster 30000 + +# sentinel parallel-syncs +# +# How many slaves we can reconfigure to point to the new slave simultaneously +# during the failover. Use a low number if you use the slaves to serve query +# to avoid that all the slaves will be unreachable at about the same +# time while performing the synchronization with the master. +sentinel config-epoch mymaster 17 + +# sentinel failover-timeout +# +# Specifies the failover timeout in milliseconds. It is used in many ways: +# +# - The time needed to re-start a failover after a previous failover was +# already tried against the same master by a given Sentinel, is two +# times the failover timeout. +# +# - The time needed for a slave replicating to a wrong master according +# to a Sentinel current configuration, to be forced to replicate +# with the right master, is exactly the failover timeout (counting since +# the moment a Sentinel detected the misconfiguration). +# +# - The time needed to cancel a failover that is already in progress but +# did not produced any configuration change (SLAVEOF NO ONE yet not +# acknowledged by the promoted slave). +# +# - The maximum time a failover in progress waits for all the slaves to be +# reconfigured as slaves of the new master. However even after this time +# the slaves will be reconfigured by the Sentinels anyway, but not with +# the exact parallel-syncs progression as specified. +# +# Default is 3 minutes. +sentinel leader-epoch mymaster 26 + +# SCRIPTS EXECUTION +# +# sentinel notification-script and sentinel reconfig-script are used in order +# to configure scripts that are called to notify the system administrator +# or to reconfigure clients after a failover. The scripts are executed +# with the following rules for error handling: +# +# If script exists with "1" the execution is retried later (up to a maximum +# number of times currently set to 10). +# +# If script exists with "2" (or an higher value) the script execution is +# not retried. +# +# If script terminates because it receives a signal the behavior is the same +# as exit code 1. +# +# A script has a maximum running time of 60 seconds. After this limit is +# reached the script is terminated with a SIGKILL and the execution retried. + +# NOTIFICATION SCRIPT +# +# sentinel notification-script +# +# Call the specified notification script for any sentinel event that is +# generated in the WARNING level (for instance -sdown, -odown, and so forth). +# This script should notify the system administrator via email, SMS, or any +# other messaging system, that there is something wrong with the monitored +# Redis systems. +# +# The script is called with just two arguments: the first is the event type +# and the second the event description. +# +# The script must exist and be executable in order for sentinel to start if +# this option is provided. +# +# Example: +# +# sentinel notification-script mymaster /var/redis/notify.sh + +# CLIENTS RECONFIGURATION SCRIPT +# +# sentinel client-reconfig-script +# +# When the master changed because of a failover a script can be called in +# order to perform application-specific tasks to notify the clients that the +# configuration has changed and the master is at a different address. +# +# The following arguments are passed to the script: +# +# +# +# is currently always "failover" +# is either "leader" or "observer" +# +# The arguments from-ip, from-port, to-ip, to-port are used to communicate +# the old address of the master and the new address of the elected slave +# (now a master). +# +# This script should be resistant to multiple invocations. +# +# Example: +# +# sentinel client-reconfig-script mymaster /var/redis/reconfig.sh diff --git a/src/main/resources/reference.conf b/src/main/resources/reference.conf index 2ee8cfe..63fcd73 100644 --- a/src/main/resources/reference.conf +++ b/src/main/resources/reference.conf @@ -1,10 +1,9 @@ -brando { - # Default connection retry delay on disconnect - connection_retry = 2s +brando.connection{ + timeout = 2s - #Max number of times to attempt connection before failing - #connection_attempts = 3 -} + #Delay before trying to reconnect + retry.delay = 1 s -#Redis connection/authentication timeout -redis.timeout = 2s + #Number of connect attempts before failure + retry.attempts = 3 +} diff --git a/src/main/scala/Brando.scala b/src/main/scala/Brando.scala index 65ca613..85e27ed 100644 --- a/src/main/scala/Brando.scala +++ b/src/main/scala/Brando.scala @@ -1,231 +1,84 @@ package brando -import akka.actor.{ Actor, ActorContext, ActorRef, Props, Status, Stash, Terminated, PoisonPill } -import akka.actor.ActorDSL._ -import akka.io.{ IO, Tcp } -import akka.pattern._ -import akka.util.{ ByteString, Timeout } -import scala.collection.mutable +import akka.actor._ + import scala.concurrent.duration._ -import scala.concurrent.Future -import scala.util.Try import com.typesafe.config.ConfigFactory -import java.net.InetSocketAddress import java.util.concurrent.TimeUnit -class BrandoException(message: String) extends Exception(message) { - override lazy val toString = "%s: %s\n".format(getClass.getName, message) -} -case class PubSubMessage(channel: String, message: String) -private case class Connect(address: InetSocketAddress) -private case class CommandAck(sender: ActorRef) extends Tcp.Event - -trait BrandoStateChange -case object Disconnected extends BrandoStateChange -case object Connected extends BrandoStateChange -case object AuthenticationFailed extends BrandoStateChange -case object ConnectionFailed extends BrandoStateChange - -private class Connection( - brando: ActorRef, - address: InetSocketAddress, - connectionRetry: Long, - maxConnectionAttempts: Option[Int], - connectionTimeout: FiniteDuration) extends Actor with ReplyParser { - import context.dispatcher - - var socket: ActorRef = _ - - val requesterQueue = mutable.Queue.empty[ActorRef] - var subscribers: Map[ByteString, Seq[ActorRef]] = Map.empty - - var connectionAttempts = 0 - - self ! Connect(address) - - def getSubscribers(channel: ByteString): Seq[ActorRef] = - subscribers.get(channel).getOrElse(Seq.empty[ActorRef]) - - def receive = { - case subRequest: Request if (subRequest.command.utf8String.toLowerCase == "subscribe") ⇒ - - subRequest.params map { x ⇒ - subscribers = subscribers + ((x, getSubscribers(x).+:(sender))) - } - socket ! Tcp.Write(subRequest.toByteString, CommandAck(sender)) - - case request: Request ⇒ - socket ! Tcp.Write(request.toByteString, CommandAck(sender)) - - case CommandAck(sender) ⇒ requesterQueue.enqueue(sender) - - case Tcp.Received(data) ⇒ - parseReply(data) { reply ⇒ - reply match { - case Some(List(Some(x: ByteString), Some(channel: ByteString), Some(message: ByteString))) if (x.utf8String == "message") ⇒ - - val pubSubMessage = PubSubMessage(channel.utf8String, message.utf8String) - getSubscribers(channel).map { x ⇒ - x ! pubSubMessage - } - - case _ ⇒ - requesterQueue.dequeue ! (reply match { - case Some(failure: Status.Failure) ⇒ - failure - case success ⇒ - success - }) - } - } - - case Tcp.CommandFailed(writeMessage: Tcp.Write) ⇒ - socket ! writeMessage //just retry immediately - - case Tcp.CommandFailed(_: Tcp.Connect) ⇒ - if (maxConnectionAttempts.isDefined && connectionAttempts >= maxConnectionAttempts.get) { - brando ! ConnectionFailed - } else { - connectionAttempts += 1 - context.system.scheduler.scheduleOnce(connectionRetry.milliseconds, self, Connect(address)) - } - - case x: Tcp.ConnectionClosed ⇒ - requesterQueue.clear - brando ! x - context.system.scheduler.scheduleOnce(connectionRetry.milliseconds, self, Connect(address)) - - case Connect(address) ⇒ - IO(Tcp)(context.system) ! Tcp.Connect(address, timeout = Some(connectionTimeout)) - - case x: Tcp.Connected ⇒ - socket = sender - connectionAttempts = 0 - socket ! Tcp.Register(self, useResumeWriting = false) - brando ! x - - case _ ⇒ - } -} - object Brando { + def apply(): Props = apply("localhost", 6379) def apply( host: String, port: Int, - database: Option[Int] = None, + database: Int = 0, auth: Option[String] = None, - listeners: Set[ActorRef] = Set()): Props = Props(classOf[Brando], host, port, database, auth, listeners) - def apply(): Props = apply("localhost", 6379, None, None, Set()) + listeners: Set[ActorRef] = Set(), + connectionTimeout: Option[FiniteDuration] = None, + connectionRetryDelay: Option[FiniteDuration] = None, + connectionRetryAttempts: Option[Int] = None, + connectionHeartbeatDelay: Option[FiniteDuration] = None): Props = { + + val config = ConfigFactory.load() + Props(classOf[Brando], + host, + port, + database, + auth, + listeners, + connectionTimeout.getOrElse( + config.getDuration("brando.connection.timeout", TimeUnit.MILLISECONDS).millis), + Some(connectionRetryDelay.getOrElse( + config.getDuration("brando.connection.retry.delay", TimeUnit.MILLISECONDS).millis)), + connectionRetryAttempts, + connectionHeartbeatDelay) + } + + case class AuthenticationFailed(host: String, port: Int) extends Connection.StateChange } class Brando( - host: String, - port: Int, - database: Option[Int], - auth: Option[String], - private[brando] var listeners: Set[ActorRef]) extends Actor with Stash { + host: String, + port: Int, + database: Int, + auth: Option[String], + listeners: Set[ActorRef], + connectionTimeout: FiniteDuration, + connectionRetryDelay: Option[FiniteDuration], + connectionRetryAttempts: Option[Int], + connectionHeartbeatDelay: Option[FiniteDuration]) extends ConnectionSupervisor( + database, auth, listeners, connectionTimeout, connectionHeartbeatDelay) { + + import ConnectionSupervisor.{ Connect, Reconnect } import context.dispatcher - val config = context.system.settings.config - val connectionTimeout: Long = config.getDuration("redis.timeout", TimeUnit.MILLISECONDS) - val connectionRetry: Long = config.getDuration("brando.connection_retry", TimeUnit.MILLISECONDS) - val maxConnectionAttempts: Option[Int] = Try(config.getInt("brando.connection_attempts")).toOption - implicit val timeout = Timeout(connectionTimeout, TimeUnit.MILLISECONDS) - - case object Authenticating - case object Authenticated - - val address = new InetSocketAddress(host, port) - val connection = context.actorOf(Props(classOf[Connection], - self, address, connectionRetry, maxConnectionAttempts, connectionTimeout.millis)) - - listeners.map(context.watch(_)) - - def receive = disconnected orElse cleanListeners - - def authenticated: Receive = { - case request: Request ⇒ - connection forward request - - case batch: Batch ⇒ - val requester = sender - val batcher = actor(new Act { - var responses = List[Any]() - become { - case response if (responses.size + 1) < batch.requests.size ⇒ - responses = responses :+ response - case response ⇒ - requester ! (responses :+ response) - self ! PoisonPill - } - }) - batch.requests.foreach(connection.tell(_, batcher)) - - case x: Tcp.ConnectionClosed ⇒ - notifyStateChange(Disconnected) - context.become(disconnected orElse cleanListeners) - case s: ActorRef ⇒ - listeners = listeners + s - } - - def disconnected: Receive = { - case batch: Batch ⇒ - stash() + var retries = 0 - case request: Request ⇒ - stash() - - case x: Tcp.Connected ⇒ - context.become(authenticating orElse cleanListeners) - - (for { - auth ← if (auth.isDefined) connection ? Request(ByteString("AUTH"), ByteString(auth.get)) else Future.successful(Unit) - database ← if (database.isDefined) connection ? Request(ByteString("SELECT"), ByteString(database.get.toString)) else Future.successful(Unit) - } yield (Connected)) map { - self ! _ - } onFailure { - case e: Exception ⇒ - self ! AuthenticationFailed - } - - case ConnectionFailed ⇒ - notifyStateChange(ConnectionFailed) - - case s: ActorRef ⇒ - listeners = listeners + s + override def preStart: Unit = { + listeners.map(context.watch(_)) + self ! Connect(host, port) } - def authenticating: Receive = { - case batch: Batch ⇒ - stash() - - case request: Request ⇒ - stash() - - case x: Tcp.ConnectionClosed ⇒ - notifyStateChange(Disconnected) - context.become(disconnected orElse cleanListeners) + override def disconnected: Receive = + disconnectedWithRetry orElse super.disconnected - case Connected ⇒ + def disconnectedWithRetry: Receive = { + case ("auth_ok", x: Connection.Connected) ⇒ + retries = 0 + notifyStateChange(x) + context.become(connected) unstashAll() - notifyStateChange(Connected) - context.become(authenticated orElse cleanListeners) - case AuthenticationFailed ⇒ - notifyStateChange(AuthenticationFailed) - - case s: ActorRef ⇒ - listeners = listeners + s - } - - def cleanListeners: Receive = { - case Terminated(l) ⇒ - listeners = listeners - l - } - - private def notifyStateChange(newState: BrandoStateChange) { - listeners foreach { _ ! newState } + case Reconnect ⇒ + (connectionRetryDelay, connectionRetryAttempts) match { + case (Some(delay), Some(maxAttempts)) if (maxAttempts > retries) ⇒ + retries += 1 + context.system.scheduler.scheduleOnce(delay, connection, Connection.Connect) + case (Some(delay), None) ⇒ + retries += 1 + context.system.scheduler.scheduleOnce(delay, connection, Connection.Connect) + case _ ⇒ + } } - } diff --git a/src/main/scala/BrandoSentinel.scala b/src/main/scala/BrandoSentinel.scala new file mode 100644 index 0000000..d6bdc10 --- /dev/null +++ b/src/main/scala/BrandoSentinel.scala @@ -0,0 +1,101 @@ +package brando + +import akka.actor._ +import akka.pattern._ +import akka.util._ + +import scala.concurrent._ +import scala.concurrent.duration._ + +import com.typesafe.config.ConfigFactory +import java.util.concurrent.TimeUnit + +object BrandoSentinel { + def apply( + name: String, + sentinel: ActorRef, + database: Int = 0, + auth: Option[String] = None, + listeners: Set[ActorRef] = Set(), + connectionTimeout: Option[FiniteDuration] = None, + connectionRetryDelay: Option[FiniteDuration] = None, + connectionHeartbeatDelay: Option[FiniteDuration] = None): Props = { + + val config = ConfigFactory.load() + Props(classOf[BrandoSentinel], + name, + sentinel, + database, + auth, + listeners, + connectionTimeout.getOrElse( + config.getDuration("brando.connection.timeout", TimeUnit.MILLISECONDS).millis), + connectionRetryDelay.getOrElse( + config.getDuration("brando.connection.retry.delay", TimeUnit.MILLISECONDS).millis), + connectionHeartbeatDelay) + } + + private[brando] case object SentinelConnect +} + +class BrandoSentinel( + name: String, + sentinel: ActorRef, + database: Int, + auth: Option[String], + listeners: Set[ActorRef], + connectionTimeout: FiniteDuration, + connectionRetryDelay: FiniteDuration, + connectionHeartbeatDelay: Option[FiniteDuration]) extends ConnectionSupervisor(database, auth, + listeners, connectionTimeout, connectionHeartbeatDelay) { + + import BrandoSentinel._ + import ConnectionSupervisor.{ Connect, Reconnect } + import context.dispatcher + + override def preStart: Unit = { + listeners.map(context.watch(_)) + self ! SentinelConnect + } + + override def disconnected: Receive = + disconnectedWithSentinel orElse super.disconnected + + def disconnectedWithSentinel: Receive = { + case Reconnect ⇒ + context.system.scheduler.scheduleOnce(connectionRetryDelay, self, SentinelConnect) + + case SentinelConnect ⇒ + (sentinel ? Request("SENTINEL", "MASTER", name)) map { + case Response.AsStrings(res) ⇒ + val (ip, port) = extractIpPort(res) + self ! Connect(ip, port) + } recover { case _ ⇒ self ! Reconnect } + + case x: Connection.Connected ⇒ + isValidMaster map { + case true ⇒ + authenticate(x) + case false ⇒ + self ! Reconnect + } recover { case _ ⇒ self ! Reconnect } + } + + def extractIpPort(config: Seq[String]): (String, Int) = { + var i, port = 0 + var ip: String = "" + while ((i < config.size) && (ip == "" || port == 0)) { + if (config(i) == "port") port = config(i + 1).toInt + if (config(i) == "ip") ip = config(i + 1) + i = i + 1 + } + (ip, port) + } + + def isValidMaster: Future[Boolean] = { + (connection ? Request("INFO")) map { + case Response.AsString(res) ⇒ + res.contains("role:master") + } + } +} diff --git a/src/main/scala/Connection.scala b/src/main/scala/Connection.scala new file mode 100644 index 0000000..a9e0eea --- /dev/null +++ b/src/main/scala/Connection.scala @@ -0,0 +1,137 @@ +package brando + +import akka.actor._ +import akka.actor.ActorDSL._ +import akka.pattern._ +import akka.io._ +import akka.util._ + +import scala.collection.mutable +import scala.concurrent._ +import scala.concurrent.duration._ + +import java.net.InetSocketAddress + +object Connection { + trait StateChange + case class Connecting(host: String, port: Int) extends StateChange + case class Connected(host: String, port: Int) extends StateChange + case class Disconnected(host: String, port: Int) extends StateChange + case class ConnectionFailed(host: String, port: Int) extends StateChange + + private[brando] case object Connect + private[brando] case class CommandAck(sender: ActorRef) extends Tcp.Event + private[brando] case class Heartbeat(delay: FiniteDuration) +} + +private[brando] class Connection( + listener: ActorRef, + host: String, + port: Int, + connectionTimeout: FiniteDuration, + heartbeatDelay: Option[FiniteDuration]) extends Actor with ReplyParser { + + import Connection._ + import context.dispatcher + + var socket: ActorRef = _ + + val requesterQueue = mutable.Queue.empty[ActorRef] + var subscribers: Map[ByteString, Seq[ActorRef]] = Map.empty + + def getSubscribers(channel: ByteString): Seq[ActorRef] = + subscribers.get(channel).getOrElse(Seq.empty[ActorRef]) + + override def preStart(): Unit = self ! Connect + + def receive = { + case subRequest: Request if (subRequest.command.utf8String.toLowerCase == "subscribe") ⇒ + subRequest.params map { x ⇒ + subscribers = subscribers + ((x, getSubscribers(x).+:(sender))) + } + socket ! Tcp.Write(subRequest.toByteString, CommandAck(sender)) + + case request: Request ⇒ + socket ! Tcp.Write(request.toByteString, CommandAck(sender)) + + case batch: Batch ⇒ + val requester = sender + val batcher = actor(sender.path.name + "-batcher")(new Act { + var responses = List[Any]() + become { + case response if (responses.size + 1) < batch.requests.size ⇒ + responses = responses :+ response + case response ⇒ + requester ! (responses :+ response) + self ! PoisonPill + } + }) + batch.requests.foreach(self.tell(_, batcher)) + + case CommandAck(sender) ⇒ + requesterQueue.enqueue(sender) + + case Tcp.Received(data) ⇒ + parseReply(data) { reply ⇒ + reply match { + case Some(List( + Some(x: ByteString), + Some(channel: ByteString), + Some(message: ByteString))) if (x.utf8String == "message") ⇒ + + val pubSubMessage = PubSubMessage(channel.utf8String, message.utf8String) + getSubscribers(channel).map { x ⇒ + x ! pubSubMessage + } + + case _ ⇒ + requesterQueue.dequeue ! (reply match { + case Some(failure: Status.Failure) ⇒ + failure + case success ⇒ + success + }) + } + } + + case Tcp.CommandFailed(writeMessage: Tcp.Write) ⇒ + socket ! writeMessage //just retry immediately + case Tcp.CommandFailed(_: Tcp.Connect) ⇒ + listener ! ConnectionFailed(host, port) + + case x: Tcp.ConnectionClosed ⇒ + requesterQueue.clear + listener ! Disconnected(host, port) + + case Connect ⇒ + val address = new InetSocketAddress(host, port) + listener ! Connecting(host, port) + IO(Tcp)(context.system) ! Tcp.Connect(address, timeout = Some(connectionTimeout)) + + case x: Tcp.Connected ⇒ + socket = sender + socket ! Tcp.Register(self, useResumeWriting = false) + ping { + case _ ⇒ + listener ! Connected(host, port) + heartbeatDelay map (d ⇒ + context.system.scheduler.scheduleOnce(d, self, Heartbeat(d))) + } recover { + case _ ⇒ + listener ! ConnectionFailed(host, port) + } + + case x @ Heartbeat(delay) ⇒ + ping { + case _ ⇒ + context.system.scheduler.scheduleOnce(delay, self, x) + } recover { case _ ⇒ socket ! Tcp.Close } + + case _ ⇒ + } + + def ping(function: PartialFunction[Any, Any]): Future[Any] = { + (self ? Request("PING"))(connectionTimeout) map (function) + } +} + diff --git a/src/main/scala/ConnectionSupervisor.scala b/src/main/scala/ConnectionSupervisor.scala new file mode 100644 index 0000000..ca65b0c --- /dev/null +++ b/src/main/scala/ConnectionSupervisor.scala @@ -0,0 +1,97 @@ +package brando + +import akka.actor._ +import akka.pattern._ +import akka.util._ + +import scala.concurrent.duration._ +import scala.concurrent.Future + +object ConnectionSupervisor { + private[brando] case class Connect(host: String, port: Int) + private[brando] case object Reconnect +} + +private[brando] abstract class ConnectionSupervisor( + database: Int, + auth: Option[String], + var listeners: Set[ActorRef], + connectionTimeout: FiniteDuration, + connectionHeartbeatDelay: Option[FiniteDuration]) extends Actor with Stash { + + import ConnectionSupervisor.{ Connect, Reconnect } + import context.dispatcher + + implicit val timeout = Timeout(connectionTimeout) + + var connection = context.system.deadLetters + + def receive = disconnected + + def connected: Receive = handleListeners orElse { + case request: Request ⇒ + connection forward request + + case batch: Batch ⇒ + connection forward batch + + case x: Connection.Disconnected ⇒ + notifyStateChange(x) + context.become(disconnected) + self ! Reconnect + } + + def disconnected: Receive = handleListeners orElse { + case request: Request ⇒ + stash() + + case batch: Batch ⇒ + stash() + + case Connect(host, port) ⇒ + connection ! PoisonPill + connection = context.actorOf(Props(classOf[Connection], + self, host, port, connectionTimeout, connectionHeartbeatDelay)) + + case x: Connection.Connecting ⇒ + notifyStateChange(x) + + case x: Connection.Connected ⇒ + authenticate(x) + + case ("auth_ok", x: Connection.Connected) ⇒ + notifyStateChange(x) + context.become(connected) + unstashAll() + + case x: Connection.ConnectionFailed ⇒ + notifyStateChange(x) + self ! Reconnect + } + + def handleListeners: Receive = { + case s: ActorRef ⇒ + listeners = listeners + s + + case Terminated(l) ⇒ + listeners = listeners - l + } + + def notifyStateChange(newState: Connection.StateChange) { + listeners foreach { _ ! newState } + } + + def authenticate(x: Connection.Connected) { + (for { + auth ← if (auth.isDefined) + connection ? Request(ByteString("AUTH"), ByteString(auth.get)) else Future.successful(Unit) + database ← if (database != 0) + connection ? Request(ByteString("SELECT"), ByteString(database.toString)) else Future.successful(Unit) + } yield ("auth_ok", x)) map { + self ! _ + } onFailure { + case e: Exception ⇒ + notifyStateChange(Brando.AuthenticationFailed(x.host, x.port)) + } + } +} diff --git a/src/main/scala/HealthMonitor.scala b/src/main/scala/HealthMonitor.scala deleted file mode 100644 index 6f1d2dd..0000000 --- a/src/main/scala/HealthMonitor.scala +++ /dev/null @@ -1,41 +0,0 @@ -package brando - -import concurrent.duration._ -import akka.actor.{ ActorRef, Props } -import akka.pattern.ask -import akka.util.{ ByteString, Timeout } - -case object NonRespondingShardRestarted extends BrandoStateChange - -trait HealthMonitor extends ShardManager { - - val healthCheckRate: FiniteDuration - - implicit val ec = context.dispatcher - implicit lazy val timeout = Timeout(healthCheckRate) - - override def preStart() = { - context.system.scheduler.schedule(healthCheckRate, healthCheckRate)(healthCheck) - super.preStart() - } - - def healthCheck = { - pool.foreach { case (id, shard) ⇒ checkShard(shard) } - } - - private def checkShard(shardRef: ActorRef) = { - def ping = (shardRef ? Request(ByteString("PING"))) map { - case None ⇒ throw new Exception("Unexpected response") - case _ ⇒ - } - - ping recoverWith { case e: Exception ⇒ ping } recover { case e: Exception ⇒ restartShard(shardRef) } - } - - private def restartShard(shardRef: ActorRef) = { - shardLookup.get(shardRef) map { shard ⇒ - listeners foreach { l ⇒ l ! ShardStateChange(shard, NonRespondingShardRestarted) } - self ! shard - } - } -} diff --git a/src/main/scala/Request.scala b/src/main/scala/Request.scala index abd572d..11a291f 100644 --- a/src/main/scala/Request.scala +++ b/src/main/scala/Request.scala @@ -35,4 +35,4 @@ object BroadcastRequest { case class BroadcastRequest(command: ByteString, params: ByteString*) -case class Batch(requests: Request*) \ No newline at end of file +case class Batch(requests: Request*) diff --git a/src/main/scala/Response.scala b/src/main/scala/Response.scala index 0e5b308..c2b630d 100644 --- a/src/main/scala/Response.scala +++ b/src/main/scala/Response.scala @@ -2,6 +2,12 @@ package brando import akka.util.ByteString +case class PubSubMessage(channel: String, message: String) + +class BrandoException(message: String) extends Exception(message) { + override lazy val toString = "%s: %s\n".format(getClass.getName, message) +} + object Response { def collectItems[T](value: Any, mapper: PartialFunction[Any, T]): Option[Seq[T]] = { diff --git a/src/main/scala/SentinelClient.scala b/src/main/scala/SentinelClient.scala new file mode 100644 index 0000000..8b6aca0 --- /dev/null +++ b/src/main/scala/SentinelClient.scala @@ -0,0 +1,108 @@ +package brando + +import akka.actor._ +import akka.pattern._ +import akka.util._ + +import scala.concurrent._ +import scala.concurrent.duration._ + +import com.typesafe.config.ConfigFactory +import java.util.concurrent.TimeUnit + +object SentinelClient { + def apply(): Props = apply(Seq(Sentinel("localhost", 26379))) + def apply( + instances: Seq[Sentinel], + listeners: Set[ActorRef] = Set(), + connectionTimeout: Option[FiniteDuration] = None, + connectionHeartbeatDelay: Option[FiniteDuration] = None): Props = { + + val config = ConfigFactory.load() + Props(classOf[SentinelClient], instances, listeners, + connectionTimeout.getOrElse( + config.getDuration("brando.connection.timeout", TimeUnit.MILLISECONDS).millis), + connectionHeartbeatDelay) + } + + case class Sentinel(host: String, port: Int) + private[brando] case class Connect(instances: Seq[Sentinel]) + case class ConnectionFailed(sentinels: Seq[Sentinel]) extends Connection.StateChange +} + +class SentinelClient( + var sentinels: Seq[SentinelClient.Sentinel], + var listeners: Set[ActorRef], + connectionTimeout: FiniteDuration, + connectionHeartbeatDelay: Option[FiniteDuration]) extends Actor with Stash { + + import SentinelClient._ + import context.dispatcher + + implicit val timeout = Timeout(connectionTimeout) + + var connection = context.system.deadLetters + var retries = 0 + + override def preStart: Unit = { + listeners.map(context.watch(_)) + self ! Connect(sentinels) + } + + def receive: Receive = disconnected + + def connected: Receive = handleListeners orElse { + case x: Connection.Disconnected ⇒ + connection ! PoisonPill + context.become(disconnected) + notifyStateChange(x) + self ! Connect(sentinels) + + case request: Request ⇒ + connection forward request + + case _ ⇒ + } + + def disconnected: Receive = handleListeners orElse { + case Connect(Sentinel(host, port) :: tail) ⇒ + notifyStateChange(Connection.Connecting(host, port)) + retries += 1 + connection = context.actorOf(Props(classOf[Connection], + self, host, port, connectionTimeout, connectionHeartbeatDelay)) + + case x: Connection.Connected ⇒ + context.become(connected) + unstashAll() + retries = 0 + val Sentinel(host, port) = sentinels.head + notifyStateChange(Connection.Connected(host, port)) + + case x: Connection.ConnectionFailed ⇒ + context.become(disconnected) + (retries < sentinels.size) match { + case true ⇒ + sentinels = sentinels.tail :+ sentinels.head + self ! Connect(sentinels) + case false ⇒ + notifyStateChange(ConnectionFailed(sentinels)) + } + + case request: Request ⇒ + stash() + + case _ ⇒ + } + + def handleListeners: Receive = { + case s: ActorRef ⇒ + listeners = listeners + s + + case Terminated(l) ⇒ + listeners = listeners - l + } + + def notifyStateChange(newState: Connection.StateChange) { + listeners foreach { _ ! newState } + } +} diff --git a/src/main/scala/ShardManager.scala b/src/main/scala/ShardManager.scala index e37330e..3194ff6 100644 --- a/src/main/scala/ShardManager.scala +++ b/src/main/scala/ShardManager.scala @@ -1,16 +1,16 @@ package brando -import akka.actor.{ Actor, ActorRef, Props, Terminated } -import akka.util.ByteString +import akka.actor._ +import akka.util._ import collection.mutable import java.util.zip.CRC32 -import concurrent.Future -import concurrent.duration.FiniteDuration -import scala.util.Failure -case class Shard(id: String, host: String, port: Int, database: Option[Int] = None, auth: Option[String] = None) +import scala.util.Failure +import scala.concurrent._ +import scala.concurrent.duration._ -case class ShardStateChange(shard: Shard, state: BrandoStateChange) +import com.typesafe.config.ConfigFactory +import java.util.concurrent.TimeUnit object ShardManager { def defaultHashFunction(input: Array[Byte]): Long = { @@ -19,33 +19,54 @@ object ShardManager { crc32.getValue } - def apply(shards: Seq[Shard], + def apply( + shards: Seq[Shard], + listeners: Set[ActorRef] = Set(), + sentinel: Option[ActorRef] = None, hashFunction: (Array[Byte] ⇒ Long) = defaultHashFunction, - listeners: Set[ActorRef] = Set()): Props = { - Props(classOf[ShardManager], shards, hashFunction, listeners) + connectionTimeout: Option[FiniteDuration] = None, + connectionRetryDelay: Option[FiniteDuration] = None, + connectionHeartbeatDelay: Option[FiniteDuration] = None): Props = { + + val config = ConfigFactory.load() + Props(classOf[ShardManager], shards, hashFunction, listeners, sentinel, + connectionTimeout.getOrElse( + config.getDuration("brando.connection.timeout", TimeUnit.MILLISECONDS).millis), + connectionRetryDelay.getOrElse( + config.getDuration("brando.connection.retry.delay", TimeUnit.MILLISECONDS).millis), + connectionHeartbeatDelay) } - def withHealthMonitor(shards: Seq[Shard], - healthChkRate: FiniteDuration, - hashFunction: (Array[Byte] ⇒ Long) = defaultHashFunction, - listeners: Set[ActorRef] = Set()): Props = { - Props(new ShardManager(shards, hashFunction, listeners) with HealthMonitor { val healthCheckRate = healthChkRate }) - } + private[brando] trait Shard { val id: String } + case class RedisShard(id: String, host: String, + port: Int, database: Int = 0, + auth: Option[String] = None) extends Shard + case class SentinelShard(id: String, database: Int = 0, + auth: Option[String] = None) extends Shard + + private[brando] case class SetShard(shard: Shard) } class ShardManager( - shards: Seq[Shard], + shards: Seq[ShardManager.Shard], hashFunction: (Array[Byte] ⇒ Long), - private[brando] var listeners: Set[ActorRef] = Set()) extends Actor { + var listeners: Set[ActorRef] = Set(), + sentinel: Option[ActorRef] = None, + connectionTimeout: FiniteDuration, + connectionRetryDelay: FiniteDuration, + connectionHeartbeatDelay: Option[FiniteDuration]) extends Actor { + import ShardManager._ import context.dispatcher val pool = mutable.Map.empty[String, ActorRef] - var poolKeys: Seq[String] = Seq() val shardLookup = mutable.Map.empty[ActorRef, Shard] + var poolKeys: Seq[String] = Seq() - shards.map(create(_)) - listeners.map(context.watch(_)) + override def preStart: Unit = { + listeners.map(context.watch(_)) + shards.map(self ! SetShard(_)) + } def receive = { case (key: ByteString, request: Request) ⇒ @@ -68,27 +89,28 @@ class ShardManager( shard forward Request(broadcast.command, broadcast.params: _*) } - case shard: Shard ⇒ - pool.get(shard.id) match { - case Some(client) ⇒ - create(shard) - context.stop(client) - + case SetShard(shard) ⇒ + pool.get(shard.id) map (context.stop(_)) + (shard, sentinel) match { + case (RedisShard(id, host, port, database, auth), _) ⇒ + val client = + context.actorOf(Brando(host, port, database, auth, listeners, + Some(connectionTimeout), Some(connectionRetryDelay), None, + connectionHeartbeatDelay)) + add(shard, client) + case (SentinelShard(id, database, auth), Some(sentinel)) ⇒ + val client = + context.actorOf(BrandoSentinel(id, sentinel, database, auth, + listeners, Some(connectionTimeout), Some(connectionRetryDelay), + connectionHeartbeatDelay)) + add(shard, client) case _ ⇒ - println("Update received for unknown shard ID " + shard.id + "\r\n") - } - - case stateChange: BrandoStateChange ⇒ - shardLookup.get(sender) match { - case Some(shard) ⇒ - listeners foreach { l ⇒ l ! ShardStateChange(shard, stateChange) } - case None ⇒ println("Update received for unknown shard actorRef " + sender + "\r\n") } case Terminated(l) ⇒ listeners = listeners - l - case x ⇒ println("ShardManager received unexpected " + x + "\r\n") + case _ ⇒ } def forward(key: ByteString, req: Request) = { @@ -103,9 +125,7 @@ class ShardManager( pool(id) } - def create(shard: Shard) { - val client = context.actorOf( - Brando(shard.host, shard.port, shard.database, shard.auth, Set(self))) + def add(shard: Shard, client: ActorRef) { shardLookup(client) = shard pool(shard.id) = client poolKeys = pool.keys.toIndexedSeq diff --git a/src/test/resources/application.conf b/src/test/resources/application.conf index 98ec50b..5c041ac 100644 --- a/src/test/resources/application.conf +++ b/src/test/resources/application.conf @@ -1 +1,4 @@ -brando.connection_attempts = 3 \ No newline at end of file +akka { + log-dead-letters = 0 + log-dead-letters-during-shutdown = off +} diff --git a/src/test/scala/BrandoSentinelTest.scala b/src/test/scala/BrandoSentinelTest.scala new file mode 100644 index 0000000..a68f1d9 --- /dev/null +++ b/src/test/scala/BrandoSentinelTest.scala @@ -0,0 +1,102 @@ +package brando + +import akka.actor._ +import akka.pattern._ +import akka.testkit._ + +import scala.concurrent._ +import scala.concurrent.duration._ + +import org.scalatest._ + +class BrandoSentinelTest extends TestKit(ActorSystem("SentinelTest")) with FunSpecLike + with ImplicitSender { + + import BrandoSentinel._ + import SentinelClient._ + import Connection._ + + describe("BrandoSentinel") { + describe("when connecting") { + it("should use sentinel to resolve the ip and port") { + val brandoProbe = TestProbe() + val sentinelProbe = TestProbe() + val brando = system.actorOf(BrandoSentinel("mymaster", sentinelProbe.ref, 0, None, Set(brandoProbe.ref))) + + sentinelProbe.expectMsg(Request("SENTINEL", "MASTER", "mymaster")) + } + + it("should connect to sentinel and redis") { + val brandoProbe = TestProbe() + val sentinelProbe = TestProbe() + val sentinel = system.actorOf(SentinelClient(Seq( + Sentinel("localhost", 26379)), Set(sentinelProbe.ref))) + val brando = system.actorOf(BrandoSentinel("mymaster", sentinel, 0, None, Set(brandoProbe.ref))) + + sentinelProbe.expectMsg( + Connecting("localhost", 26379)) + sentinelProbe.expectMsg( + Connected("localhost", 26379)) + brandoProbe.expectMsg( + Connecting("127.0.0.1", 6379)) + brandoProbe.expectMsg( + Connected("127.0.0.1", 6379)) + } + } + + describe("when disconnected") { + it("should recreate a connection using sentinel") { + val brandoProbe = TestProbe() + val sentinelProbe = TestProbe() + val sentinel = system.actorOf(SentinelClient(Seq( + Sentinel("localhost", 26379)), Set(sentinelProbe.ref))) + val brando = system.actorOf(BrandoSentinel("mymaster", sentinel, 0, None, Set(brandoProbe.ref))) + + sentinelProbe.expectMsg( + Connecting("localhost", 26379)) + sentinelProbe.expectMsg( + Connected("localhost", 26379)) + brandoProbe.expectMsg( + Connecting("127.0.0.1", 6379)) + brandoProbe.expectMsg( + Connected("127.0.0.1", 6379)) + + brando ! Disconnected("127.0.0.1", 6379) + + brandoProbe.expectMsg( + Disconnected("127.0.0.1", 6379)) + brandoProbe.expectMsg( + Connecting("127.0.0.1", 6379)) + brandoProbe.expectMsg( + Connected("127.0.0.1", 6379)) + } + + it("should stash requests") { + val brandoProbe = TestProbe() + val sentinelProbe = TestProbe() + val sentinel = system.actorOf(SentinelClient(Seq( + Sentinel("localhost", 26379)), Set(sentinelProbe.ref))) + val brando = system.actorOf(BrandoSentinel("mymaster", sentinel, 0, None, Set(brandoProbe.ref))) + + brandoProbe.expectMsg( + Connecting("127.0.0.1", 6379)) + brandoProbe.expectMsg( + Connected("127.0.0.1", 6379)) + + brando ! Disconnected("127.0.0.1", 6379) + brandoProbe.expectMsg( + Disconnected("127.0.0.1", 6379)) + + brando ! Request("PING") + + brandoProbe.expectMsg( + Connecting("127.0.0.1", 6379)) + brandoProbe.expectMsg( + Connected("127.0.0.1", 6379)) + + expectMsg(Some(Pong)) + } + } + } +} + diff --git a/src/test/scala/BrandoTest.scala b/src/test/scala/BrandoTest.scala index ab7429b..6c8a9db 100644 --- a/src/test/scala/BrandoTest.scala +++ b/src/test/scala/BrandoTest.scala @@ -9,10 +9,13 @@ import akka.util._ import scala.concurrent.Await import scala.concurrent.duration._ import java.util.UUID +import java.net.ServerSocket class BrandoTest extends TestKit(ActorSystem("BrandoTest")) with FunSpecLike with ImplicitSender { + import Connection._ + describe("ping") { it("should respond with Pong") { val brando = system.actorOf(Brando()) @@ -239,7 +242,7 @@ class BrandoTest extends TestKit(ActorSystem("BrandoTest")) with FunSpecLike describe("select") { it("should execute commands on the selected database") { - val brando = system.actorOf(Brando("localhost", 6379, Some(5))) + val brando = system.actorOf(Brando("localhost", 6379, 5)) brando ! Request("SET", "mykey", "somevalue") @@ -267,7 +270,7 @@ class BrandoTest extends TestKit(ActorSystem("BrandoTest")) with FunSpecLike describe("multi/exec requests") { it("should support multi requests as an atomic transaction") { - val brando = system.actorOf(Brando("localhost", 6379, Some(5))) + val brando = system.actorOf(Brando("localhost", 6379, 5)) brando ! Batch(Request("MULTI"), Request("SET", "mykey", "somevalue"), Request("GET", "mykey"), Request("EXEC")) expectMsg(List(Some(Ok), Some(Queued), @@ -276,7 +279,7 @@ class BrandoTest extends TestKit(ActorSystem("BrandoTest")) with FunSpecLike } it("should support multi requests with multiple results") { - val brando = system.actorOf(Brando("localhost", 6379, Some(5))) + val brando = system.actorOf(Brando("localhost", 6379, 5)) brando ! Batch(Request("MULTI"), Request("SET", "mykey", "somevalue"), Request("GET", "mykey"), Request("GET", "mykey"), Request("EXEC")) expectMsg(List(Some(Ok), Some(Queued), @@ -368,29 +371,40 @@ class BrandoTest extends TestKit(ActorSystem("BrandoTest")) with FunSpecLike } } - describe("State notifications") { - - it("should send an Authenticated event if connecting succeeds") { + describe("notifications") { + it("should send a Connected event if connecting succeeds") { val probe = TestProbe() val brando = system.actorOf(Brando("localhost", 6379, listeners = Set(probe.ref))) - probe.expectMsg(Connected) + probe.expectMsg(Connecting("localhost", 6379)) + probe.expectMsg(Connected("localhost", 6379)) } - it("should send an ConnectionFailed event if connecting fails after the configured number of retries") { + it("should send an ConnectionFailed event if connecting fails") { val probe = TestProbe() val brando = system.actorOf(Brando("localhost", 13579, listeners = Set(probe.ref))) - //3 retries * 2 seconds = 6 seconds - probe.expectNoMsg(5900.milliseconds) - probe.expectMsg(ConnectionFailed) + probe.expectMsg(Connecting("localhost", 13579)) + probe.expectMsg(ConnectionFailed("localhost", 13579)) } it("should send an AuthenticationFailed event if connecting succeeds but authentication fails") { val probe = TestProbe() val brando = system.actorOf(Brando("localhost", 6379, auth = Some("not-the-auth"), listeners = Set(probe.ref))) - probe.expectMsg(AuthenticationFailed) + probe.expectMsg(Connecting("localhost", 6379)) + probe.expectMsg(Brando.AuthenticationFailed("localhost", 6379)) + } + + it("should send a ConnectionFailed if redis is not responsive during connection") { + val serverSocket = new ServerSocket(0) + val port = serverSocket.getLocalPort() + + val probe = TestProbe() + val brando = system.actorOf(Brando("localhost", port, listeners = Set(probe.ref))) + + probe.expectMsg(Connecting("localhost", port)) + probe.expectMsg(ConnectionFailed("localhost", port)) } it("should send a notification to later added listener") { @@ -399,36 +413,59 @@ class BrandoTest extends TestKit(ActorSystem("BrandoTest")) with FunSpecLike val brando = system.actorOf(Brando("localhost", 13579, listeners = Set(probe2.ref))) brando ! probe.ref - //3 retries * 2 seconds = 6 seconds - probe.expectNoMsg(5900.milliseconds) - probe2.expectMsg(ConnectionFailed) - probe.expectMsg(ConnectionFailed) + probe2.expectMsg(Connecting("localhost", 13579)) + probe.expectMsg(Connecting("localhost", 13579)) + probe2.expectMsg(ConnectionFailed("localhost", 13579)) + probe.expectMsg(ConnectionFailed("localhost", 13579)) } } - describe("Connection") { - it("should keep retrying to connect if brando.connection_attempts is not defined") { - val socket = TestProbe() - val brando = TestProbe() - val address = new java.net.InetSocketAddress("test.com", 16379) - val connection = TestActorRef(new Connection(brando.ref, address, 1000000, None, 1.seconds)) + describe("connection") { + import Connection._ + it("should try to reconnect if connectionRetryDelay and connectionRetryAttempts are defined") { + val listener = TestProbe() + val brando = TestActorRef(new Brando( + "localhost", 6379, 0, None, Set(listener.ref), 2.seconds, Some(1.seconds), Some(1), None)) - for (i ← 1 to 10) { - connection ! Tcp.CommandFailed(Tcp.Connect(address)) - assert(connection.underlyingActor.connectionAttempts === i) - } - brando.expectNoMsg + listener.expectMsg(Connecting("localhost", 6379)) + assert(brando.underlyingActor.retries === 0) + listener.expectMsg(Connected("localhost", 6379)) + assert(brando.underlyingActor.retries === 0) + + brando ! Disconnected("localhost", 6379) + + listener.expectMsg(Disconnected("localhost", 6379)) + listener.expectMsg(Connecting("localhost", 6379)) + } + + it("should not try to reconnect if connectionRetryDelay and connectionRetryAttempts are not defined") { + val listener = TestProbe() + val brando = TestActorRef(new Brando( + "localhost", 6379, 0, None, Set(listener.ref), 2.seconds, None, None, None)) + + listener.expectMsg(Connecting("localhost", 6379)) + listener.expectMsg(Connected("localhost", 6379)) + + brando ! Disconnected("localhost", 6379) + + listener.expectMsg(Disconnected("localhost", 6379)) + listener.expectNoMsg } - it("should stop retrying to connect and timeout once brando.connection_attempts is reached") { - val socket = TestProbe() - val brando = TestProbe() - val address = new java.net.InetSocketAddress("test.com", 16379) - val connection = TestActorRef(new Connection(brando.ref, address, 10, Some(1), 1.seconds)) + it("should not try to reconnect once the max retry attempts is reached") { + val listener = TestProbe() + val brando = TestActorRef(new Brando( + "localhost", 16379, 0, None, Set(listener.ref), 2.seconds, Some(1.seconds), Some(1), None)) + + listener.expectMsg(Connecting("localhost", 16379)) + assert(brando.underlyingActor.retries === 0) + listener.expectMsg(ConnectionFailed("localhost", 16379)) + + listener.expectMsg(Connecting("localhost", 16379)) + assert(brando.underlyingActor.retries === 1) + listener.expectMsg(ConnectionFailed("localhost", 16379)) - connection ! Tcp.CommandFailed(Tcp.Connect(address)) - assert(connection.underlyingActor.connectionAttempts === 1) - brando.expectMsg(ConnectionFailed) + listener.expectNoMsg } } } diff --git a/src/test/scala/HealthMonitorTest.scala b/src/test/scala/HealthMonitorTest.scala deleted file mode 100644 index 6888504..0000000 --- a/src/test/scala/HealthMonitorTest.scala +++ /dev/null @@ -1,66 +0,0 @@ -package brando - -import org.scalatest.{ FunSpecLike, BeforeAndAfterAll } -import akka.testkit._ -import akka.actor._ -import scala.concurrent.duration._ -import akka.util.ByteString -import collection.mutable - -class TestHealthMonitor(responder: ActorRef, listeners: Set[ActorRef]) - extends ShardManager(Seq(), ShardManager.defaultHashFunction, listeners) - with HealthMonitor { - - val shard = Shard("1", "localhost", 6379) - - override val healthCheckRate = 500.milliseconds - - override val pool = mutable.Map("1" -> responder) - override val shardLookup = mutable.Map(responder -> shard) -} - -class HealthMonitorTest extends TestKit(ActorSystem("HealthMonitorTest")) - with FunSpecLike with BeforeAndAfterAll { - - override def afterAll { system.shutdown() } - - describe("the health monitor") { - - it("should send pings to the redis shard") { - val probe = TestProbe() - - val manager = TestActorRef(new TestHealthMonitor(probe.ref, Set())) - - probe.expectMsg(Request("PING")) - probe.expectMsg(Request("PING")) - manager ! PoisonPill - } - - it("should cleaned up any dead listeners") { - - val probe1 = TestProbe() - val probe2 = TestProbe() - - val brando = TestActorRef(new Brando("localhost", 6379, None, None, listeners = Set(probe1.ref, probe2.ref))).underlyingActor - assertResult(2)(brando.listeners.size) - - probe1.ref ! PoisonPill - probe2.expectMsg(Connected) - - assertResult(1)(brando.listeners.size) - - } - - it("should restart the shard, and notify, when healthcheck fails") { - val probe = TestProbe() - val listener = TestProbe() - - val manager = TestActorRef(new TestHealthMonitor(probe.ref, Set(listener.ref))) - - val shard = manager.underlyingActor.shard - - listener.expectMsg(ShardStateChange(shard, NonRespondingShardRestarted)) - manager ! PoisonPill - } - } -} diff --git a/src/test/scala/SentinelClientTest.scala b/src/test/scala/SentinelClientTest.scala new file mode 100644 index 0000000..0b7cfdc --- /dev/null +++ b/src/test/scala/SentinelClientTest.scala @@ -0,0 +1,122 @@ +package brando + +import akka.actor._ +import akka.pattern._ +import akka.testkit._ + +import scala.concurrent._ +import scala.concurrent.duration._ + +import org.scalatest._ + +class SentinelClientTest extends TestKit(ActorSystem("SentinelTest")) with FunSpecLike + with ImplicitSender { + + import SentinelClient._ + import Connection._ + + describe("SentinelClient") { + describe("connection to sentinel instances") { + it("should connect to the first working sentinel instance") { + val probe = TestProbe() + val sentinel = system.actorOf(SentinelClient(Seq( + Sentinel("wrong-host", 26379), + Sentinel("localhost", 26379)), Set(probe.ref))) + + probe.expectMsg(Connecting("wrong-host", 26379)) + probe.expectMsg(Connecting("localhost", 26379)) + probe.expectMsg(Connected("localhost", 26379)) + } + + it("should send a notification to the listeners when connecting") { + val probe = TestProbe() + val sentinel = system.actorOf(SentinelClient(Seq( + Sentinel("localhost", 26379)), + Set(probe.ref))) + + probe.expectMsg(Connecting("localhost", 26379)) + } + + it("should send a notification to the listeners when connected") { + val probe = TestProbe() + val sentinel = system.actorOf(SentinelClient(Seq( + Sentinel("localhost", 26379)), Set(probe.ref))) + + probe.receiveN(1) + probe.expectMsg(Connected("localhost", 26379)) + } + + it("should send a notification to the listeners when disconnected") { + val probe = TestProbe() + val sentinel = system.actorOf(SentinelClient(Seq( + Sentinel("localhost", 26379)), Set(probe.ref))) + + probe.receiveN(1) + probe.expectMsg(Connected("localhost", 26379)) + + sentinel ! Disconnected("localhost", 26379) + + probe.expectMsg(Disconnected("localhost", 26379)) + } + + it("should send a notification to the listeners for connection failure") { + val probe = TestProbe() + val sentinels = Seq(Sentinel("wrong-host", 26379)) + val sentinel = system.actorOf(SentinelClient(sentinels, Set(probe.ref))) + + probe.receiveN(1) + probe.expectMsg(SentinelClient.ConnectionFailed(sentinels)) + } + + it("should make sure the working instance will be tried first next reconnection") { + val probe = TestProbe() + val sentinel = system.actorOf(SentinelClient(Seq( + Sentinel("wrong-host", 26379), + Sentinel("localhost", 26379)), Set(probe.ref))) + + probe.expectMsg(Connecting("wrong-host", 26379)) + probe.expectMsg(Connecting("localhost", 26379)) + probe.expectMsg(Connected("localhost", 26379)) + + sentinel ! Disconnected("localhost", 26379) + + probe.expectMsg(Disconnected("localhost", 26379)) + + probe.expectMsg(Connecting("localhost", 26379)) + } + + it("should send a notification to the listeners if it can't connect to any instance") { + val probe = TestProbe() + val sentinels = Seq( + Sentinel("wrong-host-1", 26379), + Sentinel("wrong-host-2", 26379)) + val sentinel = system.actorOf(SentinelClient(sentinels.reverse, Set(probe.ref))) + + probe.receiveN(2) + probe.expectMsg(SentinelClient.ConnectionFailed(sentinels)) + } + } + + describe("Request") { + it("should stash requests when disconnected") { + val probe = TestProbe() + val sentinel = system.actorOf(SentinelClient(Seq( + Sentinel("localhost", 26379)), Set(probe.ref))) + + probe.expectMsg(Connecting("localhost", 26379)) + probe.expectMsg(Connected("localhost", 26379)) + + sentinel ! Disconnected("localhost", 26379) + probe.expectMsg(Disconnected("localhost", 26379)) + + sentinel ! Request("PING") + + probe.expectMsg(Connecting("localhost", 26379)) + probe.expectMsg(Connected("localhost", 26379)) + + expectMsg(Some(Pong)) + } + } + } +} + diff --git a/src/test/scala/ShardManagerTest.scala b/src/test/scala/ShardManagerTest.scala index 84c90f5..225689f 100644 --- a/src/test/scala/ShardManagerTest.scala +++ b/src/test/scala/ShardManagerTest.scala @@ -11,46 +11,71 @@ import scala.util.Failure class ShardManagerTest extends TestKit(ActorSystem("ShardManagerTest")) with FunSpecLike with ImplicitSender { + import ShardManager._ + import Connection._ + describe("creating shards") { it("should create a pool of clients mapped to ids") { val shards = Seq( - Shard("server1", "localhost", 6379, Some(0)), - Shard("server2", "localhost", 6379, Some(1)), - Shard("server3", "localhost", 6379, Some(2))) + RedisShard("server1", "localhost", 6379, 0), + RedisShard("server2", "localhost", 6379, 1), + RedisShard("server3", "localhost", 6379, 2)) - val shardManager = TestActorRef(new ShardManager(shards, ShardManager.defaultHashFunction)) + val shardManager = TestActorRef[ShardManager](ShardManager( + shards)) assert(shardManager.underlyingActor.pool.keys === Set("server1", "server2", "server3")) } it("should support updating existing shards but not creating new ones") { val shards = Seq( - Shard("server1", "localhost", 6379, Some(0)), - Shard("server2", "localhost", 6379, Some(1)), - Shard("server3", "localhost", 6379, Some(2))) + RedisShard("server1", "localhost", 6379, 0), + RedisShard("server2", "localhost", 6379, 1), + RedisShard("server3", "localhost", 6379, 2)) - val shardManager = TestActorRef(new ShardManager(shards, ShardManager.defaultHashFunction)) + val shardManager = TestActorRef[ShardManager](ShardManager( + shards)) assert(shardManager.underlyingActor.pool.keys === Set("server1", "server2", "server3")) - shardManager ! Shard("server1", "localhost", 6379, Some(6)) + shardManager ! RedisShard("server1", "localhost", 6379, 6) assert(shardManager.underlyingActor.pool.keys === Set("server1", "server2", "server3")) - shardManager ! Shard("new_server", "localhost", 6378, Some(3)) + shardManager ! RedisShard("new_server", "localhost", 6378, 3) assert(shardManager.underlyingActor.pool.keys === Set("server1", "server2", "server3")) } } describe("sending requests") { + describe("using sentinel") { + it("should forward each request to the appropriate client transparently") { + val shards = Seq( + SentinelShard("mymaster", 0)) + + val sentinel = system.actorOf(SentinelClient()) + val shardManager = TestActorRef[ShardManager](ShardManager( + shards, Set(), Some(sentinel))) + + shardManager ! ("key", Request("SET", "shard_manager_test", "some value")) + + expectMsg(Some(Ok)) + + shardManager ! ("key", Request("GET", "shard_manager_test")) + + expectMsg(Some(ByteString("some value"))) + } + } + it("should forward each request to the appropriate client transparently") { val shards = Seq( - Shard("server1", "localhost", 6379, Some(0)), - Shard("server2", "localhost", 6379, Some(1)), - Shard("server3", "localhost", 6379, Some(2))) + RedisShard("server1", "localhost", 6379, 0), + RedisShard("server2", "localhost", 6379, 1), + RedisShard("server3", "localhost", 6379, 2)) - val shardManager = TestActorRef(new ShardManager(shards, ShardManager.defaultHashFunction)) + val shardManager = TestActorRef[ShardManager](ShardManager( + shards)) shardManager ! ("key", Request("SET", "shard_manager_test", "some value")) @@ -63,11 +88,12 @@ class ShardManagerTest extends TestKit(ActorSystem("ShardManagerTest")) it("should infer the key from the params list") { val shards = Seq( - Shard("server1", "localhost", 6379, Some(0)), - Shard("server2", "localhost", 6379, Some(1)), - Shard("server3", "localhost", 6379, Some(2))) + RedisShard("server1", "localhost", 6379, 0), + RedisShard("server2", "localhost", 6379, 1), + RedisShard("server3", "localhost", 6379, 2)) - val shardManager = TestActorRef(new ShardManager(shards, ShardManager.defaultHashFunction)) + val shardManager = TestActorRef[ShardManager](ShardManager( + shards)) shardManager ! Request("SET", "shard_manager_test", "some value") @@ -80,11 +106,12 @@ class ShardManagerTest extends TestKit(ActorSystem("ShardManagerTest")) it("should fail with IllegalArgumentException when params is empty") { val shards = Seq( - Shard("server1", "localhost", 6379, Some(0)), - Shard("server2", "localhost", 6379, Some(1)), - Shard("server3", "localhost", 6379, Some(2))) + RedisShard("server1", "localhost", 6379, 0), + RedisShard("server2", "localhost", 6379, 1), + RedisShard("server3", "localhost", 6379, 2)) - val shardManager = TestActorRef(new ShardManager(shards, ShardManager.defaultHashFunction)) + val shardManager = TestActorRef[ShardManager](ShardManager( + shards)) shardManager ! Request("SET") @@ -93,11 +120,12 @@ class ShardManagerTest extends TestKit(ActorSystem("ShardManagerTest")) it("should broadcast a Request to all shards") { val shards = Seq( - Shard("server1", "localhost", 6379, Some(0)), - Shard("server2", "localhost", 6379, Some(1)), - Shard("server3", "localhost", 6379, Some(2))) + RedisShard("server1", "localhost", 6379, 0), + RedisShard("server2", "localhost", 6379, 1), + RedisShard("server3", "localhost", 6379, 2)) - val shardManager = TestActorRef(new ShardManager(shards, ShardManager.defaultHashFunction)) + val shardManager = TestActorRef[ShardManager](ShardManager( + shards)) val listName = scala.util.Random.nextString(5) @@ -112,45 +140,47 @@ class ShardManagerTest extends TestKit(ActorSystem("ShardManagerTest")) } describe("Listening to Shard state changes") { - it("should notify listeners when a shard connect successfully") { - val shards = Seq(Shard("server1", "localhost", 6379, Some(0))) + val shards = Seq(RedisShard("server1", "localhost", 6379, 0)) val probe = TestProbe() - val shardManager = TestActorRef(new ShardManager(shards, ShardManager.defaultHashFunction, Set(probe.ref))) + val shardManager = TestActorRef[ShardManager](ShardManager( + shards, Set(probe.ref))) - probe.expectMsg(ShardStateChange(shards(0), Connected)) + probe.expectMsg(Connecting("localhost", 6379)) + probe.expectMsg(Connected("localhost", 6379)) } it("should notify listeners when a shard fails to connect") { val shards = Seq( - Shard("server1", "localhost", 6379, Some(0)), - Shard("server2", "localhost", 13579, Some(1))) + RedisShard("server2", "localhost", 13579, 1)) val probe = TestProbe() - val shardManager = TestActorRef(new ShardManager(shards, ShardManager.defaultHashFunction, Set(probe.ref))) + val shardManager = TestActorRef[ShardManager](ShardManager( + shards, Set(probe.ref))) - probe.expectMsg(ShardStateChange(shards(0), Connected)) - probe.expectNoMsg(5900.milliseconds) - probe.expectMsg(ShardStateChange(shards(1), ConnectionFailed)) + probe.expectMsg(Connecting("localhost", 13579)) + probe.expectMsg(ConnectionFailed("localhost", 13579)) } it("should cleaned up any dead listeners") { val shards = Seq( - Shard("server1", "localhost", 6379, Some(0)), - Shard("server2", "localhost", 13579, Some(1))) + RedisShard("server1", "localhost", 6379, 0)) val probe1 = TestProbe() val probe2 = TestProbe() - val shardManager = TestActorRef(new ShardManager(shards, ShardManager.defaultHashFunction, Set(probe1.ref, probe2.ref))).underlyingActor + val shardManager = TestActorRef[ShardManager](ShardManager( + shards, Set(probe1.ref, probe2.ref))).underlyingActor assertResult(2)(shardManager.listeners.size) probe1.ref ! PoisonPill - probe2.expectMsg(ShardStateChange(shards(0), Connected)) + + probe2.expectMsg(Connecting("localhost", 6379)) + probe2.expectMsg(Connected("localhost", 6379)) assertResult(1)(shardManager.listeners.size) @@ -158,15 +188,18 @@ class ShardManagerTest extends TestKit(ActorSystem("ShardManagerTest")) it("should notify listeners when a shard fails to authenticate") { val shards = Seq( - Shard("server1", "localhost", 6379, Some(0)), - Shard("server2", "localhost", 6379, Some(1), auth = Some("not-valid-auth"))) + RedisShard("server1", "localhost", 6379, 0), + RedisShard("server2", "localhost", 6379, 1, auth = Some("not-valid-auth"))) val probe = TestProbe() - val shardManager = TestActorRef(new ShardManager(shards, ShardManager.defaultHashFunction, Set(probe.ref))) + val shardManager = TestActorRef[ShardManager](ShardManager( + shards, Set(probe.ref))) - probe.expectMsg(ShardStateChange(shards(0), Connected)) - probe.expectMsg(ShardStateChange(shards(1), AuthenticationFailed)) + probe.expectMsg(Connecting("localhost", 6379)) + probe.expectMsg(Connecting("localhost", 6379)) + probe.expectMsg(Connected("localhost", 6379)) + probe.expectMsg(Brando.AuthenticationFailed("localhost", 6379)) } } } From 2413a0e937f7064d57af75526bf982360cb98b40 Mon Sep 17 00:00:00 2001 From: Damien Levin Date: Wed, 15 Apr 2015 22:40:48 -0400 Subject: [PATCH 2/3] API update Added pub/sub test for SentinelClient Renamed Brando -> Redis ; BrandoSentinel -> RedisSentinel --- .travis.yml | 11 +-- README.md | 55 ++++++----- build.sbt | 2 + src/main/scala/Connection.scala | 2 +- src/main/scala/{Brando.scala => Redis.scala} | 14 ++- ....scala => RedisConnectionSupervisor.scala} | 4 +- ...andoSentinel.scala => RedisSentinel.scala} | 24 ++--- src/main/scala/ReplyParser.scala | 2 +- src/main/scala/Response.scala | 2 +- .../{SentinelClient.scala => Sentinel.scala} | 23 +++-- src/main/scala/ShardManager.scala | 40 ++++---- ...inelTest.scala => RedisSentinelTest.scala} | 75 +++++++++------ .../{BrandoTest.scala => RedisTest.scala} | 92 ++++++++++--------- ...nelClientTest.scala => SentinelTest.scala} | 78 +++++++++++----- src/test/scala/ShardManagerTest.scala | 19 ++-- .../redis-slave.conf | 2 +- {redis-config => test-config}/redis.conf | 0 {redis-config => test-config}/sentinel.conf | 0 18 files changed, 247 insertions(+), 198 deletions(-) rename src/main/scala/{Brando.scala => Redis.scala} (90%) rename src/main/scala/{ConnectionSupervisor.scala => RedisConnectionSupervisor.scala} (94%) rename src/main/scala/{BrandoSentinel.scala => RedisSentinel.scala} (85%) rename src/main/scala/{SentinelClient.scala => Sentinel.scala} (81%) rename src/test/scala/{BrandoSentinelTest.scala => RedisSentinelTest.scala} (50%) rename src/test/scala/{BrandoTest.scala => RedisTest.scala} (82%) rename src/test/scala/{SentinelClientTest.scala => SentinelTest.scala} (54%) rename {redis-config => test-config}/redis-slave.conf (99%) rename {redis-config => test-config}/redis.conf (100%) rename {redis-config => test-config}/sentinel.conf (100%) diff --git a/.travis.yml b/.travis.yml index dfda515..a09a650 100644 --- a/.travis.yml +++ b/.travis.yml @@ -6,13 +6,10 @@ cache: directories: - $HOME/.ivy2 before_script: - - sudo redis-server `pwd`/redis-config/sentinel.conf --sentinel & - - sleep 15 - - sudo redis-server `pwd`/redis-config/redis.conf --loglevel verbose - - sleep 15 + - sudo redis-server `pwd`/test-config/sentinel.conf --sentinel & + - sudo redis-server `pwd`/test-config/redis.conf --loglevel verbose - sudo mkdir /var/lib/redis-slave - - sudo redis-server `pwd`/redis-config/redis-slave.conf --loglevel verbose - - sleep 15 + - sudo redis-server `pwd`/test-config/redis-slave.conf --loglevel verbose - cat /var/log/redis/redis-slave-server.log - cat /var/log/redis/redis-server.log - + - sleep 5 diff --git a/README.md b/README.md index 0e7d53e..4154013 100644 --- a/README.md +++ b/README.md @@ -17,17 +17,17 @@ In your build.sbt Brando is a lightweight wrapper around the [Redis protocol](http://redis.io/topics/protocol). -Create a Brando actor with your server host and port. +Create a Redis actor with your server host and port. import brando._ - val redis = system.actorOf(Brando("localhost", 6379)) + val redis = system.actorOf(Redis("localhost", 6379)) You should specify a database and password if you intend to use them. - val redis = system.actorOf(Brando("localhost", 6379, database = 5, auth = "password")) + val redis = system.actorOf(Redis("localhost", 6379, database = 5, auth = "password")) -This is important; if your Brando actor restarts you want be sure it reconnects successfully and to the same database. +This is important; if your Redis actor restarts you want be sure it reconnects successfully and to the same database. Next, send it a command and get your response as a reply. @@ -47,7 +47,7 @@ Error replies are returned as `akka.actor.Status.Failure` objects containing an redis ! Request("EXPIRE", "1", "key") - // Response: Failure(brando.BrandoException: ERR value is not an integer or out of range) + // Response: Failure(brando.RedisException: ERR value is not an integer or out of range) Integer replies are returned as `Option[Long]`. @@ -75,7 +75,7 @@ NULL replies are returned as `None` and may appear either on their own or nested If you're not sure what to expect in response to a request, please refer to the Redis command documentation at [http://redis.io/commands](http://redis.io/commands) where the reply type for each is clearly stated. -To ensure that a list of requests are executed back to back, the brando actor can receive the following message : +To ensure that a list of requests are executed back to back, the Redis actor can receive the following message : redis ! Batch(Request("MULTI"), Request("SET", "mykey", "somevalue"), Request("GET", "mykey"), Request("EXEC")) @@ -106,32 +106,32 @@ Use the provided response extractors to map your Redis reply to a more appropria ### Monitoring Connection State Changes -If a set of listeners is provided to the Brando actor when it is created , it will inform the those listeners about state changes to the underlying Redis connection. For example (from inside an actor): +If a set of listeners is provided to the Redis actor when it is created , it will inform the those listeners about state changes to the underlying Redis connection. For example (from inside an actor): - val redis = context.actorOf(Brando("localhost", 6379, listeners = Set(self))) + val redis = context.actorOf(Redis("localhost", 6379, listeners = Set(self))) Currently, the possible messages sent to each listener include the following: * `Connecting`: When creating a TCP connection. * `Connected`: When a TCP connection has been created, and Authentication (if applicable) has succeeded. - * `Disconnected`: The connection has been lost. Brando transparently handles disconnects and will automatically reconnect, so typically no user action at all is needed here. During the time that Brando is disconnected, Redis commands sent to Brando will be queued, and will be processed when a connection is established. + * `Disconnected`: The connection has been lost. Redis transparently handles disconnects and will automatically reconnect, so typically no user action at all is needed here. During the time that Redis is disconnected, Redis commands sent will be queued be processed once the connection is reestablished. * `AuthenticationFailed`: The TCP connected was made, but Redis auth failed. - * `ConnectionFailed`: A connection could not be (re-) established after three attempts. Brando will not attempt to recover from this state; the user should take action. + * `ConnectionFailed`: A connection could not be established after the number of attempts defined during creation `connectionRetryAttempts`. Brando will not attempt to recover from this state; the user should take action. All these messages inherit from the `Connection.StateChange` trait. ### Sentinel -#### SentinelClient +#### Sentinel Client -Brando provides support for `monitoring`, `notification` and `automatic failover` using [sentinel](http://redis.io/topics/sentinel). It is implemented based on the following [guidelines](http://redis.io/topics/sentinel-clients) +Sentinel provides support for `monitoring`, `notification` and `automatic failover` using [sentinel](http://redis.io/topics/sentinel). It is implemented based on the following [guidelines](http://redis.io/topics/sentinel-clients) and requires redis 2.8.12 or later. -A sentinel client can be created like this. Here, we are using two instances and we provide a listener to receive `Connection.StateChange` events. +A sentinel client can be created like this. Here, we are using two servers and we provide a listener to receive `Connection.StateChange` events. - val sentinel = system.actorOf(SentinelClient(Seq( - Instance("localhost", 26380), - Instance("localhost", 26379)), Set(probe.ref))) + val sentinel = system.actorOf(Sentinel(Seq( + Server("localhost", 26380), + Server("localhost", 26379)), Set(probe.ref))) You can listen for events using the following: @@ -142,25 +142,25 @@ You can also send commands such as sentinel ! Request("SENTINEL", "MASTERS") -#### BrandoSentinel +#### Redis with Sentinel -Brando can be used with Sentinel to provide automatic failover and discovery. To do so you need to create a `SentinelClient` and `BrandoSentinel`. In this example we are connecting to the master `mymaster` +Redis can be used with Sentinel to provide automatic failover and discovery. To do so you need to create a `Sentinel` and a `RedisSentinel` actor. In this example we are connecting to the master `mymaster` - val sentinel = system.actorOf(SentinelClient(Seq( - Instance("localhost", 26380), - Instance("localhost", 26379)))) + val sentinel = system.actorOf(Sentinel(Seq( + Server("localhost", 26380), + Server("localhost", 26379)))) - val redis = system.actorOf(BrandoSentinel("mymaster", sentinel)) + val redis = system.actorOf(RedisSentinel("mymaster", sentinel)) redis ! Request("PING") -For reliability we encourage to pass `connectionHeartbeatDelay` when using BrandoSentinel, this will generate a heartbeat to Redis and will improve failures detections in the case of network partitions. +For reliability we encourage to pass `connectionHeartbeatDelay` when using RedisSentinel, this will generate a heartbeat to Redis and will improve failures detections in the case of network partitions. ### Sharding Brando provides support for sharding, as outlined [in the Redis documentation](http://redis.io/topics/partitioning) and in [this blog post from antirez](http://oldblog.antirez.com/post/redis-presharding.html). -To use it, simply create an instance of `ShardManager`, passing it a list of Redis shards you'd like it to connect to. From there, we create a pool of `Brando` instances - one for each shard. +To use it, simply create an instance of `ShardManager`, passing it a list of Redis shards you'd like it to connect to. From there, we create a pool of `Redis` instances - one for each shard. val shards = Seq(RedisShard("redis1", "10.0.0.1", 6379), RedisShard("redis2", "10.0.0.2", 6379), @@ -200,11 +200,10 @@ It's possible to use sharding with Sentinel, to do so you need to use `SentinelS SentinelShard("mymaster1"), SentinelShard("mymaster2")) - val sentinel = system.actorOf(SentinelClient()) + val sentinel = system.actorOf(Sentinel()) //defaults host and port are localhost:26379 val shardManager = context.actorOf(ShardManager(shards,sentinel)) - ## Run the tests * Start sentinel @@ -213,9 +212,9 @@ It's possible to use sharding with Sentinel, to do so you need to use `SentinelS * Start a Redis master and slave - sudo redis-server redis-config/redis.conf --loglevel verbose + sudo redis-server test-config/redis.conf --loglevel verbose sudo mkdir /var/lib/redis-slave - sudo redis-server redis-config/redis-slave.conf --loglevel verbose + sudo redis-server test-config/redis-slave.conf --loglevel verbose * Run the tests diff --git a/build.sbt b/build.sbt index 4ca13f5..a92e8cf 100644 --- a/build.sbt +++ b/build.sbt @@ -16,6 +16,8 @@ libraryDependencies ++= Seq( "com.typesafe.akka" %% "akka-testkit" % "2.3.9" % "test" ) +parallelExecution in Test := false + resolvers += "Typesafe Repository" at "http://repo.typesafe.com/typesafe/releases/" publishTo <<= version { (v: String) => diff --git a/src/main/scala/Connection.scala b/src/main/scala/Connection.scala index a9e0eea..adb407b 100644 --- a/src/main/scala/Connection.scala +++ b/src/main/scala/Connection.scala @@ -56,7 +56,7 @@ private[brando] class Connection( case batch: Batch ⇒ val requester = sender - val batcher = actor(sender.path.name + "-batcher")(new Act { + val batcher = actor(new Act { var responses = List[Any]() become { case response if (responses.size + 1) < batch.requests.size ⇒ diff --git a/src/main/scala/Brando.scala b/src/main/scala/Redis.scala similarity index 90% rename from src/main/scala/Brando.scala rename to src/main/scala/Redis.scala index 85e27ed..05f5bfa 100644 --- a/src/main/scala/Brando.scala +++ b/src/main/scala/Redis.scala @@ -7,11 +7,10 @@ import scala.concurrent.duration._ import com.typesafe.config.ConfigFactory import java.util.concurrent.TimeUnit -object Brando { - def apply(): Props = apply("localhost", 6379) +object Redis { def apply( - host: String, - port: Int, + host: String = "localhost", + port: Int = 6379, database: Int = 0, auth: Option[String] = None, listeners: Set[ActorRef] = Set(), @@ -21,7 +20,7 @@ object Brando { connectionHeartbeatDelay: Option[FiniteDuration] = None): Props = { val config = ConfigFactory.load() - Props(classOf[Brando], + Props(classOf[Redis], host, port, database, @@ -38,7 +37,7 @@ object Brando { case class AuthenticationFailed(host: String, port: Int) extends Connection.StateChange } -class Brando( +class Redis( host: String, port: Int, database: Int, @@ -47,7 +46,7 @@ class Brando( connectionTimeout: FiniteDuration, connectionRetryDelay: Option[FiniteDuration], connectionRetryAttempts: Option[Int], - connectionHeartbeatDelay: Option[FiniteDuration]) extends ConnectionSupervisor( + connectionHeartbeatDelay: Option[FiniteDuration]) extends RedisConnectionSupervisor( database, auth, listeners, connectionTimeout, connectionHeartbeatDelay) { import ConnectionSupervisor.{ Connect, Reconnect } @@ -76,7 +75,6 @@ class Brando( retries += 1 context.system.scheduler.scheduleOnce(delay, connection, Connection.Connect) case (Some(delay), None) ⇒ - retries += 1 context.system.scheduler.scheduleOnce(delay, connection, Connection.Connect) case _ ⇒ } diff --git a/src/main/scala/ConnectionSupervisor.scala b/src/main/scala/RedisConnectionSupervisor.scala similarity index 94% rename from src/main/scala/ConnectionSupervisor.scala rename to src/main/scala/RedisConnectionSupervisor.scala index ca65b0c..4e4d7d9 100644 --- a/src/main/scala/ConnectionSupervisor.scala +++ b/src/main/scala/RedisConnectionSupervisor.scala @@ -12,7 +12,7 @@ object ConnectionSupervisor { private[brando] case object Reconnect } -private[brando] abstract class ConnectionSupervisor( +private[brando] abstract class RedisConnectionSupervisor( database: Int, auth: Option[String], var listeners: Set[ActorRef], @@ -91,7 +91,7 @@ private[brando] abstract class ConnectionSupervisor( self ! _ } onFailure { case e: Exception ⇒ - notifyStateChange(Brando.AuthenticationFailed(x.host, x.port)) + notifyStateChange(Redis.AuthenticationFailed(x.host, x.port)) } } } diff --git a/src/main/scala/BrandoSentinel.scala b/src/main/scala/RedisSentinel.scala similarity index 85% rename from src/main/scala/BrandoSentinel.scala rename to src/main/scala/RedisSentinel.scala index d6bdc10..b3baa50 100644 --- a/src/main/scala/BrandoSentinel.scala +++ b/src/main/scala/RedisSentinel.scala @@ -10,10 +10,10 @@ import scala.concurrent.duration._ import com.typesafe.config.ConfigFactory import java.util.concurrent.TimeUnit -object BrandoSentinel { +object RedisSentinel { def apply( - name: String, - sentinel: ActorRef, + master: String, + sentinelClient: ActorRef, database: Int = 0, auth: Option[String] = None, listeners: Set[ActorRef] = Set(), @@ -22,9 +22,9 @@ object BrandoSentinel { connectionHeartbeatDelay: Option[FiniteDuration] = None): Props = { val config = ConfigFactory.load() - Props(classOf[BrandoSentinel], - name, - sentinel, + Props(classOf[RedisSentinel], + master, + sentinelClient, database, auth, listeners, @@ -38,18 +38,18 @@ object BrandoSentinel { private[brando] case object SentinelConnect } -class BrandoSentinel( - name: String, - sentinel: ActorRef, +class RedisSentinel( + master: String, + sentinelClient: ActorRef, database: Int, auth: Option[String], listeners: Set[ActorRef], connectionTimeout: FiniteDuration, connectionRetryDelay: FiniteDuration, - connectionHeartbeatDelay: Option[FiniteDuration]) extends ConnectionSupervisor(database, auth, + connectionHeartbeatDelay: Option[FiniteDuration]) extends RedisConnectionSupervisor(database, auth, listeners, connectionTimeout, connectionHeartbeatDelay) { - import BrandoSentinel._ + import RedisSentinel._ import ConnectionSupervisor.{ Connect, Reconnect } import context.dispatcher @@ -66,7 +66,7 @@ class BrandoSentinel( context.system.scheduler.scheduleOnce(connectionRetryDelay, self, SentinelConnect) case SentinelConnect ⇒ - (sentinel ? Request("SENTINEL", "MASTER", name)) map { + (sentinelClient ? Request("SENTINEL", "MASTER", master)) map { case Response.AsStrings(res) ⇒ val (ip, port) = extractIpPort(res) self ! Connect(ip, port) diff --git a/src/main/scala/ReplyParser.scala b/src/main/scala/ReplyParser.scala index 55b372d..61021a6 100644 --- a/src/main/scala/ReplyParser.scala +++ b/src/main/scala/ReplyParser.scala @@ -65,7 +65,7 @@ private[brando] trait ReplyParser { def readErrorReply(buffer: ByteString) = splitLine(buffer) match { case Some((error, rest)) ⇒ - Success(Some(Status.Failure(new BrandoException(error))), rest) + Success(Some(Status.Failure(new RedisException(error))), rest) case _ ⇒ Failure(buffer) } diff --git a/src/main/scala/Response.scala b/src/main/scala/Response.scala index c2b630d..0248aad 100644 --- a/src/main/scala/Response.scala +++ b/src/main/scala/Response.scala @@ -4,7 +4,7 @@ import akka.util.ByteString case class PubSubMessage(channel: String, message: String) -class BrandoException(message: String) extends Exception(message) { +class RedisException(message: String) extends Exception(message) { override lazy val toString = "%s: %s\n".format(getClass.getName, message) } diff --git a/src/main/scala/SentinelClient.scala b/src/main/scala/Sentinel.scala similarity index 81% rename from src/main/scala/SentinelClient.scala rename to src/main/scala/Sentinel.scala index 8b6aca0..ae09eb7 100644 --- a/src/main/scala/SentinelClient.scala +++ b/src/main/scala/Sentinel.scala @@ -10,33 +10,32 @@ import scala.concurrent.duration._ import com.typesafe.config.ConfigFactory import java.util.concurrent.TimeUnit -object SentinelClient { - def apply(): Props = apply(Seq(Sentinel("localhost", 26379))) +object Sentinel { def apply( - instances: Seq[Sentinel], + sentinels: Seq[Server] = Seq(Server("localhost", 26379)), listeners: Set[ActorRef] = Set(), connectionTimeout: Option[FiniteDuration] = None, connectionHeartbeatDelay: Option[FiniteDuration] = None): Props = { val config = ConfigFactory.load() - Props(classOf[SentinelClient], instances, listeners, + Props(classOf[Sentinel], sentinels, listeners, connectionTimeout.getOrElse( config.getDuration("brando.connection.timeout", TimeUnit.MILLISECONDS).millis), connectionHeartbeatDelay) } - case class Sentinel(host: String, port: Int) - private[brando] case class Connect(instances: Seq[Sentinel]) - case class ConnectionFailed(sentinels: Seq[Sentinel]) extends Connection.StateChange + case class Server(host: String, port: Int) + private[brando] case class Connect(sentinels: Seq[Server]) + case class ConnectionFailed(sentinels: Seq[Server]) extends Connection.StateChange } -class SentinelClient( - var sentinels: Seq[SentinelClient.Sentinel], +class Sentinel( + var sentinels: Seq[Sentinel.Server], var listeners: Set[ActorRef], connectionTimeout: FiniteDuration, connectionHeartbeatDelay: Option[FiniteDuration]) extends Actor with Stash { - import SentinelClient._ + import Sentinel._ import context.dispatcher implicit val timeout = Timeout(connectionTimeout) @@ -65,7 +64,7 @@ class SentinelClient( } def disconnected: Receive = handleListeners orElse { - case Connect(Sentinel(host, port) :: tail) ⇒ + case Connect(Server(host, port) :: tail) ⇒ notifyStateChange(Connection.Connecting(host, port)) retries += 1 connection = context.actorOf(Props(classOf[Connection], @@ -75,7 +74,7 @@ class SentinelClient( context.become(connected) unstashAll() retries = 0 - val Sentinel(host, port) = sentinels.head + val Server(host, port) = sentinels.head notifyStateChange(Connection.Connected(host, port)) case x: Connection.ConnectionFailed ⇒ diff --git a/src/main/scala/ShardManager.scala b/src/main/scala/ShardManager.scala index 3194ff6..88ad70d 100644 --- a/src/main/scala/ShardManager.scala +++ b/src/main/scala/ShardManager.scala @@ -13,23 +13,17 @@ import com.typesafe.config.ConfigFactory import java.util.concurrent.TimeUnit object ShardManager { - def defaultHashFunction(input: Array[Byte]): Long = { - val crc32 = new CRC32 - crc32.update(input) - crc32.getValue - } - def apply( shards: Seq[Shard], listeners: Set[ActorRef] = Set(), - sentinel: Option[ActorRef] = None, + sentinelClient: Option[ActorRef] = None, hashFunction: (Array[Byte] ⇒ Long) = defaultHashFunction, connectionTimeout: Option[FiniteDuration] = None, connectionRetryDelay: Option[FiniteDuration] = None, connectionHeartbeatDelay: Option[FiniteDuration] = None): Props = { val config = ConfigFactory.load() - Props(classOf[ShardManager], shards, hashFunction, listeners, sentinel, + Props(classOf[ShardManager], shards, hashFunction, listeners, sentinelClient, connectionTimeout.getOrElse( config.getDuration("brando.connection.timeout", TimeUnit.MILLISECONDS).millis), connectionRetryDelay.getOrElse( @@ -37,6 +31,12 @@ object ShardManager { connectionHeartbeatDelay) } + def defaultHashFunction(input: Array[Byte]): Long = { + val crc32 = new CRC32 + crc32.update(input) + crc32.getValue + } + private[brando] trait Shard { val id: String } case class RedisShard(id: String, host: String, port: Int, database: Int = 0, @@ -51,7 +51,7 @@ class ShardManager( shards: Seq[ShardManager.Shard], hashFunction: (Array[Byte] ⇒ Long), var listeners: Set[ActorRef] = Set(), - sentinel: Option[ActorRef] = None, + sentinelClient: Option[ActorRef] = None, connectionTimeout: FiniteDuration, connectionRetryDelay: FiniteDuration, connectionHeartbeatDelay: Option[FiniteDuration]) extends Actor { @@ -91,19 +91,19 @@ class ShardManager( case SetShard(shard) ⇒ pool.get(shard.id) map (context.stop(_)) - (shard, sentinel) match { + (shard, sentinelClient) match { case (RedisShard(id, host, port, database, auth), _) ⇒ - val client = - context.actorOf(Brando(host, port, database, auth, listeners, + val brando = + context.actorOf(Redis(host, port, database, auth, listeners, Some(connectionTimeout), Some(connectionRetryDelay), None, connectionHeartbeatDelay)) - add(shard, client) - case (SentinelShard(id, database, auth), Some(sentinel)) ⇒ - val client = - context.actorOf(BrandoSentinel(id, sentinel, database, auth, + add(shard, brando) + case (SentinelShard(id, database, auth), Some(sClient)) ⇒ + val brando = + context.actorOf(RedisSentinel(id, sClient, database, auth, listeners, Some(connectionTimeout), Some(connectionRetryDelay), connectionHeartbeatDelay)) - add(shard, client) + add(shard, brando) case _ ⇒ } @@ -125,9 +125,9 @@ class ShardManager( pool(id) } - def add(shard: Shard, client: ActorRef) { - shardLookup(client) = shard - pool(shard.id) = client + def add(shard: Shard, brando: ActorRef) { + shardLookup(brando) = shard + pool(shard.id) = brando poolKeys = pool.keys.toIndexedSeq } } diff --git a/src/test/scala/BrandoSentinelTest.scala b/src/test/scala/RedisSentinelTest.scala similarity index 50% rename from src/test/scala/BrandoSentinelTest.scala rename to src/test/scala/RedisSentinelTest.scala index a68f1d9..9396163 100644 --- a/src/test/scala/BrandoSentinelTest.scala +++ b/src/test/scala/RedisSentinelTest.scala @@ -9,89 +9,104 @@ import scala.concurrent.duration._ import org.scalatest._ -class BrandoSentinelTest extends TestKit(ActorSystem("SentinelTest")) with FunSpecLike +class RedisClientSentinelTest extends TestKit(ActorSystem("RedisClientSentinelTest")) with FunSpecLike with ImplicitSender { - import BrandoSentinel._ - import SentinelClient._ + import RedisSentinel._ + import Sentinel._ import Connection._ - describe("BrandoSentinel") { + describe("RedisClientSentinel") { describe("when connecting") { it("should use sentinel to resolve the ip and port") { - val brandoProbe = TestProbe() val sentinelProbe = TestProbe() - val brando = system.actorOf(BrandoSentinel("mymaster", sentinelProbe.ref, 0, None, Set(brandoProbe.ref))) + val brando = system.actorOf( + RedisSentinel("mymaster", sentinelProbe.ref, 0, None)) sentinelProbe.expectMsg(Request("SENTINEL", "MASTER", "mymaster")) } it("should connect to sentinel and redis") { - val brandoProbe = TestProbe() + val redisProbe = TestProbe() val sentinelProbe = TestProbe() - val sentinel = system.actorOf(SentinelClient(Seq( - Sentinel("localhost", 26379)), Set(sentinelProbe.ref))) - val brando = system.actorOf(BrandoSentinel("mymaster", sentinel, 0, None, Set(brandoProbe.ref))) + + val sentinel = system.actorOf(Sentinel( + sentinels = Seq(Server("localhost", 26379)), + listeners = Set(sentinelProbe.ref))) + val brando = system.actorOf(RedisSentinel( + master = "mymaster", + sentinelClient = sentinel, + listeners = Set(redisProbe.ref))) sentinelProbe.expectMsg( Connecting("localhost", 26379)) sentinelProbe.expectMsg( Connected("localhost", 26379)) - brandoProbe.expectMsg( + redisProbe.expectMsg( Connecting("127.0.0.1", 6379)) - brandoProbe.expectMsg( + redisProbe.expectMsg( Connected("127.0.0.1", 6379)) } } describe("when disconnected") { it("should recreate a connection using sentinel") { - val brandoProbe = TestProbe() + val redisProbe = TestProbe() val sentinelProbe = TestProbe() - val sentinel = system.actorOf(SentinelClient(Seq( - Sentinel("localhost", 26379)), Set(sentinelProbe.ref))) - val brando = system.actorOf(BrandoSentinel("mymaster", sentinel, 0, None, Set(brandoProbe.ref))) + + val sentinel = system.actorOf(Sentinel( + sentinels = Seq(Server("localhost", 26379)), + listeners = Set(sentinelProbe.ref))) + val brando = system.actorOf(RedisSentinel( + master = "mymaster", + sentinelClient = sentinel, + listeners = Set(redisProbe.ref))) sentinelProbe.expectMsg( Connecting("localhost", 26379)) sentinelProbe.expectMsg( Connected("localhost", 26379)) - brandoProbe.expectMsg( + redisProbe.expectMsg( Connecting("127.0.0.1", 6379)) - brandoProbe.expectMsg( + redisProbe.expectMsg( Connected("127.0.0.1", 6379)) brando ! Disconnected("127.0.0.1", 6379) - brandoProbe.expectMsg( + redisProbe.expectMsg( Disconnected("127.0.0.1", 6379)) - brandoProbe.expectMsg( + redisProbe.expectMsg( Connecting("127.0.0.1", 6379)) - brandoProbe.expectMsg( + redisProbe.expectMsg( Connected("127.0.0.1", 6379)) } it("should stash requests") { - val brandoProbe = TestProbe() + val redisProbe = TestProbe() val sentinelProbe = TestProbe() - val sentinel = system.actorOf(SentinelClient(Seq( - Sentinel("localhost", 26379)), Set(sentinelProbe.ref))) - val brando = system.actorOf(BrandoSentinel("mymaster", sentinel, 0, None, Set(brandoProbe.ref))) - brandoProbe.expectMsg( + val sentinel = system.actorOf(Sentinel( + sentinels = Seq(Server("localhost", 26379)), + listeners = Set(sentinelProbe.ref))) + val brando = system.actorOf(RedisSentinel( + master = "mymaster", + sentinelClient = sentinel, + listeners = Set(redisProbe.ref))) + + redisProbe.expectMsg( Connecting("127.0.0.1", 6379)) - brandoProbe.expectMsg( + redisProbe.expectMsg( Connected("127.0.0.1", 6379)) brando ! Disconnected("127.0.0.1", 6379) - brandoProbe.expectMsg( + redisProbe.expectMsg( Disconnected("127.0.0.1", 6379)) brando ! Request("PING") - brandoProbe.expectMsg( + redisProbe.expectMsg( Connecting("127.0.0.1", 6379)) - brandoProbe.expectMsg( + redisProbe.expectMsg( Connected("127.0.0.1", 6379)) expectMsg(Some(Pong)) diff --git a/src/test/scala/BrandoTest.scala b/src/test/scala/RedisTest.scala similarity index 82% rename from src/test/scala/BrandoTest.scala rename to src/test/scala/RedisTest.scala index 6c8a9db..4d1c1ce 100644 --- a/src/test/scala/BrandoTest.scala +++ b/src/test/scala/RedisTest.scala @@ -11,14 +11,14 @@ import scala.concurrent.duration._ import java.util.UUID import java.net.ServerSocket -class BrandoTest extends TestKit(ActorSystem("BrandoTest")) with FunSpecLike +class RedisClientTest extends TestKit(ActorSystem("RedisTest")) with FunSpecLike with ImplicitSender { import Connection._ describe("ping") { it("should respond with Pong") { - val brando = system.actorOf(Brando()) + val brando = system.actorOf(Redis()) brando ! Request("PING") @@ -28,7 +28,7 @@ class BrandoTest extends TestKit(ActorSystem("BrandoTest")) with FunSpecLike describe("flushdb") { it("should respond with OK") { - val brando = system.actorOf(Brando()) + val brando = system.actorOf(Redis()) brando ! Request("FLUSHDB") @@ -38,7 +38,7 @@ class BrandoTest extends TestKit(ActorSystem("BrandoTest")) with FunSpecLike describe("set") { it("should respond with OK") { - val brando = system.actorOf(Brando()) + val brando = system.actorOf(Redis()) brando ! Request("SET", "mykey", "somevalue") @@ -51,7 +51,7 @@ class BrandoTest extends TestKit(ActorSystem("BrandoTest")) with FunSpecLike describe("get") { it("should respond with value option for existing key") { - val brando = system.actorOf(Brando()) + val brando = system.actorOf(Redis()) brando ! Request("SET", "mykey", "somevalue") @@ -66,7 +66,7 @@ class BrandoTest extends TestKit(ActorSystem("BrandoTest")) with FunSpecLike } it("should respond with None for non-existent key") { - val brando = system.actorOf(Brando()) + val brando = system.actorOf(Redis()) brando ! Request("GET", "mykey") @@ -76,7 +76,7 @@ class BrandoTest extends TestKit(ActorSystem("BrandoTest")) with FunSpecLike describe("incr") { it("should increment and return value for existing key") { - val brando = system.actorOf(Brando()) + val brando = system.actorOf(Redis()) brando ! Request("SET", "incr-test", "10") @@ -91,7 +91,7 @@ class BrandoTest extends TestKit(ActorSystem("BrandoTest")) with FunSpecLike } it("should return 1 for non-existent key") { - val brando = system.actorOf(Brando()) + val brando = system.actorOf(Redis()) brando ! Request("INCR", "incr-test") @@ -104,7 +104,7 @@ class BrandoTest extends TestKit(ActorSystem("BrandoTest")) with FunSpecLike describe("sadd") { it("should return number of members added to set") { - val brando = system.actorOf(Brando()) + val brando = system.actorOf(Redis()) brando ! Request("SADD", "sadd-test", "one") @@ -125,7 +125,7 @@ class BrandoTest extends TestKit(ActorSystem("BrandoTest")) with FunSpecLike describe("smembers") { it("should return all members in a set") { - val brando = system.actorOf(Brando()) + val brando = system.actorOf(Redis()) brando ! Request("SADD", "smembers-test", "one", "two", "three", "four") @@ -146,7 +146,7 @@ class BrandoTest extends TestKit(ActorSystem("BrandoTest")) with FunSpecLike describe("pipelining") { it("should respond to a Seq of multiple requests all at once") { - val brando = system.actorOf(Brando()) + val brando = system.actorOf(Redis()) val ping = Request("PING") brando ! ping @@ -160,7 +160,7 @@ class BrandoTest extends TestKit(ActorSystem("BrandoTest")) with FunSpecLike } it("should support pipelines of setex commands") { - val brando = system.actorOf(Brando()) + val brando = system.actorOf(Redis()) val setex = Request("SETEX", "pipeline-setex-path", "10", "Some data") brando ! setex @@ -173,7 +173,7 @@ class BrandoTest extends TestKit(ActorSystem("BrandoTest")) with FunSpecLike } it("should receive responses in the right order") { - val brando = system.actorOf(Brando()) + val brando = system.actorOf(Redis()) val ping = Request("PING") val setex = Request("SETEX", "pipeline-setex-path", "10", "Some data") @@ -203,7 +203,7 @@ class BrandoTest extends TestKit(ActorSystem("BrandoTest")) with FunSpecLike val largeText = new String(bytes, "UTF-8") - val brando = system.actorOf(Brando()) + val brando = system.actorOf(Redis()) brando ! Request("SET", "crime+and+punishment", largeText) @@ -220,13 +220,13 @@ class BrandoTest extends TestKit(ActorSystem("BrandoTest")) with FunSpecLike describe("error reply") { it("should receive a failure with the redis error message") { - val brando = system.actorOf(Brando()) + val brando = system.actorOf(Redis()) brando ! Request("SET", "key") expectMsgPF(5.seconds) { case Status.Failure(e) ⇒ - assert(e.isInstanceOf[BrandoException]) + assert(e.isInstanceOf[RedisException]) assert(e.getMessage === "ERR wrong number of arguments for 'set' command") } @@ -234,7 +234,7 @@ class BrandoTest extends TestKit(ActorSystem("BrandoTest")) with FunSpecLike expectMsgPF(5.seconds) { case Status.Failure(e) ⇒ - assert(e.isInstanceOf[BrandoException]) + assert(e.isInstanceOf[RedisException]) assert(e.getMessage === "ERR value is not an integer or out of range") } } @@ -242,7 +242,7 @@ class BrandoTest extends TestKit(ActorSystem("BrandoTest")) with FunSpecLike describe("select") { it("should execute commands on the selected database") { - val brando = system.actorOf(Brando("localhost", 6379, 5)) + val brando = system.actorOf(Redis("localhost", 6379, 5)) brando ! Request("SET", "mykey", "somevalue") @@ -270,7 +270,7 @@ class BrandoTest extends TestKit(ActorSystem("BrandoTest")) with FunSpecLike describe("multi/exec requests") { it("should support multi requests as an atomic transaction") { - val brando = system.actorOf(Brando("localhost", 6379, 5)) + val brando = system.actorOf(Redis("localhost", 6379, 5)) brando ! Batch(Request("MULTI"), Request("SET", "mykey", "somevalue"), Request("GET", "mykey"), Request("EXEC")) expectMsg(List(Some(Ok), Some(Queued), @@ -279,7 +279,7 @@ class BrandoTest extends TestKit(ActorSystem("BrandoTest")) with FunSpecLike } it("should support multi requests with multiple results") { - val brando = system.actorOf(Brando("localhost", 6379, 5)) + val brando = system.actorOf(Redis("localhost", 6379, 5)) brando ! Batch(Request("MULTI"), Request("SET", "mykey", "somevalue"), Request("GET", "mykey"), Request("GET", "mykey"), Request("EXEC")) expectMsg(List(Some(Ok), Some(Queued), @@ -294,7 +294,7 @@ class BrandoTest extends TestKit(ActorSystem("BrandoTest")) with FunSpecLike it("should be able to subscribe to a pubsub channel") { val channel = UUID.randomUUID().toString - val subscriber = system.actorOf(Brando()) + val subscriber = system.actorOf(Redis()) subscriber ! Request("SUBSCRIBE", channel) @@ -306,8 +306,8 @@ class BrandoTest extends TestKit(ActorSystem("BrandoTest")) with FunSpecLike it("should receive published messages from a pubsub channel") { val channel = UUID.randomUUID().toString - val subscriber = system.actorOf(Brando()) - val publisher = system.actorOf(Brando()) + val subscriber = system.actorOf(Redis()) + val publisher = system.actorOf(Redis()) subscriber ! Request("SUBSCRIBE", channel) @@ -324,8 +324,8 @@ class BrandoTest extends TestKit(ActorSystem("BrandoTest")) with FunSpecLike it("should be able to unsubscribe from a pubsub channel") { val channel = UUID.randomUUID().toString - val subscriber = system.actorOf(Brando()) - val publisher = system.actorOf(Brando()) + val subscriber = system.actorOf(Redis()) + val publisher = system.actorOf(Redis()) subscriber ! Request("SUBSCRIBE", channel) @@ -349,20 +349,26 @@ class BrandoTest extends TestKit(ActorSystem("BrandoTest")) with FunSpecLike } describe("should be able to block on blpop") { - val brando = system.actorOf(Brando()) + val brando = system.actorOf(Redis()) try { val channel = UUID.randomUUID().toString - val popBrando = system.actorOf(Brando()) - popBrando ! Request("BLPOP", "blpop:list", "0") + val popRedis = system.actorOf(Redis()) - expectNoMsg + val probeRedis = TestProbe() + val probePopRedis = TestProbe() - brando ! Request("LPUSH", "blpop:list", "blpop-value") - expectMsgType[Option[Long]] + popRedis.tell(Request("BLPOP", "blpop:list", "0"), probePopRedis.ref) - expectMsg(Some(List(Some( - ByteString("blpop:list")), - Some(ByteString("blpop-value"))))) + probePopRedis.expectNoMsg + + brando.tell(Request("LPUSH", "blpop:list", "blpop-value"), probeRedis.ref) + + probePopRedis.expectMsg( + Some(List(Some( + ByteString("blpop:list")), + Some(ByteString("blpop-value"))))) + + probeRedis.expectMsg(Some(1)) } finally { implicit val timeout = Timeout(1.seconds) @@ -374,7 +380,7 @@ class BrandoTest extends TestKit(ActorSystem("BrandoTest")) with FunSpecLike describe("notifications") { it("should send a Connected event if connecting succeeds") { val probe = TestProbe() - val brando = system.actorOf(Brando("localhost", 6379, listeners = Set(probe.ref))) + val brando = system.actorOf(Redis("localhost", 6379, listeners = Set(probe.ref))) probe.expectMsg(Connecting("localhost", 6379)) probe.expectMsg(Connected("localhost", 6379)) @@ -382,7 +388,7 @@ class BrandoTest extends TestKit(ActorSystem("BrandoTest")) with FunSpecLike it("should send an ConnectionFailed event if connecting fails") { val probe = TestProbe() - val brando = system.actorOf(Brando("localhost", 13579, listeners = Set(probe.ref))) + val brando = system.actorOf(Redis("localhost", 13579, listeners = Set(probe.ref))) probe.expectMsg(Connecting("localhost", 13579)) probe.expectMsg(ConnectionFailed("localhost", 13579)) @@ -390,10 +396,10 @@ class BrandoTest extends TestKit(ActorSystem("BrandoTest")) with FunSpecLike it("should send an AuthenticationFailed event if connecting succeeds but authentication fails") { val probe = TestProbe() - val brando = system.actorOf(Brando("localhost", 6379, auth = Some("not-the-auth"), listeners = Set(probe.ref))) + val brando = system.actorOf(Redis("localhost", 6379, auth = Some("not-the-auth"), listeners = Set(probe.ref))) probe.expectMsg(Connecting("localhost", 6379)) - probe.expectMsg(Brando.AuthenticationFailed("localhost", 6379)) + probe.expectMsg(Redis.AuthenticationFailed("localhost", 6379)) } it("should send a ConnectionFailed if redis is not responsive during connection") { @@ -401,7 +407,7 @@ class BrandoTest extends TestKit(ActorSystem("BrandoTest")) with FunSpecLike val port = serverSocket.getLocalPort() val probe = TestProbe() - val brando = system.actorOf(Brando("localhost", port, listeners = Set(probe.ref))) + val brando = system.actorOf(Redis("localhost", port, listeners = Set(probe.ref))) probe.expectMsg(Connecting("localhost", port)) probe.expectMsg(ConnectionFailed("localhost", port)) @@ -410,7 +416,7 @@ class BrandoTest extends TestKit(ActorSystem("BrandoTest")) with FunSpecLike it("should send a notification to later added listener") { val probe = TestProbe() val probe2 = TestProbe() - val brando = system.actorOf(Brando("localhost", 13579, listeners = Set(probe2.ref))) + val brando = system.actorOf(Redis("localhost", 13579, listeners = Set(probe2.ref))) brando ! probe.ref probe2.expectMsg(Connecting("localhost", 13579)) @@ -424,7 +430,7 @@ class BrandoTest extends TestKit(ActorSystem("BrandoTest")) with FunSpecLike import Connection._ it("should try to reconnect if connectionRetryDelay and connectionRetryAttempts are defined") { val listener = TestProbe() - val brando = TestActorRef(new Brando( + val brando = TestActorRef(new Redis( "localhost", 6379, 0, None, Set(listener.ref), 2.seconds, Some(1.seconds), Some(1), None)) listener.expectMsg(Connecting("localhost", 6379)) @@ -440,7 +446,7 @@ class BrandoTest extends TestKit(ActorSystem("BrandoTest")) with FunSpecLike it("should not try to reconnect if connectionRetryDelay and connectionRetryAttempts are not defined") { val listener = TestProbe() - val brando = TestActorRef(new Brando( + val brando = TestActorRef(new Redis( "localhost", 6379, 0, None, Set(listener.ref), 2.seconds, None, None, None)) listener.expectMsg(Connecting("localhost", 6379)) @@ -454,7 +460,7 @@ class BrandoTest extends TestKit(ActorSystem("BrandoTest")) with FunSpecLike it("should not try to reconnect once the max retry attempts is reached") { val listener = TestProbe() - val brando = TestActorRef(new Brando( + val brando = TestActorRef(new Redis( "localhost", 16379, 0, None, Set(listener.ref), 2.seconds, Some(1.seconds), Some(1), None)) listener.expectMsg(Connecting("localhost", 16379)) diff --git a/src/test/scala/SentinelClientTest.scala b/src/test/scala/SentinelTest.scala similarity index 54% rename from src/test/scala/SentinelClientTest.scala rename to src/test/scala/SentinelTest.scala index 0b7cfdc..56687e0 100644 --- a/src/test/scala/SentinelClientTest.scala +++ b/src/test/scala/SentinelTest.scala @@ -1,6 +1,7 @@ package brando import akka.actor._ +import akka.util._ import akka.pattern._ import akka.testkit._ @@ -9,19 +10,19 @@ import scala.concurrent.duration._ import org.scalatest._ -class SentinelClientTest extends TestKit(ActorSystem("SentinelTest")) with FunSpecLike +class SentinelTest extends TestKit(ActorSystem("SentinelTest")) with FunSpecLike with ImplicitSender { - import SentinelClient._ + import Sentinel._ import Connection._ - describe("SentinelClient") { + describe("Sentinel") { describe("connection to sentinel instances") { it("should connect to the first working sentinel instance") { val probe = TestProbe() - val sentinel = system.actorOf(SentinelClient(Seq( - Sentinel("wrong-host", 26379), - Sentinel("localhost", 26379)), Set(probe.ref))) + val sentinel = system.actorOf(Sentinel(Seq( + Server("wrong-host", 26379), + Server("localhost", 26379)), Set(probe.ref))) probe.expectMsg(Connecting("wrong-host", 26379)) probe.expectMsg(Connecting("localhost", 26379)) @@ -30,8 +31,8 @@ class SentinelClientTest extends TestKit(ActorSystem("SentinelTest")) with FunSp it("should send a notification to the listeners when connecting") { val probe = TestProbe() - val sentinel = system.actorOf(SentinelClient(Seq( - Sentinel("localhost", 26379)), + val sentinel = system.actorOf(Sentinel(Seq( + Server("localhost", 26379)), Set(probe.ref))) probe.expectMsg(Connecting("localhost", 26379)) @@ -39,8 +40,8 @@ class SentinelClientTest extends TestKit(ActorSystem("SentinelTest")) with FunSp it("should send a notification to the listeners when connected") { val probe = TestProbe() - val sentinel = system.actorOf(SentinelClient(Seq( - Sentinel("localhost", 26379)), Set(probe.ref))) + val sentinel = system.actorOf(Sentinel(Seq( + Server("localhost", 26379)), Set(probe.ref))) probe.receiveN(1) probe.expectMsg(Connected("localhost", 26379)) @@ -48,8 +49,8 @@ class SentinelClientTest extends TestKit(ActorSystem("SentinelTest")) with FunSp it("should send a notification to the listeners when disconnected") { val probe = TestProbe() - val sentinel = system.actorOf(SentinelClient(Seq( - Sentinel("localhost", 26379)), Set(probe.ref))) + val sentinel = system.actorOf(Sentinel(Seq( + Server("localhost", 26379)), Set(probe.ref))) probe.receiveN(1) probe.expectMsg(Connected("localhost", 26379)) @@ -61,18 +62,18 @@ class SentinelClientTest extends TestKit(ActorSystem("SentinelTest")) with FunSp it("should send a notification to the listeners for connection failure") { val probe = TestProbe() - val sentinels = Seq(Sentinel("wrong-host", 26379)) - val sentinel = system.actorOf(SentinelClient(sentinels, Set(probe.ref))) + val sentinels = Seq(Server("wrong-host", 26379)) + val sentinel = system.actorOf(Sentinel(sentinels, Set(probe.ref))) probe.receiveN(1) - probe.expectMsg(SentinelClient.ConnectionFailed(sentinels)) + probe.expectMsg(Sentinel.ConnectionFailed(sentinels)) } it("should make sure the working instance will be tried first next reconnection") { val probe = TestProbe() - val sentinel = system.actorOf(SentinelClient(Seq( - Sentinel("wrong-host", 26379), - Sentinel("localhost", 26379)), Set(probe.ref))) + val sentinel = system.actorOf(Sentinel(Seq( + Server("wrong-host", 26379), + Server("localhost", 26379)), Set(probe.ref))) probe.expectMsg(Connecting("wrong-host", 26379)) probe.expectMsg(Connecting("localhost", 26379)) @@ -88,20 +89,20 @@ class SentinelClientTest extends TestKit(ActorSystem("SentinelTest")) with FunSp it("should send a notification to the listeners if it can't connect to any instance") { val probe = TestProbe() val sentinels = Seq( - Sentinel("wrong-host-1", 26379), - Sentinel("wrong-host-2", 26379)) - val sentinel = system.actorOf(SentinelClient(sentinels.reverse, Set(probe.ref))) + Server("wrong-host-1", 26379), + Server("wrong-host-2", 26379)) + val sentinel = system.actorOf(Sentinel(sentinels.reverse, Set(probe.ref))) probe.receiveN(2) - probe.expectMsg(SentinelClient.ConnectionFailed(sentinels)) + probe.expectMsg(Sentinel.ConnectionFailed(sentinels)) } } describe("Request") { it("should stash requests when disconnected") { val probe = TestProbe() - val sentinel = system.actorOf(SentinelClient(Seq( - Sentinel("localhost", 26379)), Set(probe.ref))) + val sentinel = system.actorOf(Sentinel(Seq( + Server("localhost", 26379)), Set(probe.ref))) probe.expectMsg(Connecting("localhost", 26379)) probe.expectMsg(Connected("localhost", 26379)) @@ -117,6 +118,33 @@ class SentinelClientTest extends TestKit(ActorSystem("SentinelTest")) with FunSp expectMsg(Some(Pong)) } } + + describe("Subscriptions") { + it("should receive pub/sub notifications") { + val sentinel = system.actorOf(Sentinel(Seq( + Server("localhost", 26379)))) + val sentinel2 = system.actorOf(Sentinel(Seq( + Server("localhost", 26379)))) + + sentinel ! Request("subscribe", "+failover-end") + + expectMsg(Some(List( + Some(ByteString("subscribe")), + Some(ByteString("+failover-end")), + Some(1)))) + + sentinel2 ! Request("sentinel", "failover", "mymaster") + expectMsg(Some(Ok)) + + expectMsg(PubSubMessage("+failover-end", "master mymaster 127.0.0.1 6379")) + + Thread.sleep(2000) + + sentinel2 ! Request("sentinel", "failover", "mymaster") + expectMsg(Some(Ok)) + + expectMsg(PubSubMessage("+failover-end", "master mymaster 127.0.0.1 6380")) + } + } } } - diff --git a/src/test/scala/ShardManagerTest.scala b/src/test/scala/ShardManagerTest.scala index 225689f..a698918 100644 --- a/src/test/scala/ShardManagerTest.scala +++ b/src/test/scala/ShardManagerTest.scala @@ -51,12 +51,17 @@ class ShardManagerTest extends TestKit(ActorSystem("ShardManagerTest")) describe("sending requests") { describe("using sentinel") { it("should forward each request to the appropriate client transparently") { - val shards = Seq( - SentinelShard("mymaster", 0)) - - val sentinel = system.actorOf(SentinelClient()) - val shardManager = TestActorRef[ShardManager](ShardManager( - shards, Set(), Some(sentinel))) + val redisProbe = TestProbe() + val sentinel = system.actorOf(Sentinel()) + val shardManager = system.actorOf(ShardManager( + shards = Seq(SentinelShard("mymaster", 0)), + sentinelClient = Some(sentinel), + listeners = Set(redisProbe.ref))) + + redisProbe.expectMsg( + Connecting("127.0.0.1", 6379)) + redisProbe.expectMsg( + Connected("127.0.0.1", 6379)) shardManager ! ("key", Request("SET", "shard_manager_test", "some value")) @@ -199,7 +204,7 @@ class ShardManagerTest extends TestKit(ActorSystem("ShardManagerTest")) probe.expectMsg(Connecting("localhost", 6379)) probe.expectMsg(Connecting("localhost", 6379)) probe.expectMsg(Connected("localhost", 6379)) - probe.expectMsg(Brando.AuthenticationFailed("localhost", 6379)) + probe.expectMsg(Redis.AuthenticationFailed("localhost", 6379)) } } } diff --git a/redis-config/redis-slave.conf b/test-config/redis-slave.conf similarity index 99% rename from redis-config/redis-slave.conf rename to test-config/redis-slave.conf index 8faf54b..ae261d5 100755 --- a/redis-config/redis-slave.conf +++ b/test-config/redis-slave.conf @@ -204,7 +204,7 @@ dir "/var/lib/redis-slave" # but to INFO and SLAVEOF. # slave-serve-stale-data yes - +slaveof 127.0.0.1 6379 # You can configure a slave instance to accept writes or not. Writing against # a slave instance may be useful to store some ephemeral data (because data # written on a slave will be easily deleted after resync with the master) but diff --git a/redis-config/redis.conf b/test-config/redis.conf similarity index 100% rename from redis-config/redis.conf rename to test-config/redis.conf diff --git a/redis-config/sentinel.conf b/test-config/sentinel.conf similarity index 100% rename from redis-config/sentinel.conf rename to test-config/sentinel.conf From 06a5e90f0a642b27a23fc82acba2ef683715f5cc Mon Sep 17 00:00:00 2001 From: Damien Levin Date: Thu, 21 May 2015 14:17:32 -0400 Subject: [PATCH 3/3] Remove stash when disconnected --- src/main/scala/Redis.scala | 4 +- .../scala/RedisConnectionSupervisor.scala | 16 +-- src/main/scala/RedisSentinel.scala | 3 + src/main/scala/Response.scala | 5 +- src/main/scala/Sentinel.scala | 5 +- ...st.scala => RedisClientSentinelTest.scala} | 27 +---- src/test/scala/RedisTest.scala | 104 ++++++++++++---- src/test/scala/SentinelTest.scala | 24 ++-- src/test/scala/ShardManagerTest.scala | 113 +++++++++++++++--- 9 files changed, 203 insertions(+), 98 deletions(-) rename src/test/scala/{RedisSentinelTest.scala => RedisClientSentinelTest.scala} (78%) diff --git a/src/main/scala/Redis.scala b/src/main/scala/Redis.scala index 05f5bfa..68d664f 100644 --- a/src/main/scala/Redis.scala +++ b/src/main/scala/Redis.scala @@ -63,11 +63,13 @@ class Redis( disconnectedWithRetry orElse super.disconnected def disconnectedWithRetry: Receive = { + case _@ (_: Request | _: Batch) ⇒ + sender ! Status.Failure(new RedisDisconnectedException(s"Disconnected from $host:$port")) + case ("auth_ok", x: Connection.Connected) ⇒ retries = 0 notifyStateChange(x) context.become(connected) - unstashAll() case Reconnect ⇒ (connectionRetryDelay, connectionRetryAttempts) match { diff --git a/src/main/scala/RedisConnectionSupervisor.scala b/src/main/scala/RedisConnectionSupervisor.scala index 4e4d7d9..a40c4c3 100644 --- a/src/main/scala/RedisConnectionSupervisor.scala +++ b/src/main/scala/RedisConnectionSupervisor.scala @@ -17,7 +17,7 @@ private[brando] abstract class RedisConnectionSupervisor( auth: Option[String], var listeners: Set[ActorRef], connectionTimeout: FiniteDuration, - connectionHeartbeatDelay: Option[FiniteDuration]) extends Actor with Stash { + connectionHeartbeatDelay: Option[FiniteDuration]) extends Actor { import ConnectionSupervisor.{ Connect, Reconnect } import context.dispatcher @@ -29,11 +29,8 @@ private[brando] abstract class RedisConnectionSupervisor( def receive = disconnected def connected: Receive = handleListeners orElse { - case request: Request ⇒ - connection forward request - - case batch: Batch ⇒ - connection forward batch + case m @ (_: Request | _: Batch) ⇒ + connection forward m case x: Connection.Disconnected ⇒ notifyStateChange(x) @@ -42,12 +39,6 @@ private[brando] abstract class RedisConnectionSupervisor( } def disconnected: Receive = handleListeners orElse { - case request: Request ⇒ - stash() - - case batch: Batch ⇒ - stash() - case Connect(host, port) ⇒ connection ! PoisonPill connection = context.actorOf(Props(classOf[Connection], @@ -62,7 +53,6 @@ private[brando] abstract class RedisConnectionSupervisor( case ("auth_ok", x: Connection.Connected) ⇒ notifyStateChange(x) context.become(connected) - unstashAll() case x: Connection.ConnectionFailed ⇒ notifyStateChange(x) diff --git a/src/main/scala/RedisSentinel.scala b/src/main/scala/RedisSentinel.scala index b3baa50..4910a26 100644 --- a/src/main/scala/RedisSentinel.scala +++ b/src/main/scala/RedisSentinel.scala @@ -62,6 +62,9 @@ class RedisSentinel( disconnectedWithSentinel orElse super.disconnected def disconnectedWithSentinel: Receive = { + case _@ (_: Request | _: Batch) ⇒ + sender ! Status.Failure(new RedisDisconnectedException(s"Disconnected from $master")) + case Reconnect ⇒ context.system.scheduler.scheduleOnce(connectionRetryDelay, self, SentinelConnect) diff --git a/src/main/scala/Response.scala b/src/main/scala/Response.scala index 0248aad..75b63f4 100644 --- a/src/main/scala/Response.scala +++ b/src/main/scala/Response.scala @@ -4,7 +4,10 @@ import akka.util.ByteString case class PubSubMessage(channel: String, message: String) -class RedisException(message: String) extends Exception(message) { +case class RedisException(message: String) extends Exception(message) { + override lazy val toString = "%s: %s\n".format(getClass.getName, message) +} +case class RedisDisconnectedException(message: String) extends Exception(message) { override lazy val toString = "%s: %s\n".format(getClass.getName, message) } diff --git a/src/main/scala/Sentinel.scala b/src/main/scala/Sentinel.scala index ae09eb7..9edab87 100644 --- a/src/main/scala/Sentinel.scala +++ b/src/main/scala/Sentinel.scala @@ -33,7 +33,7 @@ class Sentinel( var sentinels: Seq[Sentinel.Server], var listeners: Set[ActorRef], connectionTimeout: FiniteDuration, - connectionHeartbeatDelay: Option[FiniteDuration]) extends Actor with Stash { + connectionHeartbeatDelay: Option[FiniteDuration]) extends Actor { import Sentinel._ import context.dispatcher @@ -72,7 +72,6 @@ class Sentinel( case x: Connection.Connected ⇒ context.become(connected) - unstashAll() retries = 0 val Server(host, port) = sentinels.head notifyStateChange(Connection.Connected(host, port)) @@ -88,7 +87,7 @@ class Sentinel( } case request: Request ⇒ - stash() + sender ! Status.Failure(new RedisException("Disconnected from the sentinel cluster")) case _ ⇒ } diff --git a/src/test/scala/RedisSentinelTest.scala b/src/test/scala/RedisClientSentinelTest.scala similarity index 78% rename from src/test/scala/RedisSentinelTest.scala rename to src/test/scala/RedisClientSentinelTest.scala index 9396163..b511d31 100644 --- a/src/test/scala/RedisSentinelTest.scala +++ b/src/test/scala/RedisClientSentinelTest.scala @@ -81,35 +81,16 @@ class RedisClientSentinelTest extends TestKit(ActorSystem("RedisClientSentinelTe Connected("127.0.0.1", 6379)) } - it("should stash requests") { - val redisProbe = TestProbe() - val sentinelProbe = TestProbe() - + it("should return a failure when disconnected") { val sentinel = system.actorOf(Sentinel( - sentinels = Seq(Server("localhost", 26379)), - listeners = Set(sentinelProbe.ref))) + sentinels = Seq(Server("localhost", 26379)))) val brando = system.actorOf(RedisSentinel( master = "mymaster", - sentinelClient = sentinel, - listeners = Set(redisProbe.ref))) - - redisProbe.expectMsg( - Connecting("127.0.0.1", 6379)) - redisProbe.expectMsg( - Connected("127.0.0.1", 6379)) - - brando ! Disconnected("127.0.0.1", 6379) - redisProbe.expectMsg( - Disconnected("127.0.0.1", 6379)) + sentinelClient = sentinel)) brando ! Request("PING") - redisProbe.expectMsg( - Connecting("127.0.0.1", 6379)) - redisProbe.expectMsg( - Connected("127.0.0.1", 6379)) - - expectMsg(Some(Pong)) + expectMsg(Status.Failure(new RedisDisconnectedException("Disconnected from mymaster"))) } } } diff --git a/src/test/scala/RedisTest.scala b/src/test/scala/RedisTest.scala index 4d1c1ce..e7c61eb 100644 --- a/src/test/scala/RedisTest.scala +++ b/src/test/scala/RedisTest.scala @@ -18,7 +18,9 @@ class RedisClientTest extends TestKit(ActorSystem("RedisTest")) with FunSpecLike describe("ping") { it("should respond with Pong") { - val brando = system.actorOf(Redis()) + val brando = system.actorOf(Redis(listeners = Set(self))) + expectMsg(Connecting("localhost", 6379)) + expectMsg(Connected("localhost", 6379)) brando ! Request("PING") @@ -28,7 +30,9 @@ class RedisClientTest extends TestKit(ActorSystem("RedisTest")) with FunSpecLike describe("flushdb") { it("should respond with OK") { - val brando = system.actorOf(Redis()) + val brando = system.actorOf(Redis(listeners = Set(self))) + expectMsg(Connecting("localhost", 6379)) + expectMsg(Connected("localhost", 6379)) brando ! Request("FLUSHDB") @@ -38,7 +42,9 @@ class RedisClientTest extends TestKit(ActorSystem("RedisTest")) with FunSpecLike describe("set") { it("should respond with OK") { - val brando = system.actorOf(Redis()) + val brando = system.actorOf(Redis(listeners = Set(self))) + expectMsg(Connecting("localhost", 6379)) + expectMsg(Connected("localhost", 6379)) brando ! Request("SET", "mykey", "somevalue") @@ -51,7 +57,9 @@ class RedisClientTest extends TestKit(ActorSystem("RedisTest")) with FunSpecLike describe("get") { it("should respond with value option for existing key") { - val brando = system.actorOf(Redis()) + val brando = system.actorOf(Redis(listeners = Set(self))) + expectMsg(Connecting("localhost", 6379)) + expectMsg(Connected("localhost", 6379)) brando ! Request("SET", "mykey", "somevalue") @@ -66,7 +74,9 @@ class RedisClientTest extends TestKit(ActorSystem("RedisTest")) with FunSpecLike } it("should respond with None for non-existent key") { - val brando = system.actorOf(Redis()) + val brando = system.actorOf(Redis(listeners = Set(self))) + expectMsg(Connecting("localhost", 6379)) + expectMsg(Connected("localhost", 6379)) brando ! Request("GET", "mykey") @@ -76,7 +86,9 @@ class RedisClientTest extends TestKit(ActorSystem("RedisTest")) with FunSpecLike describe("incr") { it("should increment and return value for existing key") { - val brando = system.actorOf(Redis()) + val brando = system.actorOf(Redis(listeners = Set(self))) + expectMsg(Connecting("localhost", 6379)) + expectMsg(Connected("localhost", 6379)) brando ! Request("SET", "incr-test", "10") @@ -91,7 +103,9 @@ class RedisClientTest extends TestKit(ActorSystem("RedisTest")) with FunSpecLike } it("should return 1 for non-existent key") { - val brando = system.actorOf(Redis()) + val brando = system.actorOf(Redis(listeners = Set(self))) + expectMsg(Connecting("localhost", 6379)) + expectMsg(Connected("localhost", 6379)) brando ! Request("INCR", "incr-test") @@ -104,7 +118,9 @@ class RedisClientTest extends TestKit(ActorSystem("RedisTest")) with FunSpecLike describe("sadd") { it("should return number of members added to set") { - val brando = system.actorOf(Redis()) + val brando = system.actorOf(Redis(listeners = Set(self))) + expectMsg(Connecting("localhost", 6379)) + expectMsg(Connected("localhost", 6379)) brando ! Request("SADD", "sadd-test", "one") @@ -125,7 +141,9 @@ class RedisClientTest extends TestKit(ActorSystem("RedisTest")) with FunSpecLike describe("smembers") { it("should return all members in a set") { - val brando = system.actorOf(Redis()) + val brando = system.actorOf(Redis(listeners = Set(self))) + expectMsg(Connecting("localhost", 6379)) + expectMsg(Connected("localhost", 6379)) brando ! Request("SADD", "smembers-test", "one", "two", "three", "four") @@ -146,7 +164,10 @@ class RedisClientTest extends TestKit(ActorSystem("RedisTest")) with FunSpecLike describe("pipelining") { it("should respond to a Seq of multiple requests all at once") { - val brando = system.actorOf(Redis()) + val brando = system.actorOf(Redis(listeners = Set(self))) + expectMsg(Connecting("localhost", 6379)) + expectMsg(Connected("localhost", 6379)) + val ping = Request("PING") brando ! ping @@ -160,7 +181,10 @@ class RedisClientTest extends TestKit(ActorSystem("RedisTest")) with FunSpecLike } it("should support pipelines of setex commands") { - val brando = system.actorOf(Redis()) + val brando = system.actorOf(Redis(listeners = Set(self))) + expectMsg(Connecting("localhost", 6379)) + expectMsg(Connected("localhost", 6379)) + val setex = Request("SETEX", "pipeline-setex-path", "10", "Some data") brando ! setex @@ -173,7 +197,10 @@ class RedisClientTest extends TestKit(ActorSystem("RedisTest")) with FunSpecLike } it("should receive responses in the right order") { - val brando = system.actorOf(Redis()) + val brando = system.actorOf(Redis(listeners = Set(self))) + expectMsg(Connecting("localhost", 6379)) + expectMsg(Connected("localhost", 6379)) + val ping = Request("PING") val setex = Request("SETEX", "pipeline-setex-path", "10", "Some data") @@ -203,7 +230,9 @@ class RedisClientTest extends TestKit(ActorSystem("RedisTest")) with FunSpecLike val largeText = new String(bytes, "UTF-8") - val brando = system.actorOf(Redis()) + val brando = system.actorOf(Redis(listeners = Set(self))) + expectMsg(Connecting("localhost", 6379)) + expectMsg(Connected("localhost", 6379)) brando ! Request("SET", "crime+and+punishment", largeText) @@ -220,7 +249,9 @@ class RedisClientTest extends TestKit(ActorSystem("RedisTest")) with FunSpecLike describe("error reply") { it("should receive a failure with the redis error message") { - val brando = system.actorOf(Redis()) + val brando = system.actorOf(Redis(listeners = Set(self))) + expectMsg(Connecting("localhost", 6379)) + expectMsg(Connected("localhost", 6379)) brando ! Request("SET", "key") @@ -242,7 +273,9 @@ class RedisClientTest extends TestKit(ActorSystem("RedisTest")) with FunSpecLike describe("select") { it("should execute commands on the selected database") { - val brando = system.actorOf(Redis("localhost", 6379, 5)) + val brando = system.actorOf(Redis("localhost", 6379, 5, listeners = Set(self))) + expectMsg(Connecting("localhost", 6379)) + expectMsg(Connected("localhost", 6379)) brando ! Request("SET", "mykey", "somevalue") @@ -270,7 +303,10 @@ class RedisClientTest extends TestKit(ActorSystem("RedisTest")) with FunSpecLike describe("multi/exec requests") { it("should support multi requests as an atomic transaction") { - val brando = system.actorOf(Redis("localhost", 6379, 5)) + val brando = system.actorOf(Redis("localhost", 6379, 5, listeners = Set(self))) + expectMsg(Connecting("localhost", 6379)) + expectMsg(Connected("localhost", 6379)) + brando ! Batch(Request("MULTI"), Request("SET", "mykey", "somevalue"), Request("GET", "mykey"), Request("EXEC")) expectMsg(List(Some(Ok), Some(Queued), @@ -279,7 +315,10 @@ class RedisClientTest extends TestKit(ActorSystem("RedisTest")) with FunSpecLike } it("should support multi requests with multiple results") { - val brando = system.actorOf(Redis("localhost", 6379, 5)) + val brando = system.actorOf(Redis("localhost", 6379, 5, listeners = Set(self))) + expectMsg(Connecting("localhost", 6379)) + expectMsg(Connected("localhost", 6379)) + brando ! Batch(Request("MULTI"), Request("SET", "mykey", "somevalue"), Request("GET", "mykey"), Request("GET", "mykey"), Request("EXEC")) expectMsg(List(Some(Ok), Some(Queued), @@ -294,7 +333,9 @@ class RedisClientTest extends TestKit(ActorSystem("RedisTest")) with FunSpecLike it("should be able to subscribe to a pubsub channel") { val channel = UUID.randomUUID().toString - val subscriber = system.actorOf(Redis()) + val subscriber = system.actorOf(Redis(listeners = Set(self))) + expectMsg(Connecting("localhost", 6379)) + expectMsg(Connected("localhost", 6379)) subscriber ! Request("SUBSCRIBE", channel) @@ -306,8 +347,13 @@ class RedisClientTest extends TestKit(ActorSystem("RedisTest")) with FunSpecLike it("should receive published messages from a pubsub channel") { val channel = UUID.randomUUID().toString - val subscriber = system.actorOf(Redis()) - val publisher = system.actorOf(Redis()) + val subscriber = system.actorOf(Redis(listeners = Set(self))) + expectMsg(Connecting("localhost", 6379)) + expectMsg(Connected("localhost", 6379)) + + val publisher = system.actorOf(Redis(listeners = Set(self))) + expectMsg(Connecting("localhost", 6379)) + expectMsg(Connected("localhost", 6379)) subscriber ! Request("SUBSCRIBE", channel) @@ -324,8 +370,13 @@ class RedisClientTest extends TestKit(ActorSystem("RedisTest")) with FunSpecLike it("should be able to unsubscribe from a pubsub channel") { val channel = UUID.randomUUID().toString - val subscriber = system.actorOf(Redis()) - val publisher = system.actorOf(Redis()) + val subscriber = system.actorOf(Redis(listeners = Set(self))) + expectMsg(Connecting("localhost", 6379)) + expectMsg(Connected("localhost", 6379)) + + val publisher = system.actorOf(Redis(listeners = Set(self))) + expectMsg(Connecting("localhost", 6379)) + expectMsg(Connected("localhost", 6379)) subscriber ! Request("SUBSCRIBE", channel) @@ -349,10 +400,15 @@ class RedisClientTest extends TestKit(ActorSystem("RedisTest")) with FunSpecLike } describe("should be able to block on blpop") { - val brando = system.actorOf(Redis()) + val brando = system.actorOf(Redis(listeners = Set(self))) + expectMsg(Connecting("localhost", 6379)) + expectMsg(Connected("localhost", 6379)) + try { val channel = UUID.randomUUID().toString - val popRedis = system.actorOf(Redis()) + val popRedis = system.actorOf(Redis(listeners = Set(self))) + expectMsg(Connecting("localhost", 6379)) + expectMsg(Connected("localhost", 6379)) val probeRedis = TestProbe() val probePopRedis = TestProbe() diff --git a/src/test/scala/SentinelTest.scala b/src/test/scala/SentinelTest.scala index 56687e0..377b7d7 100644 --- a/src/test/scala/SentinelTest.scala +++ b/src/test/scala/SentinelTest.scala @@ -99,32 +99,28 @@ class SentinelTest extends TestKit(ActorSystem("SentinelTest")) with FunSpecLike } describe("Request") { - it("should stash requests when disconnected") { - val probe = TestProbe() + it("should return a failure when disconnected") { val sentinel = system.actorOf(Sentinel(Seq( - Server("localhost", 26379)), Set(probe.ref))) - - probe.expectMsg(Connecting("localhost", 26379)) - probe.expectMsg(Connected("localhost", 26379)) - - sentinel ! Disconnected("localhost", 26379) - probe.expectMsg(Disconnected("localhost", 26379)) + Server("localhost", 26379)))) sentinel ! Request("PING") - probe.expectMsg(Connecting("localhost", 26379)) - probe.expectMsg(Connected("localhost", 26379)) + expectMsg(Status.Failure(new RedisException("Disconnected from the sentinel cluster"))) - expectMsg(Some(Pong)) } } describe("Subscriptions") { it("should receive pub/sub notifications") { val sentinel = system.actorOf(Sentinel(Seq( - Server("localhost", 26379)))) + Server("localhost", 26379)), Set(self))) val sentinel2 = system.actorOf(Sentinel(Seq( - Server("localhost", 26379)))) + Server("localhost", 26379)), Set(self))) + + expectMsg(Connecting("localhost", 26379)) + expectMsg(Connecting("localhost", 26379)) + expectMsg(Connected("localhost", 26379)) + expectMsg(Connected("localhost", 26379)) sentinel ! Request("subscribe", "+failover-end") diff --git a/src/test/scala/ShardManagerTest.scala b/src/test/scala/ShardManagerTest.scala index a698918..da6b101 100644 --- a/src/test/scala/ShardManagerTest.scala +++ b/src/test/scala/ShardManagerTest.scala @@ -51,13 +51,19 @@ class ShardManagerTest extends TestKit(ActorSystem("ShardManagerTest")) describe("sending requests") { describe("using sentinel") { it("should forward each request to the appropriate client transparently") { + val sentinelProbe = TestProbe() val redisProbe = TestProbe() - val sentinel = system.actorOf(Sentinel()) + val sentinel = system.actorOf(Sentinel(listeners = Set(sentinelProbe.ref))) val shardManager = system.actorOf(ShardManager( shards = Seq(SentinelShard("mymaster", 0)), sentinelClient = Some(sentinel), listeners = Set(redisProbe.ref))) + sentinelProbe.expectMsg( + Connecting("localhost", 26379)) + sentinelProbe.expectMsg( + Connected("localhost", 26379)) + redisProbe.expectMsg( Connecting("127.0.0.1", 6379)) redisProbe.expectMsg( @@ -75,12 +81,36 @@ class ShardManagerTest extends TestKit(ActorSystem("ShardManagerTest")) it("should forward each request to the appropriate client transparently") { val shards = Seq( - RedisShard("server1", "localhost", 6379, 0), - RedisShard("server2", "localhost", 6379, 1), - RedisShard("server3", "localhost", 6379, 2)) - - val shardManager = TestActorRef[ShardManager](ShardManager( - shards)) + RedisShard("server1", "127.0.0.1", 6379, 0), + RedisShard("server2", "127.0.0.1", 6379, 1), + RedisShard("server3", "127.0.0.1", 6379, 2)) + + val sentinelProbe = TestProbe() + val redisProbe = TestProbe() + val sentinel = system.actorOf(Sentinel(listeners = Set(sentinelProbe.ref))) + val shardManager = system.actorOf(ShardManager( + shards = shards, + sentinelClient = Some(sentinel), + listeners = Set(redisProbe.ref))) + + sentinelProbe.expectMsg( + Connecting("localhost", 26379)) + sentinelProbe.expectMsg( + Connected("localhost", 26379)) + + redisProbe.expectMsg( + Connecting("127.0.0.1", 6379)) + redisProbe.expectMsg( + Connecting("127.0.0.1", 6379)) + redisProbe.expectMsg( + Connecting("127.0.0.1", 6379)) + + redisProbe.expectMsg( + Connected("127.0.0.1", 6379)) + redisProbe.expectMsg( + Connected("127.0.0.1", 6379)) + redisProbe.expectMsg( + Connected("127.0.0.1", 6379)) shardManager ! ("key", Request("SET", "shard_manager_test", "some value")) @@ -93,12 +123,27 @@ class ShardManagerTest extends TestKit(ActorSystem("ShardManagerTest")) it("should infer the key from the params list") { val shards = Seq( - RedisShard("server1", "localhost", 6379, 0), - RedisShard("server2", "localhost", 6379, 1), - RedisShard("server3", "localhost", 6379, 2)) + RedisShard("server1", "127.0.0.1", 6379, 0), + RedisShard("server2", "127.0.0.1", 6379, 1), + RedisShard("server3", "127.0.0.1", 6379, 2)) + val redisProbe = TestProbe() val shardManager = TestActorRef[ShardManager](ShardManager( - shards)) + shards, listeners = Set(redisProbe.ref))) + + redisProbe.expectMsg( + Connecting("127.0.0.1", 6379)) + redisProbe.expectMsg( + Connecting("127.0.0.1", 6379)) + redisProbe.expectMsg( + Connecting("127.0.0.1", 6379)) + + redisProbe.expectMsg( + Connected("127.0.0.1", 6379)) + redisProbe.expectMsg( + Connected("127.0.0.1", 6379)) + redisProbe.expectMsg( + Connected("127.0.0.1", 6379)) shardManager ! Request("SET", "shard_manager_test", "some value") @@ -111,12 +156,27 @@ class ShardManagerTest extends TestKit(ActorSystem("ShardManagerTest")) it("should fail with IllegalArgumentException when params is empty") { val shards = Seq( - RedisShard("server1", "localhost", 6379, 0), - RedisShard("server2", "localhost", 6379, 1), - RedisShard("server3", "localhost", 6379, 2)) + RedisShard("server1", "127.0.0.1", 6379, 0), + RedisShard("server2", "127.0.0.1", 6379, 1), + RedisShard("server3", "127.0.0.1", 6379, 2)) + val redisProbe = TestProbe() val shardManager = TestActorRef[ShardManager](ShardManager( - shards)) + shards, listeners = Set(redisProbe.ref))) + + redisProbe.expectMsg( + Connecting("127.0.0.1", 6379)) + redisProbe.expectMsg( + Connecting("127.0.0.1", 6379)) + redisProbe.expectMsg( + Connecting("127.0.0.1", 6379)) + + redisProbe.expectMsg( + Connected("127.0.0.1", 6379)) + redisProbe.expectMsg( + Connected("127.0.0.1", 6379)) + redisProbe.expectMsg( + Connected("127.0.0.1", 6379)) shardManager ! Request("SET") @@ -125,12 +185,27 @@ class ShardManagerTest extends TestKit(ActorSystem("ShardManagerTest")) it("should broadcast a Request to all shards") { val shards = Seq( - RedisShard("server1", "localhost", 6379, 0), - RedisShard("server2", "localhost", 6379, 1), - RedisShard("server3", "localhost", 6379, 2)) + RedisShard("server1", "127.0.0.1", 6379, 0), + RedisShard("server2", "127.0.0.1", 6379, 1), + RedisShard("server3", "127.0.0.1", 6379, 2)) + val redisProbe = TestProbe() val shardManager = TestActorRef[ShardManager](ShardManager( - shards)) + shards, listeners = Set(redisProbe.ref))) + + redisProbe.expectMsg( + Connecting("127.0.0.1", 6379)) + redisProbe.expectMsg( + Connecting("127.0.0.1", 6379)) + redisProbe.expectMsg( + Connecting("127.0.0.1", 6379)) + + redisProbe.expectMsg( + Connected("127.0.0.1", 6379)) + redisProbe.expectMsg( + Connected("127.0.0.1", 6379)) + redisProbe.expectMsg( + Connected("127.0.0.1", 6379)) val listName = scala.util.Random.nextString(5)