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 uptime column to the dashboard #170

Merged
merged 5 commits into from
Oct 23, 2024
Merged

Add uptime column to the dashboard #170

merged 5 commits into from
Oct 23, 2024

Conversation

dthaler
Copy link
Collaborator

@dthaler dthaler commented Oct 23, 2024

Add uptime column to the dashboard where percentage is computed from "hydrophone stream" events over the past week

Summary by CodeRabbit

  • New Features

    • Introduced a new "Up%" column in the node status table, displaying the uptime percentage for each node.
    • Enhanced uptime calculations based on recent events for improved monitoring of Orcanodes.
  • Bug Fixes

    • Improved data fetching for Orcanode events, ensuring accurate uptime reporting.

Copy link

coderabbitai bot commented Oct 23, 2024

Caution

Review failed

The head commit changed during the review from 9be2e49 to dc29989.

Walkthrough

The changes introduce a new column titled "Up%" in the table of the Index.cshtml page, which displays the uptime percentage for various nodes. This is achieved by implementing a new method, GetUptimePercentage, in the IndexModel class of Index.cshtml.cs. The method calculates the uptime based on events related to each node over the past week. Additionally, the OnGetAsync method is modified to retrieve relevant Orcanode events from the database, enhancing the model's monitoring capabilities.

Changes

File Change Summary
OrcanodeMonitor/Pages/Index.cshtml Added a new column "Up%" to the existing table, displaying uptime percentage for each node.
OrcanodeMonitor/Pages/Index.cshtml.cs Introduced a private field _events for storing Orcanode events; added GetUptimePercentage method to calculate uptime; modified OnGetAsync to fetch and filter events from the database.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant IndexPage as Index.cshtml
    participant IndexModel as Index.cshtml.cs
    participant Database

    User->>IndexPage: Request Page
    IndexPage->>IndexModel: OnGetAsync()
    IndexModel->>Database: Fetch Orcanode Events
    Database-->>IndexModel: Return Events
    IndexModel->>IndexModel: Filter Events
    IndexModel->>IndexModel: GetUptimePercentage()
    IndexModel-->>IndexPage: Render Page with Uptime
    IndexPage-->>User: Display Page with Uptime Column
Loading

🐰 "In a table bright and new,
We show the uptime, just for you!
With events that help us see,
How our nodes are fairing, whee!
A hop, a skip, a joyful cheer,
For uptime's here, let's all draw near!" 🐇✨

Possibly related PRs

  • Change column order #165: The changes in the Index.cshtml file regarding the display of node statuses may relate to the new "Up%" column, as both involve modifications to the table structure and how node information is presented.

Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🧹 Outside diff range and nitpick comments (3)
OrcanodeMonitor/Pages/Index.cshtml.cs (2)

96-96: Add XML documentation for the method.

Add documentation to describe the method's purpose, parameters, return value, and behavior for edge cases.

Add this documentation:

/// <summary>
/// Calculates the uptime percentage for a node over the past 7 days based on hydrophone stream events.
/// </summary>
/// <param name="node">The node to calculate uptime for.</param>
/// <returns>
/// The percentage of time (0-100) the node was up over the past week.
/// Returns 0 if no events exist or if the events list is null.
/// </returns>

Line range hint 146-158: Add error handling and consider separating concerns.

The method has several areas for improvement:

  1. Missing error handling for database operations
  2. Combines node and event fetching which could be separated
  3. Could benefit from explaining the filtering criteria in comments

Consider refactoring like this:

 public async Task OnGetAsync()
 {
+    try
+    {
         // Fetch nodes for display.
+        // Filter out nodes that are absent or unauthorized, excluding dev environment
         var nodes = await _databaseContext.Orcanodes.ToListAsync();
         _nodes = nodes.Where(n => ((n.DataplicityConnectionStatus != OrcanodeOnlineStatus.Absent) ||
                                   (n.OrcasoundStatus != OrcanodeOnlineStatus.Absent) ||
                                   (n.S3StreamStatus != OrcanodeOnlineStatus.Absent &&
                                    n.S3StreamStatus != OrcanodeOnlineStatus.Unauthorized)) &&
                                  (n.OrcasoundHost != "dev.orcasound.net"))
                      .OrderBy(n => n.DisplayName)
                      .ToList();

         // Fetch events for uptime computation.
+        // Only consider hydrophone stream events as they indicate node availability
         var events = await _databaseContext.OrcanodeEvents.ToListAsync();
         _events = events.Where(e => e.Type == "hydrophone stream").ToList();
+    }
+    catch (Exception ex)
+    {
+        _logger.LogError(ex, "Failed to fetch nodes or events");
+        // Consider setting an error message to display to the user
+        _nodes = new List<Orcanode>();
+        _events = new List<OrcanodeEvent>();
+    }
 }

