splunkhecmock_test.go 4.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182
  1. package splunk
  2. import (
  3. "compress/gzip"
  4. "context"
  5. "encoding/json"
  6. "fmt"
  7. "io"
  8. "io/ioutil"
  9. "net"
  10. "net/http"
  11. "sync"
  12. "testing"
  13. )
  14. func (message *splunkMessage) EventAsString() (string, error) {
  15. if val, ok := message.Event.(string); ok {
  16. return val, nil
  17. }
  18. return "", fmt.Errorf("Cannot cast Event %v to string", message.Event)
  19. }
  20. func (message *splunkMessage) EventAsMap() (map[string]interface{}, error) {
  21. if val, ok := message.Event.(map[string]interface{}); ok {
  22. return val, nil
  23. }
  24. return nil, fmt.Errorf("Cannot cast Event %v to map", message.Event)
  25. }
  26. type HTTPEventCollectorMock struct {
  27. tcpAddr *net.TCPAddr
  28. tcpListener *net.TCPListener
  29. mu sync.Mutex
  30. token string
  31. simulateServerError bool
  32. blockingCtx context.Context
  33. test *testing.T
  34. connectionVerified bool
  35. gzipEnabled *bool
  36. messages []*splunkMessage
  37. numOfRequests int
  38. }
  39. func NewHTTPEventCollectorMock(t *testing.T) *HTTPEventCollectorMock {
  40. tcpAddr := &net.TCPAddr{IP: []byte{127, 0, 0, 1}, Port: 0, Zone: ""}
  41. tcpListener, err := net.ListenTCP("tcp", tcpAddr)
  42. if err != nil {
  43. t.Fatal(err)
  44. }
  45. return &HTTPEventCollectorMock{
  46. tcpAddr: tcpAddr,
  47. tcpListener: tcpListener,
  48. token: "4642492F-D8BD-47F1-A005-0C08AE4657DF",
  49. simulateServerError: false,
  50. test: t,
  51. connectionVerified: false}
  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 = ioutil.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. }