| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307 |
- package tests
- import (
- "context"
- "os"
- "strconv"
- "sync"
- "testing"
- "time"
- "google.golang.org/protobuf/types/known/durationpb"
- "google.golang.org/protobuf/types/known/timestamppb"
- hthv1 "hth/internal/gen/hth/api/v1"
- "hth/internal/grpcserver"
- "hth/internal/ids"
- )
- func TestShortSoakMock(t *testing.T) {
- if testing.Short() {
- t.Skip("short")
- }
- _, obs, ctl := startMockApp(t)
- ctx, cancel := context.WithTimeout(context.Background(), 8*time.Second)
- defer cancel()
- oconn, err := grpcserver.DialUnix(obs, time.Second)
- if err != nil {
- t.Fatal(err)
- }
- defer oconn.Close()
- cconn, err := grpcserver.DialUnix(ctl, time.Second)
- if err != nil {
- t.Fatal(err)
- }
- defer cconn.Close()
- obsCli := hthv1.NewObserveServiceClient(oconn)
- ctrl := hthv1.NewControlServiceClient(cconn)
- lease, err := ctrl.AcquireControlLease(ctx, &hthv1.AcquireControlLeaseRequest{
- DeviceId: "prod2u-0", Holder: "soak", Ttl: durationpb.New(5 * time.Second),
- })
- if err != nil {
- t.Fatal(err)
- }
- var wg sync.WaitGroup
- errCh := make(chan error, 8)
- for i := 0; i < 3; i++ {
- wg.Add(1)
- go func() {
- defer wg.Done()
- st, err := obsCli.SubscribeTelemetry(ctx, &hthv1.SubscribeTelemetryRequest{DeviceId: "prod2u-0"})
- if err != nil {
- errCh <- err
- return
- }
- n := 0
- for {
- s, err := st.Recv()
- if err != nil {
- return
- }
- n++
- if s.DataGap && s.DroppedTelemetryCount == 0 {
- errCh <- errSoak("gap without drop count")
- return
- }
- if n > 40 {
- return
- }
- }
- }()
- }
- wg.Add(1)
- go func() {
- defer wg.Done()
- st, err := obsCli.SubscribeTelemetry(ctx, &hthv1.SubscribeTelemetryRequest{DeviceId: "prod2u-0"})
- if err != nil {
- errCh <- err
- return
- }
- for {
- if _, err := st.Recv(); err != nil {
- return
- }
- time.Sleep(80 * time.Millisecond)
- }
- }()
- deadline := time.Now().Add(4 * time.Second)
- n := 0
- for time.Now().Before(deadline) {
- _, _ = ctrl.RenewControlLease(ctx, &hthv1.RenewControlLeaseRequest{
- DeviceId: "prod2u-0", LeaseId: lease.Lease.LeaseId, LeaseEpoch: lease.Lease.LeaseEpoch, Ttl: durationpb.New(5 * time.Second),
- })
- snap, err := obsCli.GetSnapshot(ctx, &hthv1.GetSnapshotRequest{DeviceId: "prod2u-0"})
- if err != nil {
- t.Fatal(err)
- }
- door := float64(20 + (n%3)*10)
- _, err = ctrl.ApplyAction(ctx, &hthv1.ApplyActionRequest{Batch: &hthv1.ActionBatch{
- DeviceId: "prod2u-0", CommandId: time.Now().Format("soak-20060102150405.000000000"),
- LeaseId: lease.Lease.LeaseId, LeaseEpoch: lease.Lease.LeaseEpoch,
- BasedOnSnapshotSeq: snap.Snapshot.SnapshotSeq, ExpectedControlRevision: snap.Snapshot.ControlRevision, ClientId: "soak",
- ValidUntil: timestamppb.New(time.Now().Add(20 * time.Second)),
- ContinuousTargets: []*hthv1.ContinuousTarget{
- {Id: ids.Fan1, Value: 10}, {Id: ids.Fan2, Value: 10}, {Id: ids.Fan3, Value: 10}, {Id: ids.Fan4, Value: 10},
- {Id: ids.PTC1, Value: 0}, {Id: ids.PTC2, Value: 0}, {Id: ids.PTC3, Value: 0}, {Id: ids.PTC4, Value: 0},
- {Id: ids.DoorX, Value: door}, {Id: ids.DoorY, Value: door}, {Id: ids.DoorZ, Value: door},
- },
- }})
- if err != nil {
- t.Fatal(err)
- }
- n++
- time.Sleep(50 * time.Millisecond)
- }
- cancel()
- wg.Wait()
- select {
- case err := <-errCh:
- if err != nil {
- t.Fatal(err)
- }
- default:
- }
- if n < 5 {
- t.Fatalf("too few actions %d", n)
- }
- }
- func TestPRSoakMock(t *testing.T) {
- sec, _ := strconv.Atoi(os.Getenv("HTH_SOAK_SECONDS"))
- if sec < 30 {
- t.Skip("set HTH_SOAK_SECONDS>=30 for PR soak (3–5 minutes recommended)")
- }
- if testing.Short() {
- t.Skip("short")
- }
- _, obs, ctl := startMockApp(t)
- ctx, cancel := context.WithTimeout(context.Background(), time.Duration(sec+15)*time.Second)
- defer cancel()
- oconn, err := grpcserver.DialUnix(obs, time.Second)
- if err != nil {
- t.Fatal(err)
- }
- defer oconn.Close()
- cconn, err := grpcserver.DialUnix(ctl, time.Second)
- if err != nil {
- t.Fatal(err)
- }
- defer cconn.Close()
- obsCli := hthv1.NewObserveServiceClient(oconn)
- ctrl := hthv1.NewControlServiceClient(cconn)
- lease, err := ctrl.AcquireControlLease(ctx, &hthv1.AcquireControlLeaseRequest{
- DeviceId: "prod2u-0", Holder: "soak-pr", Ttl: durationpb.New(5 * time.Second),
- })
- if err != nil {
- t.Fatal(err)
- }
- deadline := time.Now().Add(time.Duration(sec) * time.Second)
- n := 0
- for time.Now().Before(deadline) {
- _, _ = ctrl.RenewControlLease(ctx, &hthv1.RenewControlLeaseRequest{
- DeviceId: "prod2u-0", LeaseId: lease.Lease.LeaseId, LeaseEpoch: lease.Lease.LeaseEpoch, Ttl: durationpb.New(5 * time.Second),
- })
- snap, err := obsCli.GetSnapshot(ctx, &hthv1.GetSnapshotRequest{DeviceId: "prod2u-0"})
- if err != nil {
- t.Fatal(err)
- }
- _, err = ctrl.ApplyAction(ctx, &hthv1.ApplyActionRequest{Batch: &hthv1.ActionBatch{
- DeviceId: "prod2u-0", CommandId: time.Now().Format("prsoak-20060102150405.000000000"),
- LeaseId: lease.Lease.LeaseId, LeaseEpoch: lease.Lease.LeaseEpoch,
- BasedOnSnapshotSeq: snap.Snapshot.SnapshotSeq, ExpectedControlRevision: snap.Snapshot.ControlRevision, ClientId: "soak-pr",
- ValidUntil: timestamppb.New(time.Now().Add(20 * time.Second)),
- ContinuousTargets: []*hthv1.ContinuousTarget{
- {Id: ids.Fan1, Value: 10}, {Id: ids.Fan2, Value: 10}, {Id: ids.Fan3, Value: 10}, {Id: ids.Fan4, Value: 10},
- {Id: ids.PTC1, Value: 0}, {Id: ids.PTC2, Value: 0}, {Id: ids.PTC3, Value: 0}, {Id: ids.PTC4, Value: 0},
- {Id: ids.DoorX, Value: 0}, {Id: ids.DoorY, Value: 0}, {Id: ids.DoorZ, Value: 0},
- },
- }})
- if err != nil {
- t.Fatal(err)
- }
- n++
- time.Sleep(200 * time.Millisecond)
- }
- if n < 20 {
- t.Fatalf("PR soak too few actions %d", n)
- }
- }
- type soakErr string
- func (e soakErr) Error() string { return string(e) }
- func errSoak(s string) error { return soakErr(s) }
- func TestObserveSocketCannotApply(t *testing.T) {
- _, obs, _ := startMockApp(t)
- conn, err := grpcserver.DialUnix(obs, time.Second)
- if err != nil {
- t.Fatal(err)
- }
- defer conn.Close()
- ctrl := hthv1.NewControlServiceClient(conn)
- _, err = ctrl.ApplyAction(context.Background(), &hthv1.ApplyActionRequest{Batch: &hthv1.ActionBatch{CommandId: "x"}})
- if err == nil {
- t.Fatal("observe socket must not serve ApplyAction")
- }
- }
- func tcpListenKeys(pid int) map[string]struct{} {
- owned := socketInodes(pid)
- out := map[string]struct{}{}
- for _, name := range []string{"tcp", "tcp6"} {
- b, err := os.ReadFile("/proc/" + strconv.Itoa(pid) + "/net/" + name)
- if err != nil {
- continue
- }
- for i, line := range splitLines(string(b)) {
- if i == 0 {
- continue
- }
- fields := splitWS(line)
- if len(fields) < 10 {
- continue
- }
- if fields[3] != "0A" {
- continue
- }
- inode := fields[9]
- if len(owned) > 0 {
- if _, ok := owned[inode]; !ok {
- continue
- }
- }
- out[name+" "+fields[1]] = struct{}{}
- }
- }
- return out
- }
- func socketInodes(pid int) map[string]struct{} {
- out := map[string]struct{}{}
- dir := "/proc/" + strconv.Itoa(pid) + "/fd"
- ents, err := os.ReadDir(dir)
- if err != nil {
- return out
- }
- for _, e := range ents {
- target, err := os.Readlink(dir + "/" + e.Name())
- if err != nil {
- continue
- }
- const p = "socket:["
- if len(target) > len(p) && target[:len(p)] == p && target[len(target)-1] == ']' {
- out[target[len(p):len(target)-1]] = struct{}{}
- }
- }
- return out
- }
- func TestNoTCPListen(t *testing.T) {
- pid := os.Getpid()
- before := tcpListenKeys(pid)
- _, obs, ctl := startMockApp(t)
- if obs == "" || ctl == "" {
- t.Fatal("missing sockets")
- }
- after := tcpListenKeys(pid)
- for k := range after {
- if _, ok := before[k]; !ok {
- t.Fatalf("hthd opened a new TCP listen socket: %s", k)
- }
- }
- }
- func splitLines(s string) []string {
- out := []string{}
- start := 0
- for i := 0; i < len(s); i++ {
- if s[i] == '\n' {
- out = append(out, s[start:i])
- start = i + 1
- }
- }
- if start < len(s) {
- out = append(out, s[start:])
- }
- return out
- }
- func splitWS(s string) []string {
- var out []string
- field := ""
- for _, r := range s {
- if r == ' ' || r == '\t' {
- if field != "" {
- out = append(out, field)
- field = ""
- }
- continue
- }
- field += string(r)
- }
- if field != "" {
- out = append(out, field)
- }
- return out
- }
|