Skip to content
This repository has been archived by the owner on Jul 9, 2020. It is now read-only.

Commit

Permalink
Merge pull request #2 from rogeralsing/dev
Browse files Browse the repository at this point in the history
Dev
  • Loading branch information
rogeralsing committed Oct 18, 2015
2 parents 6a763ff + b6264d1 commit 952a43b
Show file tree
Hide file tree
Showing 29 changed files with 190 additions and 406 deletions.
105 changes: 105 additions & 0 deletions Microphone.Core/Cluster.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,105 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Consul;

namespace Microphone.Core
{
public static class Cluster
{
private static string ServiceName;
private static string ServiceId;

public static string GetConfig()
{
var client = new Client();
var key = "ServiceConfig:" + ServiceName;
var response = client.KV.Get(key);
var res = Encoding.UTF8.GetString(response.Response.Value);
return res;
}

public static ServiceInformation[] FindService(string name)
{
Logger.Information("{ServiceName} lookup {OtherServiceName}", ServiceName, name);
var client = new Client();
var others = client.Health.Service(name, null, true);

return
others.Response.Select(other => new ServiceInformation(other.Service.Address, other.Service.Port))
.ToArray();
}

public static void RegisterService(string serviceName, string serviceId, string version, Uri uri)
{
ServiceName = serviceName;
ServiceId = serviceId;
var client = new Client();
client.Agent.ServiceRegister(new AgentServiceRegistration
{
Address = uri.Host,
ID = serviceId,
Name = serviceName,
Port = uri.Port,
Tags = new[] {version},
Check = new AgentServiceCheck
{
HTTP = uri + "status",
Interval = TimeSpan.FromSeconds(1),
TTL = TimeSpan.Zero,
Timeout = TimeSpan.Zero
}
});
StartReaper();
}

private static void StartReaper()
{
Task.Factory.StartNew(async () =>
{
await Task.Delay(1000).ConfigureAwait(false);
Logger.Information("Reaper: started..");
var client = new Client();
var lookup = new HashSet<string>();
while (true)
{
try
{
var checks = client.Agent.Checks();
foreach (var check in checks.Response)
{
if (Equals(check.Value.Status, CheckStatus.Critical))
{
//dont delete new services
if (lookup.Contains(check.Value.ServiceID))
{
client.Agent.ServiceDeregister(check.Value.ServiceID);
Logger.Information("Reaper: Removing {ServiceId}", check.Value.ServiceID);
}
else
{
Logger.Information("Reaper: Marking {ServiceId}", check.Value.ServiceID);
lookup.Add(check.Value.ServiceID);
}

}
else
{
//if service is ok, remove it from reaper set
lookup.Remove(check.Value.ServiceID);
}
}
}
catch(Exception x)
{
Logger.Error(x,"Crashed");
}

await Task.Delay(5000).ConfigureAwait(false);
}
});
}
}
}
27 changes: 27 additions & 0 deletions Microphone.Core/Configuration.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
using System;
using System.Net;
using System.Net.Sockets;

namespace Microphone.Core
{
public static class Configuration
{


public static Uri GetUri(int port = 0)
{
port = port == 0 ? FreeTcpPort() : port;
var uri = new Uri("http://localhost:" + port);
return uri;
}

private static int FreeTcpPort()
{
var l = new TcpListener(IPAddress.Loopback, 0);
l.Start();
var port = ((IPEndPoint)l.LocalEndpoint).Port;
l.Stop();
return port;
}
}
}
17 changes: 11 additions & 6 deletions Microphone.Core/Logger.cs
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
using System;
using Serilog;
using Serilog.Events;

