diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..66e6f12 --- /dev/null +++ b/.gitignore @@ -0,0 +1,574 @@ +# Added by me +Builds/ + +# Created by https://www.toptal.com/developers/gitignore/api/csharp,visualstudio +# Edit at https://www.toptal.com/developers/gitignore?templates=csharp,visualstudio + +### Csharp ### +## Ignore Visual Studio temporary files, build results, and +## files generated by popular Visual Studio add-ons. +## +## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore + +# User-specific files +*.rsuser +*.suo +*.user +*.userosscache +*.sln.docstates + +# User-specific files (MonoDevelop/Xamarin Studio) +*.userprefs + +# Mono auto generated files +mono_crash.* + +# Build results +[Dd]ebug/ +[Dd]ebugPublic/ +[Rr]elease/ +[Rr]eleases/ +x64/ +x86/ +[Ww][Ii][Nn]32/ +[Aa][Rr][Mm]/ +[Aa][Rr][Mm]64/ +bld/ +[Bb]in/ +[Oo]bj/ +[Ll]og/ +[Ll]ogs/ + +# Visual Studio 2015/2017 cache/options directory +.vs/ +# Uncomment if you have tasks that create the project's static files in wwwroot +#wwwroot/ + +# Visual Studio 2017 auto generated files +Generated\ Files/ + +# MSTest test Results +[Tt]est[Rr]esult*/ +[Bb]uild[Ll]og.* + +# NUnit +*.VisualState.xml +TestResult.xml +nunit-*.xml + +# Build Results of an ATL Project +[Dd]ebugPS/ +[Rr]eleasePS/ +dlldata.c + +# Benchmark Results +BenchmarkDotNet.Artifacts/ + +# .NET Core +project.lock.json +project.fragment.lock.json +artifacts/ + +# ASP.NET Scaffolding +ScaffoldingReadMe.txt + +# StyleCop +StyleCopReport.xml + +# Files built by Visual Studio +*_i.c +*_p.c +*_h.h +*.ilk +*.meta +*.obj +*.iobj +*.pch +*.pdb +*.ipdb +*.pgc +*.pgd +*.rsp +*.sbr +*.tlb +*.tli +*.tlh +*.tmp +*.tmp_proj +*_wpftmp.csproj +*.log +*.tlog +*.vspscc +*.vssscc +.builds +*.pidb +*.svclog +*.scc + +# Chutzpah Test files +_Chutzpah* + +# Visual C++ cache files +ipch/ +*.aps +*.ncb +*.opendb +*.opensdf +*.sdf +*.cachefile +*.VC.db +*.VC.VC.opendb + +# Visual Studio profiler +*.psess +*.vsp +*.vspx +*.sap + +# Visual Studio Trace Files +*.e2e + +# TFS 2012 Local Workspace +$tf/ + +# Guidance Automation Toolkit +*.gpState + +# ReSharper is a .NET coding add-in +_ReSharper*/ +*.[Rr]e[Ss]harper +*.DotSettings.user + +# TeamCity is a build add-in +_TeamCity* + +# DotCover is a Code Coverage Tool +*.dotCover + +# AxoCover is a Code Coverage Tool +.axoCover/* +!.axoCover/settings.json + +# Coverlet is a free, cross platform Code Coverage Tool +coverage*.json +coverage*.xml +coverage*.info + +# Visual Studio code coverage results +*.coverage +*.coveragexml + +# NCrunch +_NCrunch_* +.*crunch*.local.xml +nCrunchTemp_* + +# MightyMoose +*.mm.* +AutoTest.Net/ + +# Web workbench (sass) +.sass-cache/ + +# Installshield output folder +[Ee]xpress/ + +# DocProject is a documentation generator add-in +DocProject/buildhelp/ +DocProject/Help/*.HxT +DocProject/Help/*.HxC +DocProject/Help/*.hhc +DocProject/Help/*.hhk +DocProject/Help/*.hhp +DocProject/Help/Html2 +DocProject/Help/html + +# Click-Once directory +publish/ + +# Publish Web Output +*.[Pp]ublish.xml +*.azurePubxml +# Note: Comment the next line if you want to checkin your web deploy settings, +# but database connection strings (with potential passwords) will be unencrypted +*.pubxml +*.publishproj + +# Microsoft Azure Web App publish settings. Comment the next line if you want to +# checkin your Azure Web App publish settings, but sensitive information contained +# in these scripts will be unencrypted +PublishScripts/ + +# NuGet Packages +*.nupkg +# NuGet Symbol Packages +*.snupkg +# The packages folder can be ignored because of Package Restore +**/[Pp]ackages/* +# except build/, which is used as an MSBuild target. +!**/[Pp]ackages/build/ +# Uncomment if necessary however generally it will be regenerated when needed +#!**/[Pp]ackages/repositories.config +# NuGet v3's project.json files produces more ignorable files +*.nuget.props +*.nuget.targets + +# Nuget personal access tokens and Credentials +nuget.config + +# Microsoft Azure Build Output +csx/ +*.build.csdef + +# Microsoft Azure Emulator +ecf/ +rcf/ + +# Windows Store app package directories and files +AppPackages/ +BundleArtifacts/ +Package.StoreAssociation.xml +_pkginfo.txt +*.appx +*.appxbundle +*.appxupload + +# Visual Studio cache files +# files ending in .cache can be ignored +*.[Cc]ache +# but keep track of directories ending in .cache +!?*.[Cc]ache/ + +# Others +ClientBin/ +~$* +*~ +*.dbmdl +*.dbproj.schemaview +*.jfm +*.pfx +*.publishsettings +orleans.codegen.cs + +# Including strong name files can present a security risk +# (https://github.com/github/gitignore/pull/2483#issue-259490424) +#*.snk + +# Since there are multiple workflows, uncomment next line to ignore bower_components +# (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) +#bower_components/ + +# RIA/Silverlight projects +Generated_Code/ + +# Backup & report files from converting an old project file +# to a newer Visual Studio version. Backup files are not needed, +# because we have git ;-) +_UpgradeReport_Files/ +Backup*/ +UpgradeLog*.XML +UpgradeLog*.htm +ServiceFabricBackup/ +*.rptproj.bak + +# SQL Server files +*.mdf +*.ldf +*.ndf + +# Business Intelligence projects +*.rdl.data +*.bim.layout +*.bim_*.settings +*.rptproj.rsuser +*- [Bb]ackup.rdl +*- [Bb]ackup ([0-9]).rdl +*- [Bb]ackup ([0-9][0-9]).rdl + +# Microsoft Fakes +FakesAssemblies/ + +# GhostDoc plugin setting file +*.GhostDoc.xml + +# Node.js Tools for Visual Studio +.ntvs_analysis.dat +node_modules/ + +# Visual Studio 6 build log +*.plg + +# Visual Studio 6 workspace options file +*.opt + +# Visual Studio 6 auto-generated workspace file (contains which files were open etc.) +*.vbw + +# Visual Studio LightSwitch build output +**/*.HTMLClient/GeneratedArtifacts +**/*.DesktopClient/GeneratedArtifacts +**/*.DesktopClient/ModelManifest.xml +**/*.Server/GeneratedArtifacts +**/*.Server/ModelManifest.xml +_Pvt_Extensions + +# Paket dependency manager +.paket/paket.exe +paket-files/ + +# FAKE - F# Make +.fake/ + +# CodeRush personal settings +.cr/personal + +# Python Tools for Visual Studio (PTVS) +__pycache__/ +*.pyc + +# Cake - Uncomment if you are using it +# tools/** +# !tools/packages.config + +# Tabs Studio +*.tss + +# Telerik's JustMock configuration file +*.jmconfig + +# BizTalk build output +*.btp.cs +*.btm.cs +*.odx.cs +*.xsd.cs + +# OpenCover UI analysis results +OpenCover/ + +# Azure Stream Analytics local run output +ASALocalRun/ + +# MSBuild Binary and Structured Log +*.binlog + +# NVidia Nsight GPU debugger configuration file +*.nvuser + +# MFractors (Xamarin productivity tool) working folder +.mfractor/ + +# Local History for Visual Studio +.localhistory/ + +# BeatPulse healthcheck temp database +healthchecksdb + +# Backup folder for Package Reference Convert tool in Visual Studio 2017 +MigrationBackup/ + +# Ionide (cross platform F# VS Code tools) working folder +.ionide/ + +# Fody - auto-generated XML schema +FodyWeavers.xsd + +# VS Code files for those working on multiple tools +.vscode/* +!.vscode/settings.json +!.vscode/tasks.json +!.vscode/launch.json +!.vscode/extensions.json +*.code-workspace + +# Local History for Visual Studio Code +.history/ + +# Windows Installer files from build outputs +*.cab +*.msi +*.msix +*.msm +*.msp + +# JetBrains Rider +.idea/ +*.sln.iml + +### VisualStudio ### + +# User-specific files + +# User-specific files (MonoDevelop/Xamarin Studio) + +# Mono auto generated files + +# Build results + +# Visual Studio 2015/2017 cache/options directory +# Uncomment if you have tasks that create the project's static files in wwwroot + +# Visual Studio 2017 auto generated files + +# MSTest test Results + +# NUnit + +# Build Results of an ATL Project + +# Benchmark Results + +# .NET Core + +# ASP.NET Scaffolding + +# StyleCop + +# Files built by Visual Studio + +# Chutzpah Test files + +# Visual C++ cache files + +# Visual Studio profiler + +# Visual Studio Trace Files + +# TFS 2012 Local Workspace + +# Guidance Automation Toolkit + +# ReSharper is a .NET coding add-in + +# TeamCity is a build add-in + +# DotCover is a Code Coverage Tool + +# AxoCover is a Code Coverage Tool + +# Coverlet is a free, cross platform Code Coverage Tool + +# Visual Studio code coverage results + +# NCrunch + +# MightyMoose + +# Web workbench (sass) + +# Installshield output folder + +# DocProject is a documentation generator add-in + +# Click-Once directory + +# Publish Web Output +# Note: Comment the next line if you want to checkin your web deploy settings, +# but database connection strings (with potential passwords) will be unencrypted + +# Microsoft Azure Web App publish settings. Comment the next line if you want to +# checkin your Azure Web App publish settings, but sensitive information contained +# in these scripts will be unencrypted + +# NuGet Packages +# NuGet Symbol Packages +# The packages folder can be ignored because of Package Restore +# except build/, which is used as an MSBuild target. +# Uncomment if necessary however generally it will be regenerated when needed +# NuGet v3's project.json files produces more ignorable files + +# Nuget personal access tokens and Credentials + +# Microsoft Azure Build Output + +# Microsoft Azure Emulator + +# Windows Store app package directories and files + +# Visual Studio cache files +# files ending in .cache can be ignored +# but keep track of directories ending in .cache + +# Others + +# Including strong name files can present a security risk +# (https://github.com/github/gitignore/pull/2483#issue-259490424) + +# Since there are multiple workflows, uncomment next line to ignore bower_components +# (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) + +# RIA/Silverlight projects + +# Backup & report files from converting an old project file +# to a newer Visual Studio version. Backup files are not needed, +# because we have git ;-) + +# SQL Server files + +# Business Intelligence projects + +# Microsoft Fakes + +# GhostDoc plugin setting file + +# Node.js Tools for Visual Studio + +# Visual Studio 6 build log + +# Visual Studio 6 workspace options file + +# Visual Studio 6 auto-generated workspace file (contains which files were open etc.) + +# Visual Studio LightSwitch build output + +# Paket dependency manager + +# FAKE - F# Make + +# CodeRush personal settings + +# Python Tools for Visual Studio (PTVS) + +# Cake - Uncomment if you are using it +# tools/** +# !tools/packages.config + +# Tabs Studio + +# Telerik's JustMock configuration file + +# BizTalk build output + +# OpenCover UI analysis results + +# Azure Stream Analytics local run output + +# MSBuild Binary and Structured Log + +# NVidia Nsight GPU debugger configuration file + +# MFractors (Xamarin productivity tool) working folder + +# Local History for Visual Studio + +# BeatPulse healthcheck temp database + +# Backup folder for Package Reference Convert tool in Visual Studio 2017 + +# Ionide (cross platform F# VS Code tools) working folder + +# Fody - auto-generated XML schema + +# VS Code files for those working on multiple tools + +# Local History for Visual Studio Code + +# Windows Installer files from build outputs + +# JetBrains Rider + +### VisualStudio Patch ### +# Additional files built by Visual Studio + +# End of https://www.toptal.com/developers/gitignore/api/csharp,visualstudio + +Source/MonitorIotaNode/settings.json diff --git a/Source/MonitorIotaNode.sln b/Source/MonitorIotaNode.sln new file mode 100644 index 0000000..1744506 --- /dev/null +++ b/Source/MonitorIotaNode.sln @@ -0,0 +1,25 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio Version 16 +VisualStudioVersion = 16.0.31624.102 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "MonitorIotaNode", "MonitorIotaNode\MonitorIotaNode.csproj", "{02FFB943-5097-4062-9F4D-53D2AEB6BBDA}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {02FFB943-5097-4062-9F4D-53D2AEB6BBDA}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {02FFB943-5097-4062-9F4D-53D2AEB6BBDA}.Debug|Any CPU.Build.0 = Debug|Any CPU + {02FFB943-5097-4062-9F4D-53D2AEB6BBDA}.Release|Any CPU.ActiveCfg = Release|Any CPU + {02FFB943-5097-4062-9F4D-53D2AEB6BBDA}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection + GlobalSection(ExtensibilityGlobals) = postSolution + SolutionGuid = {02EC43CF-FCA1-4B19-9B93-F32BD920E229} + EndGlobalSection +EndGlobal diff --git a/Source/MonitorIotaNode/MonitorIotaNode.csproj b/Source/MonitorIotaNode/MonitorIotaNode.csproj new file mode 100644 index 0000000..5ba75ad --- /dev/null +++ b/Source/MonitorIotaNode/MonitorIotaNode.csproj @@ -0,0 +1,22 @@ + + + + Exe + net5.0 + + + + + + + + + + + + + Always + + + + diff --git a/Source/MonitorIotaNode/NodeEndpoint.cs b/Source/MonitorIotaNode/NodeEndpoint.cs new file mode 100644 index 0000000..ecb987f --- /dev/null +++ b/Source/MonitorIotaNode/NodeEndpoint.cs @@ -0,0 +1,44 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Runtime.CompilerServices; +using System.Text; +using Newtonsoft.Json; +using Newtonsoft.Json.Linq; +using RestSharp; + +namespace MonitorIotaNode +{ + public class NodeEndpoint + { + public Uri Uri { get; private set; } + + private RestClient client; + private RestRequest request; + + public NodeEndpoint(Uri uri) + { + this.Uri = uri; + client = new RestClient(Uri); + request = new RestRequest("", DataFormat.None); + } + + public NodeInfo RetrieveNodeInfo() + { + IRestResponse response = client.Get(request); + string json = response.Content; + return JsonConvert.DeserializeObject(json); + } + + public override bool Equals(object obj) + { + Uri otherUri = (Uri)obj; + return Uri.Equals(otherUri); + } + + public override int GetHashCode() + { + return Uri.GetHashCode(); + } + } +} diff --git a/Source/MonitorIotaNode/NodeInfo.cs b/Source/MonitorIotaNode/NodeInfo.cs new file mode 100644 index 0000000..22cd136 --- /dev/null +++ b/Source/MonitorIotaNode/NodeInfo.cs @@ -0,0 +1,80 @@ +using Newtonsoft.Json; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace MonitorIotaNode +{ + public class NodeInfo + { + public string Version { get; set; } + public int NetworkVersion { get; set; } + public string IdentityIdShort { get; set; } + public int SolidMessageCount { get; set; } + public int TotalMessageCount { get; set; } + public TangleTime TangleTime { get; set; } + public Mana Mana { get; set; } + } + + public class TangleTime + { + public bool Synced { get; set; } + public long Time { get; set; } + + [JsonIgnore] + public DateTime DateTime => UnixTimeStampToDateTime(Time / 1_000_000_000); + + public override string ToString() + { + return $"TangleTime is {DateTime} and is{(Synced ? " " : " NOT ")}synced"; + } + + private static DateTime UnixTimeStampToDateTime(double unixTimeStamp) + { + // Unix timestamp is seconds past epoch + DateTime dateTime = new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc); + dateTime = dateTime.AddSeconds(unixTimeStamp).ToLocalTime(); + return dateTime; + } + } + + public class Mana + { + public decimal Access { get; set; } + public decimal Consensus { get; set; } + + public static Mana operator +(Mana manaOne) => manaOne; + + public static Mana operator -(Mana manaOne) => new Mana(-manaOne.Access, -manaOne.Consensus); + + public static Mana operator +(Mana manaOne, Mana manaTwo) => new Mana(manaOne.Access + manaTwo.Access, manaOne.Consensus + manaTwo.Consensus); + + public static Mana operator -(Mana manaOne, Mana manaTwo) => manaOne + (-manaTwo); + + public static Mana operator /(Mana manaOne, Mana manaTwo) + { + if (manaTwo.Access == 0 || manaTwo.Consensus == 0) + { + throw new DivideByZeroException(); + } + return new Mana(manaOne.Access / manaTwo.Access, manaOne.Consensus / manaTwo.Consensus); + } + + public static Mana operator *(Mana manaOne, Mana manaTwo) => new Mana(manaOne.Access * manaTwo.Access, manaOne.Consensus * manaTwo.Consensus); + + public static Mana operator *(Mana manaOne, int factor) => new Mana(manaOne.Access * factor, manaOne.Consensus * factor); + + public Mana(decimal access, decimal consensus) + { + Access = access; + Consensus = consensus; + } + + public override string ToString() + { + return $"Access Mana: {Access:0} - Consensus Mana: {Consensus}"; + } + } +} diff --git a/Source/MonitorIotaNode/Program.cs b/Source/MonitorIotaNode/Program.cs new file mode 100644 index 0000000..4b5f470 --- /dev/null +++ b/Source/MonitorIotaNode/Program.cs @@ -0,0 +1,241 @@ +using System; +using System.Collections.Generic; +using System.IO; +using Newtonsoft.Json; +using Newtonsoft.Json.Linq; +using Serilog; +using Serilog.Events; +using System.Linq; +using RestSharp; +using System.Threading; + +namespace MonitorIotaNode +{ + class Program + { + public static Settings settings; + private static string settingsFile; + private static Timer timerStatusCheck = null; + private static Timer timerSyncCheck = null; + + private static Dictionary previousNodeInfos = new Dictionary(); + + // status info: + // totalMessageCount (plus delta since last time) + // mana.access, mana.consensus (plus delta since last time) + + static void Main(string[] args) + { + Log.Logger = new LoggerConfiguration() + .MinimumLevel.Verbose() //send all events to sinks + .WriteTo.Console(restrictedToMinimumLevel: LogEventLevel.Information) //Todo: be configurable + .WriteTo.File("log.txt", //Todo: be configurable + rollingInterval: RollingInterval.Day, + rollOnFileSizeLimit: true, + restrictedToMinimumLevel: LogEventLevel.Verbose) //Todo: be configurable + .CreateLogger(); + + Log.Logger.Information(("Monitor IOTA Nodes v0.1\n")); + Log.Logger.Information(" Escape to quit"); + + settingsFile = ParseArguments(args); + + if (!File.Exists(settingsFile)) + { + Log.Logger.Error($"Settingsfile {settingsFile} not found!"); ; + Log.Logger.Information($"Creating new one... Please review it and fill in the blanks!"); ; + Settings.SaveSettings(settingsFile, Settings.DefaultSettings()); + Environment.Exit(1); + } + + //settingsFile = $"c:\temp\settings.json"; //override for testing purposes + + Log.Logger.Information($"Loading settings from {settingsFile}\n"); + + ReloadSettings(); + SettingsWatcher settingsWatcher = new SettingsWatcher(settingsFile, SettingsChanged); + + while (true) + { + Thread.Sleep(1000); + + if (Console.KeyAvailable) + { + ConsoleKeyInfo cki = Console.ReadKey(true); + if (cki.Key == ConsoleKey.Escape) Environment.Exit(0); + } + } + } + + private static void ReloadSettings() + { + settings = Settings.LoadSettings(settingsFile); + SetTimers(); + } + + private static void SetTimers() + { + //clear timers because enabled and interval settings can be changed + timerStatusCheck?.Dispose(); + timerSyncCheck?.Dispose(); + + if (settings.StatusCheckInterval.Enabled) timerStatusCheck = new Timer(TimerStatusCheck_Interval, null, 0, settings.StatusCheckInterval.IntervalInMinutes * 60 * 1000); + if (settings.SyncCheckInterval.Enabled) timerSyncCheck = new Timer(TimerSyncCheck_Interval, null, 0, settings.SyncCheckInterval.IntervalInMinutes * 60 * 1000); + } + + private static void CheckStatus() + { + foreach (IotaNode iotaNode in settings.IncludedNodesForStatusCheck) + { + NodeEndpoint nodeEndpoint = new NodeEndpoint(iotaNode.InfoUrl); + NodeInfo nodeInfo = nodeEndpoint.RetrieveNodeInfo(); + + NodeInfo previousNodeInfo; + bool previousAvailable = previousNodeInfos.TryGetValue(iotaNode.InfoUrl, out previousNodeInfo); + + string deltaManaMessage = ""; + string deltaTotalMessageCountMessage = ""; + if (previousAvailable) + { + Mana deltaMana = nodeInfo.Mana - previousNodeInfo.Mana; + Mana deltaManaPercentage = (deltaMana / previousNodeInfo.Mana) * 100; + + deltaManaMessage = $"Change in Access Mana={deltaMana.Access}({deltaManaPercentage.Access:0.##}%)\nChange in Consensus Mana={deltaMana.Consensus}({deltaManaPercentage.Consensus:0.##}%)\n"; + Log.Logger.Information(deltaManaMessage); + + int deltaTotalMessageCount = nodeInfo.TotalMessageCount - previousNodeInfo.TotalMessageCount; + decimal deltaTotalMessageCountPercentage = ((decimal)deltaTotalMessageCount / previousNodeInfo.TotalMessageCount) * 100; + deltaTotalMessageCountMessage = $"Change in Total Message Count={deltaTotalMessageCount}({deltaTotalMessageCountPercentage:0.###}%)\n"; + Log.Logger.Information(deltaTotalMessageCountMessage); + + + previousNodeInfos[iotaNode.InfoUrl] = nodeInfo; //does exist so update + } + else previousNodeInfos.Add(iotaNode.InfoUrl, nodeInfo); //is new so add + + string title = $"Status of Node {nodeInfo.IdentityIdShort}"; + string message = $"Version {nodeInfo.Version}\nNetworkVersion {nodeInfo.NetworkVersion}\n" + + $"{nodeInfo.TangleTime}\n" + + $"Messages (solid/total): {nodeInfo.SolidMessageCount}/{nodeInfo.TotalMessageCount}\n" + + $"{deltaTotalMessageCountMessage}" + + $"{nodeInfo.Mana}\n" + + $"{deltaManaMessage}" + + $"Info: {iotaNode.InfoUrl.AbsoluteUri}"; + + if (iotaNode.DashboardUrl?.AbsoluteUri.Length > 0) message += $"\nDashboard: {iotaNode.DashboardUrl.AbsoluteUri}"; + + Log.Logger.Information($"Sending a notification:\n{title}\n{message}"); + + SendNotifications(settings.PushOver.ApiKey, settings.PushOver.UserKey, settings.IncludedDeviceNames, title, message); + } + } + + private static void CheckSync() + { + foreach (IotaNode iotaNode in settings.IncludedNodesForSyncCheck) + { + NodeEndpoint nodeEndpoint = new NodeEndpoint(iotaNode.InfoUrl); + NodeInfo nodeInfo = nodeEndpoint.RetrieveNodeInfo(); + + if (!nodeInfo.TangleTime.Synced) + { + string title = $"Node {nodeInfo.IdentityIdShort} NOT synced!"; + string message = $"Version {nodeInfo.Version}\nNetworkVersion {nodeInfo.NetworkVersion}\n" + + $"{nodeInfo.TangleTime}\n" + + $"Messages (solid/total): {nodeInfo.SolidMessageCount}/{nodeInfo.TotalMessageCount}\n" + + $"{nodeInfo.Mana}\n" + + $"Info: {iotaNode.InfoUrl.AbsoluteUri}"; + + if (iotaNode.DashboardUrl?.AbsoluteUri.Length > 0) message += $"\nDashboard: {iotaNode.DashboardUrl.AbsoluteUri}"; + + Log.Logger.Information($"Sending a notification:\n{title}\n{message}"); + + SendNotifications(settings.PushOver.ApiKey, settings.PushOver.UserKey, settings.IncludedDeviceNames, title, message); + } + } + } + + private static void TimerStatusCheck_Interval(Object o) + { + Log.Logger.Information("In TimerStatusCheck_Interval: " + DateTime.Now); + CheckStatus(); + } + + private static void TimerSyncCheck_Interval(Object o) + { + Log.Logger.Information("In TimerSyncCheck_Interval: " + DateTime.Now); + CheckSync(); + } + + private static void SettingsChanged(SettingsWatcher settingsWatcher) + { + Log.Logger.Information($"Settings in {settingsWatcher.Filename} changed! Reloading... New settings are:"); + ReloadSettings(); + Log.Logger.Information($"{settings}"); + } + + private static string ParseArguments(string[] args) + { + if (args.Length > 1) + { + Log.Logger.Fatal("Error in arguments!"); + Log.Logger.Information("Syntax: [settingsfile]"); + Environment.Exit(1); + } + + string settingsFile; + if (args.Length == 0) + { + string currentFolder = Directory.GetCurrentDirectory(); + settingsFile = Settings.DefaultSettingsFile(currentFolder); + } + else + { + settingsFile = args[0]; + } + + return settingsFile; + } + + static bool SendNotifications(string token, string user, List devices, string title, string message) + { + if (!settings.PushOver.Enabled) return true; + + bool sendAllSucceeded = true; + + foreach (var device in devices) + { + var client = new RestClient($"https://api.pushover.net/1/messages.json?token={token}&user={user}&device={device}&title={title}&message={message}"); + var request = new RestRequest(Method.POST); + request.AddHeader("cache-control", "no-cache"); + request.AddHeader("Content-Type", "application/x-www-form-urlencoded"); + IRestResponse response = null; + try + { + response = client.Execute(request); + } + finally + { + if (response != null && !response.IsSuccessful) + { + Log.Logger.Error(response.ErrorMessage); + sendAllSucceeded = false; + } + } + } + return sendAllSucceeded; + } + + public static long SecondsSinceEpoch(DateTime utcDateTime) + { + TimeSpan t = utcDateTime - new DateTime(1970, 1, 1); + long secondsSinceEpoch = (long)t.TotalSeconds; + return secondsSinceEpoch; + } + + public static long SecondsSinceEpoch() + { + return SecondsSinceEpoch(DateTime.UtcNow); + } + } +} diff --git a/Source/MonitorIotaNode/Settings.cs b/Source/MonitorIotaNode/Settings.cs new file mode 100644 index 0000000..5ea0dc0 --- /dev/null +++ b/Source/MonitorIotaNode/Settings.cs @@ -0,0 +1,143 @@ +using Newtonsoft.Json; +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace MonitorIotaNode +{ + public class Settings + { + [JsonProperty(Required = Required.Always)] + public CheckInterval StatusCheckInterval { get; set; } + + [JsonProperty(Required = Required.Always)] + public CheckInterval SyncCheckInterval { get; set; } + + [JsonProperty(Required = Required.Always)] + public List IotaNodes { get; set; } + + [JsonProperty(Required = Required.Always)] + public PushOver PushOver { get; set; } + + [JsonIgnore] + public List IncludedDeviceNames => PushOver + .Devices + .Where(device => device.Include) + .Select(device => device.Name).ToList(); + + [JsonIgnore] + public List IncludedNodesForStatusCheck => IotaNodes.Where(node => node.IncludeForStatusCheck).ToList(); + + [JsonIgnore] + public List IncludedNodesForSyncCheck => IotaNodes.Where(node => node.IncludeForSyncCheck).ToList(); + + public static Settings LoadSettings(string filename) + { + string settingsJson = File.ReadAllText(filename); + + return JsonConvert.DeserializeObject(settingsJson); + } + + public static void SaveSettings(string filename, Settings settings) + { + string settingsJson = JsonConvert.SerializeObject(settings, Formatting.Indented); + + File.WriteAllText(filename, settingsJson); + } + + public static string DefaultSettingsFile(string path = "") + { + path = Path.Combine(path, " ").TrimEnd(); + return @$"{path}settings.json"; + } + + public static Settings DefaultSettings() + { + Settings settings = new Settings(); + settings.StatusCheckInterval = new CheckInterval + { + IntervalInMinutes = 24 * 60, //every day + Enabled = true + }; + settings.SyncCheckInterval = new CheckInterval + { + IntervalInMinutes = 1, //every minute + Enabled = true + }; + settings.IotaNodes = new List() { new IotaNode() { DashboardUrl = new Uri("http://localhost:8081/dashboard"), InfoUrl = new Uri("http://localhost:8080/info"), IncludeForStatusCheck = true, IncludeForSyncCheck = true } }; + settings.PushOver = new PushOver() { Enabled=true, ApiKey = "Fill me in, login into https://pushover.net/", UserKey = "Fill me in, login into https://pushover.net/", Devices = new List() { new Device() { Name = "Fill me in, login into https://pushover.net/", Include = true } } }; + return settings; + } + + public override string ToString() + { + return JsonConvert.SerializeObject(this, Formatting.Indented); + } + } + + public class CheckInterval + { + private int intervalInMinutes; + + [JsonProperty(Required = Required.Always)] + public int IntervalInMinutes + { + get => intervalInMinutes; + set + { + if (value < 1) throw new FormatException("IntervalInMinutes must be >=1"); + intervalInMinutes = value; + } + } + + [JsonProperty(Required = Required.Always)] + public bool Enabled { get; set; } + } + + public class IotaNode + { + [JsonProperty(Required = Required.Default)] //optional + public Uri DashboardUrl { get; set; } + + [JsonProperty(Required = Required.Always)] + public Uri InfoUrl { get; set; } + + [JsonProperty(Required = Required.Always)] + public bool IncludeForStatusCheck { get; set; } + + [JsonProperty(Required = Required.Always)] + public bool IncludeForSyncCheck { get; set; } + } + + public class PushOver + { + [JsonProperty(Required = Required.Always)] + public bool Enabled { get; set; } + + [JsonProperty(Required = Required.Always)] + public string ApiKey { get; set; } + + [JsonProperty(Required = Required.Always)] + public string UserKey { get; set; } + + [JsonProperty(Required = Required.Always)] + public List Devices { get; set; } + } + + public class Device + { + [JsonProperty(Required = Required.Always)] + public string Name { get; set; } + + [JsonProperty(Required = Required.Always)] + public bool Include { get; set; } + + public override string ToString() + { + return $"Device name {Name}"; + } + } +} diff --git a/Source/MonitorIotaNode/SettingsWatcher.cs b/Source/MonitorIotaNode/SettingsWatcher.cs new file mode 100644 index 0000000..b9c95ab --- /dev/null +++ b/Source/MonitorIotaNode/SettingsWatcher.cs @@ -0,0 +1,65 @@ +using Serilog; +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace MonitorIotaNode +{ + public class SettingsWatcher + { + public DateTime LastChange { get; private set; } + public string Filename { get; private set; } + + private const int minimumFileAgeInSeconds = 5; + private readonly FileSystemWatcher watcher; + private Action eventHandler; + + public SettingsWatcher(string filename, Action eventHandler) + { + Filename = filename; + LastChange = DateTime.MinValue; + this.eventHandler = eventHandler; + + if (File.Exists(filename)) + { + watcher = new FileSystemWatcher(Path.GetDirectoryName(filename), Path.GetFileName(filename)); + watcher.EnableRaisingEvents = true; + watcher.Changed += Watcher_Changed; + } + else throw new ArgumentException($"File {filename} does not exist!"); + } + + private void Watcher_Changed(object sender, FileSystemEventArgs e) + { + if ((DateTime.Now - LastChange).Seconds > minimumFileAgeInSeconds && !IsFileLocked(e.FullPath)) //Avoid code executing multiple times + { + Log.Logger.Information($"Settings in {watcher.Filter} changed!"); + LastChange = DateTime.Now; + + if (eventHandler != null) eventHandler(this); + } + } + + private bool IsFileLocked(string filePath) + { + FileStream stream = null; + try + { + stream = File.OpenRead(filePath); + } + catch (IOException) + { + return true; + } + finally + { + if (stream != null) + stream.Close(); + } + return false; + } + } +} diff --git a/buildAll.bat b/buildAll.bat new file mode 100644 index 0000000..7534597 --- /dev/null +++ b/buildAll.bat @@ -0,0 +1,59 @@ +set version=1.0 +set dotnetcore=net5.0 + +rem Root solution folder +cd /d "C:\Users\Jan Oonk\Source\repos\MonitorIotaNode" + + +rem Delete Builds folder +del /f /q /s Builds\*.* > nul +rmdir /q /s Builds +mkdir Builds + + +rem Delete bin folder of MonitorIotaNode +del /f /q /s Source\MonitorIotaNode\bin\*.* > nul +rmdir /q /s Source\MonitorIotaNode\bin + +rem .NET Core 5 +dotnet publish Source\MonitorIotaNode\MonitorIotaNode.csproj /p:PublishProfile=Source\MonitorIotaNode\Properties\PublishProfiles\linux-arm.pubxml --configuration Release +dotnet publish Source\MonitorIotaNode\MonitorIotaNode.csproj /p:PublishProfile=Source\MonitorIotaNode\Properties\PublishProfiles\linux-x64.pubxml --configuration Release +dotnet publish Source\MonitorIotaNode\MonitorIotaNode.csproj /p:PublishProfile=Source\MonitorIotaNode\Properties\PublishProfiles\osx-x64.pubxml --configuration Release +dotnet publish Source\MonitorIotaNode\MonitorIotaNode.csproj /p:PublishProfile=Source\MonitorIotaNode\Properties\PublishProfiles\win-x64.pubxml --configuration Release +dotnet publish Source\MonitorIotaNode\MonitorIotaNode.csproj /p:PublishProfile=Source\MonitorIotaNode\Properties\PublishProfiles\win-x86.pubxml --configuration Release + +rem .NET Core 3.1 +dotnet publish Source\MonitorIotaNode\MonitorIotaNode.csproj /p:PublishProfile=Source\MonitorIotaNode\Properties\PublishProfiles\linux-arm-netcoreapp3.1.pubxml --configuration Release +rem Workaround: Somehow Settings.ini does not get copied to publish folder, only to output folder?! +copy Source\MonitorIotaNode\bin\Release\netcoreapp3.1\linux-arm\Settings.ini Source\MonitorIotaNode\bin\Release\netcoreapp3.1\publish\linux-arm\ + +rem Rar all MonitorIotaNode builds +rem .NET Core 5 +cd /d "C:\Users\Jan Oonk\Source\repos\MonitorIotaNode" +cd Source\MonitorIotaNode\bin\Release\net5.0\publish\linux-arm\ +"C:\Program Files\WinRAR\rar.exe" a -r ..\..\..\..\..\..\..\Builds\MonitorIotaNode-%version%-linux-arm-%dotnetcore%.rar *.* + +cd /d "C:\Users\Jan Oonk\Source\repos\MonitorIotaNode" +cd Source\MonitorIotaNode\bin\Release\net5.0\publish\linux-x64\ +"C:\Program Files\WinRAR\rar.exe" a -r ..\..\..\..\..\..\..\Builds\MonitorIotaNode-%version%-linux-x64-%dotnetcore%.rar *.* + +cd /d "C:\Users\Jan Oonk\Source\repos\MonitorIotaNode" +cd Source\MonitorIotaNode\bin\Release\net5.0\publish\osx-x64\ +"C:\Program Files\WinRAR\rar.exe" a -r ..\..\..\..\..\..\..\Builds\MonitorIotaNode-%version%-osx-x64-%dotnetcore%.rar *.* + +cd /d "C:\Users\Jan Oonk\Source\repos\MonitorIotaNode" +cd Source\MonitorIotaNode\bin\Release\net5.0\publish\win-x64\ +"C:\Program Files\WinRAR\rar.exe" a -r ..\..\..\..\..\..\..\Builds\MonitorIotaNode-%version%-win-x64-%dotnetcore%.rar *.* + +cd /d "C:\Users\Jan Oonk\Source\repos\MonitorIotaNode" +cd Source\MonitorIotaNode\bin\Release\net5.0\publish\win-x86\ +"C:\Program Files\WinRAR\rar.exe" a -r ..\..\..\..\..\..\..\Builds\MonitorIotaNode-%version%-win-x86-%dotnetcore%.rar *.* + +rem Rar all MonitorIotaNode builds +rem .NET Core 3.1 +cd /d "C:\Users\Jan Oonk\Source\repos\MonitorIotaNode" +cd Source\MonitorIotaNode\bin\Release\netcoreapp3.1\publish\linux-arm\ +"C:\Program Files\WinRAR\rar.exe" a -r ..\..\..\..\..\..\..\Builds\MonitorIotaNode-%version%-linux-arm-netcoreapp3.1.rar *.* + + +cd /d "C:\Users\Jan Oonk\Source\repos\MonitorIotaNode"