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 2 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
57 changes: 57 additions & 0 deletions OrcanodeMonitor/Models/Orcanode.cs
Original file line number Diff line number Diff line change
Expand Up @@ -392,6 +392,63 @@ public string OrcasoundOnlineStatusString {

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

public static int GetUptimePercentage(string orcanodeId, List<OrcanodeEvent> events, DateTime 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 == 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;
}

/// <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
32 changes: 17 additions & 15 deletions OrcanodeMonitor/Pages/Index.cshtml
Original file line number Diff line number Diff line change
Expand Up @@ -71,8 +71,10 @@
</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">
@Model.GetUptimePercentage(item)%
</a>
</td>
@if (item.OrcasoundStatus == Models.OrcanodeOnlineStatus.Absent)
{
Expand Down Expand Up @@ -175,20 +177,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>
60 changes: 5 additions & 55 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,64 +95,13 @@ 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)
{
int value = GetUptimePercentage(node);
int value = Orcanode.GetUptimePercentage(node.ID, _events, SinceTime);
if (value < 1)
{
return ColorTranslator.ToHtml(Color.Red);
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>
59 changes: 59 additions & 0 deletions OrcanodeMonitor/Pages/NodeEvents.cshtml.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
// 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;
using System.Xml.Linq;

namespace OrcanodeMonitor.Pages
{
public class NodeEventsModel : PageModel
{
private 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 void OnPost(string selected, string id)
{
Selected = selected;
_nodeId = id;
FetchEvents();
}
dthaler marked this conversation as resolved.
Show resolved Hide resolved
}
}
20 changes: 20 additions & 0 deletions OrcanodeMonitor/Pages/NodeEvents.cshtml.css
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
table, th, td {
border: 1px solid black;
border-collapse: collapse;
}

th, td {
padding: 5px;
}

h1 {
font-size: 32px;
}

.selected {
background-color: blue;
color: white;
}
.unselected {
border-color: blue;
}