splunkhecmock_test.go 4.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181
  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. func (hec *HTTPEventCollectorMock) simulateErr(b bool) {
  53. hec.mu.Lock()
  54. hec.simulateServerError = b
  55. hec.mu.Unlock()
  56. }
  57. func (hec *HTTPEventCollectorMock) withBlock(ctx context.Context) {
  58. hec.mu.Lock()
  59. hec.blockingCtx = ctx
  60. hec.mu.Unlock()
  61. }
  62. func (hec *HTTPEventCollectorMock) URL() string {
  63. return "http://" + hec.tcpListener.Addr().String()
  64. }
  65. func (hec *HTTPEventCollectorMock) Serve() error {
  66. return http.Serve(hec.tcpListener, hec)
  67. }
  68. func (hec *HTTPEventCollectorMock) Close() error {
  69. return hec.tcpListener.Close()
  70. }
  71. func (hec *HTTPEventCollectorMock) ServeHTTP(writer http.ResponseWriter, request *http.Request) {
  72. var err error
  73. hec.numOfRequests++
  74. hec.mu.Lock()
  75. simErr := hec.simulateServerError
  76. ctx := hec.blockingCtx
  77. hec.mu.Unlock()
  78. if ctx != nil {
  79. <-hec.blockingCtx.Done()
  80. }
  81. if simErr {
  82. if request.Body != nil {
  83. defer request.Body.Close()
  84. }
  85. writer.WriteHeader(http.StatusInternalServerError)
  86. return
  87. }
  88. switch request.Method {
  89. case http.MethodOptions:
  90. // Verify that options method is getting called only once
  91. if hec.connectionVerified {
  92. hec.test.Errorf("Connection should not be verified more than once. Got second request with %s method.", request.Method)
  93. }
  94. hec.connectionVerified = true
  95. writer.WriteHeader(http.StatusOK)
  96. case http.MethodPost:
  97. // Always verify that Driver is using correct path to HEC
  98. if request.URL.String() != "/services/collector/event/1.0" {
  99. hec.test.Errorf("Unexpected path %v", request.URL)
  100. }
  101. defer request.Body.Close()
  102. if authorization, ok := request.Header["Authorization"]; !ok || authorization[0] != ("Splunk "+hec.token) {
  103. hec.test.Error("Authorization header is invalid.")
  104. }
  105. gzipEnabled := false
  106. if contentEncoding, ok := request.Header["Content-Encoding"]; ok && contentEncoding[0] == "gzip" {
  107. gzipEnabled = true
  108. }
  109. if hec.gzipEnabled == nil {
  110. hec.gzipEnabled = &gzipEnabled
  111. } else if gzipEnabled != *hec.gzipEnabled {
  112. // Nothing wrong with that, but we just know that Splunk Logging Driver does not do that
  113. hec.test.Error("Driver should not change Content Encoding.")
  114. }
  115. var gzipReader *gzip.Reader
  116. var reader io.Reader
  117. if gzipEnabled {
  118. gzipReader, err = gzip.NewReader(request.Body)
  119. if err != nil {
  120. hec.test.Fatal(err)
  121. }
  122. reader = gzipReader
  123. } else {
  124. reader = request.Body
  125. }
  126. // Read body
  127. var body []byte
  128. body, err = io.ReadAll(reader)
  129. if err != nil {
  130. hec.test.Fatal(err)
  131. }
  132. // Parse message
  133. messageStart := 0
  134. for i := 0; i < len(body); i++ {
  135. if i == len(body)-1 || (body[i] == '}' && body[i+1] == '{') {
  136. var message splunkMessage
  137. err = json.Unmarshal(body[messageStart:i+1], &message)
  138. if err != nil {
  139. hec.test.Log(string(body[messageStart : i+1]))
  140. hec.test.Fatal(err)
  141. }
  142. hec.messages = append(hec.messages, &message)
  143. messageStart = i + 1
  144. }
  145. }
  146. if gzipEnabled {
  147. gzipReader.Close()
  148. }
  149. writer.WriteHeader(http.StatusOK)
  150. default:
  151. hec.test.Errorf("Unexpected HTTP method %s", http.MethodOptions)
  152. writer.WriteHeader(http.StatusBadRequest)
  153. }
  154. }