main.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405
  1. package main
  2. import (
  3. "context"
  4. "flag"
  5. "fmt"
  6. "os"
  7. "strings"
  8. "time"
  9. "google.golang.org/grpc"
  10. "google.golang.org/grpc/health/grpc_health_v1"
  11. "google.golang.org/protobuf/encoding/protojson"
  12. "google.golang.org/protobuf/proto"
  13. "google.golang.org/protobuf/types/known/durationpb"
  14. "google.golang.org/protobuf/types/known/timestamppb"
  15. "hth/internal/app"
  16. "hth/internal/config"
  17. hthv1 "hth/internal/gen/hth/api/v1"
  18. "hth/internal/grpcserver"
  19. "hth/internal/profile"
  20. )
  21. func main() {
  22. fs := flag.NewFlagSet("hthctl", flag.ExitOnError)
  23. observe := fs.String("observe-sock", "/tmp/hth-mock/observe.sock", "observe unix socket")
  24. control := fs.String("control-sock", "/tmp/hth-mock/control.sock", "control unix socket")
  25. deviceID := fs.String("device", "prod2u-0", "device id")
  26. cfgPath := fs.String("config", "", "optional local config for doctor")
  27. realHW := fs.Bool("i-understand-this-is-real-hardware", false, "required for commands that mutate device state on non-mock backends")
  28. timeout := fs.Duration("timeout", 0, "rpc timeout; 0 uses TimingCapabilities for mutating commands, 5s for observe")
  29. count := fs.Int("count", 0, "watch/events count (0=until interrupt)")
  30. holder := fs.String("holder", "hthctl", "lease holder")
  31. ttl := fs.Duration("ttl", 10*time.Second, "lease ttl")
  32. file := fs.String("file", "", "JSON ActionBatch for validate-action")
  33. allowClamp := fs.Bool("allow-clamp", false, "allow clamp on validate/apply")
  34. cmd := parseHthctlArgs(fs, os.Args[1:])
  35. if cmd == "" {
  36. 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")
  37. os.Exit(2)
  38. }
  39. if err := requireActionFile(cmd, *file); err != nil {
  40. fmt.Fprintln(os.Stderr, err)
  41. os.Exit(2)
  42. }
  43. if commandMutatesDevice(cmd) && (cmd != "doctor" || *cfgPath == "") {
  44. if err := requireRealAck(*observe, *realHW); err != nil {
  45. fmt.Fprintln(os.Stderr, err)
  46. os.Exit(2)
  47. }
  48. }
  49. rpcTimeout := *timeout
  50. if rpcTimeout <= 0 {
  51. if commandMutatesDevice(cmd) {
  52. ms, err := timingDeadlineMS(*observe, *deviceID)
  53. if err != nil || ms <= 0 {
  54. fmt.Fprintln(os.Stderr, "FAIL CLOSED: mutating command requires --timeout or GetCapabilities TimingCapabilities.recommended_rpc_deadline_ms:", err)
  55. os.Exit(2)
  56. }
  57. rpcTimeout = time.Duration(ms) * time.Millisecond
  58. } else {
  59. rpcTimeout = 5 * time.Second
  60. }
  61. }
  62. ctx, cancel := context.WithTimeout(context.Background(), rpcTimeout)
  63. defer cancel()
  64. switch cmd {
  65. case "doctor":
  66. fatal(runDoctor(ctx, *cfgPath, *observe))
  67. case "devices":
  68. c := observeClient(*observe, rpcTimeout)
  69. resp, err := c.ListDevices(ctx, &hthv1.ListDevicesRequest{})
  70. fatal(err)
  71. printMsg(resp)
  72. case "capabilities":
  73. c := observeClient(*observe, rpcTimeout)
  74. resp, err := c.GetCapabilities(ctx, &hthv1.GetCapabilitiesRequest{DeviceId: *deviceID})
  75. fatal(err)
  76. printMsg(resp)
  77. case "snapshot":
  78. c := observeClient(*observe, rpcTimeout)
  79. resp, err := c.GetSnapshot(ctx, &hthv1.GetSnapshotRequest{DeviceId: *deviceID})
  80. fatal(err)
  81. printMsg(resp)
  82. case "watch":
  83. c := observeClient(*observe, rpcTimeout)
  84. st, err := c.SubscribeTelemetry(context.Background(), &hthv1.SubscribeTelemetryRequest{DeviceId: *deviceID})
  85. fatal(err)
  86. n := 0
  87. for {
  88. s, err := st.Recv()
  89. fatal(err)
  90. printMsg(s)
  91. n++
  92. if *count > 0 && n >= *count {
  93. return
  94. }
  95. }
  96. case "events":
  97. c := observeClient(*observe, rpcTimeout)
  98. st, err := c.SubscribeEvents(context.Background(), &hthv1.SubscribeEventsRequest{DeviceId: *deviceID})
  99. fatal(err)
  100. n := 0
  101. for {
  102. e, err := st.Recv()
  103. fatal(err)
  104. printMsg(e)
  105. n++
  106. if *count > 0 && n >= *count {
  107. return
  108. }
  109. }
  110. case "faults":
  111. c := observeClient(*observe, rpcTimeout)
  112. resp, err := c.GetFaults(ctx, &hthv1.GetFaultsRequest{DeviceId: *deviceID, IncludeInactive: true})
  113. fatal(err)
  114. printMsg(resp)
  115. case "health":
  116. conn := mustDial(*observe, rpcTimeout)
  117. defer conn.Close()
  118. hc := grpc_health_v1.NewHealthClient(conn)
  119. resp, err := hc.Check(ctx, &grpc_health_v1.HealthCheckRequest{})
  120. fatal(err)
  121. fmt.Println(resp.Status.String())
  122. oc := hthv1.NewObserveServiceClient(conn)
  123. st, err := oc.WatchHealth(ctx, &hthv1.WatchHealthRequest{})
  124. fatal(err)
  125. msg, err := st.Recv()
  126. fatal(err)
  127. printMsg(msg)
  128. case "validate-action":
  129. batch := loadBatch(*file, *deviceID, *allowClamp)
  130. c := controlClient(*control, rpcTimeout)
  131. res, err := c.ValidateAction(ctx, &hthv1.ValidateActionRequest{Batch: batch})
  132. fatal(err)
  133. printAction(res)
  134. case "apply-action":
  135. cc := controlClient(*control, rpcTimeout)
  136. oc := observeClient(*observe, rpcTimeout)
  137. lease, err := cc.AcquireControlLease(ctx, &hthv1.AcquireControlLeaseRequest{
  138. DeviceId: *deviceID, Holder: *holder, Ttl: durationpb.New(*ttl),
  139. })
  140. fatal(err)
  141. snap, err := oc.GetSnapshot(ctx, &hthv1.GetSnapshotRequest{DeviceId: *deviceID})
  142. fatal(err)
  143. batch := loadBatch(*file, *deviceID, *allowClamp)
  144. batch.LeaseId = lease.Lease.LeaseId
  145. batch.LeaseEpoch = lease.Lease.LeaseEpoch
  146. batch.BasedOnSnapshotSeq = snap.Snapshot.GetSnapshotSeq()
  147. batch.ExpectedControlRevision = snap.Snapshot.GetControlRevision()
  148. if batch.ValidUntil == nil {
  149. batch.ValidUntil = timestamppb.New(time.Now().Add(rpcTimeout))
  150. }
  151. if batch.CommandId == "" || batch.CommandId == "hthctl-validate" {
  152. batch.CommandId = fmt.Sprintf("hthctl-%d", time.Now().UnixNano())
  153. }
  154. res, err := cc.ApplyAction(ctx, &hthv1.ApplyActionRequest{Batch: batch})
  155. fatal(err)
  156. printAction(res)
  157. case "enter-safe-mode":
  158. cc := controlClient(*control, rpcTimeout)
  159. lease, err := cc.AcquireControlLease(ctx, &hthv1.AcquireControlLeaseRequest{
  160. DeviceId: *deviceID, Holder: *holder, Ttl: durationpb.New(*ttl),
  161. })
  162. fatal(err)
  163. res, err := cc.EnterSafeMode(ctx, &hthv1.EnterSafeModeRequest{
  164. DeviceId: *deviceID, LeaseId: lease.Lease.LeaseId, LeaseEpoch: lease.Lease.LeaseEpoch, Reason: "hthctl",
  165. })
  166. fatal(err)
  167. printAction(res)
  168. case "resume-from-safe":
  169. cc := controlClient(*control, rpcTimeout)
  170. oc := observeClient(*observe, rpcTimeout)
  171. lease, err := cc.AcquireControlLease(ctx, &hthv1.AcquireControlLeaseRequest{
  172. DeviceId: *deviceID, Holder: *holder, Ttl: durationpb.New(*ttl),
  173. })
  174. fatal(err)
  175. snap, err := oc.GetSnapshot(ctx, &hthv1.GetSnapshotRequest{DeviceId: *deviceID})
  176. fatal(err)
  177. batch := loadBatch(*file, *deviceID, false)
  178. if len(batch.GetContinuousTargets()) == 0 {
  179. 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"))
  180. }
  181. batch.LeaseId = lease.Lease.LeaseId
  182. batch.LeaseEpoch = lease.Lease.LeaseEpoch
  183. batch.BasedOnSnapshotSeq = snap.Snapshot.GetSnapshotSeq()
  184. batch.ExpectedControlRevision = snap.Snapshot.GetControlRevision()
  185. if batch.ValidUntil == nil {
  186. batch.ValidUntil = timestamppb.New(time.Now().Add(rpcTimeout))
  187. }
  188. if batch.CommandId == "" || batch.CommandId == "hthctl-validate" {
  189. batch.CommandId = fmt.Sprintf("hthctl-resume-%d", time.Now().UnixNano())
  190. }
  191. res, err := cc.ResumeFromSafe(ctx, &hthv1.ResumeFromSafeRequest{
  192. DeviceId: *deviceID, LeaseId: lease.Lease.LeaseId, LeaseEpoch: lease.Lease.LeaseEpoch, Batch: batch,
  193. })
  194. fatal(err)
  195. printAction(res)
  196. case "step-replay":
  197. cc := controlClient(*control, rpcTimeout)
  198. res, err := cc.StepReplay(ctx, &hthv1.StepReplayRequest{DeviceId: *deviceID})
  199. fatal(err)
  200. printMsg(res)
  201. default:
  202. fmt.Fprintln(os.Stderr, "unknown command", cmd)
  203. os.Exit(2)
  204. }
  205. }
  206. // parseHthctlArgs accepts both `hthctl --file x resume-from-safe` and
  207. // `hthctl resume-from-safe --file x`. Go's FlagSet stops at the first
  208. // non-flag, so flags after the subcommand must be parsed in a second pass.
  209. func parseHthctlArgs(fs *flag.FlagSet, argv []string) string {
  210. _ = fs.Parse(argv)
  211. args := fs.Args()
  212. if len(args) == 0 {
  213. return ""
  214. }
  215. cmd := args[0]
  216. if len(args) > 1 {
  217. _ = fs.Parse(args[1:])
  218. }
  219. return cmd
  220. }
  221. func commandMutatesDevice(cmd string) bool {
  222. switch cmd {
  223. case "apply-action", "enter-safe-mode", "resume-from-safe", "step-replay":
  224. return true
  225. default:
  226. return false
  227. }
  228. }
  229. func timingDeadlineMS(observe, deviceID string) (uint32, error) {
  230. conn, err := grpcserver.DialUnix(observe, 2*time.Second)
  231. if err != nil {
  232. return 0, err
  233. }
  234. defer conn.Close()
  235. cli := hthv1.NewObserveServiceClient(conn)
  236. ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
  237. defer cancel()
  238. resp, err := cli.GetCapabilities(ctx, &hthv1.GetCapabilitiesRequest{DeviceId: deviceID})
  239. if err != nil {
  240. return 0, err
  241. }
  242. t := resp.GetCapabilities().GetTiming()
  243. if t == nil || t.GetRecommendedRpcDeadlineMs() == 0 {
  244. return 0, fmt.Errorf("capabilities.timing.recommended_rpc_deadline_ms missing")
  245. }
  246. return t.GetRecommendedRpcDeadlineMs(), nil
  247. }
  248. func requireActionFile(cmd, file string) error {
  249. switch cmd {
  250. case "validate-action", "apply-action", "resume-from-safe":
  251. if strings.TrimSpace(file) == "" {
  252. return fmt.Errorf("%s requires --file with a complete ActionBatch JSON; refusing implicit fan1=10", cmd)
  253. }
  254. }
  255. return nil
  256. }
  257. func backendRequiresHardwareAck(kind string) bool {
  258. switch strings.ToLower(strings.TrimSpace(kind)) {
  259. case "mock", "replay":
  260. return false
  261. default:
  262. return true
  263. }
  264. }
  265. func refuseIfSerialNeedsAck(kind, observe string, ack bool) error {
  266. if !backendRequiresHardwareAck(kind) {
  267. return nil
  268. }
  269. if ack {
  270. return nil
  271. }
  272. 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)
  273. }
  274. func requireRealAck(observe string, ack bool) error {
  275. conn, err := grpcserver.DialUnix(observe, 2*time.Second)
  276. if err != nil {
  277. return fmt.Errorf("cannot read DeviceIdentity.backend_kind from observe socket %s: %w", observe, err)
  278. }
  279. defer conn.Close()
  280. cli := hthv1.NewObserveServiceClient(conn)
  281. ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
  282. defer cancel()
  283. resp, err := cli.ListDevices(ctx, &hthv1.ListDevicesRequest{})
  284. if err != nil {
  285. return fmt.Errorf("ListDevices for backend_kind: %w", err)
  286. }
  287. if len(resp.GetDevices()) == 0 {
  288. return refuseIfSerialNeedsAck("unknown", observe, ack)
  289. }
  290. for _, d := range resp.GetDevices() {
  291. kind := ""
  292. if d.GetIdentity() != nil {
  293. kind = d.GetIdentity().GetBackendKind()
  294. }
  295. if err := refuseIfSerialNeedsAck(kind, observe, ack); err != nil {
  296. return err
  297. }
  298. }
  299. return nil
  300. }
  301. func runDoctor(ctx context.Context, cfgPath, observe string) error {
  302. if cfgPath != "" {
  303. cfg, err := config.Load(cfgPath)
  304. if err != nil {
  305. return err
  306. }
  307. p, err := profile.LoadStrict(cfg.Profile)
  308. if err != nil {
  309. return err
  310. }
  311. if err := cfg.Validate(p); err != nil {
  312. return err
  313. }
  314. fmt.Print(app.DoctorText(cfg, p))
  315. }
  316. conn, err := grpcserver.DialUnix(observe, 2*time.Second)
  317. if err != nil {
  318. if cfgPath != "" {
  319. fmt.Println("live observe socket: not connected (", err, ")")
  320. return nil
  321. }
  322. return err
  323. }
  324. defer conn.Close()
  325. hc := grpc_health_v1.NewHealthClient(conn)
  326. st, err := hc.Check(ctx, &grpc_health_v1.HealthCheckRequest{})
  327. if err != nil {
  328. return err
  329. }
  330. fmt.Println("grpc_health", st.Status.String())
  331. return nil
  332. }
  333. func observeClient(path string, d time.Duration) hthv1.ObserveServiceClient {
  334. return hthv1.NewObserveServiceClient(mustDial(path, d))
  335. }
  336. func controlClient(path string, d time.Duration) hthv1.ControlServiceClient {
  337. return hthv1.NewControlServiceClient(mustDial(path, d))
  338. }
  339. func mustDial(path string, d time.Duration) *grpc.ClientConn {
  340. c, err := grpcserver.DialUnix(path, d)
  341. fatal(err)
  342. return c
  343. }
  344. func printMsg(m proto.Message) {
  345. b, err := protojson.MarshalOptions{Multiline: true, UseProtoNames: true}.Marshal(m)
  346. if err != nil {
  347. fmt.Println(err)
  348. return
  349. }
  350. fmt.Println(string(b))
  351. }
  352. func printAction(res *hthv1.ActionResult) {
  353. fmt.Println("accepted", res.Accepted, "confirmation", res.Confirmation.String(), "reject", res.RejectReason.String())
  354. fmt.Println("message", res.Message)
  355. fmt.Println("replayed_from_cache", res.ReplayedFromCache)
  356. printNamed("requested", res.Requested)
  357. printNamed("accepted", res.AcceptedAction)
  358. printNamed("dispatched", res.Dispatched)
  359. }
  360. func printNamed(name string, rec *hthv1.ActionRecord) {
  361. if rec == nil {
  362. fmt.Println(name, "(none)")
  363. return
  364. }
  365. b, _ := protojson.MarshalOptions{UseProtoNames: true}.Marshal(rec)
  366. fmt.Println(name, string(b))
  367. }
  368. func loadBatch(path, deviceID string, clamp bool) *hthv1.ActionBatch {
  369. b := &hthv1.ActionBatch{DeviceId: deviceID, CommandId: "hthctl-validate", AllowClamp: clamp, ClientId: "hthctl"}
  370. if strings.TrimSpace(path) == "" {
  371. fatal(fmt.Errorf("ActionBatch --file is required"))
  372. }
  373. raw, err := os.ReadFile(path)
  374. fatal(err)
  375. fatal(protojson.Unmarshal(raw, b))
  376. if b.DeviceId == "" {
  377. b.DeviceId = deviceID
  378. }
  379. return b
  380. }
  381. func fatal(err error) {
  382. if err != nil {
  383. fmt.Fprintln(os.Stderr, err)
  384. os.Exit(1)
  385. }
  386. }