namespace Microphone.Core
{
public class Logger
public static class Logger
{
private static readonly ILogger _logger;

Expand All @@ -12,23 +13,27 @@ static Logger()
_logger = new LoggerConfiguration().WriteTo.ColoredConsole(LogEventLevel.Debug).CreateLogger();
}


public void Debug(string template, params object[] args)
public static void Debug(string template, params object[] args)
{
_logger.Debug(template,args);
}

public void Information(string template, params object[] args)
public static void Information(string template, params object[] args)
{
_logger.Information(template, args);
}

public void Error(string template, params object[] args)
public static void Error(string template, params object[] args)
{
_logger.Error(template, args);
}

public void Warning(string template, params object[] args)
public static void Error(Exception cause, string template, params object[] args)
{
_logger.Error(cause,template, args);
}

public static void Warning(string template, params object[] args)
{
_logger.Warning(template, args);
}
Expand Down
11 changes: 11 additions & 0 deletions Microphone.Core/Microphone.Core.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,14 @@
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<ItemGroup>
<Reference Include="Consul, Version=0.5.2.65, Culture=neutral, PublicKeyToken=20a6ad9a81df1d95, processorArchitecture=MSIL">
<HintPath>..\packages\Consul.0.5.2.65\lib\net45\Consul.dll</HintPath>
<Private>True</Private>
</Reference>
<Reference Include="Newtonsoft.Json, Version=7.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed, processorArchitecture=MSIL">
<HintPath>..\packages\Newtonsoft.Json.7.0.1\lib\net45\Newtonsoft.Json.dll</HintPath>
<Private>True</Private>
</Reference>
<Reference Include="Serilog, Version=1.5.0.0, Culture=neutral, PublicKeyToken=24c2f752a8e58a10, processorArchitecture=MSIL">
<HintPath>..\packages\Serilog.1.5.11\lib\net45\Serilog.dll</HintPath>
<Private>True</Private>
Expand All @@ -48,11 +56,14 @@
<Reference Include="System.Xml" />
</ItemGroup>
<ItemGroup>
<Compile Include="Cluster.cs" />
<Compile Include="Configuration.cs" />
<Compile Include="Logger.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
<Compile Include="ServiceInformation.cs" />
</ItemGroup>
<ItemGroup>
<None Include="build.bat" />
<None Include="Microphone.Core.nuspec" />
<None Include="packages.config" />
</ItemGroup>
Expand Down
4 changes: 2 additions & 2 deletions Microphone.Core/Properties/AssemblyInfo.cs
Original file line number Diff line number Diff line change
Expand Up @@ -33,5 +33,5 @@
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("0.1.0.0")]
[assembly: AssemblyFileVersion("0.1.0.0")]
[assembly: AssemblyVersion("0.1.3.0")]
[assembly: AssemblyFileVersion("0.1.3.0")]
3 changes: 2 additions & 1 deletion Microphone.Core/build.bat
Original file line number Diff line number Diff line change
@@ -1,2 +1,3 @@
del *.nupkg
nuget pack Microphone.Core.csproj -IncludeReferencedProjects -Prop Configuration=Release
nuget push Microphone.Core.0.1.0.0.nupkg
nuget push Microphone.Core.0.1.3.0.nupkg
2 changes: 2 additions & 0 deletions Microphone.Core/packages.config
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
<?xml version="1.0" encoding="utf-8"?>
<packages>
<package id="Consul" version="0.5.2.65" targetFramework="net46" />
<package id="Newtonsoft.Json" version="7.0.1" targetFramework="net46" />
<package id="Serilog" version="1.5.11" targetFramework="net46" />
</packages>
42 changes: 4 additions & 38 deletions Microphone.Nancy/AutoRegisterModule.cs
Original file line number Diff line number Diff line change
@@ -1,51 +1,17 @@
using System.Collections.Generic;
using System.Linq;
using Consul;
using Microphone.Core;
using Microphone.Core;
using Nancy;

