Skip to content

Commit

Permalink
#50
Browse files Browse the repository at this point in the history
  • Loading branch information
odesyatnyk committed Mar 16, 2020
1 parent 374694c commit 005bf43
Show file tree
Hide file tree
Showing 21 changed files with 420 additions and 145 deletions.
9 changes: 3 additions & 6 deletions Elfo.Wardein.Core/DependencyInjection/ServicesContainer.cs
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ protected ServicesContainer()
protected void Configure()
{

serviceCollection = serviceCollection = new ServiceCollection()
serviceCollection = serviceCollection = new ServiceCollection()
.AddSingleton<Func<string, IAmMailConfigurationManager>>(sp => filePath => new MailConfigurationManagerFromJSON(filePath))
.AddSingleton<Func<string, IAmWardeinConfigurationManager>>(sp => filePath => new WardeinConfigurationManagerFromJSON(filePath))
.AddTransient<Func<string, IAmPersistenceService<WindowsServiceStats>>>(sp => filePath => new WindowsServiceStatsPersistenceInJSON(filePath))
Expand All @@ -55,7 +55,7 @@ protected void Configure()
throw new KeyNotFoundException($"Notification service {notificationType.ToString()} not supported yet");
}
})
.AddTransient<Func<ServiceManagerType, string, IAmServiceManager>>(sp => (serviceManagerType, serviceName) =>
.AddTransient<Func<ServiceManagerType, string, IAmServiceManager>>(sp => (serviceManagerType, serviceName) =>
{
switch (serviceManagerType)
{
Expand All @@ -66,8 +66,7 @@ protected void Configure()
default:
throw new KeyNotFoundException($"Notification service {serviceManagerType.ToString()} not supported yet");
}
})
.AddTransient<WardeinInstance>();
});

serviceProvider = serviceCollection.BuildServiceProvider();
}
Expand Down Expand Up @@ -129,8 +128,6 @@ public static IAmServiceManager ServiceManager(string serviceName, ServiceManage
return instanceResolver(serviceManagerType, serviceName);
}

public static WardeinInstance WardeinInstance => Current.serviceProvider.GetService<WardeinInstance>();

#endregion
}
}
18 changes: 18 additions & 0 deletions Elfo.Wardein.Core/Helpers/StringExtensions.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Elfo.Wardein.Core.Helpers
{
public static class StringExtensions
{
public static string Repeat(this string source, int times)
{
if (source == null)
throw new ArgumentNullException(nameof(source));

return string.Concat(Enumerable.Repeat(source, times));
}
}
}
5 changes: 0 additions & 5 deletions Elfo.Wardein.Core/Models/WardeinConfig.cs
Original file line number Diff line number Diff line change
Expand Up @@ -16,9 +16,6 @@ public class WardeinConfig
[JsonProperty(PropertyName = "numberOfNotificationsWithoutRateLimitation")]
public int NumberOfNotificationsWithoutRateLimitation { get; set; } = 2; // Default values

[JsonProperty(PropertyName = "services")]
public IList<WindowsService> Services { get; set; }

[JsonProperty(PropertyName = "persistenceType")]
public string PersistenceType { get; set; } = "JSON";

Expand All @@ -29,7 +26,5 @@ public class WardeinConfig
IsInMaintenanceMode = false,
MaintenanceModeStartDateInUTC = DateTime.UtcNow
}; // Default values
[JsonProperty(PropertyName = "cleanUps")]
public CleanUps[] CleanUps { get; set; }
}
}
20 changes: 20 additions & 0 deletions Elfo.Wardein.Watchers/Elfo.Wardein.Watchers.csproj
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<TargetFramework>netcoreapp2.0</TargetFramework>
</PropertyGroup>

<ItemGroup>
<PackageReference Include="Elfo.CleanUpManager" Version="0.0.12" />
<PackageReference Include="Microsoft.AspNetCore" Version="2.2.0" />
<PackageReference Include="Microsoft.AspNetCore.Hosting" Version="2.2.0" />
<PackageReference Include="PeterKottas.DotNetCore.WindowsService" Version="2.0.11" />
<PackageReference Include="Warden" Version="2.0.0" />
</ItemGroup>

<ItemGroup>
<ProjectReference Include="..\Elfo.Wardein.APIs\Elfo.Wardein.APIs.csproj" />
<ProjectReference Include="..\Elfo.Wardein.Core\Elfo.Wardein.Core.csproj" />
</ItemGroup>

</Project>
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,9 @@
using System.Collections.Generic;
using System.Text;

