github.com/instana/go-sensor@v1.62.2-0.20240520081010-4919868049e1/integration_test.go (about) 1 // (c) Copyright IBM Corp. 2021 2 // (c) Copyright Instana Inc. 2020 3 4 //go:build integration 5 // +build integration 6 7 package instana_test 8 9 import ( 10 "encoding/json" 11 "fmt" 12 "io/ioutil" 13 "log" 14 "net" 15 "net/http" 16 "os" 17 ) 18 19 type serverlessAgentPluginPayload struct { 20 EntityID string 21 Data map[string]interface{} 22 } 23 24 type serverlessAgentRequest struct { 25 Header http.Header 26 Body []byte 27 } 28 29 type serverlessAgent struct { 30 Bundles []serverlessAgentRequest 31 32 ln net.Listener 33 restoreEnvFn func() 34 } 35 36 func setupServerlessAgent() (*serverlessAgent, error) { 37 ln, err := net.Listen("tcp", "127.0.0.1:0") 38 if err != nil { 39 return nil, fmt.Errorf("failed to initialize the serverless agent listener: %s", err) 40 } 41 42 srv := &serverlessAgent{ 43 ln: ln, 44 restoreEnvFn: restoreEnvVarFunc("INSTANA_ENDPOINT_URL"), 45 } 46 47 mux := http.NewServeMux() 48 mux.HandleFunc("/bundle", srv.HandleBundle) 49 50 go http.Serve(ln, mux) 51 52 os.Setenv("INSTANA_ENDPOINT_URL", "http://"+ln.Addr().String()) 53 54 return srv, nil 55 } 56 57 func (srv *serverlessAgent) HandleBundle(w http.ResponseWriter, req *http.Request) { 58 body, err := ioutil.ReadAll(req.Body) 59 if err != nil { 60 log.Printf("ERROR: failed to read serverless agent spans request body: %s", err) 61 body = nil 62 } 63 64 var root Root 65 err = json.Unmarshal(body, &root) 66 if err != nil { 67 log.Printf("ERROR: failed to unmarshal serverless agent spans request body: %s", err.Error()) 68 } else { 69 if len(root.Spans) > 0 && (root.Spans[0].Data.SDKCustom.Tags.ReturnError == "true" || 70 root.Spans[0].Data.Lambda.ReturnError == "true") { 71 72 w.WriteHeader(http.StatusInternalServerError) 73 return 74 } 75 } 76 77 srv.Bundles = append(srv.Bundles, serverlessAgentRequest{ 78 Header: req.Header, 79 Body: body, 80 }) 81 82 w.WriteHeader(http.StatusNoContent) 83 } 84 85 func (srv *serverlessAgent) Reset() { 86 srv.Bundles = nil 87 } 88 89 func (srv *serverlessAgent) Teardown() { 90 srv.restoreEnvFn() 91 srv.ln.Close() 92 } 93 94 func restoreEnvVarFunc(key string) func() { 95 if oldValue, ok := os.LookupEnv(key); ok { 96 return func() { os.Setenv(key, oldValue) } 97 } 98 99 return func() { os.Unsetenv(key) } 100 } 101 102 type Data struct { 103 SDKCustom struct { 104 Tags struct { 105 ReturnError string `json:"returnError"` 106 } `json:"tags"` 107 } `json:"sdk.custom"` 108 Lambda LambdaData `json:"lambda"` 109 } 110 111 type LambdaData struct { 112 ReturnError string `json:"error"` 113 } 114 115 type Span struct { 116 Data Data `json:"data"` 117 } 118 119 type Root struct { 120 Spans []Span `json:"spans"` 121 }