|
| 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 | + "errors" |
| 9 | + "fmt" |
| 10 | + "io/ioutil" |
| 11 | + "net/http" |
| 12 | + "os" |
| 13 | + "time" |
| 14 | + |
| 15 | + "aws-lambda-extensions/go-example-logs-api-extension/logsapi" |
| 16 | + "github.com/golang-collections/go-datastructures/queue" |
| 17 | +) |
| 18 | + |
| 19 | +// DefaulHttpListenerPort is used to set the URL where the logs will be sent by Logs API |
| 20 | +const DefaulHttpListenerPort = "1234" |
| 21 | + |
| 22 | +// LogsApiHttpListener is used to listen to the Logs API using HTTP |
| 23 | +type LogsApiHttpListener struct { |
| 24 | + httpServer *http.Server |
| 25 | + // logQueue is a synchronous queue and is used to put the received logs to be consumed later (see main) |
| 26 | + logQueue *queue.Queue |
| 27 | +} |
| 28 | + |
| 29 | +// NewLogsApiHttpListener returns a LogsApiHttpListener with the given log queue |
| 30 | +func NewLogsApiHttpListener(lq *queue.Queue) (*LogsApiHttpListener, error) { |
| 31 | + |
| 32 | + return &LogsApiHttpListener{ |
| 33 | + httpServer: nil, |
| 34 | + logQueue: lq, |
| 35 | + }, nil |
| 36 | +} |
| 37 | + |
| 38 | +// Start initiates the server in a goroutine where the logs will be sent |
| 39 | +func (s *LogsApiHttpListener) Start() (bool, error) { |
| 40 | + s.httpServer = &http.Server{Addr: ":" + DefaulHttpListenerPort} |
| 41 | + http.HandleFunc("/", s.http_handler) |
| 42 | + go func() { |
| 43 | + logger.Infof("Serving agent on %s", ":"+DefaulHttpListenerPort) |
| 44 | + err := s.httpServer.ListenAndServe() |
| 45 | + if err != http.ErrServerClosed { |
| 46 | + logger.Errorf("Unexpected stop on Http Server: %v", err) |
| 47 | + s.Shutdown() |
| 48 | + } else { |
| 49 | + logger.Errorf("Http Server closed %v", err) |
| 50 | + } |
| 51 | + }() |
| 52 | + return true, nil |
| 53 | +} |
| 54 | + |
| 55 | +// http_handler handles the requests coming from the Logs API. |
| 56 | +// Everytime Logs API sends logs, this function will read the logs from the response body |
| 57 | +// and put them into a synchronous queue to be read by the main goroutine. |
| 58 | +// Logging or printing besides the error cases below is not recommended if you have subscribed to receive extension logs. |
| 59 | +// Otherwise, logging here will cause Logs API to send new logs for the printed lines which will create an infinite loop. |
| 60 | +func (h *LogsApiHttpListener) http_handler(w http.ResponseWriter, r *http.Request) { |
| 61 | + body, err := ioutil.ReadAll(r.Body) |
| 62 | + if err != nil { |
| 63 | + logger.Errorf("Error reading body: %+v", err) |
| 64 | + return |
| 65 | + } |
| 66 | + |
| 67 | + // Puts the log message into the queue |
| 68 | + err = h.logQueue.Put(string(body)) |
| 69 | + if err != nil { |
| 70 | + logger.Errorf("Can't push logs to destination: %v", err) |
| 71 | + } |
| 72 | +} |
| 73 | + |
| 74 | +// Shutdown terminates the HTTP server listening for logs |
| 75 | +func (s *LogsApiHttpListener) Shutdown() { |
| 76 | + if s.httpServer != nil { |
| 77 | + ctx, _ := context.WithTimeout(context.Background(), 1*time.Second) |
| 78 | + err := s.httpServer.Shutdown(ctx) |
| 79 | + if err != nil { |
| 80 | + logger.Errorf("Failed to shutdown http server gracefully %s", err) |
| 81 | + } else { |
| 82 | + s.httpServer = nil |
| 83 | + } |
| 84 | + } |
| 85 | +} |
| 86 | + |
| 87 | +// HttpAgent has the listener that receives the logs and the logger that handles the received logs |
| 88 | +type HttpAgent struct { |
| 89 | + listener *LogsApiHttpListener |
| 90 | + logger *S3Logger |
| 91 | +} |
| 92 | + |
| 93 | +// NewHttpAgent returns an agent to listen and handle logs coming from Logs API for HTTP |
| 94 | +// Make sure the agent is initialized by calling Init(agentId) before subscription for the Logs API. |
| 95 | +func NewHttpAgent(s3Logger *S3Logger, jq *queue.Queue) (*HttpAgent, error) { |
| 96 | + |
| 97 | + logsApiListener, err := NewLogsApiHttpListener(jq) |
| 98 | + if err != nil { |
| 99 | + return nil, err |
| 100 | + } |
| 101 | + |
| 102 | + return &HttpAgent{ |
| 103 | + logger: s3Logger, |
| 104 | + listener: logsApiListener, |
| 105 | + }, nil |
| 106 | +} |
| 107 | + |
| 108 | +// Init initializes the configuration for the Logs API and subscribes to the Logs API for HTTP |
| 109 | +func (a HttpAgent) Init(agentID string) error { |
| 110 | + extensions_api_address, ok := os.LookupEnv("AWS_LAMBDA_RUNTIME_API") |
| 111 | + if !ok { |
| 112 | + return errors.New("AWS_LAMBDA_RUNTIME_API is not set") |
| 113 | + } |
| 114 | + |
| 115 | + logsApiBaseUrl := fmt.Sprintf("http://%s", extensions_api_address) |
| 116 | + |
| 117 | + logsApiClient, err := logsapi.NewClient(logsApiBaseUrl) |
| 118 | + if err != nil { |
| 119 | + return err |
| 120 | + } |
| 121 | + |
| 122 | + _, err = a.listener.Start() |
| 123 | + if err != nil { |
| 124 | + return err |
| 125 | + } |
| 126 | + |
| 127 | + eventTypes := []logsapi.EventType{logsapi.Platform, logsapi.Function} |
| 128 | + bufferingCfg := logsapi.BufferingCfg{ |
| 129 | + MaxItems: 10000, |
| 130 | + MaxBytes: 262144, |
| 131 | + TimeoutMS: 1000, |
| 132 | + } |
| 133 | + if err != nil { |
| 134 | + return err |
| 135 | + } |
| 136 | + destination := logsapi.Destination{ |
| 137 | + Protocol: logsapi.HttpProto, |
| 138 | + URI: logsapi.URI(fmt.Sprintf("http://sandbox:%s", DefaulHttpListenerPort)), |
| 139 | + HttpMethod: logsapi.HttpPost, |
| 140 | + Encoding: logsapi.JSON, |
| 141 | + } |
| 142 | + |
| 143 | + _, err = logsApiClient.Subscribe(eventTypes, bufferingCfg, destination, agentID) |
| 144 | + return err |
| 145 | +} |
| 146 | + |
| 147 | +// Shutdown finalizes the logging and terminates the listener |
| 148 | +func (a *HttpAgent) Shutdown() { |
| 149 | + err := a.logger.Shutdown() |
| 150 | + if err != nil { |
| 151 | + logger.Errorf("Error when trying to shutdown logger: %v", err) |
| 152 | + } |
| 153 | + |
| 154 | + a.listener.Shutdown() |
| 155 | +} |
0 commit comments