This repository has been archived by the owner on Dec 11, 2018. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Syncer.cs
244 lines (186 loc) · 8.59 KB
/
Syncer.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
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.WindowsAzure.Storage;
using Microsoft.WindowsAzure.Storage.Table;
namespace Tasync
{
internal class Syncer
{
private const string MetatableName = "aaametatasync";
private static readonly DateTimeOffset LowestTimestamp = new DateTimeOffset(1601, 1, 1, 0, 0, 0, TimeSpan.Zero);
private readonly CloudTableClient _dstClient;
private readonly CloudTableClient _srcClient;
private readonly CancellationToken _token;
private IDictionary<CloudTable, DateTimeOffset> _timestamps;
public Syncer(CloudStorageAccount source, CloudStorageAccount destination, CancellationToken token)
{
_token = token;
_srcClient = source.CreateCloudTableClient();
_dstClient = destination.CreateCloudTableClient();
}
public async Task SyncOneWay()
{
await Prechecks();
await GatherInfo();
await DoSync();
await SaveInfo();
}
public async Task DeleteInDestination()
{
Console.WriteLine("cleaning up destination");
Task<HashSet<Tuple<string, string, string>>> srcTask = LoadAllIds(_srcClient);
Task<HashSet<Tuple<string, string, string>>> dstTask = LoadAllIds(_dstClient);
await DeleteInDestination(await srcTask, await dstTask);
}
private async Task<HashSet<Tuple<string, string, string>>> LoadAllIds(CloudTableClient client)
{
var result = new HashSet<Tuple<string, string, string>>();
var query = new TableQuery<TableEntity> {SelectColumns = new List<string> {"PartitionKey", "RowKey"}};
foreach (var kv in _timestamps)
{
CloudTable table = client.GetTableReference(kv.Key.Name);
IList<TableEntity> allFuckingEntities = await table.ExecuteQueryAsync(
query, _token, list => Console.WriteLine("loaded {0} rows", list.Count));
foreach (TableEntity entity in allFuckingEntities)
{
result.Add(Tuple.Create(table.Name, entity.PartitionKey, entity.RowKey));
}
}
return result;
}
private async Task DeleteInDestination(HashSet<Tuple<string, string, string>> src,
HashSet<Tuple<string, string, string>> dst)
{
dst.ExceptWith(src);
int n = 0;
// group by table + partition
foreach (var batch1 in dst.GroupBy(x => x.Item1 + x.Item2))
{
CloudTable dstTable = _dstClient.GetTableReference(batch1.First().Item1);
if (_token.IsCancellationRequested)
return;
foreach (var batch2 in batch1.Batch(100))
{
if (_token.IsCancellationRequested)
return;
var op = new TableBatchOperation();
foreach (var tuple in batch2)
{
op.Delete(new TableEntity(tuple.Item2, tuple.Item3) {ETag = "*"});
}
await dstTable.ExecuteBatchAsync(op, _token);
n += Math.Min(op.Count, 100);
Console.WriteLine("deleted {0} rows", n);
}
}
}
private async Task Prechecks()
{
await _dstClient.GetTableReference(MetatableName).CreateIfNotExistsAsync(_token);
}
private async Task GatherInfo()
{
IList<CloudTable> tables = await _srcClient.ListTablesAsync(_token);
_timestamps = await LoadTimestampsFromMetatable(tables);
if (_token.IsCancellationRequested)
return;
Console.WriteLine("destination status");
foreach (var kv in _timestamps.OrderBy(x => x.Key.Name))
{
Console.WriteLine("{0,-40}{1}", kv.Key.Name, kv.Value);
}
}
private async Task DoSync()
{
foreach (var kv in _timestamps.OrderBy(x => x.Key.Name))
{
if (_token.IsCancellationRequested)
return;
Console.WriteLine("syncing table {0}", kv.Key.Name);
await SyncTableSince(kv.Key, kv.Value);
}
}
private async Task SaveInfo()
{
CloudTable metatable = _dstClient.GetTableReference(MetatableName);
Console.WriteLine("new destination status");
var op = new TableBatchOperation();
foreach (var batch in _timestamps.OrderBy(x => x.Key.Name).Batch(100))
{
foreach (var item in batch)
{
var entity = new DynamicTableEntity("SyncTimestamps", item.Key.Name);
entity.Properties["SourceTimestamp"] = new EntityProperty(item.Value);
op.InsertOrReplace(entity);
Console.WriteLine("{0,-40}{1}", item.Key.Name, item.Value);
}
await metatable.ExecuteBatchAsync(op, _token);
}
}
private async Task SyncTableSince(CloudTable table, DateTimeOffset timestamp)
{
var query = new TableQuery<DynamicTableEntity>
{
FilterString = TableQuery.GenerateFilterConditionForDate("Timestamp", "gt", timestamp),
};
IList<DynamicTableEntity> allFuckingEntities = await table.ExecuteQueryAsync(
query, _token, list => Console.WriteLine("loaded {0} rows", list.Count));
CloudTable dstTable = _dstClient.GetTableReference(table.Name);
await dstTable.CreateIfNotExistsAsync();
int n = 0;
DateTimeOffset maxSourceTs = timestamp;
foreach (var batch1 in allFuckingEntities.GroupBy(x => x.PartitionKey))
{
if (_token.IsCancellationRequested)
return;
foreach (var batch2 in batch1.Batch(100))
{
if (_token.IsCancellationRequested)
return;
var op = new TableBatchOperation();
foreach (DynamicTableEntity entity in batch2)
{
op.InsertOrReplace(entity);
if (entity.Timestamp > maxSourceTs)
{
maxSourceTs = entity.Timestamp;
}
}
await dstTable.ExecuteBatchAsync(op, _token);
n += Math.Min(op.Count, 100);
Console.WriteLine("sent {0} rows", n);
}
}
_timestamps[table] = maxSourceTs;
}
private async Task<IDictionary<CloudTable, DateTimeOffset>> LoadTimestampsFromMetatable(
IEnumerable<CloudTable> tables)
{
var result = new Dictionary<CloudTable, DateTimeOffset>();
foreach (CloudTable table in tables)
{
result[table] = LowestTimestamp;
}
CloudTable metatable = _dstClient.GetTableReference(MetatableName);
string tableList = string.Join(
" or ", result.Select(x => TableQuery.GenerateFilterCondition("RowKey", "eq", x.Key.Name)));
var query = new TableQuery<DynamicTableEntity>
{
FilterString = TableQuery.CombineFilters(
TableQuery.GenerateFilterCondition("PartitionKey", "eq", "SyncTimestamps"), "and",
tableList),
SelectColumns = new List<string> {"SourceTimestamp"}
};
foreach (DynamicTableEntity entity in await metatable.ExecuteQueryAsync(query, _token))
{
KeyValuePair<CloudTable, DateTimeOffset> kv =
result.First(x => x.Key.Name == entity.RowKey);
result[kv.Key] = entity["SourceTimestamp"].DateTimeOffsetValue ?? LowestTimestamp;
}
return result;
}
}
}