ravendb /Raven.Database/Counters/Controllers/RavenCounterReplication.cs

Language C# Lines 572
MD5 Hash 8718234692797c4db0eddf7a72642f8c
Repository https://github.com/nwendel/ravendb.git View Raw File
  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
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Net;
using System.Threading;
using System.Threading.Tasks;
using Raven.Abstractions;
using Raven.Abstractions.Connection;
using Raven.Abstractions.Counters;
using Raven.Abstractions.Data;
using Raven.Abstractions.Logging;
using Raven.Json.Linq;

namespace Raven.Database.Counters.Controllers
{
	public class RavenCounterReplication:IDisposable
	{
        private static readonly ILog Log = LogManager.GetCurrentClassLogger();

        private readonly object waitForCounterUpdate = new object();
        private int actualWorkCounter = 0; // represents the number of changes in 
        private int replicatedWorkCounter = 0; // represents the last actualWorkCounter value that was checked in the last replication iteration
        private bool shouldPause = false;
        private bool IsRunning { get; set; }
        private readonly ConcurrentDictionary<string, CounterDestinationStats> destinationsStats =
            new ConcurrentDictionary<string, CounterDestinationStats>(StringComparer.OrdinalIgnoreCase);
        private int replicationAttempts;
        private readonly ConcurrentDictionary<string, SemaphoreSlim> activeReplicationTasks = new ConcurrentDictionary<string, SemaphoreSlim>();
        private readonly ConcurrentQueue<Task> activeTasks = new ConcurrentQueue<Task>();
        private HttpRavenRequestFactory httpRavenRequestFactory;

		private readonly CounterStorage storage;
		private readonly CancellationTokenSource cancellation;

        

		enum ReplicationResult
		{
			Success = 0,
			Failure = 1,
			NotReplicated = 2
		}

		public RavenCounterReplication(CounterStorage storage)
		{
			this.storage = storage;
			this.storage.CounterUpdated += SignalCounterUpdate;
			cancellation = new CancellationTokenSource();
		}

		public void SignalCounterUpdate()
		{
			lock (waitForCounterUpdate)
			{
				Interlocked.Increment(ref actualWorkCounter);
				Monitor.PulseAll(waitForCounterUpdate);
			}
		}

	    public void StartReplication()
	    {
            var replicationTask = new Task(ReplicationAction, TaskCreationOptions.LongRunning);

            httpRavenRequestFactory = new HttpRavenRequestFactory { RequestTimeoutInMs = storage.ReplicationTimeoutInMs };
            replicationTask.Start();
	    }

	    private void ReplicationAction()
	    {
	        var runningBecauseOfDataModification = false;
            var timeToWaitInMinutes = TimeSpan.FromMinutes(5);

            //NotifySiblings(); //TODO: implement

            while (!cancellation.IsCancellationRequested)
            {
                SendReplicationToAllServers(runningBecauseOfDataModification);
                runningBecauseOfDataModification = WaitForCountersUpdate(timeToWaitInMinutes);
                timeToWaitInMinutes = runningBecauseOfDataModification ? TimeSpan.FromSeconds(30) : TimeSpan.FromMinutes(5);
            }

	        IsRunning = false;
	    }

		private bool WaitForCountersUpdate(TimeSpan timeout)
		{
			if (Thread.VolatileRead(ref actualWorkCounter) != replicatedWorkCounter)
			{
				replicatedWorkCounter = actualWorkCounter;
				return true;
			}
			lock (waitForCounterUpdate)
			{
				if (Thread.VolatileRead(ref actualWorkCounter) != replicatedWorkCounter)
				{
					replicatedWorkCounter = actualWorkCounter;
					return true;
				}

				Log.Debug("No counter updates for counter storage {0} was found, will wait for updates", storage.CounterStorageUrl);
				return Monitor.Wait(waitForCounterUpdate, timeout);
			}
		}

		public void Pause()
		{
			shouldPause = true;
		}