namespace Microphone.Nancy
{
public abstract class AutoRegisterModule : NancyModule
public class StatusModule : NancyModule
{
private readonly Logger _logger;

protected Logger Logger => _logger;

protected AutoRegisterModule()
public StatusModule()
{
_logger = new Logger();
//Before += ctx =>
//{
// _logger.Information("{Url} - {Method}", ctx.Request.Url , ctx.Request.Method );
// return null;
//};

Get["/status"] = _ =>
{
Logger.Information("OK");
return "ok";
};
}

protected string GetConfig()
{
var client = new Client();
var key = "ServiceConfig:" + Bootstrap.ServiceName;
var response = client.KV.Get(key);
var res = System.Text.Encoding.UTF8.GetString(response.Response.Value);
return res;
}

protected ServiceInformation[] FindService(string name)
{
Logger.Information("{ServiceName} lookup {OtherServiceName}",Bootstrap.ServiceName,name);
var client = new Client();
var others = client.Catalog.Service(name);

return
others.Response.Select(other => new ServiceInformation(other.ServiceAddress, other.ServicePort))
.ToArray();
}
}
}
}
43 changes: 3 additions & 40 deletions Microphone.Nancy/Bootstrap.cs
Original file line number Diff line number Diff line change
@@ -1,45 +1,24 @@
using System;
using System.Net;
using System.Net.Sockets;
using System.Threading.Tasks;
using Consul;
using Microphone.Core;
using Nancy;
using Nancy.Hosting.Self;

namespace Microphone.Nancy
{
public class Bootstrap
{
public static string ServiceName { get; private set; }
public static string Version { get; private set; }

public static void Start(string serviceName, string version)
{
ServiceName = serviceName;
Version = version;
var serviceId = serviceName + Guid.NewGuid();
var uri = GetUri();
var uri = Configuration.GetUri();
var conf = GetConfiguration();
var host = GetHost(uri, conf);

Console.WriteLine("{0} running on {1}", serviceId, uri);

var client = new Client();
client.Agent.ServiceRegister(new AgentServiceRegistration
{
Address = uri.Host,
ID = serviceId,
Name = serviceName,
Port = uri.Port,
Tags = new[] {version},
Check = new AgentServiceCheck
{
HTTP = uri + "status",
Interval = TimeSpan.FromSeconds(1),
TTL = TimeSpan.Zero,
Timeout = TimeSpan.Zero
}
});
Cluster.RegisterService(serviceName, serviceId, version, uri);
}

private static NancyHost GetHost(Uri uri, HostConfiguration hostConfigs)
Expand Down Expand Up @@ -71,21 +50,5 @@ private static HostConfiguration GetConfiguration()
};
return hostConfigs;
}

private static Uri GetUri(int port = 0)
{
port = port == 0 ? FreeTcpPort() : port;
var uri = new Uri("http://localhost:" + port);
return uri;
}

private static int FreeTcpPort()
{
var l = new TcpListener(IPAddress.Loopback, 0);
l.Start();
var port = ((IPEndPoint) l.LocalEndpoint).Port;
l.Stop();
return port;
}
}
}
5 changes: 1 addition & 4 deletions Microphone.Nancy/Microphone.Nancy.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -30,10 +30,6 @@
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<ItemGroup>
<Reference Include="Consul, Version=0.5.2.65, Culture=neutral, PublicKeyToken=20a6ad9a81df1d95, processorArchitecture=MSIL">
<HintPath>..\packages\Consul.0.5.2.65\lib\net45\Consul.dll</HintPath>
<Private>True</Private>
</Reference>
<Reference Include="Nancy, Version=1.3.0.0, Culture=neutral, processorArchitecture=MSIL">
<HintPath>..\packages\Nancy.1.3.0\lib\net40\Nancy.dll</HintPath>
<Private>True</Private>
Expand Down Expand Up @@ -69,6 +65,7 @@
<Compile Include="Properties\AssemblyInfo.cs" />
</ItemGroup>
<ItemGroup>
<None Include="build.bat" />
<None Include="Microphone.Nancy.nuspec" />
<None Include="packages.config" />
</ItemGroup>
Expand Down
2 changes: 1 addition & 1 deletion Microphone.Nancy/Microphone.Nancy.nuspec
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@
<copyright>Copyright 2015</copyright>
<tags>Nancy WebApi Microservices Services ServiceDiscovery</tags>
<dependencies>
<dependency id="Microphone.Core" version="0.1.0.0" />
<dependency id="Microphone.Core" version="0.1.3.0" />
</dependencies>
</metadata>
</package>
Loading

0 comments on commit 952a43b

Please sign in to comment.