main.go 11 KB

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