soak_test.go 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307
  1. package tests
  2. import (
  3. "context"
  4. "os"
  5. "strconv"
  6. "sync"
  7. "testing"
  8. "time"
  9. "google.golang.org/protobuf/types/known/durationpb"
  10. "google.golang.org/protobuf/types/known/timestamppb"
  11. hthv1 "hth/internal/gen/hth/api/v1"
  12. "hth/internal/grpcserver"
  13. "hth/internal/ids"
  14. )
  15. func TestShortSoakMock(t *testing.T) {
  16. if testing.Short() {
  17. t.Skip("short")
  18. }
  19. _, obs, ctl := startMockApp(t)
  20. ctx, cancel := context.WithTimeout(context.Background(), 8*time.Second)
  21. defer cancel()
  22. oconn, err := grpcserver.DialUnix(obs, time.Second)
  23. if err != nil {
  24. t.Fatal(err)
  25. }
  26. defer oconn.Close()
  27. cconn, err := grpcserver.DialUnix(ctl, time.Second)
  28. if err != nil {
  29. t.Fatal(err)
  30. }
  31. defer cconn.Close()
  32. obsCli := hthv1.NewObserveServiceClient(oconn)
  33. ctrl := hthv1.NewControlServiceClient(cconn)
  34. lease, err := ctrl.AcquireControlLease(ctx, &hthv1.AcquireControlLeaseRequest{
  35. DeviceId: "prod2u-0", Holder: "soak", Ttl: durationpb.New(5 * time.Second),
  36. })
  37. if err != nil {
  38. t.Fatal(err)
  39. }
  40. var wg sync.WaitGroup
  41. errCh := make(chan error, 8)
  42. for i := 0; i < 3; i++ {
  43. wg.Add(1)
  44. go func() {
  45. defer wg.Done()
  46. st, err := obsCli.SubscribeTelemetry(ctx, &hthv1.SubscribeTelemetryRequest{DeviceId: "prod2u-0"})
  47. if err != nil {
  48. errCh <- err
  49. return
  50. }
  51. n := 0
  52. for {
  53. s, err := st.Recv()
  54. if err != nil {
  55. return
  56. }
  57. n++
  58. if s.DataGap && s.DroppedTelemetryCount == 0 {
  59. errCh <- errSoak("gap without drop count")
  60. return
  61. }
  62. if n > 40 {
  63. return
  64. }
  65. }
  66. }()
  67. }
  68. wg.Add(1)
  69. go func() {
  70. defer wg.Done()
  71. st, err := obsCli.SubscribeTelemetry(ctx, &hthv1.SubscribeTelemetryRequest{DeviceId: "prod2u-0"})
  72. if err != nil {
  73. errCh <- err
  74. return
  75. }
  76. for {
  77. if _, err := st.Recv(); err != nil {
  78. return
  79. }
  80. time.Sleep(80 * time.Millisecond)
  81. }
  82. }()
  83. deadline := time.Now().Add(4 * time.Second)
  84. n := 0
  85. for time.Now().Before(deadline) {
  86. _, _ = ctrl.RenewControlLease(ctx, &hthv1.RenewControlLeaseRequest{
  87. DeviceId: "prod2u-0", LeaseId: lease.Lease.LeaseId, LeaseEpoch: lease.Lease.LeaseEpoch, Ttl: durationpb.New(5 * time.Second),
  88. })
  89. snap, err := obsCli.GetSnapshot(ctx, &hthv1.GetSnapshotRequest{DeviceId: "prod2u-0"})
  90. if err != nil {
  91. t.Fatal(err)
  92. }
  93. door := float64(20 + (n%3)*10)
  94. _, err = ctrl.ApplyAction(ctx, &hthv1.ApplyActionRequest{Batch: &hthv1.ActionBatch{
  95. DeviceId: "prod2u-0", CommandId: time.Now().Format("soak-20060102150405.000000000"),
  96. LeaseId: lease.Lease.LeaseId, LeaseEpoch: lease.Lease.LeaseEpoch,
  97. BasedOnSnapshotSeq: snap.Snapshot.SnapshotSeq, ExpectedControlRevision: snap.Snapshot.ControlRevision, ClientId: "soak",
  98. ValidUntil: timestamppb.New(time.Now().Add(20 * time.Second)),
  99. ContinuousTargets: []*hthv1.ContinuousTarget{
  100. {Id: ids.Fan1, Value: 10}, {Id: ids.Fan2, Value: 10}, {Id: ids.Fan3, Value: 10}, {Id: ids.Fan4, Value: 10},
  101. {Id: ids.PTC1, Value: 0}, {Id: ids.PTC2, Value: 0}, {Id: ids.PTC3, Value: 0}, {Id: ids.PTC4, Value: 0},
  102. {Id: ids.DoorX, Value: door}, {Id: ids.DoorY, Value: door}, {Id: ids.DoorZ, Value: door},
  103. },
  104. }})
  105. if err != nil {
  106. t.Fatal(err)
  107. }
  108. n++
  109. time.Sleep(50 * time.Millisecond)
  110. }
  111. cancel()
  112. wg.Wait()
  113. select {
  114. case err := <-errCh:
  115. if err != nil {
  116. t.Fatal(err)
  117. }
  118. default:
  119. }
  120. if n < 5 {
  121. t.Fatalf("too few actions %d", n)
  122. }
  123. }
  124. func TestPRSoakMock(t *testing.T) {
  125. sec, _ := strconv.Atoi(os.Getenv("HTH_SOAK_SECONDS"))
  126. if sec < 30 {
  127. t.Skip("set HTH_SOAK_SECONDS>=30 for PR soak (3–5 minutes recommended)")
  128. }
  129. if testing.Short() {
  130. t.Skip("short")
  131. }
  132. _, obs, ctl := startMockApp(t)
  133. ctx, cancel := context.WithTimeout(context.Background(), time.Duration(sec+15)*time.Second)
  134. defer cancel()
  135. oconn, err := grpcserver.DialUnix(obs, time.Second)
  136. if err != nil {
  137. t.Fatal(err)
  138. }
  139. defer oconn.Close()
  140. cconn, err := grpcserver.DialUnix(ctl, time.Second)
  141. if err != nil {
  142. t.Fatal(err)
  143. }
  144. defer cconn.Close()
  145. obsCli := hthv1.NewObserveServiceClient(oconn)
  146. ctrl := hthv1.NewControlServiceClient(cconn)
  147. lease, err := ctrl.AcquireControlLease(ctx, &hthv1.AcquireControlLeaseRequest{
  148. DeviceId: "prod2u-0", Holder: "soak-pr", Ttl: durationpb.New(5 * time.Second),
  149. })
  150. if err != nil {
  151. t.Fatal(err)
  152. }
  153. deadline := time.Now().Add(time.Duration(sec) * time.Second)
  154. n := 0
  155. for time.Now().Before(deadline) {
  156. _, _ = ctrl.RenewControlLease(ctx, &hthv1.RenewControlLeaseRequest{
  157. DeviceId: "prod2u-0", LeaseId: lease.Lease.LeaseId, LeaseEpoch: lease.Lease.LeaseEpoch, Ttl: durationpb.New(5 * time.Second),
  158. })
  159. snap, err := obsCli.GetSnapshot(ctx, &hthv1.GetSnapshotRequest{DeviceId: "prod2u-0"})
  160. if err != nil {
  161. t.Fatal(err)
  162. }
  163. _, err = ctrl.ApplyAction(ctx, &hthv1.ApplyActionRequest{Batch: &hthv1.ActionBatch{
  164. DeviceId: "prod2u-0", CommandId: time.Now().Format("prsoak-20060102150405.000000000"),
  165. LeaseId: lease.Lease.LeaseId, LeaseEpoch: lease.Lease.LeaseEpoch,
  166. BasedOnSnapshotSeq: snap.Snapshot.SnapshotSeq, ExpectedControlRevision: snap.Snapshot.ControlRevision, ClientId: "soak-pr",
  167. ValidUntil: timestamppb.New(time.Now().Add(20 * time.Second)),
  168. ContinuousTargets: []*hthv1.ContinuousTarget{
  169. {Id: ids.Fan1, Value: 10}, {Id: ids.Fan2, Value: 10}, {Id: ids.Fan3, Value: 10}, {Id: ids.Fan4, Value: 10},
  170. {Id: ids.PTC1, Value: 0}, {Id: ids.PTC2, Value: 0}, {Id: ids.PTC3, Value: 0}, {Id: ids.PTC4, Value: 0},
  171. {Id: ids.DoorX, Value: 0}, {Id: ids.DoorY, Value: 0}, {Id: ids.DoorZ, Value: 0},
  172. },
  173. }})
  174. if err != nil {
  175. t.Fatal(err)
  176. }
  177. n++
  178. time.Sleep(200 * time.Millisecond)
  179. }
  180. if n < 20 {
  181. t.Fatalf("PR soak too few actions %d", n)
  182. }
  183. }
  184. type soakErr string
  185. func (e soakErr) Error() string { return string(e) }
  186. func errSoak(s string) error { return soakErr(s) }
  187. func TestObserveSocketCannotApply(t *testing.T) {
  188. _, obs, _ := startMockApp(t)
  189. conn, err := grpcserver.DialUnix(obs, time.Second)
  190. if err != nil {
  191. t.Fatal(err)
  192. }
  193. defer conn.Close()
  194. ctrl := hthv1.NewControlServiceClient(conn)
  195. _, err = ctrl.ApplyAction(context.Background(), &hthv1.ApplyActionRequest{Batch: &hthv1.ActionBatch{CommandId: "x"}})
  196. if err == nil {
  197. t.Fatal("observe socket must not serve ApplyAction")
  198. }
  199. }
  200. func tcpListenKeys(pid int) map[string]struct{} {
  201. owned := socketInodes(pid)
  202. out := map[string]struct{}{}
  203. for _, name := range []string{"tcp", "tcp6"} {
  204. b, err := os.ReadFile("/proc/" + strconv.Itoa(pid) + "/net/" + name)
  205. if err != nil {
  206. continue
  207. }
  208. for i, line := range splitLines(string(b)) {
  209. if i == 0 {
  210. continue
  211. }
  212. fields := splitWS(line)
  213. if len(fields) < 10 {
  214. continue
  215. }
  216. if fields[3] != "0A" {
  217. continue
  218. }
  219. inode := fields[9]
  220. if len(owned) > 0 {
  221. if _, ok := owned[inode]; !ok {
  222. continue
  223. }
  224. }
  225. out[name+" "+fields[1]] = struct{}{}
  226. }
  227. }
  228. return out
  229. }
  230. func socketInodes(pid int) map[string]struct{} {
  231. out := map[string]struct{}{}
  232. dir := "/proc/" + strconv.Itoa(pid) + "/fd"
  233. ents, err := os.ReadDir(dir)
  234. if err != nil {
  235. return out
  236. }
  237. for _, e := range ents {
  238. target, err := os.Readlink(dir + "/" + e.Name())
  239. if err != nil {
  240. continue
  241. }
  242. const p = "socket:["
  243. if len(target) > len(p) && target[:len(p)] == p && target[len(target)-1] == ']' {
  244. out[target[len(p):len(target)-1]] = struct{}{}
  245. }
  246. }
  247. return out
  248. }
  249. func TestNoTCPListen(t *testing.T) {
  250. pid := os.Getpid()
  251. before := tcpListenKeys(pid)
  252. _, obs, ctl := startMockApp(t)
  253. if obs == "" || ctl == "" {
  254. t.Fatal("missing sockets")
  255. }
  256. after := tcpListenKeys(pid)
  257. for k := range after {
  258. if _, ok := before[k]; !ok {
  259. t.Fatalf("hthd opened a new TCP listen socket: %s", k)
  260. }
  261. }
  262. }
  263. func splitLines(s string) []string {
  264. out := []string{}
  265. start := 0
  266. for i := 0; i < len(s); i++ {
  267. if s[i] == '\n' {
  268. out = append(out, s[start:i])
  269. start = i + 1
  270. }
  271. }
  272. if start < len(s) {
  273. out = append(out, s[start:])
  274. }
  275. return out
  276. }
  277. func splitWS(s string) []string {
  278. var out []string
  279. field := ""
  280. for _, r := range s {
  281. if r == ' ' || r == '\t' {
  282. if field != "" {
  283. out = append(out, field)
  284. field = ""
  285. }
  286. continue
  287. }
  288. field += string(r)
  289. }
  290. if field != "" {
  291. out = append(out, field)
  292. }
  293. return out
  294. }