Files
compute-blade-agent/cmd/bladectl/cmd_fan.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

210 lines
5.1 KiB
Go

package main
import (
"fmt"
"os"
"sort"
bladeapiv1alpha1 "github.com/compute-blade-community/compute-blade-agent/api/bladeapi/v1alpha1"
"github.com/olekukonko/tablewriter"
"github.com/olekukonko/tablewriter/tw"
"github.com/spf13/cobra"
"google.golang.org/protobuf/types/known/emptypb"
)
var (
percent int
auto bool
)
func init() {
cmdSetFan.Flags().IntVarP(&percent, "percent", "p", 40, "Fan speed in percent (Default: 40).")
cmdSetFan.Flags().BoolVarP(&auto, "auto", "a", false, "Set fan speed to automatic mode.")
cmdSet.AddCommand(cmdSetFan)
cmdGet.AddCommand(cmdGetFan)
cmdRemove.AddCommand(cmdRmFan)
cmdDescribe.AddCommand(cmdDescribeFan)
}
var (
fanAliases = []string{"fan_speed", "rpm"}
cmdSetFan = &cobra.Command{
Use: "fan",
Aliases: fanAliases,
Short: "Control the fan behavior of the compute-blade",
Example: "bladectl set fan --percent 50",
Args: cobra.ExactArgs(0),
RunE: func(cmd *cobra.Command, args []string) error {
autoSet := cmd.Flags().Changed("auto")
percentSet := cmd.Flags().Changed("percent")
if autoSet && percentSet {
return fmt.Errorf("only one of --auto or --percent can be specified")
}
if !autoSet && !percentSet {
return fmt.Errorf("you must specify either --auto or --percent")
}
ctx := cmd.Context()
clients := clientsFromContext(ctx)
for _, client := range clients {
var err error
if auto {
_, err = client.SetFanSpeedAuto(ctx, &emptypb.Empty{})
} else {
_, err = client.SetFanSpeed(ctx, &bladeapiv1alpha1.SetFanSpeedRequest{
Percent: int64(percent),
})
}
if err != nil {
return err
}
}
return nil
},
}
cmdRmFan = &cobra.Command{
Use: "fan",
Aliases: fanAliases,
Short: "Remove the fan speed override of the compute-blade",
Example: "bladectl unset fan",
Args: cobra.ExactArgs(0),
RunE: func(cmd *cobra.Command, args []string) error {
ctx := cmd.Context()
clients := clientsFromContext(ctx)
for _, client := range clients {
if _, err := client.SetFanSpeedAuto(ctx, &emptypb.Empty{}); err != nil {
return err
}
}
return nil
},
}
cmdGetFan = &cobra.Command{
Use: "fan",
Aliases: fanAliases,
Short: "Get the fan speed of the compute-blade",
Example: "bladectl get fan",
Args: cobra.ExactArgs(0),
RunE: func(cmd *cobra.Command, args []string) error {
ctx := cmd.Context()
clients := clientsFromContext(ctx)
for idx, client := range clients {
bladeStatus, err := client.GetStatus(ctx, &emptypb.Empty{})
if err != nil {
return err
}
rpm := bladeStatus.FanRpm
percent := bladeStatus.FanPercent
rowPrefix := bladeNames[idx]
if len(bladeNames) > 1 {
rowPrefix += ": "
} else {
rowPrefix = ""
}
fmt.Println(rpmStyle(rpm).Render(fmt.Sprint(rowPrefix + rpmLabel(rpm) + " (" + percentLabel(percent) + ")")))
}
return nil
},
}
cmdDescribeFan = &cobra.Command{
Use: "fan",
Aliases: fanAliases,
Short: "Get the fan speed curve of the compute-blade",
Example: "bladectl describe fan",
Args: cobra.ExactArgs(0),
RunE: func(cmd *cobra.Command, args []string) error {
ctx := cmd.Context()
clients := clientsFromContext(ctx)
bladeFanCurves := make([][]*bladeapiv1alpha1.FanCurveStep, len(clients))
criticalTemps := make([]int64, len(clients))
for idx, client := range clients {
bladeStatus, err := client.GetStatus(ctx, &emptypb.Empty{})
if err != nil {
return err
}
bladeFanCurves[idx] = bladeStatus.FanCurveSteps
criticalTemps[idx] = bladeStatus.CriticalTemperatureThreshold
}
printFanCurveTable(bladeFanCurves, criticalTemps)
return nil
},
}
)
func printFanCurveTable(bladeValues [][]*bladeapiv1alpha1.FanCurveStep, criticalTemps []int64) {
bladeCount := len(bladeValues)
// Map blade index -> temperature -> step
bladeTempMap := make([]map[int64]*bladeapiv1alpha1.FanCurveStep, bladeCount)
allTempsSet := make(map[int64]struct{})
for bladeIdx, steps := range bladeValues {
bladeTempMap[bladeIdx] = make(map[int64]*bladeapiv1alpha1.FanCurveStep)
for _, step := range steps {
temp := step.Temperature
bladeTempMap[bladeIdx][temp] = step
allTempsSet[temp] = struct{}{}
}
}
// Sorted temperature list
var allTemps []int64
for t := range allTempsSet {
allTemps = append(allTemps, t)
}
sort.Slice(allTemps, func(i, j int) bool {
return allTemps[i] < allTemps[j]
})
// Header: Blade | Temp1 | Temp2 | ...
header := []string{"Blade"}
for _, t := range allTemps {
header = append(header, tempLabel(t))
}
// Table writer setup
tbl := tablewriter.NewTable(os.Stdout,
tablewriter.WithHeader(header),
tablewriter.WithHeaderAlignment(tw.AlignLeft),
tablewriter.WithHeaderAutoFormat(tw.Off),
)
// Rows: one per blade
for bladeIdx, tempMap := range bladeTempMap {
row := []string{bladeNames[bladeIdx]}
for _, t := range allTemps {
if step, ok := tempMap[t]; ok {
style := tempStyle(step.Temperature, criticalTemps[bladeIdx])
colored := style.Render(percentLabel(step.Percent))
row = append(row, colored)
} else {
row = append(row, "")
}
}
_ = tbl.Append(row)
}
_ = tbl.Render()
}