Skip to content
This repository has been archived by the owner on Jan 8, 2019. It is now read-only.

Commit

Permalink
Merge pull request #2 from ThreeMammals/feature/migration-from-ocelot
Browse files Browse the repository at this point in the history
Feature/migration from ocelot
  • Loading branch information
TomPallister authored Aug 12, 2018
2 parents c3b5336 + c3240c3 commit 450353b
Show file tree
Hide file tree
Showing 29 changed files with 1,528 additions and 24 deletions.
7 changes: 3 additions & 4 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,10 +1,9 @@
[<img src="http://threemammals.com/images/ocelot_logo.png">](http://threemammals.com/ocelot)

[![Build status](https://ci.appveyor.com/api/projects/status/8ry4ailt7rr5mbu7?svg=true)](https://ci.appveyor.com/project/TomPallister/ocelot-cache-cachemanager)
Windows (AppVeyor)
[![Build Status](https://travis-ci.org/ThreeMammals/Ocelot.Provider.Rafty.svg?branch=master)](https://travis-ci.org/ThreeMammals/Ocelot.Provider.Rafty) Linux & OSX (Travis)
[![Build status](https://ci.appveyor.com/api/projects/status/up4ro24ua58h7v87?svg=true)](https://ci.appveyor.com/project/TomPallister/ocelot-provider-rafty) Windows (AppVeyor)
[![Build Status](https://travis-ci.org/ThreeMammals/Ocelot.Provider.Rafty.svg?branch=develop)](https://travis-ci.org/ThreeMammals/Ocelot.Provider.Rafty) Linux & OSX (Travis)

[![Coverage Status](https://coveralls.io/repos/github/ThreeMammals/Ocelot.Provider.Rafty/badge.svg?branch=develop)](https://coveralls.io/github/ThreeMammals/Ocelot.Provider.Rafty?branch=develop)
[![Coverage Status](https://coveralls.io/repos/github/ThreeMammals/Ocelot.Provider.Rafty/badge.svg)](https://coveralls.io/github/ThreeMammals/Ocelot.Provider.Rafty)

# Ocelot

Expand Down
16 changes: 16 additions & 0 deletions src/Ocelot.Provider.Rafty/BearerToken.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
namespace Ocelot.Provider.Rafty
{
using Newtonsoft.Json;

internal class BearerToken
{
[JsonProperty("access_token")]
public string AccessToken { get; set; }

[JsonProperty("expires_in")]
public int ExpiresIn { get; set; }

[JsonProperty("token_type")]
public string TokenType { get; set; }
}
}
14 changes: 14 additions & 0 deletions src/Ocelot.Provider.Rafty/FakeCommand.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
namespace Ocelot.Provider.Rafty
{
using global::Rafty.FiniteStateMachine;

public class FakeCommand : ICommand
{
public FakeCommand(string value)
{
this.Value = value;
}

public string Value { get; private set; }
}
}
7 changes: 7 additions & 0 deletions src/Ocelot.Provider.Rafty/FilePeer.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
namespace Ocelot.Provider.Rafty
{
public class FilePeer
{
public string HostAndPort { get; set; }
}
}
14 changes: 14 additions & 0 deletions src/Ocelot.Provider.Rafty/FilePeers.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
namespace Ocelot.Provider.Rafty
{
using System.Collections.Generic;

public class FilePeers
{
public FilePeers()
{
Peers = new List<FilePeer>();
}

public List<FilePeer> Peers { get; set; }
}
}
44 changes: 44 additions & 0 deletions src/Ocelot.Provider.Rafty/FilePeersProvider.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
namespace Ocelot.Provider.Rafty
{
using System.Net.Http;
using Configuration;
using Configuration.Repository;
using global::Rafty.Concensus.Peers;
using global::Rafty.Infrastructure;
using Microsoft.Extensions.Options;
using Middleware;
using System.Collections.Generic;

public class FilePeersProvider : IPeersProvider
{
private readonly IOptions<FilePeers> _options;
private readonly List<IPeer> _peers;
private IBaseUrlFinder _finder;
private IInternalConfigurationRepository _repo;
private IIdentityServerConfiguration _identityServerConfig;

public FilePeersProvider(IOptions<FilePeers> options, IBaseUrlFinder finder, IInternalConfigurationRepository repo, IIdentityServerConfiguration identityServerConfig)
{
_identityServerConfig = identityServerConfig;
_repo = repo;
_finder = finder;
_options = options;
_peers = new List<IPeer>();

var config = _repo.Get();
foreach (var item in _options.Value.Peers)
{
var httpClient = new HttpClient();

//todo what if this errors?
var httpPeer = new HttpPeer(item.HostAndPort, httpClient, _finder, config.Data, _identityServerConfig);
_peers.Add(httpPeer);
}
}

public List<IPeer> Get()
{
return _peers;
}
}
}
129 changes: 129 additions & 0 deletions src/Ocelot.Provider.Rafty/HttpPeer.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,129 @@
namespace Ocelot.Provider.Rafty
{
using System.Net.Http;
using System.Threading.Tasks;
using Configuration;
using global::Rafty.Concensus.Messages;
using global::Rafty.Concensus.Peers;
using global::Rafty.FiniteStateMachine;
using global::Rafty.Infrastructure;
using Middleware;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;

public class HttpPeer : IPeer
{
private readonly string _hostAndPort;
private readonly HttpClient _httpClient;
private readonly JsonSerializerSettings _jsonSerializerSettings;
private readonly string _baseSchemeUrlAndPort;
private BearerToken _token;
private readonly IInternalConfiguration _config;
private readonly IIdentityServerConfiguration _identityServerConfiguration;

public HttpPeer(string hostAndPort, HttpClient httpClient, IBaseUrlFinder finder, IInternalConfiguration config, IIdentityServerConfiguration identityServerConfiguration)
{
_identityServerConfiguration = identityServerConfiguration;
_config = config;
Id = hostAndPort;
_hostAndPort = hostAndPort;
_httpClient = httpClient;
_jsonSerializerSettings = new JsonSerializerSettings()
{
TypeNameHandling = TypeNameHandling.All
};
_baseSchemeUrlAndPort = finder.Find();
}

public string Id { get; }

public async Task<RequestVoteResponse> Request(RequestVote requestVote)
{
if (_token == null)
{
await SetToken();
}

var json = JsonConvert.SerializeObject(requestVote, _jsonSerializerSettings);
var content = new StringContent(json);
content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json");
var response = await _httpClient.PostAsync($"{_hostAndPort}/administration/raft/requestvote", content);
if (response.IsSuccessStatusCode)
{
return JsonConvert.DeserializeObject<RequestVoteResponse>(await response.Content.ReadAsStringAsync(), _jsonSerializerSettings);
}

return new RequestVoteResponse(false, requestVote.Term);
}

public async Task<AppendEntriesResponse> Request(AppendEntries appendEntries)
{
try
{
if (_token == null)
{
await SetToken();
}

var json = JsonConvert.SerializeObject(appendEntries, _jsonSerializerSettings);
var content = new StringContent(json);
content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json");
var response = await _httpClient.PostAsync($"{_hostAndPort}/administration/raft/appendEntries", content);
if (response.IsSuccessStatusCode)
{
return JsonConvert.DeserializeObject<AppendEntriesResponse>(await response.Content.ReadAsStringAsync(), _jsonSerializerSettings);
}

return new AppendEntriesResponse(appendEntries.Term, false);
}
catch (Exception ex)
{
Console.WriteLine(ex);
return new AppendEntriesResponse(appendEntries.Term, false);
}
}

public async Task<Response<T>> Request<T>(T command)
where T : ICommand
{
Console.WriteLine("SENDING REQUEST....");
if (_token == null)
{
await SetToken();
}

var json = JsonConvert.SerializeObject(command, _jsonSerializerSettings);
var content = new StringContent(json);
content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json");
var response = await _httpClient.PostAsync($"{_hostAndPort}/administration/raft/command", content);
if (response.IsSuccessStatusCode)
{
Console.WriteLine("REQUEST OK....");
var okResponse = JsonConvert.DeserializeObject<OkResponse<ICommand>>(await response.Content.ReadAsStringAsync(), _jsonSerializerSettings);
return new OkResponse<T>((T)okResponse.Command);
}

Console.WriteLine("REQUEST NOT OK....");
return new ErrorResponse<T>(await response.Content.ReadAsStringAsync(), command);
}

private async Task SetToken()
{
var tokenUrl = $"{_baseSchemeUrlAndPort}{_config.AdministrationPath}/connect/token";
var formData = new List<KeyValuePair<string, string>>
{
new KeyValuePair<string, string>("client_id", _identityServerConfiguration.ApiName),
new KeyValuePair<string, string>("client_secret", _identityServerConfiguration.ApiSecret),
new KeyValuePair<string, string>("scope", _identityServerConfiguration.ApiName),
new KeyValuePair<string, string>("grant_type", "client_credentials")
};
var content = new FormUrlEncodedContent(formData);
var response = await _httpClient.PostAsync(tokenUrl, content);
var responseContent = await response.Content.ReadAsStringAsync();
response.EnsureSuccessStatusCode();
_token = JsonConvert.DeserializeObject<BearerToken>(responseContent);
_httpClient.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue(_token.TokenType, _token.AccessToken);
}
}
}
5 changes: 3 additions & 2 deletions src/Ocelot.Provider.Rafty/Ocelot.Provider.Rafty.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
<RuntimeFrameworkVersion>2.0.0</RuntimeFrameworkVersion>
<NETStandardImplicitPackageVersion>2.0.0</NETStandardImplicitPackageVersion>
<NoPackageAnalysis>true</NoPackageAnalysis>
<Description>Provides Ocelot extensions to use CacheManager.Net</Description>
<Description>Provides Ocelot extensions to use Rafty</Description>
<AssemblyTitle>Ocelot.Provider.Rafty</AssemblyTitle>
<VersionPrefix>0.0.0-dev</VersionPrefix>
<AssemblyName>Ocelot.Provider.Rafty</AssemblyName>
Expand All @@ -26,7 +26,8 @@
<DebugSymbols>True</DebugSymbols>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Ocelot" Version="8.0.8" />
<PackageReference Include="Ocelot" Version="10.0.1" />
<PackageReference Include="Rafty" Version="0.4.4" />
<PackageReference Include="StyleCop.Analyzers" Version="1.0.2">
<PrivateAssets>all</PrivateAssets>
</PackageReference>
Expand Down
28 changes: 28 additions & 0 deletions src/Ocelot.Provider.Rafty/OcelotAdministrationBuilderExtensions.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
namespace Ocelot.Provider.Rafty
{
using Configuration.Setter;
using DependencyInjection;
using global::Rafty.Concensus.Node;
using global::Rafty.FiniteStateMachine;
using global::Rafty.Infrastructure;
using global::Rafty.Log;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;

public static class OcelotAdministrationBuilderExtensions
{
public static IOcelotAdministrationBuilder AddRafty(this IOcelotAdministrationBuilder builder)
{
var settings = new InMemorySettings(4000, 6000, 100, 10000);
builder.Services.RemoveAll<IFileConfigurationSetter>();
builder.Services.AddSingleton<IFileConfigurationSetter, RaftyFileConfigurationSetter>();
builder.Services.AddSingleton<ILog, SqlLiteLog>();
builder.Services.AddSingleton<IFiniteStateMachine, OcelotFiniteStateMachine>();
builder.Services.AddSingleton<ISettings>(settings);
builder.Services.AddSingleton<IPeersProvider, FilePeersProvider>();
builder.Services.AddSingleton<INode, Node>();
builder.Services.Configure<FilePeers>(builder.ConfigurationRoot);
return builder;
}
}
}
12 changes: 0 additions & 12 deletions src/Ocelot.Provider.Rafty/OcelotBuilderExtensions.cs

This file was deleted.

25 changes: 25 additions & 0 deletions src/Ocelot.Provider.Rafty/OcelotFiniteStateMachine.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
namespace Ocelot.Provider.Rafty
{
using System.Threading.Tasks;
using Configuration.Setter;
using global::Rafty.FiniteStateMachine;
using global::Rafty.Log;

public class OcelotFiniteStateMachine : IFiniteStateMachine
{
private readonly IFileConfigurationSetter _setter;

public OcelotFiniteStateMachine(IFileConfigurationSetter setter)
{
_setter = setter;
}

public async Task Handle(LogEntry log)
{
//todo - handle an error
//hack it to just cast as at the moment we know this is the only command :P
var hack = (UpdateFileConfiguration)log.CommandData;
await _setter.Set(hack.Configuration);
}
}
}
Loading

0 comments on commit 450353b

Please sign in to comment.