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/ids" "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") _ = fs.Parse(os.Args[1:]) args := fs.Args() if len(args) < 1 { fmt.Fprintln(os.Stderr, "usage: hthctl [flags] doctor|devices|capabilities|snapshot|watch|events|faults|health|validate-action|apply-action|enter-safe-mode|step-replay") os.Exit(2) } cmd := args[0] if cmd != "doctor" || *cfgPath == "" { if err := requireRealAck(*observe, *control, *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 "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) } } func requireRealAck(observe, control string, ack bool) error { if isMock(observe) && isMock(control) { return nil } if ack { return nil } return fmt.Errorf("refusing non-mock endpoint %s / %s without --i-understand-this-is-real-hardware; hthctl never opens serial", observe, control) } func isMock(path string) bool { p := strings.ToLower(path) return strings.Contains(p, "mock") || strings.Contains(p, "/tmp/") } 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 path == "" { b.ContinuousTargets = []*hthv1.ContinuousTarget{{Id: ids.Fan1, Value: 10}} return b } raw, err := os.ReadFile(path) fatal(err) fatal(protojson.Unmarshal(raw, b)) return b } func fatal(err error) { if err != nil { fmt.Fprintln(os.Stderr, err) os.Exit(1) } }