Skip to content

Commit

Permalink
Merge pull request #226 from gigya/develop
Browse files Browse the repository at this point in the history
New version
  • Loading branch information
yevgenyka authored Dec 19, 2018
2 parents dbcf918 + af8bbfc commit 6b3aa21
Show file tree
Hide file tree
Showing 17 changed files with 185 additions and 70 deletions.
8 changes: 4 additions & 4 deletions Gigya.Microdot.Configuration/Objects/ConfigObjectCreator.cs
Original file line number Diff line number Diff line change
Expand Up @@ -79,20 +79,20 @@ private void Init()
Reload();
ConfigCache.ConfigChanged.LinkTo(new ActionBlock<ConfigItemsCollection>(c => Reload()));
InitializeBroadcast();
healthStatus.RegisterCheck(ObjectType.Name, HealthCheck);
healthStatus.Register(ObjectType.Name, HealthCheck);
}

private HealthCheckResult HealthCheck()
private HealthMessage HealthCheck()
{
if (ValidationErrors != null)
{
return HealthCheckResult.Unhealthy("The config object failed validation.\r\n" +
return new HealthMessage(Health.Unhealthy, "The config object failed validation.\r\n" +
$"ConfigObjectType={ObjectType.FullName}\r\n" +
$"ConfigObjectPath={ConfigPath}\r\n" +
$"ValidationErrors={ValidationErrors}");
}

return HealthCheckResult.Healthy();
return new HealthMessage(Health.Healthy, "OK");
}

/// <summary>
Expand Down
8 changes: 8 additions & 0 deletions Gigya.Microdot.Ninject/NinjectExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -22,8 +22,10 @@

using System;
using System.Collections.Concurrent;
using System.Linq;
using Ninject;
using Ninject.Activation;
using Ninject.Planning.Bindings;

namespace Gigya.Microdot.Ninject
{
Expand Down Expand Up @@ -167,6 +169,12 @@ public static void BindPerString<TImplementation>(this IKernel kernel)
kernel.BindPerString<TImplementation, TImplementation>();
}

public static bool IsBinded(this IKernel kernel, Type serviceType)
{
IBinding binding = kernel.GetBindings(serviceType).FirstOrDefault();

return binding != null && binding.Target != BindingTarget.Provider;
}
}

public class DisposableConcurrentDictionary<TKey, TValue> : ConcurrentDictionary<TKey, TValue>, IDisposable
Expand Down
35 changes: 27 additions & 8 deletions Gigya.Microdot.Ninject/SystemInitializer/SystemInitializer.cs
Original file line number Diff line number Diff line change
Expand Up @@ -18,18 +18,21 @@
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
#endregion
#endregion

using System;
using System.Linq;
using System.Linq.Expressions;
using System.Net;
using System.Reflection;
using System.Threading.Tasks.Dataflow;
using Gigya.Microdot.Configuration;
using Gigya.Microdot.Configuration.Objects;
using Gigya.Microdot.Hosting.Metrics;
using Gigya.Microdot.Hosting.Validators;
using Gigya.Microdot.Interfaces;
using Ninject;
using Ninject.Planning.Bindings;

