Make Ocelot work with service fabric DNS and naming service for guest exe and stateless (#242)

* test for issue

* added service fabric sample

* working!!

* changed sample naming to Ocelot

* removed files we dont need

* removed files we dont need

* updated sample gitignore

* updated sample gitignore

* getting ocelot to work with service fabric using the reverse proxy

* #238 - added support for service fabric discovery provider, proxies requests through naming service, wont work on partioned service fabric services yet

* #238 - Manually tested service fabric using sample..all seems OK. Made some changes after testing, added docs

* #238 - added docs for servic fabric
This commit is contained in:
Tom Pallister
2018-03-03 15:24:05 +00:00
committed by GitHub
parent 9cb25ab063
commit 454ba3f9a0
71 changed files with 2394 additions and 484 deletions

View File

@ -0,0 +1,31 @@
// ------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License (MIT). See License.txt in the repo root for license information.
// ------------------------------------------------------------
namespace OcelotApplicationApiGateway
{
using System.Fabric;
using Microsoft.ServiceFabric.Services.Communication.Runtime;
using Microsoft.ServiceFabric.Services.Runtime;
using System.Collections.Generic;
/// Service that handles front-end web requests and acts as a proxy to the back-end data for the UI web page.
/// It is a stateless service that hosts a Web API application on OWIN.
internal sealed class OcelotServiceWebService : StatelessService
{
public OcelotServiceWebService(StatelessServiceContext context)
: base(context)
{ }
protected override IEnumerable<ServiceInstanceListener> CreateServiceInstanceListeners()
{
return new[]
{
new ServiceInstanceListener(
initparams => new WebCommunicationListener(string.Empty, initparams),
"OcelotServiceWebListener")
};
}
}
}

View File

@ -0,0 +1,22 @@
<Project Sdk="Microsoft.NET.Sdk.Web">
<PropertyGroup>
<Description>Stateless Web Service for Stateful OcelotApplicationApiGateway App</Description>
<Authors> </Authors>
<TargetFramework>netcoreapp2.0</TargetFramework>
<AssemblyName>OcelotApplicationApiGateway</AssemblyName>
<OutputType>Exe</OutputType>
<PackageId>OcelotApplicationApiGateway</PackageId>
</PropertyGroup>
<ItemGroup>
<None Update="configuration.json;appsettings.json;">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None>
</ItemGroup>
<ItemGroup>
<PackageReference Include="Microsoft.ServiceFabric" Version="6.1.456" />
<PackageReference Include="Microsoft.ServiceFabric.Services" Version="3.0.456" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\..\..\..\src\Ocelot\Ocelot.csproj" />
</ItemGroup>
</Project>

View File

@ -0,0 +1,51 @@
// ------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License (MIT). See License.txt in the repo root for license information.
// ------------------------------------------------------------
namespace OcelotApplicationApiGateway
{
using System;
using System.Fabric;
using System.Threading;
using Microsoft.ServiceFabric.Services.Runtime;
using System.Diagnostics.Tracing;
/// <summary>
/// The service host is the executable that hosts the Service instances.
/// </summary>
public class Program
{
public static void Main(string[] args)
{
// Create Service Fabric runtime and register the service type.
try
{
//Creating a new event listener to redirect the traces to a file
ServiceEventListener listener = new ServiceEventListener("OcelotApplicationApiGateway");
listener.EnableEvents(ServiceEventSource.Current, EventLevel.LogAlways, EventKeywords.All);
// The ServiceManifest.XML file defines one or more service type names.
// Registering a service maps a service type name to a .NET type.
// When Service Fabric creates an instance of this service type,
// an instance of the class is created in this host process.
ServiceRuntime
.RegisterServiceAsync("OcelotApplicationApiGatewayType", context => new OcelotServiceWebService (context))
.GetAwaiter()
.GetResult();
// Prevents this host process from terminating so services keep running.
Thread.Sleep(Timeout.Infinite);
}
catch (Exception ex)
{
ServiceEventSource.Current.ServiceHostInitializationFailed(ex);
throw ex;
}
}
}
}

View File

@ -0,0 +1,27 @@
{
"iisSettings": {
"windowsAuthentication": false,
"anonymousAuthentication": true,
"iisExpress": {
"applicationUrl": "http://localhost:36034/",
"sslPort": 0
}
},
"profiles": {
"IIS Express": {
"commandName": "IISExpress",
"launchBrowser": true,
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
},
"OcelotApplicationApiGateway": {
"commandName": "Project",
"launchBrowser": true,
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
},
"applicationUrl": "http://localhost:36035/"
}
}
}

View File

