main.go 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326
  1. package main
  2. import (
  3. "bufio"
  4. "context"
  5. "crypto/rand"
  6. "encoding/binary"
  7. "encoding/hex"
  8. "encoding/json"
  9. "flag"
  10. "fmt"
  11. "os"
  12. "os/signal"
  13. "path/filepath"
  14. "syscall"
  15. "time"
  16. "google.golang.org/grpc"
  17. "google.golang.org/grpc/codes"
  18. "google.golang.org/grpc/status"
  19. "google.golang.org/protobuf/encoding/protojson"
  20. "hth/internal/app"
  21. "hth/internal/capture"
  22. hthv1 "hth/internal/gen/hth/api/v1"
  23. "hth/internal/grpcserver"
  24. )
  25. func newCaptureID() string {
  26. var b [16]byte
  27. if _, err := rand.Read(b[:]); err != nil {
  28. return fmt.Sprintf("cap-%d", time.Now().UnixNano())
  29. }
  30. return hex.EncodeToString(b[:])
  31. }
  32. func main() {
  33. fs := flag.NewFlagSet("hth-capture", flag.ExitOnError)
  34. observe := fs.String("observe-sock", "/tmp/hth-mock/observe.sock", "observe unix socket")
  35. deviceID := fs.String("device", "prod2u-0", "device id")
  36. out := fs.String("out", "", "output directory")
  37. dur := fs.Duration("duration", 3*time.Second, "capture duration")
  38. thermal := fs.Bool("thermal", false, "capture 6400 snapshots instead of Legacy event stream")
  39. period := fs.Duration("period", 200*time.Millisecond, "6400 snapshot period")
  40. _ = fs.Parse(os.Args[1:])
  41. if *out == "" {
  42. fmt.Fprintln(os.Stderr, "hth-capture: --out required")
  43. os.Exit(2)
  44. }
  45. if err := os.MkdirAll(*out, 0o755); err != nil {
  46. fmt.Fprintln(os.Stderr, err)
  47. os.Exit(1)
  48. }
  49. conn, err := grpcserver.DialUnix(*observe, 5*time.Second)
  50. if err != nil {
  51. fmt.Fprintln(os.Stderr, err)
  52. os.Exit(1)
  53. }
  54. defer conn.Close()
  55. cli := hthv1.NewObserveServiceClient(conn)
  56. ctx, stop := signal.NotifyContext(context.Background(), syscall.SIGINT, syscall.SIGTERM)
  57. defer stop()
  58. if *thermal {
  59. if err := runThermalCapture(ctx, conn, *deviceID, *out, *dur, *period); err != nil {
  60. fmt.Fprintln(os.Stderr, err)
  61. os.Exit(1)
  62. }
  63. return
  64. }
  65. capCtx, capCancel := context.WithTimeout(ctx, 5*time.Second)
  66. caps, err := cli.GetCapabilities(capCtx, &hthv1.GetCapabilitiesRequest{DeviceId: *deviceID})
  67. capCancel()
  68. if err != nil {
  69. fmt.Fprintln(os.Stderr, err)
  70. os.Exit(1)
  71. }
  72. man := capture.Manifest{
  73. APIVersion: app.APIVersion,
  74. APISchemaVersion: app.APIVersion,
  75. ProfileHash: caps.Capabilities.GetProtocolContractHash(),
  76. ProfileContractHash: caps.Capabilities.GetProtocolContractHash(),
  77. ProfileID: caps.Capabilities.GetProfileId(),
  78. ProfileRevision: caps.Capabilities.GetProfileRevision(),
  79. CapabilityHash: caps.Capabilities.GetCapabilityHash(),
  80. DeviceID: *deviceID,
  81. StartedAt: time.Now().UTC(),
  82. StartTime: time.Now().UTC(),
  83. Status: capture.StatusIncomplete,
  84. CompletionStatus: capture.StatusIncomplete,
  85. CaptureID: newCaptureID(),
  86. }
  87. if err := capture.WriteManifest(*out, man); err != nil {
  88. fmt.Fprintln(os.Stderr, err)
  89. os.Exit(1)
  90. }
  91. ctx, cancel := context.WithTimeout(ctx, *dur)
  92. defer cancel()
  93. f, err := os.Create(capture.RecordsPath(*out))
  94. if err != nil {
  95. fmt.Fprintln(os.Stderr, err)
  96. os.Exit(1)
  97. }
  98. defer func() { _ = f.Close() }()
  99. ev, err := cli.SubscribeEvents(ctx, &hthv1.SubscribeEventsRequest{DeviceId: *deviceID})
  100. if err != nil {
  101. fmt.Fprintln(os.Stderr, err)
  102. os.Exit(1)
  103. }
  104. n := 0
  105. firstID, lastID := uint64(0), uint64(0)
  106. writeErr := error(nil)
  107. recvErr := error(nil)
  108. userCancel := false
  109. durationElapsed := false
  110. started := time.Now()
  111. for {
  112. e, err := ev.Recv()
  113. if err != nil {
  114. recvErr = err
  115. code := status.Code(err)
  116. switch {
  117. case ctx.Err() == context.DeadlineExceeded || code == codes.DeadlineExceeded:
  118. durationElapsed = true
  119. case ctx.Err() == context.Canceled && time.Since(started) >= *dur:
  120. durationElapsed = true
  121. case ctx.Err() == context.Canceled:
  122. userCancel = true
  123. }
  124. break
  125. }
  126. rec, err := capture.EventRecord(e)
  127. if err != nil {
  128. writeErr = err
  129. break
  130. }
  131. if err := capture.AppendRecord(f, rec); err != nil {
  132. writeErr = err
  133. break
  134. }
  135. sid := rec.SourceID()
  136. if n == 0 {
  137. firstID = sid
  138. }
  139. lastID = sid
  140. n++
  141. }
  142. closeErr := f.Close()
  143. syncErr := error(nil)
  144. if closeErr == nil {
  145. // Hash only after a successful close.
  146. if sum, err := capture.HashFile(capture.RecordsPath(*out)); err == nil {
  147. man.RecordsSHA256 = sum
  148. } else {
  149. syncErr = err
  150. }
  151. } else {
  152. syncErr = closeErr
  153. }
  154. man.EndedAt = time.Now().UTC()
  155. man.EndTime = man.EndedAt
  156. man.StartTime = man.StartedAt
  157. man.APISchemaVersion = man.APIVersion
  158. man.RecordCount = n
  159. man.FirstSourceEventID = firstID
  160. man.LastSourceEventID = lastID
  161. switch {
  162. case writeErr != nil || syncErr != nil:
  163. man.Status = capture.StatusIncomplete
  164. man.CompletionStatus = capture.StatusIncomplete
  165. if writeErr != nil {
  166. man.IncompleteReason = writeErr.Error()
  167. } else {
  168. man.IncompleteReason = syncErr.Error()
  169. }
  170. man.CompletionReason = man.IncompleteReason
  171. case durationElapsed && n > 0:
  172. man.Status = capture.StatusComplete
  173. man.CompletionStatus = capture.StatusComplete
  174. man.CompletionReason = "duration elapsed"
  175. case n > 0 && time.Since(started) >= *dur:
  176. man.Status = capture.StatusComplete
  177. man.CompletionStatus = capture.StatusComplete
  178. man.CompletionReason = "duration elapsed"
  179. case userCancel:
  180. man.Status = capture.StatusIncomplete
  181. man.CompletionStatus = capture.StatusIncomplete
  182. man.IncompleteReason = "user cancel"
  183. man.CompletionReason = man.IncompleteReason
  184. case n == 0:
  185. man.Status = capture.StatusIncomplete
  186. man.CompletionStatus = capture.StatusIncomplete
  187. man.IncompleteReason = "zero records"
  188. man.CompletionReason = man.IncompleteReason
  189. default:
  190. man.Status = capture.StatusIncomplete
  191. man.CompletionStatus = capture.StatusIncomplete
  192. if recvErr != nil {
  193. man.IncompleteReason = "stream ended: " + recvErr.Error()
  194. } else {
  195. man.IncompleteReason = "unexpected stream end"
  196. }
  197. man.CompletionReason = man.IncompleteReason
  198. }
  199. if err := capture.WriteManifest(*out, man); err != nil {
  200. fmt.Fprintf(os.Stderr, "hth-capture manifest failed after %d records: %v\n", n, err)
  201. os.Exit(1)
  202. }
  203. if writeErr != nil || syncErr != nil || man.Status != capture.StatusComplete {
  204. fmt.Fprintf(os.Stderr, "hth-capture incomplete after %d records status=%s recv=%v write=%v close=%v\n", n, man.Status, recvErr, writeErr, syncErr)
  205. os.Exit(1)
  206. }
  207. fmt.Printf("wrote %d records to %s status=%s\n", n, *out, man.Status)
  208. }
  209. func runThermalCapture(parent context.Context, conn *grpc.ClientConn, deviceID, out string, duration, period time.Duration) error {
  210. if duration <= 0 || period <= 0 {
  211. return fmt.Errorf("thermal capture duration and period must be positive")
  212. }
  213. client := hthv1.NewThermalObserveServiceClient(conn)
  214. ctx, cancel := context.WithTimeout(parent, duration)
  215. defer cancel()
  216. rawPath := filepath.Join(out, "raw-frames.bin")
  217. jsonlPath := filepath.Join(out, "thermal-snapshots.jsonl")
  218. rawFile, err := os.Create(rawPath)
  219. if err != nil {
  220. return err
  221. }
  222. jsonFile, err := os.Create(jsonlPath)
  223. if err != nil {
  224. rawFile.Close()
  225. return err
  226. }
  227. rawWriter := bufio.NewWriter(rawFile)
  228. jsonWriter := bufio.NewWriter(jsonFile)
  229. started := time.Now().UTC()
  230. count := 0
  231. contractHash := ""
  232. profile := ""
  233. ticker := time.NewTicker(period)
  234. defer ticker.Stop()
  235. for {
  236. resp, err := client.CaptureSnapshot(ctx, &hthv1.GetThermalSnapshotRequest{DeviceId: deviceID})
  237. if err != nil {
  238. if ctx.Err() != nil && count > 0 {
  239. break
  240. }
  241. return err
  242. }
  243. snapshot := resp.GetSnapshot()
  244. if snapshot == nil || len(snapshot.GetRawPayload()) == 0 {
  245. return fmt.Errorf("thermal snapshot has no raw payload")
  246. }
  247. contractHash = snapshot.GetContractSha256()
  248. profile = snapshot.GetFirmwareProfile()
  249. if err := binary.Write(rawWriter, binary.LittleEndian, uint32(len(snapshot.GetRawPayload()))); err != nil {
  250. return err
  251. }
  252. if _, err := rawWriter.Write(snapshot.GetRawPayload()); err != nil {
  253. return err
  254. }
  255. message, err := protojson.MarshalOptions{UseProtoNames: true}.Marshal(snapshot)
  256. if err != nil {
  257. return err
  258. }
  259. record, _ := json.Marshal(struct {
  260. SampleIndex int `json:"sample_index"`
  261. Snapshot json.RawMessage `json:"snapshot"`
  262. }{SampleIndex: count, Snapshot: message})
  263. if _, err := jsonWriter.Write(append(record, '\n')); err != nil {
  264. return err
  265. }
  266. count++
  267. select {
  268. case <-ctx.Done():
  269. if count > 0 {
  270. break
  271. }
  272. return ctx.Err()
  273. case <-ticker.C:
  274. continue
  275. }
  276. break
  277. }
  278. if err := rawWriter.Flush(); err != nil {
  279. return err
  280. }
  281. if err := jsonWriter.Flush(); err != nil {
  282. return err
  283. }
  284. if err := rawFile.Close(); err != nil {
  285. return err
  286. }
  287. if err := jsonFile.Close(); err != nil {
  288. return err
  289. }
  290. rawSHA, err := capture.HashFile(rawPath)
  291. if err != nil {
  292. return err
  293. }
  294. jsonSHA, err := capture.HashFile(jsonlPath)
  295. if err != nil {
  296. return err
  297. }
  298. meta := map[string]any{
  299. "schema": "hth-6400-capture-v1", "device_id": deviceID,
  300. "firmware_profile": profile, "contract_sha256": contractHash,
  301. "started_at": started, "ended_at": time.Now().UTC(), "record_count": count,
  302. "hardware_validation": "NOT RUN", "com_validation": "NOT RUN",
  303. "real_thermal_performance": "NOT RUN",
  304. }
  305. metaBytes, _ := json.MarshalIndent(meta, "", " ")
  306. runPath := filepath.Join(out, "run.json")
  307. if err := os.WriteFile(runPath, append(metaBytes, '\n'), 0o644); err != nil {
  308. return err
  309. }
  310. runSHA, err := capture.HashFile(runPath)
  311. if err != nil {
  312. return err
  313. }
  314. checksums := fmt.Sprintf("%s raw-frames.bin\n%s thermal-snapshots.jsonl\n%s run.json\n", rawSHA, jsonSHA, runSHA)
  315. if err := os.WriteFile(filepath.Join(out, "checksums.sha256"), []byte(checksums), 0o644); err != nil {
  316. return err
  317. }
  318. fmt.Printf("wrote %d thermal snapshots to %s\n", count, out)
  319. return nil
  320. }