-
Notifications
You must be signed in to change notification settings - Fork 0
/
MongoToElasticObserver.cs
199 lines (170 loc) · 7.92 KB
/
MongoToElasticObserver.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
using Elasticsearch.Net;
using log4net;
using MongoDB.Driver;
using MongoToElastic.Entities;
using Nest;
using Newtonsoft.Json;
using System;
using System.Configuration;
using System.Reflection;
using System.Threading;
using System.Threading.Tasks;
namespace MongoToElastic
{
/// <summary>
/// This class observes Mongo collection changes and syncronizes them with ElasticSearch index.
/// Synchronization uses Change Streams feature of Mongo, which is available from Mongo version 3.6.
/// From the Mongo documentation https://docs.mongodb.com/manual/changeStreams/:
/// "To open a change stream against specific collection, applications must have privileges that grant changeStream and find actions on the corresponding collection."
/// </summary>
/// <typeparam name="T">Type of the entity.</typeparam>
public sealed class MongoToElasticObserver<T> where T : class, IEntity
{
private const int ChangeStreamCheckTimeout = 5000;
private const int StopTaskTimeout = 5000;
private static readonly ILog log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
private string databaseName;
private string collectionName;
private string indexName;
private string mongoConnectionString;
private string elasticConnectionString;
private CancellationTokenSource cancellationTokenSource;
private CancellationToken cancellationToken;
private Task task;
/// <summary>
/// Constructor.
/// Requires MongoConnectionString and ElasticConnectionString parameters defined in <connectionStrings> configuration section.
/// </summary>
/// <param name="databaseName">Mongo database name.</param>
/// <param name="collectionName">Mongo collection name.</param>
/// <param name="indexName">ElasticSearch index name.</param>
public MongoToElasticObserver(string databaseName, string collectionName, string indexName)
{
if (String.IsNullOrEmpty(databaseName))
throw new ArgumentException(nameof(databaseName));
this.databaseName = databaseName;
if (String.IsNullOrEmpty(collectionName))
throw new ArgumentException(nameof(collectionName));
this.collectionName = collectionName;
if (String.IsNullOrEmpty(indexName))
throw new ArgumentException(nameof(indexName));
this.indexName = indexName;
this.mongoConnectionString = ConfigurationManager.ConnectionStrings["MongoConnectionString"].ConnectionString;
if (String.IsNullOrEmpty(mongoConnectionString))
throw new ConfigurationErrorsException(nameof(mongoConnectionString));
this.elasticConnectionString = ConfigurationManager.ConnectionStrings["ElasticConnectionString"].ConnectionString;
if (String.IsNullOrEmpty(elasticConnectionString))
throw new ConfigurationErrorsException(nameof(elasticConnectionString));
}
/// <summary>
/// Starts handling changes.
/// </summary>
public void Start()
{
this.cancellationTokenSource = new CancellationTokenSource();
this.cancellationToken = this.cancellationTokenSource.Token;
this.task = Task.Run(() =>
{
HandleChanges();
}, this.cancellationToken);
}
/// <summary>
/// Stops handling changes.
/// </summary>
public void Stop()
{
this.cancellationTokenSource.Cancel();
this.task.Wait(StopTaskTimeout);
}
/// <summary>
/// Listed to the changes in Mongo collection and synch the changes to ElasticSearch index.
/// </summary>
private void HandleChanges()
{
log.Info("HandleChanges begin");
try
{
MongoClient mongoClient = new MongoClient(this.mongoConnectionString);
ElasticClient elasticClient = new ElasticClient(new ConnectionSettings(new Uri(this.elasticConnectionString)));
IMongoDatabase database = mongoClient.GetDatabase(this.databaseName);
IMongoCollection<T> collection = database.GetCollection<T>(this.collectionName);
this.cancellationToken.ThrowIfCancellationRequested();
EnsureIndexCreated(elasticClient);
//Get the whole document instead of just the changed portion
ChangeStreamOptions options = new ChangeStreamOptions() { FullDocument = ChangeStreamFullDocumentOption.UpdateLookup };
var pipeline = new EmptyPipelineDefinition<ChangeStreamDocument<T>>()
.Match("{ operationType: { $in: [ 'insert', 'update', 'delete' ] } }");
using (var stream = collection.Watch(pipeline, options))
{
while (!this.cancellationToken.IsCancellationRequested)
{
try
{
if (stream.MoveNext())
{
var enumerator = stream.Current.GetEnumerator();
while (enumerator.MoveNext())
{
HandleChange(elasticClient,
enumerator.Current.OperationType,
enumerator.Current.FullDocument);
}
}
}
catch (Exception ex)
{
log.Error($"HandleChanges failed.", ex);
}
Thread.Sleep(ChangeStreamCheckTimeout);
this.cancellationToken.ThrowIfCancellationRequested();
}
}
}
catch (Exception ex)
{
log.Error($"HandleChanges failed.", ex);
}
}
private void HandleChange(ElasticClient elasticClient, ChangeStreamOperationType changeType, T document)
{
log.Info($"HandleChange begin, changeType: {changeType}, document.id: {document.id}");
try
{
switch (changeType)
{
case ChangeStreamOperationType.Insert:
elasticClient.Index<T>(document, i =>
i.Index(this.indexName)
.Id(document.id)
.Refresh(Refresh.True));
break;
case ChangeStreamOperationType.Update:
// We used .Index() instead of Update() since we are updating all the fields
elasticClient.Index<T>(document, i =>
i.Index(this.indexName)
.Id(document.id)
.Refresh(Refresh.True));
break;
case ChangeStreamOperationType.Delete:
elasticClient.Delete<T>(document.id, d => d.Index(this.indexName));
break;
}
}
catch (Exception ex)
{
log.Error($"HandleChange failed, changeType: {changeType}, document: {JsonConvert.SerializeObject(document)}.", ex);
}
log.Info("HandleChange end");
}
private void EnsureIndexCreated(ElasticClient elasticClient)
{
log.Info("EnsureIndexCreated begin");
if (!elasticClient.Indices.Exists(this.indexName).Exists)
{
elasticClient.Indices.Create(this.indexName);
log.Info($"EnsureIndexCreated, created a new index: {this.indexName}");
}
log.Info("EnsureIndexCreated end");
}
}
}