		public void Continue()
		{
			shouldPause = false;
		}

		public void HandleHeartbeat(string src)
		{
			ResetFailureForHeartbeat(src);
		}

		private void ResetFailureForHeartbeat(string src)
		{
			RecordSuccess(src, lastHeartbeatReceived: SystemTime.UtcNow);
			SignalCounterUpdate();
		}

		private void SendReplicationToAllServers(bool runningBecauseOfDataModifications)
		{
			IsRunning = !shouldPause;
			if (IsRunning)
			{
				try
				{
					List<CounterStorageReplicationDestination> replicationDestinations = GetReplicationDestinations();

					if (replicationDestinations != null && replicationDestinations.Count > 0)
					{
						var currentReplicationAttempts = Interlocked.Increment(ref replicationAttempts);

						var destinationForReplication = replicationDestinations.Where(
							destination => (!runningBecauseOfDataModifications || IsNotFailing(destination.CounterStorageUrl, currentReplicationAttempts)) && !destination.Disabled);

						foreach (CounterStorageReplicationDestination destination in destinationForReplication)
						{
							ReplicateToDestination(destination);
						}
					}
				}
				catch (Exception e)
				{
					Log.ErrorException("Failed to perform replication", e);
				}
			}
		}

		private void ReplicateToDestination(CounterStorageReplicationDestination destination)
		{
			var dest = destination.CounterStorageUrl;
			var holder = activeReplicationTasks.GetOrAdd(dest, s => new SemaphoreSlim(1));
			if (holder.Wait(0) == false)
				return;
			var replicationTask = Task.Factory.StartNew(
				() =>
				{
					//using (LogContext.WithDatabase(storage.Name)) //TODO: log with counter storage contexe
					//{
					try
					{
						if (ReplicateTo(destination)) SignalCounterUpdate();
					}
					catch (Exception e)
					{
						Log.ErrorException("Could not replicate to " + dest, e);
					}
					//}
				});

			activeTasks.Enqueue(replicationTask);
			replicationTask.ContinueWith(
				_ =>
				{
					// here we purge all the completed tasks at the head of the queue
					Task task;
					while (activeTasks.TryPeek(out task))
					{
						if (!task.IsCompleted && !task.IsCanceled && !task.IsFaulted) break;
						activeTasks.TryDequeue(out task); // remove it from end
					}
				});
		}

		private bool ReplicateTo(CounterStorageReplicationDestination destination)
		{
            var replicationStopwatch = Stopwatch.StartNew();
			//todo: here, build url according to :destination.Url + '/counters/' + destination.
			try
			{
				string lastError;
			    long lastEtag;
				bool result = false;

				switch (TryReplicate(destination, out lastEtag, out lastError))
				{
					case ReplicationResult.Success:
                        DateTime replicationTime = SystemTime.UtcNow;
                        RecordSuccess(destination.CounterStorageUrl, lastReplicatedEtag: lastEtag, lastReplicatedLastModified: replicationTime);
                        storage.MetricsCounters.OutgoingReplications.Mark();
						result = true;
						break;
					case ReplicationResult.NotReplicated:
						//TODO: Record not replicated
                        RecordSuccess(destination.CounterStorageUrl, SystemTime.UtcNow);
						break;
					default:
						RecordFailure(destination.CounterStorageUrl, lastError);
                        storage.MetricsCounters.OutgoingReplications.Mark();
						break;
				}

				return result;
			}
			catch (Exception ex)
			{
				Log.ErrorException("Error occured replicating to: " + destination.CounterStorageUrl, ex);
				RecordFailure(destination.CounterStorageUrl, ex.Message);
				return false;
			}
			finally
			{
                replicationStopwatch.Stop();
                storage.MetricsCounters.GetReplicationDurationHistogram(destination.CounterStorageUrl).Update((long)replicationStopwatch.Elapsed.TotalMilliseconds);
                storage.MetricsCounters.GetReplicationDurationMetric(destination.CounterStorageUrl).Mark((long)replicationStopwatch.Elapsed.TotalMilliseconds);
				var holder = activeReplicationTasks.GetOrAdd(destination.CounterStorageUrl, s => new SemaphoreSlim(0, 1));
				holder.Release();
			}
		}

