Skip to content

Commit

Permalink
#115 feat: new dashboard and started import functionality
Browse files Browse the repository at this point in the history
+ removed overwrite flag for logging and improved logging system using Microsoft.Extensions.ILogging
  • Loading branch information
joseantmazonsb committed Mar 12, 2022
1 parent 2c57052 commit 54fcabb
Show file tree
Hide file tree
Showing 82 changed files with 1,512 additions and 649 deletions.
2 changes: 1 addition & 1 deletion Linguard/Cli.Test/AddClientCommandShould.cs
Original file line number Diff line number Diff line change
Expand Up @@ -153,6 +153,6 @@ public async Task CreateClientWithAllowedIPs() {

private Interface GenerateInterface(IConfigurationManager configuration) {
return new DefaultInterfaceGenerator(configuration,
WireguardServiceMock.Object, new SystemWrapper(configuration)).Generate();
WireguardServiceMock.Object, new SystemWrapper()).Generate();
}
}
2 changes: 1 addition & 1 deletion Linguard/Cli.Test/ListClientsCommandShould.cs
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,7 @@ public async Task ListPeersForSpecificInterface() {
}

private Interface GenerateInterface(IConfigurationManager configuration) {
return new DefaultInterfaceGenerator(configuration, WireguardServiceMock.Object, new SystemWrapper(configuration))
return new DefaultInterfaceGenerator(configuration, WireguardServiceMock.Object, new SystemWrapper())
.Generate();
}

Expand Down
2 changes: 1 addition & 1 deletion Linguard/Cli.Test/ListInterfacesCommandShould.cs
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,6 @@ public async Task ListOneInterface() {
}