@ -0,0 +1,94 @@
// ------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License (MIT). See License.txt in the repo root for license information.
// ------------------------------------------------------------
namespace OcelotApplicationApiGateway
{
using System;
using System.IO;
using System.Linq;
using System.Diagnostics.Tracing;
using System.Fabric;
using System.Fabric.Common;
using System.Fabric.Common.Tracing;
using Microsoft.ServiceFabric.Services.Runtime;
using System.Globalization;
using System.Text;
/// <summary>
/// ServiceEventListener is a class which listens to the eventsources registered and redirects the traces to a file
/// Note that this class serves as a template to EventListener class and redirects the logs to /tmp/{appnameyyyyMMddHHmmssffff}.
/// You can extend the functionality by writing your code to implement rolling logs for the logs written through this class.
/// You can also write your custom listener class and handle the registered evestsources accordingly.
/// </summary>
internal class ServiceEventListener : EventListener
{
private string fileName;
private string filepath = Path.GetTempPath();
public ServiceEventListener(string appName)
{
this.fileName = appName + DateTime.Now.ToString("yyyyMMddHHmmssffff");
}
/// <summary>
/// We override this method to get a callback on every event we subscribed to with EnableEvents
/// </summary>
/// <param name="eventData">The event arguments that describe the event.</param>
protected override void OnEventWritten(EventWrittenEventArgs eventData)
{
using (StreamWriter writer = new StreamWriter( new FileStream(filepath + fileName, FileMode.Append)))
{
// report all event information
writer.Write(" {0} ", Write(eventData.Task.ToString(),
eventData.EventName,
eventData.EventId.ToString(),
eventData.Level));
if (eventData.Message != null)
{
writer.WriteLine(string.Format(CultureInfo.InvariantCulture, eventData.Message, eventData.Payload.ToArray()));
}
}
}
private static String Write(string taskName, string eventName, string id, EventLevel level)
{
StringBuilder output = new StringBuilder();
DateTime now = DateTime.UtcNow;
output.Append(now.ToString("yyyy/MM/dd-HH:mm:ss.fff", CultureInfo.InvariantCulture));
output.Append(',');
output.Append(ConvertLevelToString(level));
output.Append(',');
output.Append(taskName);
if (!string.IsNullOrEmpty(eventName))
{
output.Append('.');
output.Append(eventName);
}
if (!string.IsNullOrEmpty(id))
{
output.Append('@');
output.Append(id);
}
output.Append(',');
return output.ToString();
}
private static string ConvertLevelToString(EventLevel level)
{
switch (level)
{
case EventLevel.Informational:
return "Info";
default:
return level.ToString();
}
}
}
}

View File

@ -0,0 +1,86 @@
// ------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License (MIT). See License.txt in the repo root for license information.
// ------------------------------------------------------------
namespace OcelotApplicationApiGateway
{
using System;
using System.Diagnostics.Tracing;
using System.Fabric;
using Microsoft.ServiceFabric.Services.Runtime;
/// <summary>
/// Implements methods for logging service related events.
/// </summary>
public class ServiceEventSource : EventSource
{
public static ServiceEventSource Current = new ServiceEventSource();
// Define an instance method for each event you want to record and apply an [Event] attribute to it.
// The method name is the name of the event.
// Pass any parameters you want to record with the event (only primitive integer types, DateTime, Guid & string are allowed).
// Each event method implementation should check whether the event source is enabled, and if it is, call WriteEvent() method to raise the event.
// The number and types of arguments passed to every event method must exactly match what is passed to WriteEvent().
// Put [NonEvent] attribute on all methods that do not define an event.
// For more information see https://msdn.microsoft.com/en-us/library/system.diagnostics.tracing.eventsource.aspx
[NonEvent]
public void Message(string message, params object[] args)
{
if (this.IsEnabled())
{
var finalMessage = string.Format(message, args);
this.Message(finalMessage);
}
}
private const int MessageEventId = 1;
[Event(MessageEventId, Level = EventLevel.Informational, Message = "{0}")]
public void Message(string message)
{
if (this.IsEnabled())
{
this.WriteEvent(MessageEventId, message);
}
}
private const int ServiceTypeRegisteredEventId = 3;
[Event(ServiceTypeRegisteredEventId, Level = EventLevel.Informational, Message = "Service host process {0} registered service type {1}")]
public void ServiceTypeRegistered(int hostProcessId, string serviceType)
{
this.WriteEvent(ServiceTypeRegisteredEventId, hostProcessId, serviceType);
}
[NonEvent]
public void ServiceHostInitializationFailed(Exception e)
{
this.ServiceHostInitializationFailed(e.ToString());
}
private const int ServiceHostInitializationFailedEventId = 4;
[Event(ServiceHostInitializationFailedEventId, Level = EventLevel.Error, Message = "Service host initialization failed: {0}")]
private void ServiceHostInitializationFailed(string exception)
{
this.WriteEvent(ServiceHostInitializationFailedEventId, exception);
}
[NonEvent]
public void ServiceWebHostBuilderFailed(Exception e)
{
this.ServiceWebHostBuilderFailed(e.ToString());
}
private const int ServiceWebHostBuilderFailedEventId = 5;
[Event(ServiceWebHostBuilderFailedEventId, Level = EventLevel.Error, Message = "Service Owin Web Host Builder Failed: {0}")]
private void ServiceWebHostBuilderFailed(string exception)
{
this.WriteEvent(ServiceWebHostBuilderFailedEventId, exception);
}
}
}

