podman_test.go 5.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215
  1. // Copyright The OpenTelemetry Authors
  2. // SPDX-License-Identifier: Apache-2.0
  3. //go:build !windows
  4. // +build !windows
  5. package podmanreceiver
  6. import (
  7. "context"
  8. "fmt"
  9. "net/http"
  10. "net/http/httptest"
  11. "net/url"
  12. "os"
  13. "strings"
  14. "sync"
  15. "testing"
  16. "time"
  17. "github.com/stretchr/testify/assert"
  18. "github.com/stretchr/testify/require"
  19. "go.opentelemetry.io/collector/receiver/scraperhelper"
  20. "go.uber.org/zap"
  21. "go.uber.org/zap/zapcore"
  22. "go.uber.org/zap/zaptest/observer"
  23. )
  24. type MockClient struct {
  25. PingF func(context.Context) error
  26. StatsF func(context.Context, url.Values) ([]containerStats, error)
  27. ListF func(context.Context, url.Values) ([]container, error)
  28. EventsF func(context.Context, url.Values) (<-chan event, <-chan error)
  29. }
  30. func (c *MockClient) ping(ctx context.Context) error {
  31. return c.PingF(ctx)
  32. }
  33. func (c *MockClient) stats(ctx context.Context, options url.Values) ([]containerStats, error) {
  34. return c.StatsF(ctx, options)
  35. }
  36. func (c *MockClient) list(ctx context.Context, options url.Values) ([]container, error) {
  37. return c.ListF(ctx, options)
  38. }
  39. func (c *MockClient) events(ctx context.Context, options url.Values) (<-chan event, <-chan error) {
  40. return c.EventsF(ctx, options)
  41. }
  42. var baseClient = MockClient{
  43. PingF: func(context.Context) error {
  44. return nil
  45. },
  46. StatsF: func(context.Context, url.Values) ([]containerStats, error) {
  47. return nil, nil
  48. },
  49. ListF: func(context.Context, url.Values) ([]container, error) {
  50. return nil, nil
  51. },
  52. EventsF: func(context.Context, url.Values) (<-chan event, <-chan error) {
  53. return nil, nil
  54. },
  55. }
  56. func TestWatchingTimeouts(t *testing.T) {
  57. listener, addr := tmpSock(t)
  58. defer listener.Close()
  59. defer os.Remove(addr)
  60. config := &Config{
  61. Endpoint: fmt.Sprintf("unix://%s", addr),
  62. ScraperControllerSettings: scraperhelper.ScraperControllerSettings{
  63. Timeout: 50 * time.Millisecond,
  64. },
  65. }
  66. client, err := newLibpodClient(zap.NewNop(), config)
  67. assert.Nil(t, err)
  68. cli := newContainerScraper(client, zap.NewNop(), config)
  69. assert.NotNil(t, cli)
  70. expectedError := "context deadline exceeded"
  71. shouldHaveTaken := time.Now().Add(100 * time.Millisecond).UnixNano()
  72. err = cli.loadContainerList(context.Background())
  73. require.Error(t, err)
  74. ctx, fetchCancel := context.WithTimeout(context.Background(), config.Timeout)
  75. defer fetchCancel()
  76. container, err := cli.fetchContainerStats(ctx, container{})
  77. require.Error(t, err)
  78. assert.Contains(t, err.Error(), expectedError)
  79. assert.Empty(t, container)
  80. assert.GreaterOrEqual(
  81. t, time.Now().UnixNano(), shouldHaveTaken,
  82. "Client timeouts don't appear to have been exercised.",
  83. )
  84. }
  85. func TestEventLoopHandlesError(t *testing.T) {
  86. wg := sync.WaitGroup{}
  87. wg.Add(2) // confirm retry occurs
  88. listener, addr := tmpSock(t)
  89. defer listener.Close()
  90. defer os.Remove(addr)
  91. srv := httptest.NewUnstartedServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  92. if strings.Contains(r.URL.Path, "/events") {
  93. wg.Done()
  94. }
  95. _, err := w.Write([]byte{})
  96. assert.NoError(t, err)
  97. }))
  98. srv.Listener = listener
  99. srv.Start()
  100. defer srv.Close()
  101. observed, logs := observer.New(zapcore.WarnLevel)
  102. config := &Config{
  103. Endpoint: fmt.Sprintf("unix://%s", addr),
  104. ScraperControllerSettings: scraperhelper.ScraperControllerSettings{
  105. Timeout: 50 * time.Millisecond,
  106. },
  107. }
  108. client, err := newLibpodClient(zap.NewNop(), config)
  109. assert.Nil(t, err)
  110. cli := newContainerScraper(client, zap.New(observed), config)
  111. assert.NotNil(t, cli)
  112. go cli.containerEventLoop(context.Background())
  113. assert.Eventually(t, func() bool {
  114. for _, l := range logs.All() {
  115. assert.Contains(t, l.Message, "Error watching podman container events")
  116. assert.Contains(t, l.ContextMap()["error"], "EOF")
  117. }
  118. return len(logs.All()) > 0
  119. }, 1*time.Second, 1*time.Millisecond, "failed to find desired error logs.")
  120. finished := make(chan struct{})
  121. go func() {
  122. defer close(finished)
  123. wg.Wait()
  124. }()
  125. select {
  126. case <-time.After(5 * time.Second):
  127. t.Fatal("failed to retry events endpoint after error")
  128. case <-finished:
  129. return
  130. }
  131. }
  132. func TestEventLoopHandles(t *testing.T) {
  133. eventChan := make(chan event)
  134. errChan := make(chan error)
  135. eventClient := baseClient
  136. eventClient.EventsF = func(context.Context, url.Values) (<-chan event, <-chan error) {
  137. return eventChan, errChan
  138. }
  139. eventClient.ListF = func(context.Context, url.Values) ([]container, error) {
  140. return []container{{
  141. ID: "c1",
  142. }}, nil
  143. }
  144. cli := newContainerScraper(&eventClient, zap.NewNop(), &Config{})
  145. assert.NotNil(t, cli)
  146. assert.Equal(t, 0, len(cli.containers))
  147. go cli.containerEventLoop(context.Background())
  148. eventChan <- event{ID: "c1", Status: "start"}
  149. assert.Eventually(t, func() bool {
  150. cli.containersLock.Lock()
  151. defer cli.containersLock.Unlock()
  152. return assert.Equal(t, 1, len(cli.containers))
  153. }, 1*time.Second, 1*time.Millisecond, "failed to update containers list.")
  154. eventChan <- event{ID: "c1", Status: "died"}
  155. assert.Eventually(t, func() bool {
  156. cli.containersLock.Lock()
  157. defer cli.containersLock.Unlock()
  158. return assert.Equal(t, 0, len(cli.containers))
  159. }, 1*time.Second, 1*time.Millisecond, "failed to update containers list.")
  160. }
  161. func TestInspectAndPersistContainer(t *testing.T) {
  162. inspectClient := baseClient
  163. inspectClient.ListF = func(context.Context, url.Values) ([]container, error) {
  164. return []container{{
  165. ID: "c1",
  166. }}, nil
  167. }
  168. cli := newContainerScraper(&inspectClient, zap.NewNop(), &Config{})
  169. assert.NotNil(t, cli)
  170. assert.Equal(t, 0, len(cli.containers))
  171. stats, ok := cli.inspectAndPersistContainer(context.Background(), "c1")
  172. assert.True(t, ok)
  173. assert.NotNil(t, stats)
  174. assert.Equal(t, 1, len(cli.containers))
  175. }