Skip to content

Commit

Permalink
Add project files.
Browse files Browse the repository at this point in the history
  • Loading branch information
zimbres committed Aug 3, 2024
1 parent 7232bd2 commit 0cc5a35
Show file tree
Hide file tree
Showing 19 changed files with 451 additions and 0 deletions.
49 changes: 49 additions & 0 deletions .github/workflows/dotnet.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
name: Publish

on:
release:
types: [published]

jobs:
release:
name: Release
strategy:
matrix:
kind: ['windows']
include:
- kind: windows
os: windows-latest
target: win-x64
runs-on: ${{ matrix.os }}
steps:
- name: Checkout
uses: actions/checkout@v4

- name: Setup dotnet
uses: actions/setup-dotnet@v4
with:
dotnet-version: 8.0.x

- name: Build
shell: bash
run: |
tag=$(git describe --tags --abbrev=0)
release_name="ServiceMonitor-$tag-${{ matrix.target }}"
dotnet publish src/ServiceMonitor/ServiceMonitor.csproj --framework net8.0 --runtime "${{ matrix.target }}" --no-self-contained -p:PublishSingleFile=true -c Release -o "$release_name"
if [ "${{ matrix.target }}" == "win-x64" ]; then
7z a -tzip "${release_name}.zip" "./${release_name}/*"
else
tar czvf "${release_name}.tar.gz" "$release_name"
fi
rm -r "$release_name"
- name: Publish
uses: softprops/action-gh-release@v2
with:
files: "ServiceMonitor-*"

env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
21 changes: 21 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
MIT License

Copyright (c) 2024 zimbres

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
44 changes: 44 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
# Windows Service Monitor

This application runs as a Windows Service and is designed to monitor and manage the health of a specified service. It performs this task by either probing a TCP port to ensure it is listening or by making an HTTP request to check for a successful status code or the presence of a specific word in the response. If the monitored service is found to be unhealthy, the application will automatically restart it.

### Configuration required:

```json

{
"Logging": {
"LogLevel": {
"Default": "Warning",
"Microsoft.Hosting.Lifetime": "Warning"
}
},
"Configuration": {
"RunIntervalSeconds": 30,
"ServiceName": "YourServiceName",
"IpAddress": "127.0.0.1",
"Port": 8080,
"HttpUrl": "http://localhost:8080/api/health",
"CheckForWord": false,
"Word": "",
"CheckType" : "Tcp"
}
}

```



---

