main.go 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274
  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/ids"
  20. "hth/internal/profile"
  21. )
  22. func main() {
  23. fs := flag.NewFlagSet("hthctl", flag.ExitOnError)
  24. observe := fs.String("observe-sock", "/tmp/hth-mock/observe.sock", "observe unix socket")
  25. control := fs.String("control-sock", "/tmp/hth-mock/control.sock", "control unix socket")
  26. deviceID := fs.String("device", "prod2u-0", "device id")
  27. cfgPath := fs.String("config", "", "optional local config for doctor")
  28. realHW := fs.Bool("i-understand-this-is-real-hardware", false, "required for non-mock endpoints")
  29. timeout := fs.Duration("timeout", 5*time.Second, "rpc timeout")
  30. count := fs.Int("count", 0, "watch/events count (0=until interrupt)")
  31. holder := fs.String("holder", "hthctl", "lease holder")
  32. ttl := fs.Duration("ttl", 10*time.Second, "lease ttl")
  33. file := fs.String("file", "", "JSON ActionBatch for validate-action")
  34. allowClamp := fs.Bool("allow-clamp", false, "allow clamp on validate/apply")
  35. _ = fs.Parse(os.Args[1:])
  36. args := fs.Args()
  37. if len(args) < 1 {
  38. fmt.Fprintln(os.Stderr, "usage: hthctl [flags] doctor|devices|capabilities|snapshot|watch|events|faults|health|validate-action|apply-action|enter-safe-mode|step-replay")
  39. os.Exit(2)
  40. }
  41. cmd := args[0]
  42. if cmd != "doctor" || *cfgPath == "" {
  43. if err := requireRealAck(*observe, *control, *realHW); err != nil {
  44. fmt.Fprintln(os.Stderr, err)
  45. os.Exit(2)
  46. }
  47. }
  48. ctx, cancel := context.WithTimeout(context.Background(), *timeout)
  49. defer cancel()
  50. switch cmd {
  51. case "doctor":
  52. fatal(runDoctor(ctx, *cfgPath, *observe))
  53. case "devices":
  54. c := observeClient(*observe, *timeout)
  55. resp, err := c.ListDevices(ctx, &hthv1.ListDevicesRequest{})
  56. fatal(err)
  57. printMsg(resp)
  58. case "capabilities":
  59. c := observeClient(*observe, *timeout)
  60. resp, err := c.GetCapabilities(ctx, &hthv1.GetCapabilitiesRequest{DeviceId: *deviceID})
  61. fatal(err)
  62. printMsg(resp)
  63. case "snapshot":
  64. c := observeClient(*observe, *timeout)
  65. resp, err := c.GetSnapshot(ctx, &hthv1.GetSnapshotRequest{DeviceId: *deviceID})
  66. fatal(err)
  67. printMsg(resp)
  68. case "watch":
  69. c := observeClient(*observe, *timeout)
  70. st, err := c.SubscribeTelemetry(context.Background(), &hthv1.SubscribeTelemetryRequest{DeviceId: *deviceID})
  71. fatal(err)
  72. n := 0
  73. for {
  74. s, err := st.Recv()
  75. fatal(err)
  76. printMsg(s)
  77. n++
  78. if *count > 0 && n >= *count {
  79. return
  80. }
  81. }
  82. case "events":
  83. c := observeClient(*observe, *timeout)
  84. st, err := c.SubscribeEvents(context.Background(), &hthv1.SubscribeEventsRequest{DeviceId: *deviceID})
  85. fatal(err)
  86. n := 0
  87. for {
  88. e, err := st.Recv()
  89. fatal(err)
  90. printMsg(e)
  91. n++
  92. if *count > 0 && n >= *count {
  93. return
  94. }
  95. }
  96. case "faults":
  97. c := observeClient(*observe, *timeout)
  98. resp, err := c.GetFaults(ctx, &hthv1.GetFaultsRequest{DeviceId: *deviceID, IncludeInactive: true})
  99. fatal(err)
  100. printMsg(resp)
  101. case "health":
  102. conn := mustDial(*observe, *timeout)
  103. defer conn.Close()
  104. hc := grpc_health_v1.NewHealthClient(conn)
  105. resp, err := hc.Check(ctx, &grpc_health_v1.HealthCheckRequest{})
  106. fatal(err)
  107. fmt.Println(resp.Status.String())
  108. oc := hthv1.NewObserveServiceClient(conn)
  109. st, err := oc.WatchHealth(ctx, &hthv1.WatchHealthRequest{})
  110. fatal(err)
  111. msg, err := st.Recv()
  112. fatal(err)
  113. printMsg(msg)
  114. case "validate-action":
  115. batch := loadBatch(*file, *deviceID, *allowClamp)
  116. c := controlClient(*control, *timeout)
  117. res, err := c.ValidateAction(ctx, &hthv1.ValidateActionRequest{Batch: batch})
  118. fatal(err)
  119. printAction(res)
  120. case "apply-action":
  121. cc := controlClient(*control, *timeout)
  122. oc := observeClient(*observe, *timeout)
  123. lease, err := cc.AcquireControlLease(ctx, &hthv1.AcquireControlLeaseRequest{
  124. DeviceId: *deviceID, Holder: *holder, Ttl: durationpb.New(*ttl),
  125. })
  126. fatal(err)
  127. snap, err := oc.GetSnapshot(ctx, &hthv1.GetSnapshotRequest{DeviceId: *deviceID})
  128. fatal(err)
  129. batch := loadBatch(*file, *deviceID, *allowClamp)
  130. batch.LeaseId = lease.Lease.LeaseId
  131. batch.LeaseEpoch = lease.Lease.LeaseEpoch
  132. batch.BasedOnSnapshotSeq = snap.Snapshot.GetSnapshotSeq()
  133. batch.ExpectedControlRevision = snap.Snapshot.GetControlRevision()
  134. if batch.ValidUntil == nil {
  135. batch.ValidUntil = timestamppb.New(time.Now().Add(*timeout))
  136. }
  137. if batch.CommandId == "" || batch.CommandId == "hthctl-validate" {
  138. batch.CommandId = fmt.Sprintf("hthctl-%d", time.Now().UnixNano())
  139. }
  140. res, err := cc.ApplyAction(ctx, &hthv1.ApplyActionRequest{Batch: batch})
  141. fatal(err)
  142. printAction(res)
  143. case "enter-safe-mode":
  144. cc := controlClient(*control, *timeout)
  145. lease, err := cc.AcquireControlLease(ctx, &hthv1.AcquireControlLeaseRequest{
  146. DeviceId: *deviceID, Holder: *holder, Ttl: durationpb.New(*ttl),
  147. })
  148. fatal(err)
  149. res, err := cc.EnterSafeMode(ctx, &hthv1.EnterSafeModeRequest{
  150. DeviceId: *deviceID, LeaseId: lease.Lease.LeaseId, LeaseEpoch: lease.Lease.LeaseEpoch, Reason: "hthctl",
  151. })
  152. fatal(err)
  153. printAction(res)
  154. case "step-replay":
  155. cc := controlClient(*control, *timeout)
  156. res, err := cc.StepReplay(ctx, &hthv1.StepReplayRequest{DeviceId: *deviceID})
  157. fatal(err)
  158. printMsg(res)
  159. default:
  160. fmt.Fprintln(os.Stderr, "unknown command", cmd)
  161. os.Exit(2)
  162. }
  163. }
  164. func requireRealAck(observe, control string, ack bool) error {
  165. if isMock(observe) && isMock(control) {
  166. return nil
  167. }
  168. if ack {
  169. return nil
  170. }
  171. return fmt.Errorf("refusing non-mock endpoint %s / %s without --i-understand-this-is-real-hardware; hthctl never opens serial", observe, control)
  172. }
  173. func isMock(path string) bool {
  174. p := strings.ToLower(path)
  175. return strings.Contains(p, "mock") || strings.Contains(p, "/tmp/")
  176. }
  177. func runDoctor(ctx context.Context, cfgPath, observe string) error {
  178. if cfgPath != "" {
  179. cfg, err := config.Load(cfgPath)
  180. if err != nil {
  181. return err
  182. }
  183. p, err := profile.LoadStrict(cfg.Profile)
  184. if err != nil {
  185. return err
  186. }
  187. if err := cfg.Validate(p); err != nil {
  188. return err
  189. }
  190. fmt.Print(app.DoctorText(cfg, p))
  191. }
  192. conn, err := grpcserver.DialUnix(observe, 2*time.Second)
  193. if err != nil {
  194. if cfgPath != "" {
  195. fmt.Println("live observe socket: not connected (", err, ")")
  196. return nil
  197. }
  198. return err
  199. }
  200. defer conn.Close()
  201. hc := grpc_health_v1.NewHealthClient(conn)
  202. st, err := hc.Check(ctx, &grpc_health_v1.HealthCheckRequest{})
  203. if err != nil {
  204. return err
  205. }
  206. fmt.Println("grpc_health", st.Status.String())
  207. return nil
  208. }
  209. func observeClient(path string, d time.Duration) hthv1.ObserveServiceClient {
  210. return hthv1.NewObserveServiceClient(mustDial(path, d))
  211. }
  212. func controlClient(path string, d time.Duration) hthv1.ControlServiceClient {
  213. return hthv1.NewControlServiceClient(mustDial(path, d))
  214. }
  215. func mustDial(path string, d time.Duration) *grpc.ClientConn {
  216. c, err := grpcserver.DialUnix(path, d)
  217. fatal(err)
  218. return c
  219. }
  220. func printMsg(m proto.Message) {
  221. b, err := protojson.MarshalOptions{Multiline: true, UseProtoNames: true}.Marshal(m)
  222. if err != nil {
  223. fmt.Println(err)
  224. return
  225. }
  226. fmt.Println(string(b))
  227. }
  228. func printAction(res *hthv1.ActionResult) {
  229. fmt.Println("accepted", res.Accepted, "confirmation", res.Confirmation.String(), "reject", res.RejectReason.String())
  230. fmt.Println("message", res.Message)
  231. fmt.Println("replayed_from_cache", res.ReplayedFromCache)
  232. printNamed("requested", res.Requested)
  233. printNamed("accepted", res.AcceptedAction)
  234. printNamed("dispatched", res.Dispatched)
  235. }
  236. func printNamed(name string, rec *hthv1.ActionRecord) {
  237. if rec == nil {
  238. fmt.Println(name, "(none)")
  239. return
  240. }
  241. b, _ := protojson.MarshalOptions{UseProtoNames: true}.Marshal(rec)
  242. fmt.Println(name, string(b))
  243. }
  244. func loadBatch(path, deviceID string, clamp bool) *hthv1.ActionBatch {
  245. b := &hthv1.ActionBatch{DeviceId: deviceID, CommandId: "hthctl-validate", AllowClamp: clamp, ClientId: "hthctl"}
  246. if path == "" {
  247. b.ContinuousTargets = []*hthv1.ContinuousTarget{{Id: ids.Fan1, Value: 10}}
  248. return b
  249. }
  250. raw, err := os.ReadFile(path)
  251. fatal(err)
  252. fatal(protojson.Unmarshal(raw, b))
  253. return b
  254. }
  255. func fatal(err error) {
  256. if err != nil {
  257. fmt.Fprintln(os.Stderr, err)
  258. os.Exit(1)
  259. }
  260. }