/
ZkAdaptor.cs
273 lines (226 loc) · 8.09 KB
/
ZkAdaptor.cs
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
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
using System;
using System.Collections.Generic;
using System.Linq;
using ZooKeeperNet;
using Phial;
namespace RPCBase.Server
{
public class ZkAdaptor : IAdaptor
{
// identify current adaptor
private readonly Guid uuid = Guid.NewGuid();
public Guid Uuid
{
get { return uuid; }
}
// hold impls and delegates registered,
// when a msg arrived,
// dispatch msg to specific impl or delegate
private readonly Dictionary<string, IMessageConsumer> implements = new Dictionary<string, IMessageConsumer>();
private readonly Dictionary<string, IMessageConsumer> delegates = new Dictionary<string, IMessageConsumer>();
private ZooKeeper handle;
private ZkWatcher watcher;
private readonly Dictionary<string, Election> electionDict = new Dictionary<string,Election>();
public ZkAdaptor()
{
watcher = new ZkWatcher()
{
DataChangedHandler = OnDataChanged,
};
// zk handle
// zkServer addr, session timeout, watcher
handle = new ZooKeeper("192.168.0.103:2181,192.168.0.103:2182,192.168.0.103:2183,192.168.0.103:2184,192.168.0.103:2185", new TimeSpan(0, 0, 0, 50000), watcher);
try
{
// create root node
// no ACL
// Persistent node
handle.Create(RoutingRule.ZkRoutingRule.GetServiceRoot(), null, Ids.OPEN_ACL_UNSAFE, CreateMode.Persistent);
}
catch (KeeperException.NodeExistsException e)
{
// ignore
}
watcher.Handle = handle;
}
public void RegisterDelegate(IMessageConsumer consumer, string serviceId)
{
var rule = MetaData.GetServiceRoutingRule(serviceId);
if (rule == null)
{
throw new Exception();
}
var path = rule.ZkRule.GetServicePath();
try
{
handle.Create(path, null, Ids.OPEN_ACL_UNSAFE, CreateMode.Persistent);
}
catch (KeeperException.NodeExistsException e)
{
// ignore
}
delegates[path] = consumer;
}
public void RegisterImpl(IMessageConsumer consumer, string serviceId)
{
var rule = MetaData.GetServiceRoutingRule(serviceId);
if (rule == null)
{
throw new Exception();
}
var path = rule.ZkRule.GetServicePath();
try
{
handle.Create(path, null, Ids.OPEN_ACL_UNSAFE, CreateMode.Persistent);
}
catch (KeeperException.NodeExistsException e)
{
// ignore
}
implements[path] = consumer;
}
public void Send(byte[] buffer, byte[] dstUuid, RoutingRule routingRule)
{
// modify data associated with a node
// no need to concern version , at present
var ret = handle.SetData(routingRule.ZkRule.GetServicePath(), buffer, -1);
}
public void BeginReceive()
{
foreach (var implPath in implements.Keys)
{
handle.GetData(implPath, watcher, null);
}
}
public void Identity(string roundName)
{
if (electionDict.ContainsKey(roundName))
{
return;
}
var roundsRoot = string.Format("/{0}Rounds", RoutingRule.DistrictsName);
var thisRound = string.Format("{0}/{1}", roundsRoot, roundName);
try
{
handle.Create(roundsRoot, null, Ids.OPEN_ACL_UNSAFE, CreateMode.Persistent);
}
catch (KeeperException.NodeExistsException e)
{
// ignore
}
try
{
handle.Create(thisRound, null, Ids.OPEN_ACL_UNSAFE, CreateMode.Persistent);
}
catch (KeeperException.NodeExistsException e)
{
// ignore
}
var me = string.Format("{0}/{1}-n_", thisRound, uuid);
var ret = handle.Create(me, null, Ids.OPEN_ACL_UNSAFE, CreateMode.EphemeralSequential);
var elect = new Election(handle, thisRound, roundName, Election.PathToSeq(ret));
electionDict[roundName] = elect;
elect.AttempToBecomeLeader();
}
public bool IsLeader(string roundName)
{
Election election = null;
if (!electionDict.TryGetValue(roundName, out election))
{
throw new Exception("no round:"+roundName);
}
return election.IsLeader;
}
private void OnDataChanged(string path, byte[] buffer)
{
IMessageConsumer msgConsumer;
if (implements.TryGetValue(path, out msgConsumer))
{
msgConsumer.OnReceiveMessage(Mode.Notify, buffer, 0, null);
}
}
class Election : IWatcher
{
private readonly ZooKeeper handle;
private readonly string roundRoot;
private readonly string round;
private readonly int selfSeq;
public bool IsLeader { get; private set; }
public Election(ZooKeeper handle, string roundRoot, string round, int selfSeq)
{
this.handle = handle;
this.roundRoot = roundRoot;
this.round = round;
this.selfSeq = selfSeq;
}
public void AttempToBecomeLeader()
{
var children = handle.GetChildren(roundRoot, false);
OnRoundChildrenChanged(children);
}
public void OnRoundChildrenChanged(IEnumerable<string> children)
{
var seqs = children
.Select(p=>new KeyValuePair<string, int>(p, PathToSeq(p)))
.Where(pair=>pair.Value!=-1)
.OrderBy(pair => pair.Value)
.ToArray();
string toWatch = null;
for (int i = 0; i < seqs.Length-1; i++)
{
if (seqs[i + 1].Value == selfSeq)
{
toWatch = seqs[i].Key;
break;
}
}
if (toWatch == null)
{
Log.Info("nothing to watch , since self is leader");
IsLeader = true;
}
else
{
Log.Info("watch {0}", toWatch);
handle.Exists(roundRoot+'/'+toWatch, this);
}
}
public void Process(WatchedEvent @event)
{
if (@event.Type == EventType.NodeDeleted)
{
Log.Info("watching child {0} is deleted", @event.Path);
AttempToBecomeLeader();
}
}
public static int PathToSeq(string path)
{
var ret = path.Split('/');
var last = ret[ret.Length - 1].Split('_');
int seq = -1;
if (!int.TryParse(last[last.Length - 1], out seq))
{
return -1;
}
return seq;
}
}
class ZkWatcher : IWatcher
{
public ZooKeeper Handle { get; set; }
public Action<string, byte[]> DataChangedHandler { get; set; }
public ZkWatcher()
{
}
public void Process(WatchedEvent @event)
{
if (@event.Type == EventType.NodeDataChanged)
{
Log.Info("Process path:{0}", @event.Path);
var ret3 = Handle.GetData(@event.Path, this, null);
DataChangedHandler(@event.Path, ret3);
}
}
}
}
}