Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add a node events page #173

Merged
merged 4 commits into from
Oct 25, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 12 additions & 0 deletions OrcanodeMonitor/Core/Fetcher.cs
Original file line number Diff line number Diff line change
Expand Up @@ -1042,6 +1042,18 @@ public static List<OrcanodeEvent> GetEvents(OrcanodeMonitorContext context, int
return orcanodeEvents;
}

public static List<OrcanodeEvent> GetRecentEventsForNode(OrcanodeMonitorContext context, string id, DateTime since)
{
List<OrcanodeEvent> events = context.OrcanodeEvents.Where(e => e.OrcanodeId == id).OrderByDescending(e => e.DateTimeUtc).ToList();
List<OrcanodeEvent> orcanodeEvents = events.Where(e => e.DateTimeUtc >= since).ToList();
OrcanodeEvent? olderEvent = events.Where(e => (e.DateTimeUtc < since)).FirstOrDefault();
if (olderEvent != null)
{
return orcanodeEvents.Append(olderEvent).ToList();
}
return orcanodeEvents;
}
dthaler marked this conversation as resolved.
Show resolved Hide resolved

private static void AddOrcanodeEvent(OrcanodeMonitorContext context, Orcanode node, string type, string value)
{
var orcanodeEvent = new OrcanodeEvent(node, type, value, DateTime.UtcNow);
Expand Down
76 changes: 76 additions & 0 deletions OrcanodeMonitor/Models/Orcanode.cs
Original file line number Diff line number Diff line change
Expand Up @@ -392,6 +392,82 @@ public string OrcasoundOnlineStatusString {

public OrcanodeIftttDTO ToIftttDTO() => new OrcanodeIftttDTO(ID, DisplayName);

/// <summary>
/// Calculates the uptime percentage for a node based on its events since a specified date.
/// </summary>
/// <param name="orcanodeId">The ID of the node to calculate uptime for</param>
/// <param name="events">List of node events</param>
/// <param name="since">The start date for uptime calculation</param>
/// <returns>Uptime percentage as an integer between 0 and 100</returns>
/// <exception cref="ArgumentException">Thrown when orcanodeId is null or empty</exception>
public static int GetUptimePercentage(string orcanodeId, List<OrcanodeEvent> events, DateTime since)
{
if (string.IsNullOrEmpty(orcanodeId))
{
throw new ArgumentException("Node ID cannot be null or empty", nameof(orcanodeId));
}
if (since > DateTime.UtcNow)
{
throw new ArgumentException("Start date cannot be in the future", nameof(since));
}
if (events == null)
{
return 0;
}

TimeSpan up = TimeSpan.Zero;
TimeSpan down = TimeSpan.Zero;
DateTime start = since;
string lastValue = string.Empty;

// Get events sorted by date to ensure correct chronological processing.
var nodeEvents = events
.Where(e => e.OrcanodeId == orcanodeId)
.OrderBy(e => e.DateTimeUtc)
.ToList();

// Compute uptime percentage by looking at OrcanodeEvents over the past week.
foreach (OrcanodeEvent e in nodeEvents)
{
if (e.DateTimeUtc <= since)
{
// Event is too old.
lastValue = e.Value;
continue;
}
DateTime current = e.DateTimeUtc;
if (lastValue == OnlineString)
{
up += (current - start);
}
else
{
down += (current - start);
}
start = current;
lastValue = e.Value;
}

// Account for the reminder of the time until now.
DateTime now = DateTime.UtcNow;
if (lastValue == OnlineString)
{
up += now - start;
}
else
{
down += now - start;
}

TimeSpan totalTime = up + down;
if (totalTime == TimeSpan.Zero)
{
return 0;
}
int percentage = (int)((100.0 * up) / totalTime + 0.5);
return percentage;
}

/// <summary>
/// Derive a human-readable display name from a Dataplicity node name.
/// </summary>
Expand Down
11 changes: 9 additions & 2 deletions OrcanodeMonitor/Models/OrcanodeEvent.cs
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,13 @@ public class OrcanodeEvent
{
public OrcanodeEvent()
{
Slug = string.Empty;
Type = string.Empty;
Value = string.Empty;
OrcanodeId = string.Empty;
ID = string.Empty;
dthaler marked this conversation as resolved.
Show resolved Hide resolved
DateTimeUtc = DateTime.UtcNow;
Year = DateTimeUtc.Year;
}

public OrcanodeEvent(Orcanode node, string type, string value, DateTime timestamp)
Expand Down Expand Up @@ -97,7 +104,7 @@ public OrcanodeEvent(Orcanode node, string type, string value, DateTime timestam
public string OrcanodeId { get; set; }

// Navigation property that uses OrcanodeId.
public virtual Orcanode Orcanode { get; set; }
public virtual Orcanode? Orcanode { get; set; }

public DateTime DateTimeUtc { get; set; }

Expand Down Expand Up @@ -141,7 +148,7 @@ public int DerivedSeverity

public override string ToString()
{
return string.Format("{0} {1} => {2} at {3}", Slug, Type, Value, Fetcher.UtcToLocalDateTime(DateTimeUtc));
return string.Format("{0} {1} => {2} at {3}", NodeName, Type, Value, Fetcher.UtcToLocalDateTime(DateTimeUtc));
}

#endregion methods
Expand Down
2 changes: 2 additions & 0 deletions OrcanodeMonitor/Pages/DataplicityNode.cshtml.cs
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,8 @@ public DataplicityNodeModel(OrcanodeMonitorContext context, ILogger<IndexModel>
{
_databaseContext = context;
_logger = logger;
_serial = string.Empty;
_jsonData = string.Empty;
}

public string LastChecked
Expand Down
33 changes: 18 additions & 15 deletions OrcanodeMonitor/Pages/Index.cshtml
Original file line number Diff line number Diff line change
Expand Up @@ -71,8 +71,11 @@
</a>
</td>
}
<td style="background-color: @Model.NodeUptimePercentageBackgroundColor(item); color: @Model.NodeUptimePercentageTextColor(item)">
@Model.GetUptimePercentage(item)%
<td style="background-color: @Model.NodeUptimePercentageBackgroundColor(item)">
<a asp-page="/NodeEvents" asp-route-id="@item.ID" style="color: @Model.NodeUptimePercentageTextColor(item)" target="_blank"
aria-label="View events for @item.DisplayName (opens in new tab)">
@Model.GetUptimePercentage(item)%
</a>
</td>
@if (item.OrcasoundStatus == Models.OrcanodeOnlineStatus.Absent)
{
Expand Down Expand Up @@ -175,20 +178,20 @@
<p/>
<h1 class="display-4"><a href="/api/ifttt/v1/triggers/nodestateevents">Recent State Events</a></h1>
<table>
<tr>
<th>Timestamp</th>
<th>Event</th>
</tr>
@foreach (Models.OrcanodeEvent item in Model.RecentEvents)
{
<thead>
<tr>
<td>
@item.DateTimeLocal
</td>
<td>
@item.Description
</td>
<th>Timestamp</th>
<th>Event</th>
</tr>
}
</thead>
<tbody>
@foreach (Models.OrcanodeEvent item in Model.RecentEvents)
{
<tr>
<td>@item.DateTimeLocal.ToString("g")</td>
<td align="left">@item.Description</td>
</tr>
}
</tbody>
</table>
</div>
58 changes: 4 additions & 54 deletions OrcanodeMonitor/Pages/Index.cshtml.cs
Original file line number Diff line number Diff line change
Expand Up @@ -19,12 +19,13 @@ public class IndexModel : PageModel
public List<Orcanode> Nodes => _nodes;
private const int _maxEventCountToDisplay = 20;
public List<OrcanodeEvent> RecentEvents => Fetcher.GetEvents(_databaseContext, _maxEventCountToDisplay);
private TimeSpan _uptimeEvaluationPeriod = TimeSpan.FromDays(7); // 1 week.

public IndexModel(OrcanodeMonitorContext context, ILogger<IndexModel> logger)
{
_databaseContext = context;
_logger = logger;
_events = new List<OrcanodeEvent>();
_nodes = new List<Orcanode>();
}
public string LastChecked
{
Expand Down Expand Up @@ -94,60 +95,9 @@ private string GetTextColor(OrcanodeOnlineStatus status)

public string NodeOrcasoundTextColor(Orcanode node) => GetTextColor(node.OrcasoundStatus);

public int GetUptimePercentage(Orcanode node)
{
if (_events == null)
{
return 0;
}

TimeSpan up = TimeSpan.Zero;
TimeSpan down = TimeSpan.Zero;
DateTime start = DateTime.UtcNow - _uptimeEvaluationPeriod;
string lastValue = string.Empty;

// Get events sorted by date to ensure correct chronological processing
var nodeEvents = _events
.Where(e => e.Orcanode == node)
.OrderBy(e => e.DateTimeUtc)
.ToList();
private DateTime SinceTime => DateTime.UtcNow.AddDays(-7);
dthaler marked this conversation as resolved.
Show resolved Hide resolved

// Compute uptime percentage by looking at OrcanodeEvents over the past week.
foreach (OrcanodeEvent e in nodeEvents)
{
if (DateTime.UtcNow - e.DateTimeUtc >= _uptimeEvaluationPeriod) {
// More than a week old.
lastValue = e.Value;
continue;
}
DateTime current = e.DateTimeUtc;
if (lastValue == Orcanode.OnlineString)
{
up += (current - start);
}
else
{
down += (current - start);
}
start = current;
lastValue = e.Value;
}
if (lastValue == Orcanode.OnlineString)
{
up += DateTime.UtcNow - start;
} else
{
down += DateTime.UtcNow - start;
}

TimeSpan totalTime = up + down;
if (totalTime == TimeSpan.Zero)
{
return 0;
}
int percentage = (int)((100.0 * up) / totalTime + 0.5);
return percentage;
}
public int GetUptimePercentage(Orcanode node) => Orcanode.GetUptimePercentage(node.ID, _events, SinceTime);

public string NodeUptimePercentageBackgroundColor(Orcanode node)
{
Expand Down
51 changes: 51 additions & 0 deletions OrcanodeMonitor/Pages/NodeEvents.cshtml
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
@page "{id}"
@model OrcanodeMonitor.Pages.NodeEventsModel
@{
ViewData["Title"] = "Node Events";
}
dthaler marked this conversation as resolved.
Show resolved Hide resolved

<div class="text-center">
<h1 class="display-4">Node Events</h1>
<form method="post">
@Html.AntiForgeryToken()
<input type="hidden" name="Id" value="@Model.Id" />
<div role="group" aria-label="Time period selection">
<button type="submit" name="Selected" value="week"
class="btn @(Model.Selected == "week" ? "selected" : "unselected")"
aria-pressed="@(Model.Selected == "week" ? "true" : "false")" >
Past Week
</button>
<button type="submit" name="Selected" value="month"
class="btn @(Model.Selected == "month" ? "selected" : "unselected")"
aria-pressed="@(Model.Selected == "month" ? "true" : "false")">
Past Month
</button>
</div>
</form>
<p>
Uptime percentage: @Model.UptimePercentage%
</p>
<table class="table">
<thead>
<tr>
<th>Timestamp</th>
<th>Event</th>
</tr>
</thead>
<tbody>
@if (!Model.RecentEvents.Any())
{
<tr>
<td colspan="2" class="text-center">No events found for this time period.</td>
</tr>
}
@foreach (Models.OrcanodeEvent item in Model.RecentEvents)
{
<tr>
<td>@item.DateTimeLocal.ToString("g")</td>
<td align="left">@item.Description</td>
</tr>
}
</tbody>
</table>
</div>
64 changes: 64 additions & 0 deletions OrcanodeMonitor/Pages/NodeEvents.cshtml.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
// Copyright (c) Orcanode Monitor contributors
// SPDX-License-Identifier: MIT
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using OrcanodeMonitor.Core;
using OrcanodeMonitor.Data;
using OrcanodeMonitor.Models;

namespace OrcanodeMonitor.Pages
{
public class NodeEventsModel : PageModel
{
private readonly OrcanodeMonitorContext _databaseContext;
private readonly ILogger<NodeEventsModel> _logger;
private string _nodeId;
public string Id => _nodeId;
[BindProperty]
public string Selected { get; set; } = "week"; // Default to 'week'
private DateTime SinceTime => (Selected == "week") ? DateTime.UtcNow.AddDays(-7) : DateTime.UtcNow.AddMonths(-1);
dthaler marked this conversation as resolved.
Show resolved Hide resolved
private List<OrcanodeEvent> _events;
public List<OrcanodeEvent> RecentEvents => _events;
public int UptimePercentage => Orcanode.GetUptimePercentage(_nodeId, _events, SinceTime);

public NodeEventsModel(OrcanodeMonitorContext context, ILogger<NodeEventsModel> logger)
{
_databaseContext = context;
_logger = logger;
_nodeId = string.Empty;
_events = new List<OrcanodeEvent>();
}

private void FetchEvents()
{
try
{
_events = Fetcher.GetRecentEventsForNode(_databaseContext, _nodeId, SinceTime);
}
catch (Exception ex)
{
_logger.LogError(ex, "Failed to fetch events for node {NodeId}", _nodeId);
_events = new List<OrcanodeEvent>();
}
}

public void OnGet(string id)
{
_nodeId = id;
FetchEvents();
}

public IActionResult OnPost(string selected, string id)
{
if (selected != "week" && selected != "month")
{
_logger.LogWarning("Invalid time range selected: {selected}", selected);
return BadRequest("Invalid time range");
}
Selected = selected;
_nodeId = id;
FetchEvents();
return Page();
}
}
}
Loading