namespace Elfo.Wardein.Core.Models
namespace Elfo.Wardein.Watchers.FileSystem
{
public class CleanUps
public class FileSystemCleanUpConfig
{
[JsonProperty(PropertyName = "filePath")]
public string FilePath { get; set; }
Expand All @@ -14,6 +14,6 @@ public class CleanUps
public double TimeSpanFromSeconds { get; set; } = 10; // Default values

[JsonProperty(PropertyName = "cleanUpOptions")]
public CleanUpParams CleanUpOptions { get; set; } = new CleanUpParams();
public FileSystemCleanUpOptions CleanUpOptions { get; set; } = new FileSystemCleanUpOptions();
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,9 @@
using System.Collections.Generic;
using System.Text;

namespace Elfo.Wardein.Core.Models
namespace Elfo.Wardein.Watchers.FileSystem
{
public class CleanUpParams
public class FileSystemCleanUpOptions
{
[JsonProperty(PropertyName = "thresholdInSeconds")]
public int ThresholdInSeconds { get; set; }
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
using System;
using System.Collections.Generic;
using System.Text;
using Warden.Watchers;

namespace Elfo.Wardein.Watchers.FileSystem
{
public class WindowsServiceWatcherCheckResult : WatcherCheckResult
{
protected WindowsServiceWatcherCheckResult(FileSystemWatcher watcher, bool isValid, string description) : base(watcher, isValid, description)
{
}

public static WindowsServiceWatcherCheckResult Create(FileSystemWatcher watcher, string description)
{
var wasRunSuccessful = string.IsNullOrWhiteSpace(description);
return new WindowsServiceWatcherCheckResult(watcher, wasRunSuccessful, description);
}
}
}
30 changes: 30 additions & 0 deletions Elfo.Wardein.Watchers/FileSystem/Config/FileSystemWatcherConfig.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Text;

namespace Elfo.Wardein.Watchers.FileSystem
{
public class FileSystemWatcherConfig : IWatcherConfig
{
/// <summary>
/// Property defines if watcher has to be running in maintainance mode
/// Default value false
/// </summary>
[JsonProperty(PropertyName = "isInMaintenanceMode")]
public bool IsInMaintenanceMode { get; set; } = false;

/// <summary>
/// Property that defines frequency of watcher polling
/// Default value 10 seconds
/// </summary>
[JsonProperty(PropertyName = "timeSpanFromSeconds")]
public double TimeSpanFromSeconds { get; set; } = 10;

/// <summary>
/// List of folder configurations that has to be monitored and cleaned by criteria
/// </summary>
[JsonProperty(PropertyName = "cleanUps")]
public IEnumerable<FileSystemCleanUpConfig> CleanUps { get; set; } = new List<FileSystemCleanUpConfig>();
}
}
21 changes: 21 additions & 0 deletions Elfo.Wardein.Watchers/FileSystem/Extensions.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
using System;
using System.Collections.Generic;
using System.Text;
using Warden;
using Warden.Core;
using Warden.Watchers;

namespace Elfo.Wardein.Watchers.FileSystem
{
public static class Extensions
{
public static WardenConfiguration.Builder AddFileSystemWatcher(this WardenConfiguration.Builder builder,
FileSystemWatcherConfig config,
string group = null,
Action<WatcherHooksConfiguration.Builder> hooks = null)
{
builder.AddWatcher(FileSystemWatcher.Create(config, group), hooks, TimeSpan.FromSeconds(config.TimeSpanFromSeconds));
return builder;
}
}
}
85 changes: 85 additions & 0 deletions Elfo.Wardein.Watchers/FileSystem/FileSystemWatcher.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,85 @@
using Elfo.CleanUpManager;
using Elfo.Wardein.Core;
using Elfo.Wardein.Core.Helpers;
using Elfo.Wardein.Core.Models;
using NLog;
using PeterKottas.DotNetCore.WindowsService.Base;
using PeterKottas.DotNetCore.WindowsService.Interfaces;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
using Warden.Watchers;

namespace Elfo.Wardein.Watchers.FileSystem
{
public class FileSystemWatcher : WardeinWatcher<FileSystemWatcherConfig>
{
protected FileSystemWatcher(FileSystemWatcherConfig config, string group = null) : base(nameof(FileSystemWatcher), config, group)
{ }

public static FileSystemWatcher Create(FileSystemWatcherConfig config, string group = null)
{
return new FileSystemWatcher(config, group);
}

public override async Task<IWatcherCheckResult> ExecuteWatcherActionAsync()
{
log.Info("---\tStarting FileSystemWatcher\t---");

var resultDescription = new StringBuilder(string.Empty);

foreach (var cleanUp in Config.CleanUps)
{
var iterationMessage = string.Empty;
try
{
var guid = Guid.NewGuid();
log.Info($"{Environment.NewLine}{"-".Repeat(24)} Cache cleanup @ {guid} started {"-".Repeat(24)}");

var options = GetCleanUpOptions(cleanUp);
var filesProcessor = new Cleaner(log, options);

filesProcessor.CleanUp();

log.Info($"{Environment.NewLine}{"-".Repeat(24)} Cache cleanup @ {guid} finished {"-".Repeat(24)}{Environment.NewLine.Repeat(3)}");
}
catch (Exception ex)
{
iterationMessage = $"Exception inside path: {cleanUp.FilePath}: {ex.ToString()} stack trace: {ex.StackTrace}{Environment.NewLine}";
resultDescription.AppendLine(iterationMessage);
log.Error(ex, iterationMessage);
}
}

var watcherResultDescription = resultDescription.ToString();
return await Task.FromResult(WindowsServiceWatcherCheckResult.Create(this, watcherResultDescription));
}

private CleanUpOptions GetCleanUpOptions(FileSystemCleanUpConfig cleanUp)
{
var options = new CleanUpOptions(cleanUp.FilePath);
options.RemoveEmptyFolders = cleanUp.CleanUpOptions.RemoveEmptyFolders;
options.DisplayOnly = cleanUp.CleanUpOptions.DisplayOnly;
options.RemoveEmptyFolders = cleanUp.CleanUpOptions.RemoveEmptyFolders;
options.UseRecycleBin = cleanUp.CleanUpOptions.UseRecycleBin;
options.Recursive = cleanUp.CleanUpOptions.Recursive;
ConfigureThreshold();
return options;

#region Local Functions
void ConfigureThreshold()
{
if (cleanUp.CleanUpOptions.ThresholdInSeconds != default(int) && cleanUp.CleanUpOptions.ThresholdInDays == default(int))
options.Seconds = cleanUp.CleanUpOptions.ThresholdInSeconds;
else if (cleanUp.CleanUpOptions.ThresholdInSeconds == default(int) && cleanUp.CleanUpOptions.ThresholdInDays != default(int))
options.Days = cleanUp.CleanUpOptions.ThresholdInDays;
else if (cleanUp.CleanUpOptions.ThresholdInSeconds != default(int) && cleanUp.CleanUpOptions.ThresholdInDays != default(int))
options.Days = cleanUp.CleanUpOptions.ThresholdInDays;
else
options.Seconds = 300;
}
#endregion
}
}
}
13 changes: 13 additions & 0 deletions Elfo.Wardein.Watchers/IWatcherConfig.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
using System;
using System.Collections.Generic;
using System.Text;

namespace Elfo.Wardein.Watchers
{
public interface IWatcherConfig
{
bool IsInMaintenanceMode { get; }

double TimeSpanFromSeconds { get; }
}
}
41 changes: 41 additions & 0 deletions Elfo.Wardein.Watchers/WardeinWatcher.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
using NLog;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
using Warden.Watchers;

namespace Elfo.Wardein.Watchers
{
public abstract class WardeinWatcher<TConfig> : IWatcher where TConfig : IWatcherConfig
{
protected WardeinWatcher(string name, TConfig config, string group = null)
{
Name = name;
Group = group;
Config = config;
}

public virtual string Name { get; protected set; }

public virtual string Group { get; protected set; }

public TConfig Config { get; protected set; }

protected static ILogger log = LogManager.GetCurrentClassLogger();

public async Task<IWatcherCheckResult> ExecuteAsync()
{
if (Config.IsInMaintenanceMode)
{
var message = $"Wardein {Name} running in maintainance mode. Skipping Execution.";
log.Info(message);
return await Task.FromResult(WatcherCheckResult.Create(this, true, message));
}

return await ExecuteWatcherActionAsync();
}

public abstract Task<IWatcherCheckResult> ExecuteWatcherActionAsync();
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,9 @@
using System.Collections.Generic;
using System.Text;

namespace Elfo.Wardein.Core.Models
namespace Elfo.Wardein.Watchers.WindowsService
{
public class WindowsService
public class ObservableWindowsService
{
[JsonProperty(PropertyName = "serviceName")]
public string ServiceName { get; set; }
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
using System;
using System.Collections.Generic;
using System.Text;
using Warden.Watchers;

namespace Elfo.Wardein.Watchers.WindowsService
{
public class WindowsServiceWatcherCheckResult : WatcherCheckResult
{
protected WindowsServiceWatcherCheckResult(WindowsServiceWatcher watcher, bool isValid, string description) : base(watcher, isValid, description)
{
}

public static WindowsServiceWatcherCheckResult Create(WindowsServiceWatcher watcher, string description)
{
var wasRunSuccessful = string.IsNullOrWhiteSpace(description);
return new WindowsServiceWatcherCheckResult(watcher, wasRunSuccessful, description);
}
}
}
Loading

0 comments on commit 005bf43

Please sign in to comment.