-
Notifications
You must be signed in to change notification settings - Fork 143
/
Sentinel.scala
247 lines (205 loc) · 8.5 KB
/
Sentinel.scala
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
package redis
import redis.commands.Sentinel
import akka.actor.{ActorSystem, Props, ActorRef}
import akka.event.Logging
import redis.api.pubsub.{PMessage, Message}
import redis.actors.RedisSubscriberActorWithCallback
import java.net.InetSocketAddress
import scala.concurrent.{Await, ExecutionContext, Future}
trait SentinelCommands
extends Sentinel
case class SentinelClient(var host: String = "localhost",
var port: Int = 26379,
onMasterChange: (String, String, Int) => Unit = (masterName: String, ip: String, port: Int) => {},
onNewSentinel: (String, String, Int) => Unit = (masterName: String, sentinelip: String, sentinelport: Int) => {},
onSentinelDown: (String, String, Int) => Unit = (masterName: String, sentinelip: String, sentinelport: Int) => {},
onNewSlave: (String, String, Int) => Unit = (masterName: String, sentinelip: String, sentinelport: Int) => {},
onSlaveDown: (String, String, Int) => Unit = (masterName: String, sentinelip: String, sentinelport: Int) => {},
name: String = "SentinelClient")
(implicit _system: ActorSystem,
redisDispatcher: RedisDispatcher = Redis.dispatcher
) extends RedisClientActorLike(_system, redisDispatcher) with SentinelCommands {
val system: ActorSystem = _system
val log = Logging.getLogger(system, this)
val channels = Seq("+switch-master", "+sentinel", "+sdown", "-sdown", "+failover-state-send-slaveof-noone", "+slave")
val onMessage = (message: Message) => {
if (log.isDebugEnabled)
log.debug(s"SentinelClient.onMessage: message received:${message.channel} ${message.data.utf8String}")
message match {
case Message("+switch-master", data) => {
data.utf8String.split(" ") match {
case Array(master, oldip, oldport, newip, newport) =>
onMasterChange(master, newip, newport.toInt)
case _ => {}
}
}
case Message("+failover-state-send-slaveof-noone", data) => {
data.utf8String.split(" ") match {
case Array("slave", slaveName, slaveip, slaveport, "@", master, masterip, masterport) =>
onMasterChange(master, slaveip, slaveport.toInt)
case _ => {}
}
}
case Message("+sentinel", data) => {
data.utf8String.split(" ") match {
case Array("sentinel", sentName, sentinelip, sentinelport, "@", master, masterip, masterport) =>
onNewSentinel(master, sentinelip, sentinelport.toInt)
case _ => {}
}
}
case Message("+sdown", data) => {
data.utf8String.split(" ") match {
case Array("sentinel", sentName, sentinelip, sentinelport, "@", master, masterip, masterport) =>
onSentinelDown(master, sentinelip, sentinelport.toInt)
case Array("slave", slaveName, slaveip, slaveport, "@", master, masterip, masterport) =>
onSlaveDown(master, slaveip, slaveport.toInt)
case _ => {}
}
}
case Message("-sdown", data) => {
data.utf8String.split(" ") match {
case Array("slave", slaveName, slaveip, slaveport, "@", master, masterip, masterport) =>
onNewSlave(master, slaveip, slaveport.toInt)
case _ => {}
}
}
case Message("+slave", data) => {
data.utf8String.split(" ") match {
case Array("slave", slaveName, slaveip, slaveport, "@", master, masterip, masterport) =>
onNewSlave(master, slaveip, slaveport.toInt)
case _ => {}
}
}
case _ => {
log.warning(s"SentinelClient.onMessage: unexpected message received: $message")
}
}
}
val redisPubSubConnection: ActorRef = system.actorOf(
Props(classOf[RedisSubscriberActorWithCallback],
new InetSocketAddress(host, port), channels, Seq(), onMessage, (pmessage: PMessage) => {}, None, (status: Boolean) => {})
.withDispatcher(redisDispatcher.name),
name + '-' + Redis.tempName()
)
/**
* Disconnect from the server (stop the actors)
*/
override def stop(): Unit = {
system stop redisConnection
system stop redisPubSubConnection
}
}
abstract class SentinelMonitored(system: ActorSystem, redisDispatcher: RedisDispatcher) {
val sentinels: Seq[(String, Int)]
val master: String
val onMasterChange: (String, Int) => Unit
val onNewSlave: (String, Int) => Unit
val onSlaveDown: (String, Int) => Unit
implicit val executionContext: ExecutionContext = system.dispatchers.lookup(redisDispatcher.name)
val log = Logging.getLogger(system, this)
val sentinelClients =
collection.mutable.Map(
sentinels.map(
hp =>
(makeSentinelClientKey(hp._1, hp._2), makeSentinelClient(hp._1, hp._2))
): _*
)
def makeSentinelClientKey(host: String, port: Int) = s"$host:$port"
def internalOnNewSlave(masterName: String, ip: String, port: Int): Unit = {
if (master == masterName)
onNewSlave(ip, port)
}
def internalOnSlaveDown(masterName: String, ip: String, port: Int): Unit = {
if (master == masterName)
onSlaveDown(ip, port)
}
def onSwitchMaster(masterName: String, ip: String, port: Int): Unit = {
if (master == masterName) {
onMasterChange(ip, port)
onSlaveDown(ip, port)
}
}
def makeSentinelClient(host: String, port: Int): SentinelClient = {
new SentinelClient(host, port, onSwitchMaster, onNewSentinel, onSentinelDown, internalOnNewSlave, internalOnSlaveDown, "SMSentinelClient")(system)
}
def onNewSentinel(masterName: String, sentinelip: String, sentinelport: Int): Unit = {
val k = makeSentinelClientKey(sentinelip, sentinelport)
if (master == masterName && !sentinelClients.contains(k)) {
sentinelClients.synchronized {
if (!sentinelClients.contains(k))
sentinelClients += k -> makeSentinelClient(sentinelip, sentinelport)
}
}
}
def onSentinelDown(masterName: String, sentinelip: String, sentinelport: Int): Unit = {
val k = makeSentinelClientKey(sentinelip, sentinelport)
if (master == masterName && sentinelClients.contains(k)) {
sentinelClients.synchronized {
if (sentinelClients.contains(k)) {
sentinelClients(k).stop()
sentinelClients -= k
}
}
}
}
def withMasterAddr[T](initFunction: (String, Int) => T): T = {
import scala.concurrent.duration._
val f = sentinelClients.values.map(_.getMasterAddr(master))
val ff = Future.sequence(f).map { listAddr =>
listAddr.flatten
.headOption
.map {
case (ip: String, port: Int) => initFunction(ip, port)
}.getOrElse(throw new Exception(s"No such master '$master'"))
}
Await.result(ff, 15 seconds)
}
def withSlavesAddr[T](initFunction: Seq[(String, Int)] => T): T = {
import scala.concurrent.duration._
val fslaves = Future.sequence(sentinelClients.values.map(_.slaves(master)))
.map { lm =>
val ipPortBuilder = Set.newBuilder[(String, Int)]
for {
slaves <- lm
slave <- slaves
ip <- slave.get("ip")
port <- slave.get("port")
} yield {
ipPortBuilder += ip -> port.toInt
}
initFunction(ipPortBuilder.result().toSeq)
}
Await.result(fslaves, 15 seconds)
}
}
abstract class SentinelMonitoredRedisClientLike(system: ActorSystem, redisDispatcher: RedisDispatcher
) extends SentinelMonitored(system, redisDispatcher) with ActorRequest {
val redisClient: RedisClientActorLike
val onMasterChange = (ip: String, port: Int) => {
log.info(s"onMasterChange: $ip:$port")
redisClient.reconnect(ip, port)
}
def redisConnection = redisClient.redisConnection
/**
* Disconnect from the server (stop the actors)
*/
def stop() = {
redisClient.stop()
sentinelClients.values.foreach(_.stop())
}
}
abstract class SentinelMonitoredRedisBlockingClientLike(system: ActorSystem, redisDispatcher: RedisDispatcher
) extends SentinelMonitored(system, redisDispatcher) with ActorRequest {
val redisClient: RedisClientActorLike
val onMasterChange = (ip: String, port: Int) => {
log.info(s"onMasterChange: $ip:$port")
redisClient.reconnect(ip, port)
}
/**
* Disconnect from the server (stop the actors)
*/
def stop() = {
redisClient.stop()
sentinelClients.values.foreach(_.stop())
}
}