[Microsoft Help: Create Windows Service](https://learn.microsoft.com/en-us/dotnet/core/extensions/windows-service)

---

### Requires .Net Runtime 8.0

[Download .NET](https://dotnet.microsoft.com/en-us/download)

---

Application icon by [Flaticon](https://www.flaticon.com/br/icones-gratis/marketing-de-midia-social)
13 changes: 13 additions & 0 deletions SECURITY.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
# Security Policy

## Supported Versions

| Version | Supported |
| ---------- | ------------------ |
| 1.0.0.1 | :white_check_mark: |
| <= 1.0.0.0 | :x: |


## Reporting a Vulnerability

Create a new issue
33 changes: 33 additions & 0 deletions ServiceMonitor.sln
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 17
VisualStudioVersion = 17.10.35122.118
MinimumVisualStudioVersion = 10.0.40219.1
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ServiceMonitor", "src\ServiceMonitor\ServiceMonitor.csproj", "{A69BA395-D61F-4155-B6A1-BE7BF19BB443}"
EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items", "{1B6FDC36-CFE2-454D-9702-837B99B9778D}"
ProjectSection(SolutionItems) = preProject
.github\workflows\dotnet.yml = .github\workflows\dotnet.yml
LICENSE = LICENSE
README.md = README.md
SECURITY.md = SECURITY.md
EndProjectSection
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{A69BA395-D61F-4155-B6A1-BE7BF19BB443}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{A69BA395-D61F-4155-B6A1-BE7BF19BB443}.Debug|Any CPU.Build.0 = Debug|Any CPU
{A69BA395-D61F-4155-B6A1-BE7BF19BB443}.Release|Any CPU.ActiveCfg = Release|Any CPU
{A69BA395-D61F-4155-B6A1-BE7BF19BB443}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {1E5C575E-BB13-4B2F-A00D-AE0CE78837E3}
EndGlobalSection
EndGlobal
Binary file added assets/service.ico
Binary file not shown.
13 changes: 13 additions & 0 deletions src/ServiceMonitor/Configurations/Configuration.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
namespace ServiceMonitor.Configurations;

internal class Configuration
{
public int RunIntervalSeconds { get; set; }
public string ServiceName { get; set; }
public string IpAddress { get; set; }
public int Port { get; set; }
public string HttpUrl { get; set; }
public bool CheckForWord { get; set; }
public string Word { get; set; }
public string CheckType { get; set; }
}
9 changes: 9 additions & 0 deletions src/ServiceMonitor/GlobalSuppressions.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
// This file is used by Code Analysis to maintain SuppressMessage
// attributes that are applied to this project.
// Project-level suppressions either have no target or are given
// a specific target and scoped to a namespace, type, member, etc.

using System.Diagnostics.CodeAnalysis;

//[assembly: SuppressMessage("Interoperability", "CA1416:Validate platform compatibility", Justification = "<Pending>", Scope = "member", Target = "~M:ServiceMonitor.Worker.RestartService(System.String)")]
[assembly: SuppressMessage("Interoperability", "CA1416:Validate platform compatibility", Justification = "<Pending>", Scope = "member", Target = "~M:ServiceMonitor.Services.ControlService.RestartService(System.String)")]
7 changes: 7 additions & 0 deletions src/ServiceMonitor/GlobalUsings.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
global using ServiceMonitor;
global using ServiceMonitor.Configurations;
global using ServiceMonitor.Services;
global using System.Net.Sockets;
global using System.Reflection;
global using System.ServiceProcess;
global using System.Text.Json;
17 changes: 17 additions & 0 deletions src/ServiceMonitor/Program.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
var builder = Host.CreateApplicationBuilder(args);
builder.Services.AddWindowsService(options =>
{
options.ServiceName = "Service Monitor";
});
builder.Services.AddHttpClient();
builder.Services.AddSingleton<TcpService>();
builder.Services.AddSingleton<HttpService>();
builder.Services.AddSingleton<ControlService>();

builder.Services.AddHostedService<Worker>().Configure<HostOptions>(options =>
{
options.BackgroundServiceExceptionBehavior = BackgroundServiceExceptionBehavior.Ignore;
});

var host = builder.Build();
host.Run();
12 changes: 12 additions & 0 deletions src/ServiceMonitor/Properties/launchSettings.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
{
"$schema": "http://json.schemastore.org/launchsettings.json",
"profiles": {
"ServiceMonitor": {
"commandName": "Project",
"dotnetRunMessages": true,
"environmentVariables": {
"DOTNET_ENVIRONMENT": "Development"
}
}
}
}
25 changes: 25 additions & 0 deletions src/ServiceMonitor/ServiceMonitor.csproj
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
<Project Sdk="Microsoft.NET.Sdk.Worker">

<PropertyGroup>
<TargetFramework>net8.0</TargetFramework>
<Nullable>disable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
<UserSecretsId>dotnet-ServiceMonitor-02b8361b-7a93-472d-a2d6-7b2e8f7973af</UserSecretsId>
<AssemblyVersion>$(PackageVersion)</AssemblyVersion>
<FileVersion>$(PackageVersion)</FileVersion>
<Version>1.0.0.1</Version>
<ApplicationIcon>service.ico</ApplicationIcon>
<Copyright>Zimbres.COM</Copyright>
</PropertyGroup>

<ItemGroup>
<Content Include="service.ico" />
</ItemGroup>

<ItemGroup>
<PackageReference Include="Microsoft.Extensions.Hosting" Version="8.0.0" />
<PackageReference Include="Microsoft.Extensions.Hosting.WindowsServices" Version="8.0.0" />
<PackageReference Include="Microsoft.Extensions.Http" Version="8.0.0" />
<PackageReference Include="System.ServiceProcess.ServiceController" Version="8.0.0" />
</ItemGroup>
</Project>
45 changes: 45 additions & 0 deletions src/ServiceMonitor/Services/ControlService.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
namespace ServiceMonitor.Services;

public class ControlService
{
private readonly ILogger<ControlService> _logger;

public ControlService(ILogger<ControlService> logger)
{
_logger = logger;
}

public void RestartService(string serviceName)
{
try
{
using var serviceController = new ServiceController(serviceName);
if (serviceController.Status == ServiceControllerStatus.Stopped)
{
_logger.LogInformation("Starting service {serviceName}...", serviceName);
serviceController.Start();
}

else if (serviceController.Status == ServiceControllerStatus.Running)
{
_logger.LogInformation("Restarting service {serviceName}...", serviceName);
serviceController.Stop();
serviceController.WaitForStatus(ServiceControllerStatus.Stopped, TimeSpan.FromSeconds(60));
serviceController.Start();
}

if (serviceController.Status == ServiceControllerStatus.StopPending)
{
_logger.LogInformation("Waiting service {serviceName} to stop...", serviceName);
serviceController.WaitForStatus(ServiceControllerStatus.Stopped, TimeSpan.FromSeconds(60));
_logger.LogInformation("Starting service {serviceName}...", serviceName);
serviceController.Start();
}
serviceController.WaitForStatus(ServiceControllerStatus.Running, TimeSpan.FromSeconds(60));
}
catch (Exception ex)
{
_logger.LogError("Exception occurred while restarting service. {ex}", ex.Message);
}
}
}
58 changes: 58 additions & 0 deletions src/ServiceMonitor/Services/HttpService.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
namespace ServiceMonitor.Services;

public class HttpService
{
private readonly ILogger<HttpService> _logger;
private readonly IHttpClientFactory _httpClientFactory;
private HttpClient _httpClient;

public HttpService(ILogger<HttpService> logger, IHttpClientFactory httpClientFactory)
{
_logger = logger;
_httpClientFactory = httpClientFactory;
}

public async Task<bool> CheckHttpAsync(string url, bool checkForWord, string word = null)
{
_httpClient = _httpClientFactory.CreateClient();
try
{
var response = await _httpClient.GetAsync(url);
if (response.IsSuccessStatusCode)
{
if (!checkForWord)
{
_logger.LogInformation("HTTP request succeeded with status code {StatusCode}.", response.StatusCode);
return true;
}
else if (word != null)
{
var content = await response.Content.ReadAsStringAsync();
using var document = JsonDocument.Parse(content);
var json = document.RootElement.GetRawText();
var containsWord = json.Contains(word);

if (containsWord)
{
_logger.LogInformation("HTTP request succeeded and contains the word '{word}'.", word);
return true;
}
else
{
_logger.LogWarning("HTTP request succeeded but does not contain the word '{word}'.", word);
return false;
}
}
}
else
{
_logger.LogWarning("HTTP request failed with status code {StatusCode}.", response.StatusCode);
}
}
catch (Exception ex)
{
_logger.LogError("Exception occurred while making HTTP request to {Url}. {ex}", url, ex.Message);
}
return false;
}
}
27 changes: 27 additions & 0 deletions src/ServiceMonitor/Services/TcpService.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
namespace ServiceMonitor.Services;

public class TcpService
{
private readonly ILogger<TcpService> _logger;

public TcpService(ILogger<TcpService> logger)
{
_logger = logger;
}

public bool CheckTcpPortListening(string ipAddress, int port)
{
try
{
using var tcpClient = new TcpClient();
var result = tcpClient.BeginConnect(ipAddress, port, null, null);
var success = result.AsyncWaitHandle.WaitOne(TimeSpan.FromSeconds(1));
return success && tcpClient.Connected;
}
catch (Exception ex)
{
_logger.LogError("Exception occurred while checking port. {ex}.", ex.Message);
return false;
}
}
}
Loading

0 comments on commit 0cc5a35

Please sign in to comment.