splunkhecmock_test.go 3.9 KB

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