|
| 1 | +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. |
| 2 | +// SPDX-License-Identifier: MIT-0 |
| 3 | + |
| 4 | +package agent |
| 5 | + |
| 6 | +import ( |
| 7 | + "context" |
| 8 | + "encoding/json" |
| 9 | + "errors" |
| 10 | + "fmt" |
| 11 | + "io/ioutil" |
| 12 | + "net/http" |
| 13 | + "os" |
| 14 | + "time" |
| 15 | + |
| 16 | + "aws-lambda-extensions/go-example-adaptive-batching-extension/logsapi" |
| 17 | + "aws-lambda-extensions/go-example-adaptive-batching-extension/queuewrapper" |
| 18 | + log "github.com/sirupsen/logrus" |
| 19 | +) |
| 20 | + |
| 21 | +var httpLogger = log.WithFields(log.Fields{"agent": "httpAgent"}) |
| 22 | + |
| 23 | +// DefaultHttpListenerPort is used to set the URL where the logs will be sent by Logs API |
| 24 | +const DefaultHttpListenerPort = "1234" |
| 25 | + |
| 26 | +// LogsApiHttpListener is used to listen to the Logs API using HTTP |
| 27 | +type LogsApiHttpListener struct { |
| 28 | + httpServer *http.Server |
| 29 | + // logQueue is a synchronous queue and is used to put the received logs to be consumed later (see main) |
| 30 | + logQueue *queuewrapper.QueueWrapper |
| 31 | +} |
| 32 | + |
| 33 | +// NewLogsApiHttpListener returns a LogsApiHttpListener with the given log queue |
| 34 | +func NewLogsApiHttpListener(lq *queuewrapper.QueueWrapper) (*LogsApiHttpListener, error) { |
| 35 | + |
| 36 | + return &LogsApiHttpListener{ |
| 37 | + httpServer: nil, |
| 38 | + logQueue: lq, |
| 39 | + }, nil |
| 40 | +} |
| 41 | + |
| 42 | +func ListenOnAddress() string { |
| 43 | + env_aws_local, ok := os.LookupEnv("AWS_SAM_LOCAL") |
| 44 | + if ok && "true" == env_aws_local { |
| 45 | + return ":" + DefaultHttpListenerPort |
| 46 | + } |
| 47 | + |
| 48 | + return "sandbox.localdomain:" + DefaultHttpListenerPort |
| 49 | +} |
| 50 | + |
| 51 | +// Start initiates the server in a goroutine where the logs will be sent |
| 52 | +func (s *LogsApiHttpListener) Start() (bool, error) { |
| 53 | + address := ListenOnAddress() |
| 54 | + s.httpServer = &http.Server{Addr: address} |
| 55 | + http.HandleFunc("/", s.http_handler) |
| 56 | + go func() { |
| 57 | + logger.Infof("Serving agent on %s", address) |
| 58 | + err := s.httpServer.ListenAndServe() |
| 59 | + if err != http.ErrServerClosed { |
| 60 | + logger.Errorf("Unexpected stop on Http Server: %v", err) |
| 61 | + s.Shutdown() |
| 62 | + } else { |
| 63 | + logger.Errorf("Http Server closed %v", err) |
| 64 | + } |
| 65 | + }() |
| 66 | + return true, nil |
| 67 | +} |
| 68 | + |
| 69 | +// http_handler handles the requests coming from the Logs API. |
| 70 | +// Everytime Logs API sends logs, this function will read the logs from the response body |
| 71 | +// and put them into a synchronous queue to be read by the main goroutine. |
| 72 | +// Logging or printing besides the error cases below is not recommended if you have subscribed to receive extension logs. |
| 73 | +// Otherwise, logging here will cause Logs API to send new logs for the printed lines which will create an infinite loop. |
| 74 | +func (h *LogsApiHttpListener) http_handler(w http.ResponseWriter, r *http.Request) { |
| 75 | + body, err := ioutil.ReadAll(r.Body) |
| 76 | + if err != nil { |
| 77 | + logger.Errorf("Error reading body: %+v", err) |
| 78 | + return |
| 79 | + } |
| 80 | + |
| 81 | + //fmt.Println("Logs API event received:", string(body)) |
| 82 | + |
| 83 | + // Puts the log message into the queue |
| 84 | + err = h.logQueue.Put(string(body)) |
| 85 | + if err != nil { |
| 86 | + logger.Errorf("Can't push logs to destination: %v", err) |
| 87 | + } |
| 88 | +} |
| 89 | + |
| 90 | +// Shutdown terminates the HTTP server listening for logs |
| 91 | +func (s *LogsApiHttpListener) Shutdown() { |
| 92 | + if s.httpServer != nil { |
| 93 | + ctx, _ := context.WithTimeout(context.Background(), 1*time.Second) |
| 94 | + err := s.httpServer.Shutdown(ctx) |
| 95 | + if err != nil { |
| 96 | + logger.Errorf("Failed to shutdown http server gracefully %s", err) |
| 97 | + } else { |
| 98 | + s.httpServer = nil |
| 99 | + } |
| 100 | + } |
| 101 | +} |
| 102 | + |
| 103 | +// HttpAgent has the listener that receives the logs and the logger that handles the received logs |
| 104 | +type HttpAgent struct { |
| 105 | + listener *LogsApiHttpListener |
| 106 | + logger *S3Logger |
| 107 | +} |
| 108 | + |
| 109 | +// NewHttpAgent returns an agent to listen and handle logs coming from Logs API for HTTP |
| 110 | +// Make sure the agent is initialized by calling Init(agentId) before subscription for the Logs API. |
| 111 | +func NewHttpAgent(s3Logger *S3Logger, jq *queuewrapper.QueueWrapper) (*HttpAgent, error) { |
| 112 | + |
| 113 | + logsApiListener, err := NewLogsApiHttpListener(jq) |
| 114 | + if err != nil { |
| 115 | + return nil, err |
| 116 | + } |
| 117 | + |
| 118 | + return &HttpAgent{ |
| 119 | + logger: s3Logger, |
| 120 | + listener: logsApiListener, |
| 121 | + }, nil |
| 122 | +} |
| 123 | + |
| 124 | +// Init initializes the configuration for the Logs API and subscribes to the Logs API for HTTP |
| 125 | +func (a HttpAgent) Init(agentID string) error { |
| 126 | + extensions_api_address, ok := os.LookupEnv("AWS_LAMBDA_RUNTIME_API") |
| 127 | + if !ok { |
| 128 | + return errors.New("AWS_LAMBDA_RUNTIME_API is not set") |
| 129 | + } |
| 130 | + |
| 131 | + logsApiBaseUrl := fmt.Sprintf("http://%s", extensions_api_address) |
| 132 | + |
| 133 | + logsApiClient, err := logsapi.NewClient(logsApiBaseUrl) |
| 134 | + if err != nil { |
| 135 | + return err |
| 136 | + } |
| 137 | + |
| 138 | + _, err = a.listener.Start() |
| 139 | + if err != nil { |
| 140 | + return err |
| 141 | + } |
| 142 | + |
| 143 | + // Read environment variable ADAPTIVE_BATCHING_EXTENSION_LOG_TYPES |
| 144 | + inputJson := os.Getenv("ADAPTIVE_BATCHING_EXTENSION_LOG_TYPES") |
| 145 | + inputJsonBytes := []byte(inputJson) |
| 146 | + |
| 147 | + var eventTypes []logsapi.EventType |
| 148 | + |
| 149 | + // No Json included |
| 150 | + if inputJson == "" { |
| 151 | + // Hold defaults |
| 152 | + eventTypes = append(eventTypes, logsapi.Platform, logsapi.Function) |
| 153 | + httpLogger.Info("ADAPTIVE_BATCHING_EXTENSION_LOG_TYPES not included, subscribing to default log types") |
| 154 | + } else if !json.Valid(inputJsonBytes) { |
| 155 | + // Invalid JSON provided |
| 156 | + eventTypes = append(eventTypes, logsapi.Platform, logsapi.Function) |
| 157 | + httpLogger.Info("ADAPTIVE_BATCHING_EXTENSION_LOG_TYPES includes invalid JSON, subscribing to default log types") |
| 158 | + } else { |
| 159 | + |
| 160 | + // Unmarshal json into structure |
| 161 | + var jsonArray []logsapi.EventType |
| 162 | + |
| 163 | + err = json.Unmarshal(inputJsonBytes, &jsonArray) |
| 164 | + if err != nil { |
| 165 | + // Error unmarshaling json |
| 166 | + eventTypes = append(eventTypes, logsapi.Platform, logsapi.Function) |
| 167 | + httpLogger.Info("Unable to unmarshal json from ADAPTIVE_BATCHING_EXTENSION_LOG_TYPES, subscribing to default log types") |
| 168 | + } |
| 169 | + |
| 170 | + // If array is empty, use default values |
| 171 | + if len(jsonArray) == 0 { |
| 172 | + eventTypes = append(eventTypes, logsapi.Platform, logsapi.Function) |
| 173 | + httpLogger.Info("LogTypes in ADAPTIVE_BATCHING_EXTENSION_LOG_TYPES does not include any elements, subscribing to default log types") |
| 174 | + } |
| 175 | + |
| 176 | + // loop through elements, and check if required elements are included |
| 177 | + |
| 178 | + for _, logType := range jsonArray { |
| 179 | + switch logType { |
| 180 | + case logsapi.Platform: |
| 181 | + eventTypes = append(eventTypes, logsapi.Platform) |
| 182 | + case logsapi.Function: |
| 183 | + eventTypes = append(eventTypes, logsapi.Function) |
| 184 | + case logsapi.Extension: |
| 185 | + eventTypes = append(eventTypes, logsapi.Extension) |
| 186 | + default: |
| 187 | + httpLogger.Info("Log type ", logType, " is not valid. Not including") |
| 188 | + } |
| 189 | + } |
| 190 | + |
| 191 | + } |
| 192 | + |
| 193 | + bufferingCfg := logsapi.BufferingCfg{ |
| 194 | + MaxItems: 1000, |
| 195 | + MaxBytes: 262144, |
| 196 | + TimeoutMS: 25, |
| 197 | + } |
| 198 | + if err != nil { |
| 199 | + return err |
| 200 | + } |
| 201 | + destination := logsapi.Destination{ |
| 202 | + Protocol: logsapi.HttpProto, |
| 203 | + URI: logsapi.URI(fmt.Sprintf("http://sandbox.localdomain:%s", DefaultHttpListenerPort)), |
| 204 | + HttpMethod: logsapi.HttpPost, |
| 205 | + Encoding: logsapi.JSON, |
| 206 | + } |
| 207 | + |
| 208 | + _, err = logsApiClient.Subscribe(eventTypes, bufferingCfg, destination, agentID) |
| 209 | + return err |
| 210 | +} |
| 211 | + |
| 212 | +// Shutdown finalizes the logging and terminates the listener |
| 213 | +func (a *HttpAgent) Shutdown() { |
| 214 | + err := a.logger.Shutdown() |
| 215 | + if err != nil { |
| 216 | + logger.Errorf("Error when trying to shutdown logger: %v", err) |
| 217 | + } |
| 218 | + |
| 219 | + a.listener.Shutdown() |
| 220 | +} |
0 commit comments