namespace Gigya.Microdot.Ninject.SystemInitializer
{
Expand Down Expand Up @@ -64,17 +67,29 @@ private void SearchAssembliesAndRebindIConfig()
{
IConfigObjectCreator configObjectCreator = _kernel.Get<Func<Type, IConfigObjectCreator>>()(configType);

dynamic getLatestLambda = configObjectCreator.GetLambdaOfGetLatest(configType);
_kernel.Rebind(typeof(Func<>).MakeGenericType(configType)).ToMethod(t => getLatestLambda());
if (!_kernel.IsBinded(typeof(Func<>).MakeGenericType(configType)))
{
dynamic getLatestLambda = configObjectCreator.GetLambdaOfGetLatest(configType);
_kernel.Rebind(typeof(Func<>).MakeGenericType(configType)).ToMethod(t => getLatestLambda());
}

Type sourceBlockType = typeof(ISourceBlock<>).MakeGenericType(configType);
_kernel.Rebind(sourceBlockType).ToMethod(t => configObjectCreator.ChangeNotifications);
if (!_kernel.IsBinded(typeof(ISourceBlock<>).MakeGenericType(configType)))
{
_kernel.Rebind(sourceBlockType).ToMethod(t => configObjectCreator.ChangeNotifications);
}

dynamic changeNotificationsLambda = configObjectCreator.GetLambdaOfChangeNotifications(sourceBlockType);
_kernel.Rebind(typeof(Func<>).MakeGenericType(sourceBlockType)).ToMethod(t => changeNotificationsLambda());

_kernel.Rebind(configType).ToMethod(t => configObjectCreator.GetLatest());
if (!_kernel.IsBinded(typeof(Func<>).MakeGenericType(sourceBlockType)))
{
dynamic changeNotificationsLambda = configObjectCreator.GetLambdaOfChangeNotifications(sourceBlockType);
_kernel.Rebind(typeof(Func<>).MakeGenericType(sourceBlockType)).ToMethod(t => changeNotificationsLambda());
}

if (!_kernel.IsBinded(configType))
{
_kernel.Rebind(configType).ToMethod(t => configObjectCreator.GetLatest());
}

_configObjectsCache.RegisterConfigObjectCreator(configObjectCreator);
}
}
Expand All @@ -97,6 +112,10 @@ private void SetServicePointManagerDefaultValues(ServicePointManagerDefaultConfi

public virtual void Dispose()
{
if (_configSource == null)
{
return;
}
_configSource.Complete();
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -261,7 +261,7 @@ public IEndPointHandle GetNextHost(string affinityToken = null)
var hostOverride = TracingContext.GetHostOverride(DeploymentIdentifier.ServiceName);

if (hostOverride != null)
return new OverriddenRemoteHost(DeploymentIdentifier.ServiceName, hostOverride.Hostname, hostOverride.Port?? GetConfig().DefaultPort);
return new OverriddenRemoteHost(DeploymentIdentifier.ServiceName, hostOverride.Host, hostOverride.Port?? GetConfig().DefaultPort);

lock (_lock)
{
Expand All @@ -288,7 +288,7 @@ public async Task<IEndPointHandle> GetOrWaitForNextHost(CancellationToken cancel
var hostOverride = TracingContext.GetHostOverride(DeploymentIdentifier.ServiceName);

if (hostOverride != null)
return new OverriddenRemoteHost(DeploymentIdentifier.ServiceName, hostOverride.Hostname, hostOverride.Port ?? GetConfig().DefaultPort);
return new OverriddenRemoteHost(DeploymentIdentifier.ServiceName, hostOverride.Host, hostOverride.Port ?? GetConfig().DefaultPort);

if (ReachableHosts.Count > 0)
return GetNextHost();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -87,7 +87,7 @@ public async Task<NodeAndLoadBalancer> GetNode()
var hostOverride = TracingContext.GetHostOverride(ServiceName);
if (hostOverride != null)
return new NodeAndLoadBalancer {
Node = new Node(hostOverride.Hostname, hostOverride.Port),
Node = new Node(hostOverride.Host, hostOverride.Port),
LoadBalancer = null,
PreferredEnvironment = preferredEnvironment ?? Environment.DeploymentEnvironment,
};
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,7 @@ public async Task<object> Invoke(HttpServiceRequest request, Type resultReturnTy

private HttpRequestMessage CreateHttpRequest(HttpServiceRequest request, JsonSerializerSettings jsonSettings, HostOverride node)
{
string uri = $"{(HttpSettings.UseHttps ? "https" : "http")}://{node.Hostname}:{node.Port ?? HttpSettings.BasePort}/{ServiceName}.{request.Target.MethodName}";
string uri = $"{(HttpSettings.UseHttps ? "https" : "http")}://{node.Host}:{node.Port ?? HttpSettings.BasePort}/{ServiceName}.{request.Target.MethodName}";

return new HttpRequestMessage(HttpMethod.Post, uri)
{
Expand Down
2 changes: 1 addition & 1 deletion Gigya.Microdot.SharedLogic/Events/TracingContext.cs
Original file line number Diff line number Diff line change
Expand Up @@ -105,7 +105,7 @@ public static void SetHostOverride(string serviceName, string host, int? port=nu
overrides.Hosts.Add(hostOverride);
}

hostOverride.Hostname = host;
hostOverride.Host = host;
hostOverride.Port = port;
}

Expand Down
2 changes: 1 addition & 1 deletion Gigya.Microdot.SharedLogic/HttpService/RequestOverrides.cs
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@ public class HostOverride : ExtendableJson

[JsonRequired]
[JsonProperty]
public string Hostname { get; set; }
public string Host { get; set; }

[JsonProperty]
public int? Port { get; set; }
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,8 @@ private HealthCheckResult HealthCheck()
: "")
+ $"{r.Name}: {r.Result.Message}"));

return allHealthy ? HealthCheckResult.Healthy(message) : HealthCheckResult.Unhealthy(message);
var formattableMessage = message.Replace("{", "{{").Replace("}", "}}"); // HealthCheckResult is formatting the message string using "string.Format"
return allHealthy ? HealthCheckResult.Healthy(formattableMessage) : HealthCheckResult.Unhealthy(formattableMessage);
}

[Obsolete("Please use method Register(string,Func<HealthMessage>) instead")]
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,6 @@ public NonOrleansServiceTester(int basePortOverride, IResolutionRoot resolutionR
public override void Dispose()
{
_host.Stop();
_host.Dispose();
var completed = _stopTask.Wait(60000);

if (!completed)
Expand Down
6 changes: 3 additions & 3 deletions SolutionVersion.cs
Original file line number Diff line number Diff line change
Expand Up @@ -28,9 +28,9 @@
[assembly: AssemblyCopyright("© 2018 Gigya Inc.")]
[assembly: AssemblyDescription("Microdot Framework")]

[assembly: AssemblyVersion("1.13.0.0")]
[assembly: AssemblyFileVersion("1.13.0.0")]
[assembly: AssemblyInformationalVersion("1.13.0.0")]
[assembly: AssemblyVersion("1.13.1.0")]
[assembly: AssemblyFileVersion("1.13.1.0")]
[assembly: AssemblyInformationalVersion("1.13.1.0")]

// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@
using Gigya.Microdot.Configuration;
using Gigya.Microdot.Fakes;
using Ninject;
using Ninject.Syntax;
using Shouldly;

namespace Gigya.Microdot.Orleans.Hosting.UnitTests.Microservice.CalculatorService
Expand Down Expand Up @@ -70,9 +71,11 @@ protected override void Configure(IKernel kernel, OrleansCodeConfig commonConfig

public class WithInvalidAgeLimitServiceHost : CalculatorServiceHost
{
protected override void Configure(IKernel kernel, OrleansCodeConfig commonConfig)
protected override void OnInitilize(IResolutionRoot resolutionRoot)
{
var originConfig = kernel.Get<OrleansConfig>();
base.OnInitilize(resolutionRoot);

var originConfig = resolutionRoot.Get<OrleansConfig>();
originConfig.GrainAgeLimits = new Dictionary<string, GrainAgeLimitConfig>
{
[ServiceName] = new GrainAgeLimitConfig
Expand All @@ -81,22 +84,6 @@ protected override void Configure(IKernel kernel, OrleansCodeConfig commonConfig
GrainAgeLimitInMins = 10
}
};


kernel. Rebind<IConfigurationDataWatcher, ManualConfigurationEvents>()
.To<ManualConfigurationEvents>()
.InSingletonScope();

kernel.Rebind<IConfigItemsSource, OverridableConfigItems>()
.To<OverridableConfigItems>()
.InSingletonScope()
.WithConstructorArgument("data", new Dictionary<string, string>());

OverridableConfigItems configItems = kernel.Get<IConfigItemsSource>() as OverridableConfigItems;
configItems.SetValue("OrleansConfig.GrainAgeLimits.SiteService.grainType", "Fake - Should throw an exception.");
configItems.SetValue("OrleansConfig.GrainAgeLimits.SiteService.grainAgeLimitInMins", "10");

base.Configure(kernel, commonConfig);
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,7 @@ public void HttpServiceRequestShouldContainAdditionaPropertiesRecursively()
};
RequestOverrides requestOverrides = new RequestOverrides
{
Hosts = new[] { new HostOverride { ServiceName = "Service1", Hostname = "HostNameOverride" } }.ToList()
Hosts = new[] { new HostOverride { ServiceName = "Service1", Host = "HostNameOverride" } }.ToList()
};
InvocationTarget invocationTarget = new InvocationTarget{MethodName = "MethodName1" };

Expand Down Expand Up @@ -102,7 +102,7 @@ private void AssertShouldBeNull(HttpServiceRequest serviceRequestResult)
serviceRequestResult.TracingData.SpanID.ShouldBe("SpanID1");
serviceRequestResult.TracingData.AdditionalProperties.ShouldBeNull();

serviceRequestResult.Overrides.Hosts[0].Hostname.ShouldBe("HostNameOverride");
serviceRequestResult.Overrides.Hosts[0].Host.ShouldBe("HostNameOverride");
serviceRequestResult.Overrides.Hosts[0].AdditionalProperties.ShouldBeNull();
serviceRequestResult.Overrides.AdditionalProperties.ShouldBeNull();

Expand All @@ -119,7 +119,7 @@ private void AssertShouldNotBeNull(HttpServiceRequest serviceRequestResult)
serviceRequestResult.TracingData.AdditionalProperties.Count.ShouldBe(1);
serviceRequestResult.TracingData.AdditionalProperties.ShouldContainKeyAndValue("TracingData", "TracingData1");

serviceRequestResult.Overrides.Hosts[0].Hostname.ShouldBe("HostNameOverride");
serviceRequestResult.Overrides.Hosts[0].Host.ShouldBe("HostNameOverride");
serviceRequestResult.Overrides.Hosts[0].AdditionalProperties.Count.ShouldBe(1);
serviceRequestResult.Overrides.Hosts[0].AdditionalProperties.ShouldContainKeyAndValue("HostOverrideData", "HostOverrideData1");
serviceRequestResult.Overrides.AdditionalProperties.Count.ShouldBe(1);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
using Gigya.Microdot.Interfaces.SystemWrappers;
using Gigya.Microdot.Ninject.SystemInitializer;
using Gigya.Microdot.ServiceDiscovery;
using Gigya.Microdot.ServiceDiscovery.Config;
using Gigya.Microdot.Testing;
using Gigya.Microdot.Testing.Shared;
using Gigya.Microdot.Testing.Shared.Utils;
Expand Down Expand Up @@ -42,7 +43,7 @@ public class ConsulDiscoveryMasterFallBackTest
[SetUp]
public void SetUp()
{
_unitTestingKernel?.Dispose();

_serviceName = $"ServiceName{++id}";

_environment = Substitute.For<IEnvironment>();
Expand All @@ -68,6 +69,17 @@ public void SetUp()
Assert.AreEqual(_environment, environment);
}

[TearDown]
public void Teardown()
{
_unitTestingKernel?.Dispose();
_configDic?.Clear();
_configDic = null;
_configRefresh = null;
_consulClient?.Clear();
_consulClient = null;
}

private void SetupConsulClientMocks()
{
_consulClient = new Dictionary<string, ConsulClientMock>();
Expand Down Expand Up @@ -146,8 +158,7 @@ public async Task CreateServiceDiscoveyWithoutGetNextHostNoServiceHealthShouldAp
[Repeat(Repeat)]
public async Task ScopeZoneShouldUseServiceNameAsConsoleQuery()
{
_configDic[$"Discovery.Services.{_serviceName}.Scope"] = "Zone";
_unitTestingKernel.Get<Ninject.SystemInitializer.SystemInitializer>().Init();
_unitTestingKernel.Get<Func<DiscoveryConfig>>()().Services[_serviceName].Scope = ServiceScope.Zone;
SetMockToReturnHost(_serviceName);
var nextHost = GetServiceDiscovey().GetNextHost();
(await nextHost).HostName.ShouldBe(_serviceName);
Expand Down Expand Up @@ -280,7 +291,7 @@ public async Task EndPointsChangedShouldFireConfigChange()
_configDic[$"Discovery.Services.{_serviceName}.Source"] = "Config";

Task waitForChangeEvent = waitForEvents.WhenNextEventReceived();
_configRefresh.RaiseChangeEvent();
await _configRefresh.ApplyChanges<DiscoveryConfig>();
await waitForChangeEvent;
var host = await discovey.GetNextHost();
host.HostName.ShouldBe("localhost");
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -123,7 +123,8 @@ public async Task ServiceInEnvironmentScope()
public async Task ServiceInZoneScope()
{
_configDic[$"Discovery.Services.{SERVICE_NAME}.Scope"] = "Zone";
_unitTestingKernel.Get<Ninject.SystemInitializer.SystemInitializer>().Init();
await _unitTestingKernel.Get<ManualConfigurationEvents>().ApplyChanges<DiscoveryConfig>();

await GetFirstResult().ConfigureAwait(false);
Assert.AreEqual($"{SERVICE_NAME}", _requestedConsulServiceName);
}
Expand Down
Loading

0 comments on commit 6b3aa21

Please sign in to comment.