splunkhecmock_test.go 4.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182
  1. package splunk // import "github.com/docker/docker/daemon/logger/splunk"
  2. import (
  3. "compress/gzip"
  4. "context"
  5. "encoding/json"
  6. "fmt"
  7. "io"
  8. "net"
  9. "net/http"
  10. "sync"
  11. "testing"
  12. )
  13. func (message *splunkMessage) EventAsString() (string, error) {
  14. if val, ok := message.Event.(string); ok {
  15. return val, nil
  16. }
  17. return "", fmt.Errorf("Cannot cast Event %v to string", message.Event)
  18. }
  19. func (message *splunkMessage) EventAsMap() (map[string]interface{}, error) {
  20. if val, ok := message.Event.(map[string]interface{}); ok {
  21. return val, nil
  22. }
  23. return nil, fmt.Errorf("Cannot cast Event %v to map", message.Event)
  24. }
  25. type HTTPEventCollectorMock struct {
  26. tcpAddr *net.TCPAddr
  27. tcpListener *net.TCPListener
  28. mu sync.Mutex
  29. token string
  30. simulateServerError bool
  31. blockingCtx context.Context
  32. test *testing.T
  33. connectionVerified bool
  34. gzipEnabled *bool
  35. messages []*splunkMessage
  36. numOfRequests int
  37. }
  38. func NewHTTPEventCollectorMock(t *testing.T) *HTTPEventCollectorMock {
  39. tcpAddr := &net.TCPAddr{IP: []byte{127, 0, 0, 1}, Port: 0, Zone: ""}
  40. tcpListener, err := net.ListenTCP("tcp", tcpAddr)
  41. if err != nil {
  42. t.Fatal(err)
  43. }
  44. return &HTTPEventCollectorMock{
  45. tcpAddr: tcpAddr,
  46. tcpListener: tcpListener,
  47. token: "4642492F-D8BD-47F1-A005-0C08AE4657DF",
  48. simulateServerError: false,
  49. test: t,
  50. connectionVerified: false,
  51. }
  52. }
  53. func (hec *HTTPEventCollectorMock) simulateErr(b bool) {
  54. hec.mu.Lock()
  55. hec.simulateServerError = b
  56. hec.mu.Unlock()
  57. }
  58. func (hec *HTTPEventCollectorMock) withBlock(ctx context.Context) {
  59. hec.mu.Lock()
  60. hec.blockingCtx = ctx
  61. hec.mu.Unlock()
  62. }
  63. func (hec *HTTPEventCollectorMock) URL() string {
  64. return "http://" + hec.tcpListener.Addr().String()
  65. }
  66. func (hec *HTTPEventCollectorMock) Serve() error {
  67. return http.Serve(hec.tcpListener, hec)
  68. }
  69. func (hec *HTTPEventCollectorMock) Close() error {
  70. return hec.tcpListener.Close()
  71. }
  72. func (hec *HTTPEventCollectorMock) ServeHTTP(writer http.ResponseWriter, request *http.Request) {
  73. var err error
  74. hec.numOfRequests++
  75. hec.mu.Lock()
  76. simErr := hec.simulateServerError
  77. ctx := hec.blockingCtx
  78. hec.mu.Unlock()
  79. if ctx != nil {
  80. <-hec.blockingCtx.Done()
  81. }
  82. if simErr {
  83. if request.Body != nil {
  84. defer request.Body.Close()
  85. }
  86. writer.WriteHeader(http.StatusInternalServerError)
  87. return
  88. }
  89. switch request.Method {
  90. case http.MethodOptions:
  91. // Verify that options method is getting called only once
  92. if hec.connectionVerified {
  93. hec.test.Errorf("Connection should not be verified more than once. Got second request with %s method.", request.Method)
  94. }
  95. hec.connectionVerified = true
  96. writer.WriteHeader(http.StatusOK)
  97. case http.MethodPost:
  98. // Always verify that Driver is using correct path to HEC
  99. if request.URL.String() != "/services/collector/event/1.0" {
  100. hec.test.Errorf("Unexpected path %v", request.URL)
  101. }
  102. defer request.Body.Close()
  103. if authorization, ok := request.Header["Authorization"]; !ok || authorization[0] != ("Splunk "+hec.token) {
  104. hec.test.Error("Authorization header is invalid.")
  105. }
  106. gzipEnabled := false
  107. if contentEncoding, ok := request.Header["Content-Encoding"]; ok && contentEncoding[0] == "gzip" {
  108. gzipEnabled = true
  109. }
  110. if hec.gzipEnabled == nil {
  111. hec.gzipEnabled = &gzipEnabled
  112. } else if gzipEnabled != *hec.gzipEnabled {
  113. // Nothing wrong with that, but we just know that Splunk Logging Driver does not do that
  114. hec.test.Error("Driver should not change Content Encoding.")
  115. }
  116. var gzipReader *gzip.Reader
  117. var reader io.Reader
  118. if gzipEnabled {
  119. gzipReader, err = gzip.NewReader(request.Body)
  120. if err != nil {
  121. hec.test.Fatal(err)
  122. }
  123. reader = gzipReader
  124. } else {
  125. reader = request.Body
  126. }
  127. // Read body
  128. var body []byte
  129. body, err = io.ReadAll(reader)
  130. if err != nil {
  131. hec.test.Fatal(err)
  132. }
  133. // Parse message
  134. messageStart := 0
  135. for i := 0; i < len(body); i++ {
  136. if i == len(body)-1 || (body[i] == '}' && body[i+1] == '{') {
  137. var message splunkMessage
  138. err = json.Unmarshal(body[messageStart:i+1], &message)
  139. if err != nil {
  140. hec.test.Log(string(body[messageStart : i+1]))
  141. hec.test.Fatal(err)
  142. }
  143. hec.messages = append(hec.messages, &message)
  144. messageStart = i + 1
  145. }
  146. }
  147. if gzipEnabled {
  148. gzipReader.Close()
  149. }
  150. writer.WriteHeader(http.StatusOK)
  151. default:
  152. hec.test.Errorf("Unexpected HTTP method %s", http.MethodOptions)
  153. writer.WriteHeader(http.StatusBadRequest)
  154. }
  155. }