View File

@ -0,0 +1,125 @@
// ------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License (MIT). See License.txt in the repo root for license information.
// ------------------------------------------------------------
namespace OcelotApplicationApiGateway
{
using System;
using System.Fabric;
using System.Fabric.Description;
using System.Globalization;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Hosting;
using Microsoft.ServiceFabric.Services.Communication.Runtime;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Configuration;
using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.DependencyInjection;
using Ocelot.DependencyInjection;
using Ocelot.Middleware;
public class WebCommunicationListener : ICommunicationListener
{
private readonly string appRoot;
private readonly ServiceContext serviceInitializationParameters;
private string listeningAddress;
private string publishAddress;
// OWIN server handle.
private IWebHost webHost;
public WebCommunicationListener(string appRoot, ServiceContext serviceInitializationParameters)
{
this.appRoot = appRoot;
this.serviceInitializationParameters = serviceInitializationParameters;
}
public Task<string> OpenAsync(CancellationToken cancellationToken)
{
ServiceEventSource.Current.Message("Initialize");
EndpointResourceDescription serviceEndpoint = this.serviceInitializationParameters.CodePackageActivationContext.GetEndpoint("WebEndpoint");
int port = serviceEndpoint.Port;
this.listeningAddress = string.Format(
CultureInfo.InvariantCulture,
"http://+:{0}/{1}",
port,
string.IsNullOrWhiteSpace(this.appRoot)
? string.Empty
: this.appRoot.TrimEnd('/') + '/');
this.publishAddress = this.listeningAddress.Replace("+", FabricRuntime.GetNodeContext().IPAddressOrFQDN);
ServiceEventSource.Current.Message("Starting web server on {0}", this.listeningAddress);
try
{
this.webHost = new WebHostBuilder()
.UseKestrel()
//.UseStartup<Startup>()
.UseUrls(this.listeningAddress)
.ConfigureAppConfiguration((hostingContext, config) =>
{
config
.SetBasePath(hostingContext.HostingEnvironment.ContentRootPath)
.AddJsonFile("appsettings.json", true, true)
.AddJsonFile($"appsettings.{hostingContext.HostingEnvironment.EnvironmentName}.json", true, true)
.AddJsonFile("configuration.json")
.AddEnvironmentVariables();
})
.ConfigureLogging((hostingContext, logging) =>
{
logging.AddConfiguration(hostingContext.Configuration.GetSection("Logging"));
logging.AddConsole();
})
.ConfigureServices(s => {
s.AddOcelot();
})
.Configure(a => {
a.UseOcelot().Wait();
})
.Build();
this.webHost.Start();
}
catch (Exception ex)
{
ServiceEventSource.Current.ServiceWebHostBuilderFailed(ex);
}
return Task.FromResult(this.publishAddress);
}
public Task CloseAsync(CancellationToken cancellationToken)
{
this.StopAll();
return Task.FromResult(true);
}
public void Abort()
{
this.StopAll();
}
/// <summary>
/// Stops, cancels, and disposes everything.
/// </summary>
private void StopAll()
{
try
{
if (this.webHost != null)
{
ServiceEventSource.Current.Message("Stopping web server.");
this.webHost.Dispose();
}
}
catch (ObjectDisposedException)
{
}
}
}
}

View File

@ -0,0 +1,10 @@
{
"Logging": {
"IncludeScopes": false,
"LogLevel": {
"Default": "Trace",
"System": "Information",
"Microsoft": "Information"
}
}
}

View File

@ -0,0 +1,22 @@
{
"ReRoutes": [
{
"DownstreamPathTemplate": "/api/values",
"UpstreamPathTemplate": "/EquipmentInterfaces",
"UpstreamHttpMethod": [
"Get"
],
"DownstreamScheme": "http",
"ServiceName": "OcelotServiceApplication/OcelotApplicationService",
"UseServiceDiscovery" : true
}
],
"GlobalConfiguration": {
"RequestIdKey": "OcRequestId",
"ServiceDiscoveryProvider": {
"Host": "localhost",
"Port": 19081,
"Type": "ServiceFabric"
}
}
}