Consider extracting the fetching logic into separate methods:

private async Task FetchNodesAsync()
{
    var nodes = await _databaseContext.Orcanodes.ToListAsync();
    _nodes = nodes.Where(/* ... */).ToList();
}

private async Task FetchEventsAsync()
{
    var events = await _databaseContext.OrcanodeEvents.ToListAsync();
    _events = events.Where(e => e.Type == "hydrophone stream").ToList();
}
OrcanodeMonitor/Pages/Index.cshtml (1)

21-21: Consider enhancing the uptime column header and documentation.

The "Up%" column would benefit from:

  1. A tooltip or hover text explaining the calculation period (e.g., "7-day uptime percentage")
  2. An entry in the legend section explaining how uptime is calculated
-            <th>Up%</th>
+            <th title="Node uptime percentage over the past 7 days">Up%</th>

Also, consider adding to the legend section:

+        <li>
+            <b>Up%</b>: Percentage of time the node was operational over the past 7 days.
+        </li>
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 4827902 and 5b1d1b2.

📒 Files selected for processing (2)
  • OrcanodeMonitor/Pages/Index.cshtml (2 hunks)
  • OrcanodeMonitor/Pages/Index.cshtml.cs (4 hunks)
🧰 Additional context used
🔇 Additional comments (3)
OrcanodeMonitor/Pages/Index.cshtml.cs (2)

17-17: LGTM: Field addition follows conventions.

The private field _events is appropriately scoped and follows C# naming conventions.


96-132: Verify event types and values in the database.

Let's verify the assumptions about event types and values used in the uptime calculation.

Also applies to: 156-158

✅ Verification successful

Let me try a different approach to verify the event values and types by searching for the OrcanodeEvent class definition and its usages.

This should help us understand:

  1. The structure of OrcanodeEvent class
  2. How event values are assigned in the codebase
  3. Related monitoring/status code that might show the event value patterns

Let me try one more search strategy focusing on the OrcanodeEvent class and its usage in monitoring:

This should help us understand:

  1. The OrcanodeEvent class structure
  2. How "up" and "down" values are used
  3. The complete context of the monitoring implementation

Based on the search results, I can now provide a final verification of the uptime calculation. The code shows:

  1. The uptime calculation correctly uses events of type "hydrophone stream" (filtered in Index.cshtml.cs line: _events = events.Where(e => e.Type == "hydrophone stream").ToList();)
  2. The event values are consistently set as "up" or status string (from Orcanode.cs: return (status == OrcanodeOnlineStatus.Online) ? "up" : S3StreamStatus.ToString().ToUpper();)
  3. The uptime percentage calculation logic correctly:
    • Processes events chronologically
    • Handles the "up" and non-"up" states appropriately
    • Accounts for gaps between events
    • Considers the last known state up to the current time

The uptime calculation implementation is correct and consistent with the codebase. The code properly tracks the hydrophone stream status through events and calculates the percentage of time it was "up" over the past week.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check event types and values in the database
# Note: This assumes the code is in a .NET project with Entity Framework

# Test 1: Check unique event types
echo "Unique event types in OrcanodeEvents:"
rg -g "*.cs" -A 5 "Type\s*=\s*\".*\".*OrcanodeEvent"

# Test 2: Check event value assignments
echo "Event value assignments:"
rg -g "*.cs" -A 5 "Value\s*=\s*\".*\".*OrcanodeEvent"

Length of output: 250


Script:

#!/bin/bash
# Find OrcanodeEvent class definition and usages
echo "=== OrcanodeEvent class definition ==="
ast-grep --pattern 'class OrcanodeEvent {
  $$$
}'

echo -e "\n=== OrcanodeEvent value assignments ==="
rg -g "*.cs" "\.Value\s*=\s*" -B 2 -A 2

echo -e "\n=== Checking monitor/status related files ==="
fd -e cs -e cshtml monitor status -I | xargs cat

Length of output: 1896


Script:

#!/bin/bash
# Search for OrcanodeEvent class and monitoring logic
echo "=== OrcanodeEvent class and properties ==="
rg -g "*.cs" "class OrcanodeEvent" -B 2 -A 10