		private ReplicationResult TryReplicate(CounterStorageReplicationDestination destination, out long lastEtagSent, out string lastError)
		{
            long etag = 0;
		    lastEtagSent = 0;
			var connectionStringOptions = GetConnectionOptionsSafe(destination, out lastError);
            
            if (connectionStringOptions != null && GetLastReplicatedEtagFrom(connectionStringOptions, destination.CounterStorageUrl, out etag, out lastError))
			{
                var replicationData = GetCountersDataSinceEtag(etag, out lastEtagSent);
                
                storage.MetricsCounters.GetReplicationBatchSizeMetric(destination.CounterStorageUrl).Mark(replicationData.Counters.Count);
                storage.MetricsCounters.GetReplicationBatchSizeHistogram(destination.CounterStorageUrl).Update(replicationData.Counters.Count);

				if (replicationData.Counters.Count > 0)
				{
                    return PerformReplicationToServer(connectionStringOptions, destination.CounterStorageUrl, etag, replicationData, out lastError) ?
						ReplicationResult.Success : ReplicationResult.Failure;
				}

				return ReplicationResult.NotReplicated;
			}

			return ReplicationResult.Failure;
		}

		private bool GetLastReplicatedEtagFrom(RavenConnectionStringOptions connectionStringOptions, string counterStorageUrl, out long lastEtag, out string lastError)
		{
			if (!TryGetLastReplicatedEtagFrom(connectionStringOptions, counterStorageUrl, out lastEtag, out lastError))
			{
				if (IsFirstFailure(connectionStringOptions.Url))
				{
					return TryGetLastReplicatedEtagFrom(connectionStringOptions, counterStorageUrl, out lastEtag, out lastError);
				}
				return false;
			}

			return true;
		}

		private bool TryGetLastReplicatedEtagFrom(RavenConnectionStringOptions connectionStringOptions, string counterStorageUrl, out long lastEtag, out string lastError)
		{
			lastEtag = 0;
			try
			{
				long etag = 0;
				var url = string.Format("{0}/lastEtag?serverUrl={1}", counterStorageUrl, storage.CounterStorageUrl);
				var request = httpRavenRequestFactory.Create(url, "GET", connectionStringOptions);
				request.ExecuteRequest(etagString => etag = long.Parse(etagString.ReadToEnd()));

				lastEtag = etag;
				lastError = string.Empty;
				return true;
			}
			catch (WebException e)
			{
				lastError = HandleReplicationDistributionWebException(e, counterStorageUrl);
				return false;
			}
			catch (Exception e)
			{
				lastError = e.Message;
				return false;
			}
		}

		private bool PerformReplicationToServer(RavenConnectionStringOptions connectionStringOptions, string counterStorageUrl, long etag, ReplicationMessage message, out string lastError)
		{
			var destinationUrl = connectionStringOptions.Url;

			if (!TryPerformReplicationToServer(connectionStringOptions, counterStorageUrl, message, out lastError))
			{
				if (IsFirstFailure(destinationUrl))
				{
					return TryPerformReplicationToServer(connectionStringOptions, counterStorageUrl, message, out lastError);
				}
				return false;
			}

			return true;
		}

		private bool TryPerformReplicationToServer(RavenConnectionStringOptions connectionStringOptions, string counterStorageUrl, ReplicationMessage message, out string lastError)
		{
			try
			{
				var url = string.Format("{0}/replication", counterStorageUrl);
				lastError = string.Empty;
				var request = httpRavenRequestFactory.Create(url, "POST", connectionStringOptions);
				request.Write(RavenJObject.FromObject(message));
				request.ExecuteRequest();
                
                return true;

			}
			catch (WebException e)
			{
				lastError = HandleReplicationDistributionWebException(e, counterStorageUrl);
				return false;
			}
			catch (Exception e)
			{
				Log.ErrorException("Error occured replicating to: " + counterStorageUrl, e);
				lastError = e.Message;
				return false;
			}
		}

