package main import ( "context" "flag" "fmt" "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 non-mock endpoints") timeout := fs.Duration("timeout", 5*time.Second, "rpc timeout") 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") cmd := parseHthctlArgs(fs, os.Args[1:]) if cmd == "" { fmt.Fprintln(os.Stderr, "usage: hthctl [flags] doctor|devices|capabilities|snapshot|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 cmd != "doctor" || *cfgPath == "" { if err := requireRealAck(*observe, *realHW); err != nil { fmt.Fprintln(os.Stderr, err) os.Exit(2) } } ctx, cancel := context.WithTimeout(context.Background(), *timeout) defer cancel() switch cmd { case "doctor": fatal(runDoctor(ctx, *cfgPath, *observe)) case "devices": c := observeClient(*observe, *timeout) resp, err := c.ListDevices(ctx, &hthv1.ListDevicesRequest{}) fatal(err) printMsg(resp) case "capabilities": c := observeClient(*observe, *timeout) resp, err := c.GetCapabilities(ctx, &hthv1.GetCapabilitiesRequest{DeviceId: *deviceID}) fatal(err) printMsg(resp) case "snapshot": c := observeClient(*observe, *timeout) resp, err := c.GetSnapshot(ctx, &hthv1.GetSnapshotRequest{DeviceId: *deviceID}) fatal(err) printMsg(resp) case "watch": c := observeClient(*observe, *timeout) 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, *timeout) 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, *timeout) resp, err := c.GetFaults(ctx, &hthv1.GetFaultsRequest{DeviceId: *deviceID, IncludeInactive: true}) fatal(err) printMsg(resp) case "health": conn := mustDial(*observe, *timeout) 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, *timeout) res, err := c.ValidateAction(ctx, &hthv1.ValidateActionRequest{Batch: batch}) fatal(err) printAction(res) case "apply-action": cc := controlClient(*control, *timeout) oc := observeClient(*observe, *timeout) 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(*timeout)) } 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, *timeout) 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, *timeout) oc := observeClient(*observe, *timeout) 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(*timeout)) } 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, *timeout) 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 requireActionFile(cmd, file string) error { switch cmd { case "validate-action", "apply-action", "resume-from-safe": if strings.TrimSpace(file) == "" { return fmt.Errorf("%s requires --file with a complete ActionBatch JSON; refusing implicit fan1=10", 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 } 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 fatal(err error) { if err != nil { fmt.Fprintln(os.Stderr, err) os.Exit(1) } }