process_sigterm_linux_test.go 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309
  1. //go:build linux
  2. package tests
  3. import (
  4. "context"
  5. "net"
  6. "os"
  7. "os/exec"
  8. "path/filepath"
  9. "strings"
  10. "syscall"
  11. "testing"
  12. "time"
  13. "google.golang.org/protobuf/types/known/durationpb"
  14. "google.golang.org/protobuf/types/known/timestamppb"
  15. "hth/internal/devsim"
  16. hthv1 "hth/internal/gen/hth/api/v1"
  17. "hth/internal/grpcserver"
  18. "hth/internal/ids"
  19. "hth/internal/testutil"
  20. )
  21. func TestHthdSIGTERMSendsSafeSETALL(t *testing.T) {
  22. sim, err := devsim.Start(devsim.Options{StartupDone: true})
  23. if err != nil {
  24. t.Fatal(err)
  25. }
  26. defer sim.Close()
  27. dir := t.TempDir()
  28. obs := filepath.Join(dir, "o.sock")
  29. ctl := filepath.Join(dir, "c.sock")
  30. yaml := `
  31. api_version: hth.api.v1
  32. device_id: prod2u-0
  33. backend: serial
  34. profile: ` + testutil.ProfilePath(t) + `
  35. runtime_root: ` + dir + `
  36. serial:
  37. path: ` + sim.Name + `
  38. inter_byte_timeout_ms: 50
  39. get_motor_timeout_ms: 2000
  40. probe_timeout_ms: 2000
  41. set_all_timeout_ms: 2000
  42. sockets:
  43. observe: ` + obs + `
  44. control: ` + ctl + `
  45. observe_perm: "0660"
  46. control_perm: "0660"
  47. poll:
  48. temperature_ms: 60000
  49. motor_status_ms: 60000
  50. watchdog:
  51. heartbeat_period_ms: 5000
  52. lease:
  53. min_ttl_ms: 50
  54. max_ttl_ms: 2000
  55. safety:
  56. fan: 10
  57. ptc: 0
  58. door_close_percent: 0
  59. ring_buffer_size: 32
  60. subscriber_buffer_size: 4
  61. grpc:
  62. reflection: false
  63. `
  64. cfgPath := filepath.Join(dir, "hthd.yaml")
  65. if err := os.WriteFile(cfgPath, []byte(yaml), 0o644); err != nil {
  66. t.Fatal(err)
  67. }
  68. bin := buildHthd(t)
  69. cmd := exec.Command(bin, "--config", cfgPath)
  70. cmd.Stderr = os.Stderr
  71. if err := cmd.Start(); err != nil {
  72. t.Fatal(err)
  73. }
  74. done := make(chan error, 1)
  75. t.Cleanup(func() {
  76. if cmd.Process != nil && cmd.ProcessState == nil {
  77. _ = cmd.Process.Kill()
  78. }
  79. })
  80. go func() { done <- cmd.Wait() }()
  81. waitUnix(t, obs, 4*time.Second)
  82. waitUnix(t, ctl, 2*time.Second)
  83. deadline := time.Now().Add(8 * time.Second)
  84. for time.Now().Before(deadline) {
  85. if len(sim.SetAlls()) > 0 {
  86. break
  87. }
  88. time.Sleep(20 * time.Millisecond)
  89. }
  90. if len(sim.SetAlls()) == 0 {
  91. t.Fatal("no SET_ALL seen before SIGTERM")
  92. }
  93. oc, err := grpcserver.DialUnix(obs, time.Second)
  94. if err == nil {
  95. defer oc.Close()
  96. obsCli := hthv1.NewObserveServiceClient(oc)
  97. sctx, scancel := context.WithTimeout(context.Background(), 2*time.Second)
  98. defer scancel()
  99. s, err := obsCli.GetSnapshot(sctx, &hthv1.GetSnapshotRequest{DeviceId: "prod2u-0"})
  100. if err == nil && s.Snapshot.Lifecycle == hthv1.DeviceLifecycleState_DEVICE_LIFECYCLE_STATE_READY {
  101. cc, err := grpcserver.DialUnix(ctl, time.Second)
  102. if err == nil {
  103. defer cc.Close()
  104. ctrl := hthv1.NewControlServiceClient(cc)
  105. lease, err := ctrl.AcquireControlLease(sctx, &hthv1.AcquireControlLeaseRequest{
  106. DeviceId: "prod2u-0", Holder: "sigterm", Ttl: durationpb.New(2 * time.Second),
  107. })
  108. if err == nil {
  109. _, _ = ctrl.ApplyAction(sctx, &hthv1.ApplyActionRequest{Batch: &hthv1.ActionBatch{
  110. DeviceId: "prod2u-0", CommandId: "pre-term", ClientId: "sigterm",
  111. LeaseId: lease.Lease.LeaseId, LeaseEpoch: lease.Lease.LeaseEpoch,
  112. BasedOnSnapshotSeq: s.Snapshot.SnapshotSeq, ExpectedControlRevision: s.Snapshot.ControlRevision, AllowClamp: true,
  113. ValidUntil: timestamppb.New(time.Now().Add(5 * time.Second)),
  114. ContinuousTargets: []*hthv1.ContinuousTarget{
  115. {Id: ids.Fan1, Value: 40}, {Id: ids.DoorX, Value: 40},
  116. },
  117. }})
  118. }
  119. }
  120. }
  121. }
  122. start := time.Now()
  123. if err := cmd.Process.Signal(syscall.SIGTERM); err != nil {
  124. t.Fatal(err)
  125. }
  126. select {
  127. case err := <-done:
  128. if err != nil {
  129. t.Fatalf("hthd exit: %v", err)
  130. }
  131. case <-time.After(15 * time.Second):
  132. _ = cmd.Process.Kill()
  133. t.Fatal("hthd exceeded TimeoutStopSec-equivalent 15s after SIGTERM")
  134. }
  135. if time.Since(start) > 15*time.Second {
  136. t.Fatal("stop too slow")
  137. }
  138. sets := sim.SetAlls()
  139. if len(sets) == 0 {
  140. t.Fatal("no SET_ALL")
  141. }
  142. last := sets[len(sets)-1]
  143. if last.Fan[0] != 10 || last.PTC[0] != 0 || last.DoorX != 0 || last.DoorY != 0 || last.DoorZ != 0 {
  144. t.Fatalf("last SET_ALL is not safe frame: %+v", last)
  145. }
  146. }
  147. func TestHthdProcessHasNoNewTCPListen(t *testing.T) {
  148. dir := t.TempDir()
  149. obs := filepath.Join(dir, "o.sock")
  150. ctl := filepath.Join(dir, "c.sock")
  151. yaml := `
  152. api_version: hth.api.v1
  153. device_id: prod2u-0
  154. backend: mock
  155. profile: ` + testutil.ProfilePath(t) + `
  156. runtime_root: ` + dir + `
  157. sockets:
  158. observe: ` + obs + `
  159. control: ` + ctl + `
  160. poll:
  161. temperature_ms: 80
  162. motor_status_ms: 50
  163. watchdog:
  164. heartbeat_period_ms: 200
  165. lease:
  166. min_ttl_ms: 50
  167. max_ttl_ms: 2000
  168. safety:
  169. fan: 10
  170. ptc: 0
  171. door_close_percent: 0
  172. ring_buffer_size: 16
  173. subscriber_buffer_size: 2
  174. grpc:
  175. reflection: false
  176. mock:
  177. seed: 1
  178. startup_complete: true
  179. `
  180. cfgPath := filepath.Join(dir, "hthd.yaml")
  181. if err := os.WriteFile(cfgPath, []byte(yaml), 0o644); err != nil {
  182. t.Fatal(err)
  183. }
  184. bin := buildHthd(t)
  185. cmd := exec.Command(bin, "--config", cfgPath)
  186. if err := cmd.Start(); err != nil {
  187. t.Fatal(err)
  188. }
  189. defer func() {
  190. _ = cmd.Process.Signal(syscall.SIGTERM)
  191. _, _ = cmd.Process.Wait()
  192. }()
  193. waitUnix(t, obs, 4*time.Second)
  194. keys := tcpListenKeys(cmd.Process.Pid)
  195. if len(keys) != 0 {
  196. t.Fatalf("hthd pid %d has TCP listen sockets: %v", cmd.Process.Pid, keys)
  197. }
  198. }
  199. func TestHthdSdNotifyReadyAndStopping(t *testing.T) {
  200. dir := t.TempDir()
  201. obs := filepath.Join(dir, "o.sock")
  202. ctl := filepath.Join(dir, "c.sock")
  203. notify := filepath.Join(dir, "notify.sock")
  204. laddr := &net.UnixAddr{Name: notify, Net: "unixgram"}
  205. pc, err := net.ListenUnixgram("unixgram", laddr)
  206. if err != nil {
  207. t.Fatal(err)
  208. }
  209. defer pc.Close()
  210. _ = os.Chmod(notify, 0o777)
  211. yaml := `
  212. api_version: hth.api.v1
  213. device_id: prod2u-0
  214. backend: mock
  215. profile: ` + testutil.ProfilePath(t) + `
  216. runtime_root: ` + dir + `
  217. sockets:
  218. observe: ` + obs + `
  219. control: ` + ctl + `
  220. poll:
  221. temperature_ms: 80
  222. motor_status_ms: 50
  223. watchdog:
  224. heartbeat_period_ms: 200
  225. lease:
  226. min_ttl_ms: 50
  227. max_ttl_ms: 2000
  228. safety:
  229. fan: 10
  230. ptc: 0
  231. door_close_percent: 0
  232. ring_buffer_size: 16
  233. subscriber_buffer_size: 2
  234. grpc:
  235. reflection: false
  236. mock:
  237. seed: 1
  238. startup_complete: true
  239. `
  240. cfgPath := filepath.Join(dir, "hthd.yaml")
  241. if err := os.WriteFile(cfgPath, []byte(yaml), 0o644); err != nil {
  242. t.Fatal(err)
  243. }
  244. bin := buildHthd(t)
  245. cmd := exec.Command(bin, "--config", cfgPath)
  246. cmd.Env = append(os.Environ(), "NOTIFY_SOCKET="+notify)
  247. if err := cmd.Start(); err != nil {
  248. t.Fatal(err)
  249. }
  250. done := make(chan error, 1)
  251. go func() { done <- cmd.Wait() }()
  252. defer func() {
  253. if cmd.Process != nil {
  254. _ = cmd.Process.Signal(syscall.SIGTERM)
  255. }
  256. }()
  257. waitUnix(t, obs, 4*time.Second)
  258. _ = pc.SetReadDeadline(time.Now().Add(2 * time.Second))
  259. buf := make([]byte, 128)
  260. gotReady := false
  261. deadline := time.Now().Add(2 * time.Second)
  262. for time.Now().Before(deadline) {
  263. n, err := pc.Read(buf)
  264. if err != nil {
  265. break
  266. }
  267. if strings.Contains(string(buf[:n]), "READY=1") {
  268. gotReady = true
  269. break
  270. }
  271. }
  272. if !gotReady {
  273. t.Fatal("hthd did not send sd_notify READY=1")
  274. }
  275. if err := cmd.Process.Signal(syscall.SIGTERM); err != nil {
  276. t.Fatal(err)
  277. }
  278. _ = pc.SetReadDeadline(time.Now().Add(3 * time.Second))
  279. gotStop := false
  280. stopDeadline := time.Now().Add(3 * time.Second)
  281. for time.Now().Before(stopDeadline) {
  282. n, err := pc.Read(buf)
  283. if err != nil {
  284. break
  285. }
  286. if strings.Contains(string(buf[:n]), "STOPPING=1") {
  287. gotStop = true
  288. break
  289. }
  290. }
  291. select {
  292. case <-done:
  293. case <-time.After(5 * time.Second):
  294. _ = cmd.Process.Kill()
  295. t.Fatal("hthd did not exit after SIGTERM")
  296. }
  297. if !gotStop {
  298. t.Fatal("hthd did not send sd_notify STOPPING=1")
  299. }
  300. }