		private List<CounterStorageReplicationDestination> GetReplicationDestinations()
		{
			CounterStorageReplicationDocument replicationData;
			using (var reader = storage.CreateReader())
				replicationData = reader.GetReplicationData();
			return (replicationData != null) ? replicationData.Destinations : null;
		}
		
		private bool IsNotFailing(string destServerName, int currentReplicationAttempts)
        {
            CounterDestinationStats destinationStats;
            if (destinationsStats.TryGetValue(destServerName, out destinationStats) && destinationStats.FailureCount > 10)
			{
				bool shouldReplicateTo = false;
				var failureCount = destinationStats.FailureCount;

			    if (failureCount > 1000)
			    {
			        shouldReplicateTo = currentReplicationAttempts%10 == 0;
			    }
			    if (failureCount > 100)
			    {
			        shouldReplicateTo = currentReplicationAttempts%5 == 0;
			    }
			    if (failureCount > 10)
			    {
			        shouldReplicateTo = currentReplicationAttempts%2 == 0;
			    }
			    Log.Debug("Failure count for {0} is {1}, skipping replication: {2}",
			        destServerName, failureCount, shouldReplicateTo == false);
			    return shouldReplicateTo;
	        }
			return true;
        }

	    private ReplicationMessage GetCountersDataSinceEtag(long etag, out long lastEtagSent)
	    {
            var message = new ReplicationMessage { SendingServerName = storage.CounterStorageUrl };

            using (var reader = storage.CreateReader())
            {
                message.Counters = reader.GetCountersSinceEtag(etag + 1).Take(10240).ToList(); //TODO: Capped this...how to get remaining values?
                lastEtagSent = message.Counters.Count > 0 ? message.Counters.Max(x=>x.Etag):etag; // change this once changed this function do a reall paging
            }

	        return message;
	    }

		private RavenConnectionStringOptions GetConnectionOptionsSafe(CounterStorageReplicationDestination destination, out string lastError)
		{
			try
			{
				var connectionStringOptions = new RavenConnectionStringOptions
				{
                    Url = destination.ServerUrl,
					ApiKey = destination.ApiKey,
				};
				if (string.IsNullOrEmpty(destination.Username) == false)
				{
					connectionStringOptions.Credentials = string.IsNullOrEmpty(destination.Domain)
						? new NetworkCredential(destination.Username, destination.Password)
						: new NetworkCredential(destination.Username, destination.Password, destination.Domain);
				}
				lastError = string.Empty;
				return connectionStringOptions;
			}
			catch (Exception e)
			{
				lastError = e.Message;
				Log.ErrorException(string.Format("Ignoring bad replication config!{0}Could not figure out connection options for [Url: {1}]",
                    Environment.NewLine, destination.ServerUrl), e);
				return null;
			}
		}

        private bool IsFirstFailure(string destinationUrl)
        {
            var destStats = destinationsStats.GetOrAdd(destinationUrl, new CounterDestinationStats { Url = destinationUrl });
            return destStats.FailureCount == 0;
        }

		//Notifies servers which send us counters that we are back online
		private void NotifySiblings() //TODO: implement
		{
			var notifications = new BlockingCollection<RavenConnectionStringOptions>();

			Task.Factory.StartNew(() => NotifySibling(notifications));

			var replicationDestinations = GetReplicationDestinations();
			foreach (var replicationDestination in replicationDestinations)
			{
				string lastError;
				notifications.TryAdd(GetConnectionOptionsSafe(replicationDestination, out lastError), 15 * 1000);
			}

			//TODO: add to notifications to the source server, the servers we get the replications from
		}

		private void NotifySibling(BlockingCollection<RavenConnectionStringOptions> collection)
		{
			// using (LogContext.WithDatabase(docDb.Name)) todo:implement log context
			while (true)
			{
				RavenConnectionStringOptions connectionStringOptions;
				try
				{
					collection.TryTake(out connectionStringOptions, 15 * 1000, cancellation.Token);
					if (connectionStringOptions == null)
						return;
				}
				catch (Exception e)
				{
					Log.ErrorException("Could not get connection string options to notify sibling servers about restart", e);
					return;
				}
				try
				{
					var url = connectionStringOptions.Url + "/counters/" + storage.Name + "/replication/heartbeat?from=" + Uri.EscapeDataString(storage.CounterStorageUrl);
					var request = httpRavenRequestFactory.Create(url, "POST", connectionStringOptions);
					request.WebRequest.ContentLength = 0;
					request.ExecuteRequest();
				}
				catch (Exception e)
				{
					Log.WarnException("Could not notify " + connectionStringOptions.Url + " about sibling server being up & running", e);
				}
			}
		}
        
        private void RecordSuccess(string url,
            DateTime? lastSuccessTimestamp = null, 
            long? lastReplicatedEtag = null,
            DateTime? lastReplicatedLastModified = null,
            DateTime? lastHeartbeatReceived = null, string lastError = null)
        {
            var stats = destinationsStats.GetOrAdd(url, new CounterDestinationStats { Url = url });
            Interlocked.Exchange(ref stats.FailureCountInternal, 0);

            if (lastSuccessTimestamp.HasValue)
            {
                stats.LastSuccessTimestamp = lastSuccessTimestamp.Value;
            }

            if (lastReplicatedEtag.HasValue)
            {
                stats.LastReplicatedEtag = lastReplicatedEtag.Value;
            }

            if (lastReplicatedLastModified.HasValue)
                stats.LastSuccessTimestamp = stats.LastReplicatedLastModified = lastReplicatedLastModified;

            if (lastHeartbeatReceived.HasValue)
            {
                stats.LastHeartbeatReceived = lastHeartbeatReceived;
            }
            else
            {
                stats.LastHeartbeatReceived = SystemTime.UtcNow;
            }

            if (!string.IsNullOrWhiteSpace(lastError))
                stats.LastError = lastError;
        }

		private void RecordFailure(string url, string lastError)
		{
			var stats = destinationsStats.GetOrAdd(url, new CounterDestinationStats { Url = url });
			Interlocked.Increment(ref stats.FailureCountInternal);
			stats.LastFailureTimestamp = SystemTime.UtcNow;
			if (string.IsNullOrWhiteSpace(lastError) == false)
			{
				stats.LastError = lastError;
			}
		}

		private string HandleReplicationDistributionWebException(WebException e, string destinationUrl)
		{
			var response = e.Response as HttpWebResponse;
			if (response != null)
			{
				Stream responseStream = response.GetResponseStream();
				if (responseStream != null)
				{
					using (var streamReader = new StreamReader(responseStream))
					{
						var error = streamReader.ReadToEnd();
						Log.WarnException("Replication to " + destinationUrl + " had failed\r\n" + error, e);
					}
				}
				else
				{
					Log.WarnException("Replication to " + destinationUrl + " had failed", e);
				}
			}
			else
			{
				Log.WarnException("Replication to " + destinationUrl + " had failed", e);
			}

			return e.Message;
		}

	    public int GetActiveTasksCount()
	    {
	        return activeTasks.Count;
	    }

        public ConcurrentDictionary<string, CounterDestinationStats> DestinationStats
        {
            get { return destinationsStats; }
        }

		public void Dispose()
        {
            Task task;
            cancellation.Cancel();
            SignalCounterUpdate();

            while (activeTasks.TryDequeue(out task))
            {
                task.Wait();
            }
        }
    }
    
}
Back to Top