echo -e "\n=== Monitoring status checks ==="
rg -g "*.cs" -B 3 -A 3 "\"up\"|\"down\"|OrcanodeEvent"

echo -e "\n=== Files in OrcanodeMonitor directory ==="
fd . OrcanodeMonitor -t f -x echo "=== {} ===" \; cat "{}"

Length of output: 30644

OrcanodeMonitor/Pages/Index.cshtml (1)

74-76: 🛠️ Refactor suggestion

Enhance the uptime percentage display with formatting and visual cues.

Consider improving the uptime display with:

  1. Consistent styling with other status columns
  2. Formatted percentage values
  3. Visual indicators for different uptime ranges
-            <td>
-                @Model.GetUptimePercentage(item)%
-            </td>
+            <td style="background-color: @Model.GetUptimeBackgroundColor(item)">
+                @String.Format("{0:0.0}%", Model.GetUptimePercentage(item))
+            </td>

This assumes you'll add a GetUptimeBackgroundColor method to the model that returns appropriate colors based on uptime ranges (e.g., red for <90%, yellow for 90-98%, green for >98%).

Let's verify if the GetUptimePercentage method handles edge cases:

OrcanodeMonitor/Pages/Index.cshtml.cs Outdated Show resolved Hide resolved
Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🧹 Outside diff range and nitpick comments (1)
OrcanodeMonitor/Pages/Index.cshtml.cs (1)

Line range hint 152-164: Optimize database queries for better performance.

The current implementation loads all events into memory before filtering. Consider these improvements:

  1. Filter events in the database query
  2. Add error handling for database operations
  3. Consider limiting the time range of events fetched

Here's a suggested implementation:

 public async Task OnGetAsync()
 {
     // Fetch nodes for display.
-    var nodes = await _databaseContext.Orcanodes.ToListAsync();
+    try
+    {
+        var nodes = await _databaseContext.Orcanodes.ToListAsync();
+        _nodes = nodes.Where(n => ((n.DataplicityConnectionStatus != OrcanodeOnlineStatus.Absent) ||
+                                   (n.OrcasoundStatus != OrcanodeOnlineStatus.Absent) ||
+                                   (n.S3StreamStatus != OrcanodeOnlineStatus.Absent &&
+                                    n.S3StreamStatus != OrcanodeOnlineStatus.Unauthorized)) &&
+                                  (n.OrcasoundHost != "dev.orcasound.net"))
+                      .OrderBy(n => n.DisplayName)
+                      .ToList();

+        // Fetch events for uptime computation, filtering at the database level
+        var cutoffDate = DateTime.UtcNow - _uptimeEvaluationPeriod;
+        _events = await _databaseContext.OrcanodeEvents
+            .Where(e => e.Type == "hydrophone stream" && e.DateTimeUtc >= cutoffDate)
+            .ToListAsync();
+    }
+    catch (Exception ex)
+    {
+        _logger.LogError(ex, "Error fetching dashboard data");
+        throw;
+    }
-    _nodes = nodes.Where(n => ((n.DataplicityConnectionStatus != OrcanodeOnlineStatus.Absent) ||
-                               (n.OrcasoundStatus != OrcanodeOnlineStatus.Absent) ||
-                               (n.S3StreamStatus != OrcanodeOnlineStatus.Absent &&
-                                n.S3StreamStatus != OrcanodeOnlineStatus.Unauthorized)) &&
-                              (n.OrcasoundHost != "dev.orcasound.net"))
-                  .OrderBy(n => n.DisplayName)
-                  .ToList();

-    // Fetch events for uptime computation.
-    var events = await _databaseContext.OrcanodeEvents.ToListAsync();
-    _events = events.Where(e => e.Type == "hydrophone stream").ToList();
 }
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 5b1d1b2 and 1fae635.

📒 Files selected for processing (2)
  • OrcanodeMonitor/Pages/Index.cshtml (2 hunks)
  • OrcanodeMonitor/Pages/Index.cshtml.cs (4 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • OrcanodeMonitor/Pages/Index.cshtml
🧰 Additional context used
🔇 Additional comments (1)
OrcanodeMonitor/Pages/Index.cshtml.cs (1)

17-17: LGTM! Field declarations are well-structured.

The new fields are properly scoped and initialized with appropriate values.

Also applies to: 22-22

OrcanodeMonitor/Pages/Index.cshtml.cs Outdated Show resolved Hide resolved
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant