-
Notifications
You must be signed in to change notification settings - Fork 23
/
Copy pathRedisMembershipTable.cs
234 lines (194 loc) · 8.98 KB
/
RedisMembershipTable.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
using System;
using System.Threading.Tasks;
using Orleans.Runtime;
using StackExchange.Redis;
using Orleans.Configuration;
using Newtonsoft.Json;
using System.Linq;
using Microsoft.Extensions.Options;
using System.Runtime.CompilerServices;
using System.Globalization;
[assembly: InternalsVisibleTo("Orleans.Clustering.Redis.Test")]
namespace Orleans.Clustering.Redis
{
internal class RedisMembershipTable : IMembershipTable, IDisposable
{
private const string TableVersionKey = "Version";
private static readonly TableVersion DefaultTableVersion = new TableVersion(0, "0");
private readonly RedisClusteringOptions _redisOptions;
private readonly ClusterOptions _clusterOptions;
private readonly JsonSerializerSettings _jsonSerializerSettings;
private readonly RedisKey _clusterKey;
private IConnectionMultiplexer _muxer;
private IDatabase _db;
public RedisMembershipTable(IOptions<RedisClusteringOptions> redisOptions, IOptions<ClusterOptions> clusterOptions)
{
_redisOptions = redisOptions.Value;
_clusterOptions = clusterOptions.Value;
_clusterKey = $"{_clusterOptions.ServiceId}/{_clusterOptions.ClusterId}";
_jsonSerializerSettings = JsonSettings.JsonSerializerSettings;
}
public bool IsInitialized { get; private set; }
public async Task DeleteMembershipTableEntries(string clusterId)
{
await _db.KeyDeleteAsync(_clusterKey);
}
public async Task InitializeMembershipTable(bool tryInitTableVersion)
{
_muxer = await _redisOptions.CreateMultiplexer(_redisOptions);
_db = _muxer.GetDatabase(_redisOptions.Database);
if (tryInitTableVersion)
{
await _db.HashSetAsync(_clusterKey, TableVersionKey, SerializeVersion(DefaultTableVersion), When.NotExists);
}
this.IsInitialized = true;
}
public async Task<bool> InsertRow(MembershipEntry entry, TableVersion tableVersion)
{
return await UpsertRowInternal(entry, tableVersion, updateTableVersion: true, allowInsertOnly: true) == UpsertResult.Success;
}
private async Task<UpsertResult> UpsertRowInternal(MembershipEntry entry, TableVersion tableVersion, bool updateTableVersion, bool allowInsertOnly)
{
var tx = _db.CreateTransaction();
var rowKey = entry.SiloAddress.ToString();
if (updateTableVersion)
{
if (tableVersion.Version == 0 && "0".Equals(tableVersion.VersionEtag, StringComparison.Ordinal))
{
await _db.HashSetAsync(_clusterKey, TableVersionKey, SerializeVersion(tableVersion), When.NotExists);
}
tx.HashSetAsync(_clusterKey, TableVersionKey, SerializeVersion(tableVersion)).Ignore();
}
var versionCondition = tx.AddCondition(Condition.HashEqual(_clusterKey, TableVersionKey, SerializeVersion(Predeccessor(tableVersion))));
ConditionResult insertCondition = null;
if (allowInsertOnly)
{
insertCondition = tx.AddCondition(Condition.HashNotExists(_clusterKey, rowKey));
}
tx.HashSetAsync(_clusterKey, rowKey, Serialize(entry)).Ignore();
var success = await tx.ExecuteAsync();
if (success)
{
return UpsertResult.Success;
}
if (!versionCondition.WasSatisfied)
{
return UpsertResult.Conflict;
}
if (!insertCondition.WasSatisfied)
{
return UpsertResult.Failure;
}
return UpsertResult.Failure;
}
public async Task<MembershipTableData> ReadAll()
{
var all = await _db.HashGetAllAsync(_clusterKey);
var tableVersionRow = all.SingleOrDefault(h => TableVersionKey.Equals(h.Name, StringComparison.Ordinal));
TableVersion tableVersion = GetTableVersionFromRow(tableVersionRow.Value);
var data = all.Where(h => !TableVersionKey.Equals(h.Name, StringComparison.Ordinal) && h.Value.HasValue)
.Select(x => Tuple.Create(Deserialize(x.Value), tableVersion.VersionEtag))
.ToList();
return new MembershipTableData(data, tableVersion);
}
private static TableVersion GetTableVersionFromRow(RedisValue tableVersionRow)
{
return tableVersionRow.HasValue ? DeserializeVersion(tableVersionRow) : DefaultTableVersion;
}
public async Task<MembershipTableData> ReadRow(SiloAddress key)
{
var tx = _db.CreateTransaction();
var tableVersionRowTask = tx.HashGetAsync(_clusterKey, TableVersionKey);
var entryRowTask = tx.HashGetAsync(_clusterKey, key.ToString());
if (!await tx.ExecuteAsync())
{
throw new RedisClusteringException($"Unexpected transaction failure while reading key {key}");
}
TableVersion tableVersion = GetTableVersionFromRow(await tableVersionRowTask);
var entryRow = await entryRowTask;
if (entryRow.HasValue)
{
var entry = Deserialize(entryRow);
return new MembershipTableData(Tuple.Create(entry, tableVersion.VersionEtag), tableVersion);
}
else
{
return new MembershipTableData(tableVersion);
}
}
public async Task UpdateIAmAlive(MembershipEntry entry)
{
var key = entry.SiloAddress.ToString();
var tx = _db.CreateTransaction();
var tableVersionRowTask = tx.HashGetAsync(_clusterKey, TableVersionKey);
var entryRowTask = tx.HashGetAsync(_clusterKey, key);
if (!await tx.ExecuteAsync())
{
throw new RedisClusteringException($"Unexpected transaction failure while reading key {key}");
}
var entryRow = await entryRowTask;
if (!entryRow.HasValue)
{
throw new RedisClusteringException($"Could not find a value for the key {key}");
}
TableVersion tableVersion = GetTableVersionFromRow(await tableVersionRowTask).Next();
var existingEntry = Deserialize(entryRow);
// Update only the IAmAliveTime property.
existingEntry.IAmAliveTime = entry.IAmAliveTime;
var result = await UpsertRowInternal(existingEntry, tableVersion, updateTableVersion: false, allowInsertOnly: false);
if (result == UpsertResult.Conflict)
{
throw new RedisClusteringException($"Failed to update IAmAlive value for key {key} due to conflict");
}
else if (result != UpsertResult.Success)
{
throw new RedisClusteringException($"Failed to update IAmAlive value for key {key} for an unknown reason");
}
}
public async Task<bool> UpdateRow(MembershipEntry entry, string etag, TableVersion tableVersion)
{
return await UpsertRowInternal(entry, tableVersion, updateTableVersion: true, allowInsertOnly: false) == UpsertResult.Success;
}
public async Task CleanupDefunctSiloEntries(DateTimeOffset beforeDate)
{
var entries = await this.ReadAll();
foreach (var (entry, _) in entries.Members)
{
if (entry.Status == SiloStatus.Dead
&& new DateTime(Math.Max(entry.IAmAliveTime.Ticks, entry.StartTime.Ticks), DateTimeKind.Utc) < beforeDate)
{
await _db.HashDeleteAsync(_clusterKey, entry.SiloAddress.ToString());
}
}
}
public void Dispose()
{
_muxer?.Dispose();
}
private enum UpsertResult
{
Success = 1,
Failure = 2,
Conflict = 3,
}
private static string SerializeVersion(TableVersion tableVersion) => tableVersion.Version.ToString(CultureInfo.InvariantCulture);
private static TableVersion DeserializeVersion(string versionString)
{
if (string.IsNullOrWhiteSpace(versionString))
{
return DefaultTableVersion;
}
var version = int.Parse(versionString);
return new TableVersion(version, versionString);
}
private static TableVersion Predeccessor(TableVersion tableVersion) => new TableVersion(tableVersion.Version - 1, (tableVersion.Version - 1).ToString(CultureInfo.InvariantCulture));
private string Serialize(MembershipEntry value)
{
return JsonConvert.SerializeObject(value, _jsonSerializerSettings);
}
private MembershipEntry Deserialize(string json)
{
return JsonConvert.DeserializeObject<MembershipEntry>(json, _jsonSerializerSettings);
}
}
}