| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474 |
- package main
- import (
- "context"
- "encoding/json"
- "flag"
- "fmt"
- "io"
- "os"
- "strings"
- "time"
- "google.golang.org/grpc"
- "google.golang.org/grpc/health/grpc_health_v1"
- "google.golang.org/protobuf/encoding/protojson"
- "google.golang.org/protobuf/proto"
- "google.golang.org/protobuf/types/known/durationpb"
- "google.golang.org/protobuf/types/known/timestamppb"
- "hth/internal/app"
- "hth/internal/config"
- hthv1 "hth/internal/gen/hth/api/v1"
- "hth/internal/grpcserver"
- "hth/internal/profile"
- )
- func main() {
- fs := flag.NewFlagSet("hthctl", flag.ExitOnError)
- observe := fs.String("observe-sock", "/tmp/hth-mock/observe.sock", "observe unix socket")
- control := fs.String("control-sock", "/tmp/hth-mock/control.sock", "control unix socket")
- deviceID := fs.String("device", "prod2u-0", "device id")
- cfgPath := fs.String("config", "", "optional local config for doctor")
- realHW := fs.Bool("i-understand-this-is-real-hardware", false, "required for commands that mutate device state on non-mock backends")
- timeout := fs.Duration("timeout", 0, "rpc timeout; 0 uses TimingCapabilities for mutating commands, 5s for observe")
- count := fs.Int("count", 0, "watch/events count (0=until interrupt)")
- holder := fs.String("holder", "hthctl", "lease holder")
- ttl := fs.Duration("ttl", 10*time.Second, "lease ttl")
- file := fs.String("file", "", "JSON ActionBatch for validate-action")
- allowClamp := fs.Bool("allow-clamp", false, "allow clamp on validate/apply")
- target := fs.Int("target", -1, "6400 target temperature: 0 or 20..70 C")
- cmd := parseHthctlArgs(fs, os.Args[1:])
- if cmd == "" {
- fmt.Fprintln(os.Stderr, "usage: hthctl [flags] doctor|devices|capabilities|snapshot|thermal-snapshot|capture-snapshot|set-target|stop|run-stimulus|watch|events|faults|health|validate-action|apply-action|enter-safe-mode|resume-from-safe|step-replay")
- os.Exit(2)
- }
- if err := requireActionFile(cmd, *file); err != nil {
- fmt.Fprintln(os.Stderr, err)
- os.Exit(2)
- }
- if commandMutatesDevice(cmd) && (cmd != "doctor" || *cfgPath == "") {
- if err := requireRealAck(*observe, *realHW); err != nil {
- fmt.Fprintln(os.Stderr, err)
- os.Exit(2)
- }
- }
- rpcTimeout := *timeout
- if rpcTimeout <= 0 {
- if commandMutatesDevice(cmd) {
- ms, err := timingDeadlineMS(*observe, *deviceID)
- if err != nil || ms <= 0 {
- fmt.Fprintln(os.Stderr, "FAIL CLOSED: mutating command requires --timeout or GetCapabilities TimingCapabilities.recommended_rpc_deadline_ms:", err)
- os.Exit(2)
- }
- rpcTimeout = time.Duration(ms) * time.Millisecond
- } else {
- rpcTimeout = 5 * time.Second
- }
- }
- ctx, cancel := context.WithTimeout(context.Background(), rpcTimeout)
- defer cancel()
- switch cmd {
- case "doctor":
- fatal(runDoctor(ctx, *cfgPath, *observe))
- case "devices":
- c := observeClient(*observe, rpcTimeout)
- resp, err := c.ListDevices(ctx, &hthv1.ListDevicesRequest{})
- fatal(err)
- printMsg(resp)
- case "capabilities":
- c := observeClient(*observe, rpcTimeout)
- resp, err := c.GetCapabilities(ctx, &hthv1.GetCapabilitiesRequest{DeviceId: *deviceID})
- fatal(err)
- printMsg(resp)
- case "snapshot":
- c := observeClient(*observe, rpcTimeout)
- resp, err := c.GetSnapshot(ctx, &hthv1.GetSnapshotRequest{DeviceId: *deviceID})
- fatal(err)
- printMsg(resp)
- case "thermal-snapshot", "capture-snapshot":
- conn := mustDial(*observe, rpcTimeout)
- defer conn.Close()
- client := hthv1.NewThermalObserveServiceClient(conn)
- req := &hthv1.GetThermalSnapshotRequest{DeviceId: *deviceID}
- var resp *hthv1.GetThermalSnapshotResponse
- var err error
- if cmd == "capture-snapshot" {
- resp, err = client.CaptureSnapshot(ctx, req)
- } else {
- resp, err = client.GetSnapshot(ctx, req)
- }
- fatal(err)
- printMsg(resp)
- case "set-target":
- if *target < 0 {
- fatal(fmt.Errorf("set-target requires --target 0 or 20..70"))
- }
- conn := mustDial(*control, rpcTimeout)
- defer conn.Close()
- resp, err := hthv1.NewThermalControlServiceClient(conn).SetTarget(ctx, &hthv1.SetThermalTargetRequest{
- DeviceId: *deviceID, TemperatureC: uint32(*target),
- })
- fatal(err)
- printMsg(resp)
- case "stop":
- conn := mustDial(*control, rpcTimeout)
- defer conn.Close()
- resp, err := hthv1.NewThermalControlServiceClient(conn).Stop(ctx, &hthv1.StopThermalRequest{DeviceId: *deviceID})
- fatal(err)
- printMsg(resp)
- case "run-stimulus":
- stim := loadStimulus(*file, *deviceID)
- conn := mustDial(*control, rpcTimeout)
- defer conn.Close()
- resp, err := hthv1.NewThermalControlServiceClient(conn).RunStimulus(ctx, stim)
- fatal(err)
- printMsg(resp)
- case "watch":
- c := observeClient(*observe, rpcTimeout)
- st, err := c.SubscribeTelemetry(context.Background(), &hthv1.SubscribeTelemetryRequest{DeviceId: *deviceID})
- fatal(err)
- n := 0
- for {
- s, err := st.Recv()
- fatal(err)
- printMsg(s)
- n++
- if *count > 0 && n >= *count {
- return
- }
- }
- case "events":
- c := observeClient(*observe, rpcTimeout)
- st, err := c.SubscribeEvents(context.Background(), &hthv1.SubscribeEventsRequest{DeviceId: *deviceID})
- fatal(err)
- n := 0
- for {
- e, err := st.Recv()
- fatal(err)
- printMsg(e)
- n++
- if *count > 0 && n >= *count {
- return
- }
- }
- case "faults":
- c := observeClient(*observe, rpcTimeout)
- resp, err := c.GetFaults(ctx, &hthv1.GetFaultsRequest{DeviceId: *deviceID, IncludeInactive: true})
- fatal(err)
- printMsg(resp)
- case "health":
- conn := mustDial(*observe, rpcTimeout)
- defer conn.Close()
- hc := grpc_health_v1.NewHealthClient(conn)
- resp, err := hc.Check(ctx, &grpc_health_v1.HealthCheckRequest{})
- fatal(err)
- fmt.Println(resp.Status.String())
- oc := hthv1.NewObserveServiceClient(conn)
- st, err := oc.WatchHealth(ctx, &hthv1.WatchHealthRequest{})
- fatal(err)
- msg, err := st.Recv()
- fatal(err)
- printMsg(msg)
- case "validate-action":
- batch := loadBatch(*file, *deviceID, *allowClamp)
- c := controlClient(*control, rpcTimeout)
- res, err := c.ValidateAction(ctx, &hthv1.ValidateActionRequest{Batch: batch})
- fatal(err)
- printAction(res)
- case "apply-action":
- cc := controlClient(*control, rpcTimeout)
- oc := observeClient(*observe, rpcTimeout)
- lease, err := cc.AcquireControlLease(ctx, &hthv1.AcquireControlLeaseRequest{
- DeviceId: *deviceID, Holder: *holder, Ttl: durationpb.New(*ttl),
- })
- fatal(err)
- snap, err := oc.GetSnapshot(ctx, &hthv1.GetSnapshotRequest{DeviceId: *deviceID})
- fatal(err)
- batch := loadBatch(*file, *deviceID, *allowClamp)
- batch.LeaseId = lease.Lease.LeaseId
- batch.LeaseEpoch = lease.Lease.LeaseEpoch
- batch.BasedOnSnapshotSeq = snap.Snapshot.GetSnapshotSeq()
- batch.ExpectedControlRevision = snap.Snapshot.GetControlRevision()
- if batch.ValidUntil == nil {
- batch.ValidUntil = timestamppb.New(time.Now().Add(rpcTimeout))
- }
- if batch.CommandId == "" || batch.CommandId == "hthctl-validate" {
- batch.CommandId = fmt.Sprintf("hthctl-%d", time.Now().UnixNano())
- }
- res, err := cc.ApplyAction(ctx, &hthv1.ApplyActionRequest{Batch: batch})
- fatal(err)
- printAction(res)
- case "enter-safe-mode":
- cc := controlClient(*control, rpcTimeout)
- lease, err := cc.AcquireControlLease(ctx, &hthv1.AcquireControlLeaseRequest{
- DeviceId: *deviceID, Holder: *holder, Ttl: durationpb.New(*ttl),
- })
- fatal(err)
- res, err := cc.EnterSafeMode(ctx, &hthv1.EnterSafeModeRequest{
- DeviceId: *deviceID, LeaseId: lease.Lease.LeaseId, LeaseEpoch: lease.Lease.LeaseEpoch, Reason: "hthctl",
- })
- fatal(err)
- printAction(res)
- case "resume-from-safe":
- cc := controlClient(*control, rpcTimeout)
- oc := observeClient(*observe, rpcTimeout)
- lease, err := cc.AcquireControlLease(ctx, &hthv1.AcquireControlLeaseRequest{
- DeviceId: *deviceID, Holder: *holder, Ttl: durationpb.New(*ttl),
- })
- fatal(err)
- snap, err := oc.GetSnapshot(ctx, &hthv1.GetSnapshotRequest{DeviceId: *deviceID})
- fatal(err)
- batch := loadBatch(*file, *deviceID, false)
- if len(batch.GetContinuousTargets()) == 0 {
- fatal(fmt.Errorf("resume-from-safe FAIL CLOSED: --file must contain a complete ActionBatch; snapshot has no invented fan=10/ptc=0/doors=0 defaults"))
- }
- batch.LeaseId = lease.Lease.LeaseId
- batch.LeaseEpoch = lease.Lease.LeaseEpoch
- batch.BasedOnSnapshotSeq = snap.Snapshot.GetSnapshotSeq()
- batch.ExpectedControlRevision = snap.Snapshot.GetControlRevision()
- if batch.ValidUntil == nil {
- batch.ValidUntil = timestamppb.New(time.Now().Add(rpcTimeout))
- }
- if batch.CommandId == "" || batch.CommandId == "hthctl-validate" {
- batch.CommandId = fmt.Sprintf("hthctl-resume-%d", time.Now().UnixNano())
- }
- res, err := cc.ResumeFromSafe(ctx, &hthv1.ResumeFromSafeRequest{
- DeviceId: *deviceID, LeaseId: lease.Lease.LeaseId, LeaseEpoch: lease.Lease.LeaseEpoch, Batch: batch,
- })
- fatal(err)
- printAction(res)
- case "step-replay":
- cc := controlClient(*control, rpcTimeout)
- res, err := cc.StepReplay(ctx, &hthv1.StepReplayRequest{DeviceId: *deviceID})
- fatal(err)
- printMsg(res)
- default:
- fmt.Fprintln(os.Stderr, "unknown command", cmd)
- os.Exit(2)
- }
- }
- // parseHthctlArgs accepts both `hthctl --file x resume-from-safe` and
- // `hthctl resume-from-safe --file x`. Go's FlagSet stops at the first
- // non-flag, so flags after the subcommand must be parsed in a second pass.
- func parseHthctlArgs(fs *flag.FlagSet, argv []string) string {
- _ = fs.Parse(argv)
- args := fs.Args()
- if len(args) == 0 {
- return ""
- }
- cmd := args[0]
- if len(args) > 1 {
- _ = fs.Parse(args[1:])
- }
- return cmd
- }
- func commandMutatesDevice(cmd string) bool {
- switch cmd {
- case "apply-action", "enter-safe-mode", "resume-from-safe", "step-replay", "set-target", "stop", "run-stimulus":
- return true
- default:
- return false
- }
- }
- func timingDeadlineMS(observe, deviceID string) (uint32, error) {
- conn, err := grpcserver.DialUnix(observe, 2*time.Second)
- if err != nil {
- return 0, err
- }
- defer conn.Close()
- cli := hthv1.NewObserveServiceClient(conn)
- ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
- defer cancel()
- resp, err := cli.GetCapabilities(ctx, &hthv1.GetCapabilitiesRequest{DeviceId: deviceID})
- if err != nil {
- return 0, err
- }
- t := resp.GetCapabilities().GetTiming()
- if t == nil || t.GetRecommendedRpcDeadlineMs() == 0 {
- return 0, fmt.Errorf("capabilities.timing.recommended_rpc_deadline_ms missing")
- }
- return t.GetRecommendedRpcDeadlineMs(), nil
- }
- func requireActionFile(cmd, file string) error {
- switch cmd {
- case "validate-action", "apply-action", "resume-from-safe", "run-stimulus":
- if strings.TrimSpace(file) == "" {
- return fmt.Errorf("%s requires --file with complete JSON input; refusing implicit values", cmd)
- }
- }
- return nil
- }
- func backendRequiresHardwareAck(kind string) bool {
- switch strings.ToLower(strings.TrimSpace(kind)) {
- case "mock", "replay":
- return false
- default:
- return true
- }
- }
- func refuseIfSerialNeedsAck(kind, observe string, ack bool) error {
- if !backendRequiresHardwareAck(kind) {
- return nil
- }
- if ack {
- return nil
- }
- return fmt.Errorf("refusing serial backend kind %q at observe %s without --i-understand-this-is-real-hardware (path is not used to detect mock)", kind, observe)
- }
- func requireRealAck(observe string, ack bool) error {
- conn, err := grpcserver.DialUnix(observe, 2*time.Second)
- if err != nil {
- return fmt.Errorf("cannot read DeviceIdentity.backend_kind from observe socket %s: %w", observe, err)
- }
- defer conn.Close()
- cli := hthv1.NewObserveServiceClient(conn)
- ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
- defer cancel()
- resp, err := cli.ListDevices(ctx, &hthv1.ListDevicesRequest{})
- if err != nil {
- return fmt.Errorf("ListDevices for backend_kind: %w", err)
- }
- if len(resp.GetDevices()) == 0 {
- return refuseIfSerialNeedsAck("unknown", observe, ack)
- }
- for _, d := range resp.GetDevices() {
- kind := ""
- if d.GetIdentity() != nil {
- kind = d.GetIdentity().GetBackendKind()
- }
- if err := refuseIfSerialNeedsAck(kind, observe, ack); err != nil {
- return err
- }
- }
- return nil
- }
- func runDoctor(ctx context.Context, cfgPath, observe string) error {
- if cfgPath != "" {
- cfg, err := config.Load(cfgPath)
- if err != nil {
- return err
- }
- if cfg.IsThermal6400() {
- if err := cfg.Validate(nil); err != nil {
- return err
- }
- fmt.Print(app.DoctorText(cfg, nil))
- } else {
- p, err := profile.LoadStrict(cfg.Profile)
- if err != nil {
- return err
- }
- if err := cfg.Validate(p); err != nil {
- return err
- }
- fmt.Print(app.DoctorText(cfg, p))
- }
- }
- conn, err := grpcserver.DialUnix(observe, 2*time.Second)
- if err != nil {
- if cfgPath != "" {
- fmt.Println("live observe socket: not connected (", err, ")")
- return nil
- }
- return err
- }
- defer conn.Close()
- hc := grpc_health_v1.NewHealthClient(conn)
- st, err := hc.Check(ctx, &grpc_health_v1.HealthCheckRequest{})
- if err != nil {
- return err
- }
- fmt.Println("grpc_health", st.Status.String())
- return nil
- }
- func observeClient(path string, d time.Duration) hthv1.ObserveServiceClient {
- return hthv1.NewObserveServiceClient(mustDial(path, d))
- }
- func controlClient(path string, d time.Duration) hthv1.ControlServiceClient {
- return hthv1.NewControlServiceClient(mustDial(path, d))
- }
- func mustDial(path string, d time.Duration) *grpc.ClientConn {
- c, err := grpcserver.DialUnix(path, d)
- fatal(err)
- return c
- }
- func printMsg(m proto.Message) {
- b, err := protojson.MarshalOptions{Multiline: true, UseProtoNames: true}.Marshal(m)
- if err != nil {
- fmt.Println(err)
- return
- }
- fmt.Println(string(b))
- }
- func printAction(res *hthv1.ActionResult) {
- fmt.Println("accepted", res.Accepted, "confirmation", res.Confirmation.String(), "reject", res.RejectReason.String())
- fmt.Println("message", res.Message)
- fmt.Println("replayed_from_cache", res.ReplayedFromCache)
- printNamed("requested", res.Requested)
- printNamed("accepted", res.AcceptedAction)
- printNamed("dispatched", res.Dispatched)
- }
- func printNamed(name string, rec *hthv1.ActionRecord) {
- if rec == nil {
- fmt.Println(name, "(none)")
- return
- }
- b, _ := protojson.MarshalOptions{UseProtoNames: true}.Marshal(rec)
- fmt.Println(name, string(b))
- }
- func loadBatch(path, deviceID string, clamp bool) *hthv1.ActionBatch {
- b := &hthv1.ActionBatch{DeviceId: deviceID, CommandId: "hthctl-validate", AllowClamp: clamp, ClientId: "hthctl"}
- if strings.TrimSpace(path) == "" {
- fatal(fmt.Errorf("ActionBatch --file is required"))
- }
- raw, err := os.ReadFile(path)
- fatal(err)
- fatal(protojson.Unmarshal(raw, b))
- if b.DeviceId == "" {
- b.DeviceId = deviceID
- }
- return b
- }
- func loadStimulus(path, deviceID string) *hthv1.RunThermalStimulusRequest {
- raw, err := os.ReadFile(path)
- fatal(err)
- var input struct {
- DurationSeconds uint32 `json:"duration_seconds"`
- PTCDuty []uint32 `json:"ptc_duty"`
- FrontFanDuty []uint32 `json:"front_fan_duty"`
- RearFanDuty []uint32 `json:"rear_fan_duty"`
- }
- dec := json.NewDecoder(strings.NewReader(string(raw)))
- dec.DisallowUnknownFields()
- fatal(dec.Decode(&input))
- if err := dec.Decode(&struct{}{}); err != io.EOF {
- fatal(fmt.Errorf("stimulus JSON has trailing data"))
- }
- return &hthv1.RunThermalStimulusRequest{
- DeviceId: deviceID, DurationSeconds: input.DurationSeconds,
- PtcDuty: input.PTCDuty, FrontFanDuty: input.FrontFanDuty, RearFanDuty: input.RearFanDuty,
- }
- }
- func fatal(err error) {
- if err != nil {
- fmt.Fprintln(os.Stderr, err)
- os.Exit(1)
- }
- }
|