private Interface GenerateInterface(IConfigurationManager configuration) {
return new DefaultInterfaceGenerator(configuration, WireguardServiceMock.Object, new SystemWrapper(configuration)).Generate();
return new DefaultInterfaceGenerator(configuration, WireguardServiceMock.Object, new SystemWrapper()).Generate();
}
}
2 changes: 1 addition & 1 deletion Linguard/Cli.Test/ShowInterfaceCommandShould.cs
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,6 @@ public async Task ShowInterface() {

private static Interface GenerateInterface(IConfigurationManager configuration) {
return new DefaultInterfaceGenerator(configuration,
WireguardServiceMock.Object, new SystemWrapper(configuration)).Generate();
WireguardServiceMock.Object, new SystemWrapper()).Generate();
}
}
7 changes: 5 additions & 2 deletions Linguard/Cli.Test/Utils.cs
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,9 @@
using Linguard.Core.Models.Wireguard;
using Linguard.Core.Models.Wireguard.Validators;
using Linguard.Core.Services;
using Linguard.Log;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;
using Microsoft.Extensions.Logging;
using Moq;
using Typin;
using Typin.Console;
Expand Down Expand Up @@ -37,12 +38,14 @@ public static TestApp BuildTestApp(params Type[] commands) {
services.AddSingleton(config);
services.AddSingleton(configurationManager);
services.AddSingleton(new Mock<IWorkingDirectory>().Object);
services.AddSingleton(new Mock<ILogger>().Object);
services.AddSingleton(new Mock<IWireguardService>().Object);
services.AddTransient<AbstractValidator<Interface>, InterfaceValidator>();
services.AddTransient<IInterfaceGenerator, DefaultInterfaceGenerator>();
services.AddTransient<IClientGenerator, DefaultClientGenerator>();
services.AddTransient<AbstractValidator<Client>, ClientValidator>();
services.AddLogging(builder => {
builder.Services.TryAddSingleton(new Mock<ILogger>().Object);
});
})
.Build();
return new TestApp() {
Expand Down
6 changes: 4 additions & 2 deletions Linguard/Cli/CliStartup.cs
Original file line number Diff line number Diff line change
Expand Up @@ -22,13 +22,15 @@ public void ConfigureServices(IServiceCollection services) {
services.AddTransient<IConfiguration, Configuration>();
services.AddTransient<IWorkingDirectory, WorkingDirectory>();
services.AddSingleton<IConfigurationSerializer>(DefaultYamlConfigurationSerializer.Instance);
services.AddTransient<ILogger, NLogLogger>();
services.AddTransient<ISystemWrapper, Core.OS.SystemWrapper>();
services.AddTransient<ISystemWrapper, SystemWrapper>();
services.AddTransient<IWireguardService, WireguardService>();
services.AddTransient<IInterfaceGenerator, DefaultInterfaceGenerator>();
services.AddTransient<IClientGenerator, DefaultClientGenerator>();
services.AddTransient<AbstractValidator<Interface>, InterfaceValidator>();
services.AddTransient<AbstractValidator<Client>, ClientValidator>();
services.AddLogging(builder => {
builder.UseSimpleFileLogger();
});
}

public void Configure(CliApplicationBuilder app)
Expand Down
4 changes: 2 additions & 2 deletions Linguard/Cli/Commands/AddClientCommand.cs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
using Linguard.Core.Managers;
using Linguard.Core.Models.Wireguard;
using Linguard.Core.Services;
using Linguard.Log;
using Microsoft.Extensions.Logging;
using Typin;
using Typin.Attributes;
using Typin.Console;
Expand Down Expand Up @@ -91,7 +91,7 @@ public ValueTask ExecuteAsync(IConsole console) {
iface.Clients.Add(client);
_configurationManager.Save();
var msg = $"Added peer '{client.Name}' to interface '{iface.Name}'.";
_logger.Info(msg);
_logger.LogInformation(msg);
console.Output.WriteLine(msg);
return ValueTask.CompletedTask;
}
Expand Down
4 changes: 2 additions & 2 deletions Linguard/Cli/Commands/AddInterfaceCommand.cs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
using Linguard.Core.Managers;
using Linguard.Core.Models.Wireguard;
using Linguard.Core.Services;
using Linguard.Log;
using Microsoft.Extensions.Logging;
using Typin;
using Typin.Attributes;
using Typin.Console;
Expand Down Expand Up @@ -74,7 +74,7 @@ public virtual ValueTask ExecuteAsync(IConsole console) {
Configuration.Wireguard.Interfaces.Add(iface);
ConfigurationManager.Save();
var msg = $"Added interface '{iface.Name}'.";
Logger.Info(msg);
Logger.LogInformation(msg);
console.Output.WriteLine(msg);
return ValueTask.CompletedTask;
}
Expand Down
4 changes: 2 additions & 2 deletions Linguard/Cli/Commands/EditClientCommand.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
using Linguard.Core.Configuration;
using Linguard.Core.Managers;
using Linguard.Core.Models.Wireguard;
using Linguard.Log;
using Microsoft.Extensions.Logging;
using Typin;
using Typin.Attributes;
using Typin.Console;
Expand Down Expand Up @@ -101,7 +101,7 @@ public ValueTask ExecuteAsync(IConsole console) {

_configurationManager.Save();
var msg = $"Edited client '{peer.Name}' from interface '{iface.Name}'.";
_logger.Info(msg);
_logger.LogInformation(msg);
console.Output.WriteLine(msg);
return ValueTask.CompletedTask;
}
Expand Down
4 changes: 2 additions & 2 deletions Linguard/Cli/Commands/EditInterfaceCommand.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
using Linguard.Core.Managers;
using Linguard.Core.Models.Wireguard;
using Linguard.Core.Services;
using Linguard.Log;
using Microsoft.Extensions.Logging;
using Typin.Attributes;
using Typin.Console;

Expand All @@ -19,7 +19,7 @@ public EditInterfaceCommand(IConfigurationManager configurationManager, ILogger
public override ValueTask ExecuteAsync(IConsole console) {
var iface = Configuration.Wireguard.Interfaces.SingleOrDefault(i => i.Name.Equals(Name));
if (iface == default) {
Logger.Error($"No interface named '{Name}' was found.");
Logger.LogError($"No interface named '{Name}' was found.");
console.Error.WriteLine(Validation.InterfaceNotFound);
return ValueTask.CompletedTask;
}
Expand Down
8 changes: 4 additions & 4 deletions Linguard/Cli/Middlewares/ConfigurationSetupMiddleware.cs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
using Linguard.Core.Configuration.Exceptions;
using Linguard.Core.Managers;
using Linguard.Core.Utils;
using Linguard.Log;
using Microsoft.Extensions.Logging;
using Typin;

namespace Linguard.Cli.Middlewares;
Expand All @@ -23,13 +23,13 @@ public async Task HandleAsync(ICliContext context, CommandPipelineHandlerDelegat
return;
}
_configurationManager.WorkingDirectory.BaseDirectory = GetWorkingDirectory(context);
_logger.Info("Loading configuration...");
_logger.LogInformation("Loading configuration...");
try {
_configurationManager.Load();
_logger.Info("Configuration loaded.");
_logger.LogInformation("Configuration loaded.");
}
catch (ConfigurationNotLoadedError e) {
_logger.Warn(e, "Unable to load configuration. Using defaults.");
_logger.LogWarning(e, "Unable to load configuration. Using defaults.");
_configurationManager.LoadDefaults();
}
await next.Invoke();
Expand Down
2 changes: 1 addition & 1 deletion Linguard/Core.Test/DefaultClientGeneratorShould.cs
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ public class DefaultClientGeneratorShould {

private static readonly Mock<IConfigurationManager> ConfigurationManagerMock = new DefaultConfigurationManager();
private static readonly Mock<IWireguardService> WireguardServiceMock = new();
private static readonly ISystemWrapper SystemWrapper = new SystemWrapper(ConfigurationManagerMock.Object);
private static readonly ISystemWrapper SystemWrapper = new SystemWrapper();

private static IInterfaceGenerator InterfaceGenerator =>
new DefaultInterfaceGenerator(ConfigurationManagerMock.Object, WireguardServiceMock.Object, SystemWrapper);
Expand Down
2 changes: 1 addition & 1 deletion Linguard/Core.Test/DefaultInterfaceGeneratorShould.cs
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ public class DefaultInterfaceGeneratorShould {

private static readonly Mock<IConfigurationManager> ConfigurationManagerMock = new DefaultConfigurationManager();
private static readonly Mock<IWireguardService> WireguardServiceMock = new();
private static readonly ISystemWrapper SystemWrapper = new SystemWrapper(ConfigurationManagerMock.Object);
private static readonly ISystemWrapper SystemWrapper = new SystemWrapper();

private static IInterfaceGenerator Generator =>
new DefaultInterfaceGenerator(ConfigurationManagerMock.Object, WireguardServiceMock.Object, SystemWrapper);
Expand Down
2 changes: 2 additions & 0 deletions Linguard/Core.Test/InterfaceShould.cs
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,7 @@ public void CreateValidWireguardConfiguration() {
Gateway = _system.NetworkInterfaces.First(),
Clients = new HashSet<Client> {
new() {
Id = Guid.Parse("00000000-0000-0000-0000-000000000001"),
Endpoint = new Uri("vpn.example.com", UriKind.RelativeOrAbsolute),
Name = "peer1",
Nat = true,
Expand All @@ -70,6 +71,7 @@ public void CreateValidWireguardConfiguration() {
PrimaryDns = new Uri("8.8.8.8", UriKind.RelativeOrAbsolute)
},
new() {
Id = Guid.Parse("00000000-0000-0000-0000-000000000002"),
Endpoint = new Uri("vpn2.example.com", UriKind.RelativeOrAbsolute),
Name = "peer2",
IPv4Address = IPAddressCidr.Parse("1.1.1.2/30"),
Expand Down
41 changes: 26 additions & 15 deletions Linguard/Core.Test/Mocks/DefaultConfiguration.cs
Original file line number Diff line number Diff line change
Expand Up @@ -12,26 +12,15 @@ public sealed class DefaultConfiguration : Mock<IConfiguration> {

public DefaultConfiguration() {
SetupProperty(c => c.Wireguard, GetWireguardConfigurationMock().Object);
SetupProperty(c => c.Logging, new Mock<ILoggingConfiguration>().Object);
SetupProperty(c => c.Traffic, new Mock<ITrafficConfiguration>()
.SetupProperty(c => c.StorageDriver, new Mock<ITrafficStorageDriver>().Object)
.Object);
SetupProperty(c => c.Web, new Mock<IWebConfiguration>().Object);
SetupProperty(c => c.Logging, GetLoggingConfigurationMock().Object);
SetupProperty(c => c.Traffic, GetTrafficConfigurationMock().Object);
SetupProperty(c => c.Web, GetWebConfigurationMock().Object);
Setup(o => o.Clone()).Returns(Object);
}

private Mock<IWireguardConfiguration> GetWireguardConfigurationMock() {
var wireguardConfiguration = new Mock<IWireguardConfiguration>();
var interfaces = new HashSet<Interface>();
wireguardConfiguration.Setup(o => o.GetInterface(It.IsAny<Client>()))
.Returns<Client>(c =>
interfaces.SingleOrDefault(i => i.Clients.Contains(c))
);
wireguardConfiguration.Setup(o => o.GetInterface(It.IsAny<Guid>()))
.Returns<Guid>(id =>
interfaces.SingleOrDefault(i => i.Clients.Any(c => c.Id == id))
);
wireguardConfiguration
var wireguardConfiguration = new Mock<IWireguardConfiguration>()
.SetupProperty(c => c.Interfaces, interfaces)
.SetupProperty(c => c.Endpoint,
new Uri("vpn.example.com", UriKind.RelativeOrAbsolute))
Expand All @@ -41,6 +30,28 @@ private Mock<IWireguardConfiguration> GetWireguardConfigurationMock() {
.SetupProperty(c => c.PrimaryDns,
new Uri("8.8.8.8", UriKind.RelativeOrAbsolute))
.SetupProperty(c => c.SecondaryDns, default);
wireguardConfiguration.Setup(o => o.GetInterface(It.IsAny<Client>()))
.Returns<Client>(c =>
interfaces.SingleOrDefault(i => i.Clients.Contains(c))
);
wireguardConfiguration.Setup(o => o.GetInterface(It.IsAny<Guid>()))
.Returns<Guid>(id =>
interfaces.SingleOrDefault(i => i.Clients.Any(c => c.Id == id))
);
return wireguardConfiguration;
}

private Mock<IWebConfiguration> GetWebConfigurationMock() {
return new Mock<IWebConfiguration>();
}

private Mock<ILoggingConfiguration> GetLoggingConfigurationMock() {
return new Mock<ILoggingConfiguration>();;
}

private Mock<ITrafficConfiguration> GetTrafficConfigurationMock() {
var mock = new Mock<ITrafficConfiguration>()
.SetupProperty(c => c.StorageDriver, new Mock<ITrafficStorageDriver>().Object);
return mock;
}
}
10 changes: 10 additions & 0 deletions Linguard/Core.Test/Mocks/FileInfoMock.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
using System.IO;
using Moq;

namespace Core.Test.Mocks;

public class FileInfoMock : Mock<FileSystemInfo> {
public FileInfoMock(string name) {
SetupGet(o => o.FullName).Returns(name);
}
}
1 change: 0 additions & 1 deletion Linguard/Core.Test/Mocks/SystemMock.cs
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,6 @@ public class SystemMock : Mock<ISystemWrapper> {

public SystemMock() {
SetupGet(o => o.NetworkInterfaces).Returns(_networkInterfaces);

Setup(o => o.AddNetworkInterface(It.IsAny<Interface>()))
.Callback<Interface>(i => {
if (Object.NetworkInterfaces.Any(iface => iface.Name.Equals(i.Name))) {
Expand Down
52 changes: 52 additions & 0 deletions Linguard/Core.Test/Mocks/WireguardServiceMock.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
using System.Collections.Generic;
using System.Linq;
using Bogus;
using ByteSizeLib;
using Linguard.Core.Managers;
using Linguard.Core.Models;
using Linguard.Core.Models.Wireguard;
using Linguard.Core.OS;
using Linguard.Core.Services;
using Moq;

namespace Core.Test.Mocks;

public class WireguardServiceMock : Mock<IWireguardService> {
public WireguardServiceMock(IConfigurationManager manager, ISystemWrapper systemWrapper, Faker faker) {
Setup(o => o.StartInterface(It.IsAny<Interface>()))
.Callback<Interface>(systemWrapper.AddNetworkInterface);
Setup(o => o.StopInterface(It.IsAny<Interface>()))
.Callback<Interface>(systemWrapper.RemoveNetworkInterface);
Setup(o => o.GeneratePrivateKey())
.Returns(faker.Lorem.Sentence());
Setup(o => o.GeneratePublicKey(It.IsAny<string>()))
.Returns(faker.Lorem.Sentence());
Setup(o => o.GetTrafficData(It.IsAny<Client>()))
.Returns<Client>(client => new TrafficData {
Peer = client,
ReceivedData = ByteSize.FromBytes(faker.Random.Number((int) ByteSize.BytesInMegaByte)),
SentData = ByteSize.FromBytes(faker.Random.Number((int) ByteSize.BytesInMegaByte)),
});
Setup(o => o.GetTrafficData(It.IsAny<Interface>()))
.Returns<Interface>(iface => {
if (systemWrapper.IsInterfaceDown(iface)) {
return Enumerable.Empty<TrafficData>();
}
var data = iface.Clients.Select(client => Object.GetTrafficData(client)).ToList();
data.Add(new TrafficData {
Peer = iface,
ReceivedData = ByteSize.FromBytes(data.Sum(e => e.ReceivedData.Bytes)),
SentData = ByteSize.FromBytes(data.Sum(e => e.SentData.Bytes))
});
return data;
});
Setup(o => o.GetTrafficData())
.Returns(() => {
var data = new List<TrafficData>();
foreach (var iface in manager.Configuration.Wireguard.Interfaces) {
data.AddRange(Object.GetTrafficData(iface));
}
return data;
});
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,6 @@ public static class YamlConfigurationSerializerMock {
.WithTypeConverter<IPAddressCidrTypeConverter>()
.WithTypeConverter<NetworkInterfaceTypeConverterMock>()
.WithTypeConverter<UriTypeConverter>()
.WithTypeConverter<StyleTypeConverter>()
.WithTypeMapping<IConfiguration, Configuration>()
.WithTypeMapping<IWireguardConfiguration, WireguardConfiguration>()
.WithTypeMapping<ILoggingConfiguration, LoggingConfiguration>()
Expand Down
8 changes: 2 additions & 6 deletions Linguard/Core.Test/SystemShould.cs
Original file line number Diff line number Diff line change
@@ -1,16 +1,12 @@
using Core.Test.Mocks;
using FluentAssertions;
using Linguard.Core.Managers;
using FluentAssertions;
using Linguard.Core.OS;
using Moq;
using Xunit;

namespace Core.Test;

public class SystemShould {

private static readonly Mock<IConfigurationManager> ConfigurationManagerMock = new DefaultConfigurationManager();
private readonly ISystemWrapper _systemWrapper = new SystemWrapper(ConfigurationManagerMock.Object);
private readonly ISystemWrapper _systemWrapper = new SystemWrapper();

[Fact]
public void RunSingleCommand() {
Expand Down
Loading

0 comments on commit 54fcabb

Please sign in to comment.