main.go 15 KB

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