Files
compute-blade-agent/cmd/bladectl/cmd_monitor.go
Cedric Kienzler 781ded8e43 feat(bladectl)!: add more bladectl commands (#91)
This PR introduces a comprehensive set of new subcommands to bladectl, expanding its capabilities for querying and managing compute blade state. It also includes an internal refactor to simplify interface management across the gRPC API.

* `get`
	* `fan`: Returns current fan speed.
	* `identify`: Indicates whether the identify mode is active.
	* `stealth`: Shows if stealth mode is currently enabled.
	* `status`: Prints a full blade status report.
	* `temperature`: Retrieves current SoC temperature.
	* `critical`: Shows whether critical mode is active.
	* `power`: Reports the current power source (e.g., PoE+ or USB).
* `set`
	* `stealth`: Enables stealth mode.
* `remove`
	* `stealth`: Disables stealth mode.
* `describe`
	* `fan`: Outputs the current fan curve configuration.
* `monitor`: plot some charts about the state of the compute-blade-agent

* **gRPC API refactor**: The gRPC service definitions previously located in `internal/api` have been folded into `internal/agent`. This eliminates redundant interface declarations and ensures that all ComputeBladeAgent implementations are directly compatible with the gRPC API.
This reduces duplication and improves long-term maintainability and clarity of the interface contract.

```bash
bladectl set fan --percent 90 --blade 1 --blade 2
bladectl unset identify --blade 1 --blade 2 --blade 3 --blade 4
bladectl set stealth --blade 1 --blade 2 --blade 3 --blade 4
bladectl get status --blade 1 --blade 2 --blade 3 --blade 4
┌───────┬─────────────┬────────────────────┬───────────────┬──────────────┬──────────┬───────────────┬──────────────┐
│ BLADE │ TEMPERATURE │ FAN SPEED OVERRIDE │ FAN SPEED     │ STEALTH MODE │ IDENTIFY │ CRITICAL MODE │ POWER STATUS │
├───────┼─────────────┼────────────────────┼───────────────┼──────────────┼──────────┼───────────────┼──────────────┤
│ 1     │ 50°C        │ 90%                │ 5825 RPM(90%) │ Active       │ Off      │ Off           │ poe+         │
│ 2     │ 48°C        │ 90%                │ 5825 RPM(90%) │ Active       │ Off      │ Off           │ poe+         │
│ 3     │ 49°C        │ Not set            │ 4643 RPM(56%) │ Active       │ Off      │ Off           │ poe+         │
│ 4     │ 49°C        │ Not set            │ 4774 RPM(58%) │ Active       │ Off      │ Off           │ poe+         │
└───────┴─────────────┴────────────────────┴───────────────┴──────────────┴──────────┴───────────────┴──────────────┘
bladectl rm stealth --blade 1 --blade 2 --blade 3 --blade 4
bladectl rm fan --blade 1 --blade 2 --blade 3 --blade 4
bladectl get status --blade 1 --blade 2 --blade 3 --blade 4
┌───────┬─────────────┬────────────────────┬───────────────┬──────────────┬──────────┬───────────────┬──────────────┐
│ BLADE │ TEMPERATURE │ FAN SPEED OVERRIDE │ FAN SPEED     │ STEALTH MODE │ IDENTIFY │ CRITICAL MODE │ POWER STATUS │
├───────┼─────────────┼────────────────────┼───────────────┼──────────────┼──────────┼───────────────┼──────────────┤
│ 1     │ 51°C        │ Not set            │ 5177 RPM(66%) │ Off          │ Off      │ Off           │ poe+         │
│ 2     │ 49°C        │ Not set            │ 5177 RPM(58%) │ Off          │ Off      │ Off           │ poe+         │
│ 3     │ 50°C        │ Not set            │ 4659 RPM(60%) │ Off          │ Off      │ Off           │ poe+         │
│ 4     │ 48°C        │ Not set            │ 4659 RPM(54%) │ Off          │ Off      │ Off           │ poe+         │
└───────┴─────────────┴────────────────────┴───────────────┴──────────────┴──────────┴───────────────┴──────────────┘
```

when having multiple compute-blades in your bladeconfig:

```yaml
blades:
    - name: 1
      blade:
        server: blade-pi1:8081
        cert:
            certificate-authority-data: <redacted>
            client-certificate-data: <redacted>
            client-key-data: <redacted>
    - name: 2
      blade:
        server: blade-pi2:8081
        cert:
            certificate-authority-data: <redacted>
            client-certificate-data: <redacted>
            client-key-data: <redacted>
    - name: 3
      blade:
        server: blade-pi3:8081
        cert:
            certificate-authority-data: <redacted>
            client-certificate-data: <redacted>
            client-key-data: <redacted>
    - name: 4
      blade:
        server: blade-pi4:8081
        cert:
            certificate-authority-data: <redacted>
            client-certificate-data: <redacted>
            client-key-data: <redacted>
    - name: 4
      blade:
        server: blade-pi4:8081
        cert:
            certificate-authority-data: <redacted>
            client-certificate-data: <redacted>
            client-key-data: <redacted>
current-blade: 1
```

Fixes #4, #9 (partially), should help with #5

* test: improve unit-testing

* fix: pin github.com/warthog618/gpiod

---------

Co-authored-by: Cedric Kienzler <cedric@specht-labs.de>
2025-06-06 23:03:43 +02:00

170 lines
4.1 KiB
Go

package main
import (
"context"
"errors"
"fmt"
"math"
"time"
bladeapiv1alpha1 "github.com/compute-blade-community/compute-blade-agent/api/bladeapi/v1alpha1"
"github.com/compute-blade-community/compute-blade-agent/pkg/hal"
ui "github.com/gizak/termui/v3"
"github.com/gizak/termui/v3/widgets"
"github.com/spf13/cobra"
"google.golang.org/protobuf/types/known/emptypb"
)
func init() {
rootCmd.AddCommand(cmdMonitor)
}
var cmdMonitor = &cobra.Command{
Use: "monitor",
Aliases: fanAliases,
Short: "Render a line-chart of the fan speed and temperature of the compute-blade",
Example: "bladectl chart status",
Args: cobra.ExactArgs(0),
RunE: func(cmd *cobra.Command, args []string) error {
if len(bladeNames) > 1 {
return fmt.Errorf("cannot monitor multiple blades at once, please specify a single blade with --blade")
}
ctx := cmd.Context()
client := clientFromContext(ctx)
if err := ui.Init(); err != nil {
return fmt.Errorf("failed to initialize UI: %w", err)
}
defer ui.Close()
events := ui.PollEvents()
ticker := time.NewTicker(1 * time.Second)
defer ticker.Stop()
labelBox := widgets.NewParagraph()
labelBox.Title = fmt.Sprintf(" %s: Blade Status ", bladeNames[0])
labelBox.Border = true
labelBox.TextStyle = ui.NewStyle(ui.ColorWhite)
fanPlot := newPlot(fmt.Sprintf(" %s: Fan Speed (RPM) ", bladeNames[0]), ui.ColorGreen)
tempPlot := newPlot(fmt.Sprintf(" %s: SoC Temperature (\u00b0C) ", bladeNames[0]), ui.ColorCyan)
fanData := []float64{math.NaN(), math.NaN()}
tempData := []float64{math.NaN(), math.NaN()}
for {
select {
case <-ctx.Done():
if errors.Is(ctx.Err(), context.Canceled) {
return nil
}
return ctx.Err()
case e := <-events:
switch e.ID {
case "q", "<C-c>":
return nil
case "<Resize>":
renderCharts(nil, fanPlot, tempPlot, labelBox)
ui.Clear()
ui.Render(labelBox, fanPlot, tempPlot)
}
case <-ticker.C:
status, err := client.GetStatus(ctx, &emptypb.Empty{})
if err != nil {
labelBox.Text = "Error retrieving blade status: " + err.Error()
ui.Render(labelBox)
continue
}
fanData = append(fanData, float64(status.FanRpm))
tempData = append(tempData, float64(status.Temperature))
fanPlot.Data[0] = reversedFloats(fanData)
tempPlot.Data[0] = reversedFloats(tempData)
renderCharts(status, fanPlot, tempPlot, labelBox)
ui.Render(labelBox, fanPlot, tempPlot)
}
}
},
}
func reversedFloats(s []float64) []float64 {
r := make([]float64, len(s))
for i := range s {
r[len(s)-1-i] = s[i]
}
return r
}
func newPlot(title string, color ui.Color) *widgets.Plot {
plot := widgets.NewPlot()
plot.Title = title
plot.Data = [][]float64{{}}
plot.LineColors = []ui.Color{color}
plot.AxesColor = ui.ColorWhite
plot.DrawDirection = widgets.DrawLeft
plot.HorizontalScale = 2
return plot
}
func renderCharts(status *bladeapiv1alpha1.StatusResponse, fanPlot, tempPlot *widgets.Plot, labelBox *widgets.Paragraph) {
width, height := ui.TerminalDimensions()
labelHeight := 4
if status != nil {
if status.CriticalActive {
labelBox.Text = fmt.Sprintf(
"Critical: %s | %s",
activeLabel(status.CriticalActive),
labelBox.Text,
)
}
labelBox.Text = fmt.Sprintf(
"Temp: %d°C | Fan: %d RPM (%d%%)",
status.Temperature,
status.FanRpm,
status.FanPercent,
)
if !status.FanSpeedAutomatic {
labelBox.Text = fmt.Sprintf(
"%s | Fan Override: %s",
labelBox.Text,
fanSpeedOverrideLabel(status.FanSpeedAutomatic, status.FanPercent),
)
}
if status.StealthMode {
labelBox.Text = fmt.Sprintf(
"%s | Stealth: %s",
labelBox.Text,
activeLabel(status.StealthMode),
)
}
labelBox.Text = fmt.Sprintf(
"%s | Identify: %s | Power: %s",
labelBox.Text,
activeLabel(status.IdentifyActive),
hal.PowerStatus(status.PowerStatus).String(),
)
}
labelBox.SetRect(0, 0, width, labelHeight)
if width >= 140 {
fanPlot.SetRect(0, labelHeight, width/2, height)
tempPlot.SetRect(width/2, labelHeight, width, height)
} else {
midY := (height-labelHeight)/2 + labelHeight
fanPlot.SetRect(0, labelHeight, width, midY)
tempPlot.SetRect(0, midY, width, height)
}
}