public async Task SetPassiveAsync_DestinationBecameUnhealthy_SetUnhealthyAndScheduleReactivation() { var destination = new DestinationState("destination0"); destination.Health.Active = DestinationHealth.Healthy; destination.Health.Passive = DestinationHealth.Healthy; var cluster = CreateCluster(passive: true, active: false, destination); using var timerFactory = new TestTimerFactory(); var updater = new DestinationHealthUpdater(timerFactory, GetClusterUpdater(), new Mock <ILogger <DestinationHealthUpdater> >().Object); await updater.SetPassiveAsync(cluster, destination, DestinationHealth.Unhealthy, TimeSpan.FromSeconds(2)); timerFactory.VerifyTimer(0, 2000); Assert.Empty(cluster.DestinationsState.AvailableDestinations); Assert.Equal(DestinationHealth.Healthy, destination.Health.Active); Assert.Equal(DestinationHealth.Unhealthy, destination.Health.Passive); timerFactory.FireAll(); Assert.Equal(DestinationHealth.Healthy, destination.Health.Active); Assert.Equal(DestinationHealth.Unknown, destination.Health.Passive); Assert.Equal(1, cluster.DestinationsState.AvailableDestinations.Count); Assert.Same(destination, cluster.DestinationsState.AvailableDestinations[0]); timerFactory.AssertTimerDisposed(0); }
public virtual int _GetUniqueIdentifier() { var hashCode = 399326290; hashCode = hashCode * -1521134295 + (Id?.GetHashCode() ?? 0); hashCode = hashCode * -1521134295 + (TransportOrderNo?.GetHashCode() ?? 0); hashCode = hashCode * -1521134295 + (OrderYear?.GetHashCode() ?? 0); hashCode = hashCode * -1521134295 + (DocumentTransportNo?.GetHashCode() ?? 0); hashCode = hashCode * -1521134295 + (OrderDate?.GetHashCode() ?? 0); hashCode = hashCode * -1521134295 + (DepartureCustomerName?.GetHashCode() ?? 0); hashCode = hashCode * -1521134295 + (DepartureAddress?.GetHashCode() ?? 0); hashCode = hashCode * -1521134295 + (DepartureCity?.GetHashCode() ?? 0); hashCode = hashCode * -1521134295 + (DepartureState?.GetHashCode() ?? 0); hashCode = hashCode * -1521134295 + (DestinationName?.GetHashCode() ?? 0); hashCode = hashCode * -1521134295 + (DestinationAddress?.GetHashCode() ?? 0); hashCode = hashCode * -1521134295 + (DestinationCity?.GetHashCode() ?? 0); hashCode = hashCode * -1521134295 + (DestinationState?.GetHashCode() ?? 0); hashCode = hashCode * -1521134295 + (Qty?.GetHashCode() ?? 0); hashCode = hashCode * -1521134295 + (OrderWeight?.GetHashCode() ?? 0); hashCode = hashCode * -1521134295 + (Volume?.GetHashCode() ?? 0); hashCode = hashCode * -1521134295 + (Pallet?.GetHashCode() ?? 0); hashCode = hashCode * -1521134295 + (RetiredDate?.GetHashCode() ?? 0); hashCode = hashCode * -1521134295 + (DeliveryDate?.GetHashCode() ?? 0); hashCode = hashCode * -1521134295 + (Note?.GetHashCode() ?? 0); hashCode = hashCode * -1521134295 + (CallCustomerBefore?.GetHashCode() ?? 0); hashCode = hashCode * -1521134295 + (Telephone?.GetHashCode() ?? 0); hashCode = hashCode * -1521134295 + (DayClosed?.GetHashCode() ?? 0); hashCode = hashCode * -1521134295 + (Urgent?.GetHashCode() ?? 0); return(hashCode); }
public void GetAvailableDestinations_OneHealthCheckDisabled_UseUnknownState(bool activeEnabled, DestinationHealth active, bool passiveEnabled, DestinationHealth passive, bool isAvailable) { var cluster = new ClusterConfig() { ClusterId = "cluster1", HealthCheck = new HealthCheckConfig { Active = new ActiveHealthCheckConfig { Enabled = activeEnabled }, Passive = new PassiveHealthCheckConfig { Enabled = passiveEnabled } } }; var policy = new HealthyAndUnknownDestinationsPolicy(); var destination = new DestinationState("d0") { Health = { Active = active, Passive = passive } }; var availableDestinations = policy.GetAvailalableDestinations(cluster, new[] { destination }); if (isAvailable) { Assert.Single(availableDestinations, destination); } else { Assert.Empty(availableDestinations); } }
public void RequestProxied(ClusterState cluster, DestinationState destination, HttpContext context) { var error = context.Features.Get <IProxyErrorFeature>(); var newHealth = EvaluateProxiedRequest(cluster, destination, error != null); var reactivationPeriod = cluster.Model.Config.HealthCheck?.Passive?.ReactivationPeriod ?? _defaultReactivationPeriod; _healthUpdater.SetPassive(cluster, destination, newHealth, reactivationPeriod); }
/// <summary> /// Returns true if HistoryItem instances are equal /// </summary> /// <param name="other">Instance of HistoryItem to be compared</param> /// <returns>Boolean</returns> public bool Equals(HistoryItem other) { if (ReferenceEquals(null, other)) { return(false); } if (ReferenceEquals(this, other)) { return(true); } return (( Id == other.Id || Id != null && Id.Equals(other.Id) ) && ( ProcessId == other.ProcessId || ProcessId != null && ProcessId.Equals(other.ProcessId) ) && ( IdentityId == other.IdentityId || IdentityId != null && IdentityId.Equals(other.IdentityId) ) && ( AllowedToEmployeeNames == other.AllowedToEmployeeNames || AllowedToEmployeeNames != null && AllowedToEmployeeNames.Equals(other.AllowedToEmployeeNames) ) && ( TransitionTime == other.TransitionTime || TransitionTime != null && TransitionTime.Equals(other.TransitionTime) ) && ( Order == other.Order || Order != null && Order.Equals(other.Order) ) && ( InitialState == other.InitialState || InitialState != null && InitialState.Equals(other.InitialState) ) && ( DestinationState == other.DestinationState || DestinationState != null && DestinationState.Equals(other.DestinationState) ) && ( Command == other.Command || Command != null && Command.Equals(other.Command) )); }
public ParserState(ParserState other) { rds = other.rds; ris = other.ris; CharacterAttributes = new CharacterAttributes(other.CharacterAttributes); ParagraphAttributes = new ParagraphAttributes(other.ParagraphAttributes); SectionAttributes = new SectionAttributes(other.SectionAttributes); DocumentAttributes = new DocumentAttributes(other.DocumentAttributes); }
public ParserState() { CharacterAttributes = new CharacterAttributes(); ParagraphAttributes = new ParagraphAttributes(); SectionAttributes = new SectionAttributes(); DocumentAttributes = new DocumentAttributes(); rds = DestinationState.Normal; ris = ParserInternalState.Normal; }
public void RequestProxied(HttpContext context, ClusterState cluster, DestinationState destination) { var newHealth = EvaluateProxiedRequest(cluster, destination, DetermineIfDestinationFailed(context)); var clusterReactivationPeriod = cluster.Model.Config.HealthCheck?.Passive?.ReactivationPeriod ?? _defaultReactivationPeriod; // Avoid reactivating until the history has expired so that it does not affect future health assessments. var reactivationPeriod = clusterReactivationPeriod >= _policyOptions.DetectionWindowSize ? clusterReactivationPeriod : _policyOptions.DetectionWindowSize; _healthUpdater.SetPassive(cluster, destination, newHealth, reactivationPeriod); }
private IReverseProxyFeature GetProxyFeature(ClusterState clusterState, DestinationState destination) { return(new ReverseProxyFeature() { ProxiedDestination = destination, Cluster = clusterState.Model, Route = new RouteModel(new RouteConfig(), clusterState, HttpTransformer.Default), }); }
public void DestionationInfoReadOnlyList() { var destinationInfo = new DestinationState("destionation2"); IReadOnlyList <DestinationState> list = destinationInfo; Assert.Equal(1, list.Count); Assert.Same(destinationInfo, list[0]); Assert.Throws <IndexOutOfRangeException>(() => list[1]); }
public void AffinitizeRequest_RequestIsNotAffinitized_SetAffinityKey() { var dataProtector = GetDataProtector(); var provider = new ProviderStub(dataProtector.Object, AffinityTestHelper.GetLogger <BaseSessionAffinityPolicy <string> >().Object); var destination = new DestinationState("dest-A"); provider.AffinitizeResponse(new DefaultHttpContext(), new ClusterState("cluster"), _defaultOptions, destination); Assert.Equal("ZGVzdC1B", provider.LastSetEncryptedKey); var keyBytes = Encoding.UTF8.GetBytes(destination.DestinationId); dataProtector.Verify(p => p.Protect(It.Is <byte[]>(b => b.SequenceEqual(keyBytes))), Times.Once); }
public void ReassignProxyRequest_Success() { var client = new HttpMessageInvoker(new SocketsHttpHandler()); var context = new DefaultHttpContext(); var d1 = new DestinationState("d1"); var d2 = new DestinationState("d2"); var cc1 = new ClusterConfig() { ClusterId = "c1" }; var cm1 = new ClusterModel(cc1, client); var cs1 = new ClusterState("c1") { Model = cm1 }; var r1 = new RouteModel(new RouteConfig() { RouteId = "r1" }, cs1, HttpTransformer.Empty); var feature = new ReverseProxyFeature() { AllDestinations = d1, AvailableDestinations = d1, Cluster = cm1, Route = r1, ProxiedDestination = d1, }; context.Features.Set <IReverseProxyFeature>(feature); var cc2 = new ClusterConfig() { ClusterId = "cc2" }; var cm2 = new ClusterModel(cc2, client); var cs2 = new ClusterState("cs2") { DestinationsState = new ClusterDestinationsState(d2, d2), Model = cm2, }; context.ReassignProxyRequest(cs2); var newFeature = context.GetReverseProxyFeature(); Assert.NotSame(feature, newFeature); Assert.Same(d2, newFeature.AllDestinations); Assert.Same(d2, newFeature.AvailableDestinations); Assert.Same(d1, newFeature.ProxiedDestination); // Copied unmodified. Assert.Same(cm2, newFeature.Cluster); Assert.Same(r1, newFeature.Route); }
public async Task Invoke_SuccessfulFlow_CallNext(AffinityStatus status, string foundDestinationId) { var cluster = GetCluster(); var endpoint = GetEndpoint(cluster); DestinationState foundDestination = null; if (foundDestinationId != null) { cluster.Destinations.TryGetValue(foundDestinationId, out foundDestination); } var invokedMode = string.Empty; const string expectedMode = "Policy-B"; var policies = RegisterAffinityPolicies( true, cluster.Destinations.Values.ToList(), ("Policy-A", AffinityStatus.DestinationNotFound, (DestinationState)null, (Action <ISessionAffinityPolicy>)(p => throw new InvalidOperationException($"Policy {p.Name} call is not expected."))), (expectedMode, status, foundDestination, p => invokedMode = p.Name)); var nextInvoked = false; var middleware = new SessionAffinityMiddleware(c => { nextInvoked = true; return(Task.CompletedTask); }, policies.Select(p => p.Object), new IAffinityFailurePolicy[0], new Mock <ILogger <SessionAffinityMiddleware> >().Object); var context = new DefaultHttpContext(); context.SetEndpoint(endpoint); var destinationFeature = GetReverseProxyFeature(cluster); context.Features.Set(destinationFeature); await middleware.Invoke(context); Assert.Equal(expectedMode, invokedMode); Assert.True(nextInvoked); policies[0].VerifyGet(p => p.Name, Times.Once); policies[0].VerifyNoOtherCalls(); policies[1].VerifyAll(); if (foundDestinationId != null) { Assert.Equal(1, destinationFeature.AvailableDestinations.Count); Assert.Equal(foundDestinationId, destinationFeature.AvailableDestinations[0].DestinationId); } else { Assert.True(cluster.Destinations.Values.SequenceEqual(destinationFeature.AvailableDestinations)); } }
public void DestinationInfoEnumerator() { var destinationInfo = new DestinationState("destionation1"); var list = new List <DestinationState>(); foreach (var item in destinationInfo) { list.Add(item); } var first = Assert.Single(list); Assert.Same(destinationInfo, first); }
public override void LoadState(DestinationState state) { if (state != null) { this.SentTupleIds = state.SentIds; this.CachedOutputTuples = state.CachedOutputTuples; this.RoutingStrategy.LoadState(state.RoutingState); //this.Buffer = new BlockingCollection<CTuple>(new ConcurrentQueue<CTuple>(), BufferSize); // start a buffer from the beginning foreach (CTuple tuple in state.OutputBuffer) { Console.WriteLine($"Loadstate: inserting tuple {tuple}"); Insert(tuple); } } }
private DestinationHealth EvaluateProxiedRequest(ClusterState cluster, DestinationState destination, bool failed) { var history = _requestHistories.GetOrCreateValue(destination); var rateLimitEntry = _clusterFailureRateLimits.GetValue(cluster, c => new ParsedMetadataEntry <double>(TryParse, c, TransportFailureRateHealthPolicyOptions.FailureRateLimitMetadataName)); var rateLimit = rateLimitEntry.GetParsedOrDefault(_policyOptions.DefaultFailureRateLimit); lock (history) { var failureRate = history.AddNew( _clock.TickCount, (long)_policyOptions.DetectionWindowSize.TotalMilliseconds, _policyOptions.MinimalTotalCountThreshold, failed); return(failureRate < rateLimit ? DestinationHealth.Healthy : DestinationHealth.Unhealthy); } }
public void DelegateRequest(HttpContext context, DestinationState destination) { _ = context ?? throw new ArgumentNullException(nameof(context)); _ = destination ?? throw new ArgumentNullException(nameof(destination)); var requestDelegationFeature = context.Features.Get <IHttpSysRequestDelegationFeature>() ?? throw new InvalidOperationException($"{typeof(IHttpSysRequestDelegationFeature).FullName} is missing."); if (!requestDelegationFeature.CanDelegate) { throw new InvalidOperationException( "Current request can't be delegated. Either the request body has started to be read or the response has started to be sent."); } if (_serverDelegationFeature is null || !_queuesPerDestination.TryGetValue(destination, out var queue)) { Log.QueueNotFound(_logger, destination); context.Response.StatusCode = StatusCodes.Status503ServiceUnavailable; context.Features.Set <IForwarderErrorFeature>(new ForwarderErrorFeature(ForwarderError.NoAvailableDestinations, ex: null)); return; } // Opportunistically retry initialization if it failed previously. // This helps when the target queue wasn't yet created because // the target process hadn't yet started up. var queueState = queue.Initialize(_serverDelegationFeature); if (!queueState.IsInitialized) { Log.QueueNotInitialized(_logger, destination, queueState.InitializationException); context.Response.StatusCode = StatusCodes.Status503ServiceUnavailable; context.Features.Set <IForwarderErrorFeature>(new ForwarderErrorFeature(ForwarderError.NoAvailableDestinations, queueState.InitializationException)); return; } try { Log.DelegatingRequest(_logger, destination); requestDelegationFeature.DelegateRequest(queueState.Rule); } catch (Exception ex) { Log.DelegationFailed(_logger, destination, ex); context.Response.StatusCode = StatusCodes.Status503ServiceUnavailable; context.Features.Set <IForwarderErrorFeature>(new ForwarderErrorFeature(ForwarderError.Request, ex)); } }
public async Task SetPassiveAsync_HealthSateIsNotChanged_DoNothing(DestinationHealth health) { var destination = new DestinationState("destination0"); destination.Health.Active = DestinationHealth.Healthy; destination.Health.Passive = health; var cluster = CreateCluster(passive: true, active: false, destination); using var timerFactory = new TestTimerFactory(); var updater = new DestinationHealthUpdater(timerFactory, GetClusterUpdater(), new Mock <ILogger <DestinationHealthUpdater> >().Object); await updater.SetPassiveAsync(cluster, destination, health, TimeSpan.FromSeconds(2)); Assert.Equal(0, timerFactory.Count); Assert.Equal(DestinationHealth.Healthy, destination.Health.Active); Assert.Equal(health, destination.Health.Passive); }
/// <summary> /// Gets the hash code /// </summary> /// <returns>Hash code</returns> public override int GetHashCode() { unchecked // Overflow is fine, just wrap { var hashCode = 41; // Suitable nullity checks etc, of course :) if (Id != null) { hashCode = hashCode * 59 + Id.GetHashCode(); } if (ProcessId != null) { hashCode = hashCode * 59 + ProcessId.GetHashCode(); } if (IdentityId != null) { hashCode = hashCode * 59 + IdentityId.GetHashCode(); } if (AllowedToEmployeeNames != null) { hashCode = hashCode * 59 + AllowedToEmployeeNames.GetHashCode(); } if (TransitionTime != null) { hashCode = hashCode * 59 + TransitionTime.GetHashCode(); } if (Order != null) { hashCode = hashCode * 59 + Order.GetHashCode(); } if (InitialState != null) { hashCode = hashCode * 59 + InitialState.GetHashCode(); } if (DestinationState != null) { hashCode = hashCode * 59 + DestinationState.GetHashCode(); } if (Command != null) { hashCode = hashCode * 59 + Command.GetHashCode(); } return(hashCode); } }
public bool Equals(Entry other) { return(other != null && Code.Equals(other.Code) && Volume.Equals(other.Volume) && Count.Equals(other.Count) && Date.Equals(other.Date) && Type.Equals(other.Type) && Sender.Equals(other.Sender) && Recipient.Equals(other.Recipient) && ShipmentCountry.Equals(other.ShipmentCountry) && ShipmentState.Equals(other.ShipmentState) && ShipmentRailRoad.Equals(other.ShipmentRailRoad) && ShipmentStation.Equals(other.ShipmentStation) && DestinationCountry.Equals(other.DestinationCountry) && DestinationState.Equals(other.DestinationState) && DestinationRailRoad.Equals(other.DestinationRailRoad) && DestinationStation.Equals(other.DestinationStation)); }
public async Task SetPassiveAsync_DestinationBecameHealthy_SetNewState() { var destination = new DestinationState("destination0"); destination.Health.Active = DestinationHealth.Healthy; destination.Health.Passive = DestinationHealth.Unhealthy; var cluster = CreateCluster(passive: true, active: false, destination); using var timerFactory = new TestTimerFactory(); var updater = new DestinationHealthUpdater(timerFactory, GetClusterUpdater(), new Mock <ILogger <DestinationHealthUpdater> >().Object); await updater.SetPassiveAsync(cluster, destination, DestinationHealth.Healthy, TimeSpan.FromSeconds(2)); Assert.Equal(0, timerFactory.Count); Assert.Equal(DestinationHealth.Healthy, destination.Health.Active); Assert.Equal(DestinationHealth.Healthy, destination.Health.Passive); Assert.Equal(1, cluster.DestinationsState.AvailableDestinations.Count); Assert.Same(destination, cluster.DestinationsState.AvailableDestinations[0]); }
public override int GetHashCode() { var hashCode = 352033288; hashCode = hashCode * -1521134295 + Code.GetHashCode(); hashCode = hashCode * -1521134295 + Volume.GetHashCode(); hashCode = hashCode * -1521134295 + Count.GetHashCode(); hashCode = hashCode * -1521134295 + Date.GetHashCode(); hashCode = hashCode * -1521134295 + Type.GetHashCode(); hashCode = hashCode * -1521134295 + Sender.GetHashCode(); hashCode = hashCode * -1521134295 + Recipient.GetHashCode(); hashCode = hashCode * -1521134295 + ShipmentCountry.GetHashCode(); hashCode = hashCode * -1521134295 + ShipmentState.GetHashCode(); hashCode = hashCode * -1521134295 + ShipmentRailRoad.GetHashCode(); hashCode = hashCode * -1521134295 + ShipmentStation.GetHashCode(); hashCode = hashCode * -1521134295 + DestinationCountry.GetHashCode(); hashCode = hashCode * -1521134295 + DestinationState.GetHashCode(); hashCode = hashCode * -1521134295 + DestinationRailRoad.GetHashCode(); hashCode = hashCode * -1521134295 + DestinationStation.GetHashCode(); return(hashCode); }
public void Request_FindAffinitizedDestinations( HttpContext context, DestinationState[] allDestinations, AffinityStatus expectedStatus, DestinationState expectedDestination, byte[] expectedEncryptedKey, bool unprotectCalled, LogLevel?expectedLogLevel, EventId expectedEventId) { var dataProtector = GetDataProtector(); var logger = AffinityTestHelper.GetLogger <BaseSessionAffinityPolicy <string> >(); var provider = new ProviderStub(dataProtector.Object, logger.Object); var cluster = new ClusterState("cluster"); var affinityResult = provider.FindAffinitizedDestinations(context, cluster, _defaultOptions, allDestinations); if (unprotectCalled) { dataProtector.Verify(p => p.Unprotect(It.Is <byte[]>(b => b.SequenceEqual(expectedEncryptedKey))), Times.Once); } Assert.Equal(expectedStatus, affinityResult.Status); Assert.Same(expectedDestination, affinityResult.Destinations?.FirstOrDefault()); if (expectedLogLevel != null) { logger.Verify( l => l.Log(expectedLogLevel.Value, expectedEventId, It.IsAny <It.IsAnyType>(), It.IsAny <Exception>(), (Func <It.IsAnyType, Exception, string>)It.IsAny <object>()), Times.Once); } if (expectedDestination != null) { Assert.Equal(1, affinityResult.Destinations.Count); } else { Assert.Null(affinityResult.Destinations); } }
public void SetActive_ChangedAndUnchangedHealthStates_SetChangedStates() { var destination0 = new DestinationState("destination0"); destination0.Health.Active = DestinationHealth.Healthy; destination0.Health.Passive = DestinationHealth.Healthy; var destination1 = new DestinationState("destination1"); destination1.Health.Active = DestinationHealth.Healthy; destination1.Health.Passive = DestinationHealth.Healthy; var destination2 = new DestinationState("destination2"); destination2.Health.Active = DestinationHealth.Unhealthy; destination2.Health.Passive = DestinationHealth.Healthy; var destination3 = new DestinationState("destination3"); destination3.Health.Active = DestinationHealth.Unhealthy; destination3.Health.Passive = DestinationHealth.Healthy; var cluster = CreateCluster(passive: false, active: true, destination0, destination1, destination2, destination3); var updater = new DestinationHealthUpdater(new Mock <ITimerFactory>().Object, GetClusterUpdater(), new Mock <ILogger <DestinationHealthUpdater> >().Object); var newHealthStates = new[] { new NewActiveDestinationHealth(destination0, DestinationHealth.Unhealthy), new NewActiveDestinationHealth(destination1, DestinationHealth.Healthy), new NewActiveDestinationHealth(destination2, DestinationHealth.Unhealthy), new NewActiveDestinationHealth(destination3, DestinationHealth.Healthy) }; updater.SetActive(cluster, newHealthStates); foreach (var newHealthState in newHealthStates) { Assert.Equal(newHealthState.NewActiveHealth, newHealthState.Destination.Health.Active); Assert.Equal(DestinationHealth.Healthy, newHealthState.Destination.Health.Passive); } Assert.Equal(2, cluster.DestinationsState.AvailableDestinations.Count); Assert.Contains(cluster.DestinationsState.AvailableDestinations, d => d == destination1); Assert.Contains(cluster.DestinationsState.AvailableDestinations, d => d == destination3); }
public NewActiveDestinationHealth(DestinationState destination, DestinationHealth newActiveHealth) { Destination = destination; NewActiveHealth = newActiveHealth; }
private string[] GetCookieWithAffinity(DestinationState affinitizedDestination) { return(new[] { $"Some-Cookie=ZZZ", $"{_config.AffinityKeyName}={affinitizedDestination.DestinationId.ToUTF8BytesInBase64()}" }); }
public StubPolicy(string name, DestinationState skipDestination) { Name = name; _skipDestination = skipDestination; }
public DestinationProbingResult(DestinationState destination, HttpResponseMessage?response, Exception?exception) { Destination = destination ?? throw new ArgumentNullException(nameof(destination)); Response = response; Exception = exception; }
protected override string GetDestinationAffinityKey(DestinationState destination) { return(destination.DestinationId); }
public DestinationKeyword(String keyword, DestinationState destState) : base(keyword, KeywordType.Destination) { _destState = destState; }