-
Notifications
You must be signed in to change notification settings - Fork 574
Expand file tree
/
Copy pathAwsSpringWebCustomRuntimeEventLoop.java
More file actions
186 lines (160 loc) · 7.02 KB
/
AwsSpringWebCustomRuntimeEventLoop.java
File metadata and controls
186 lines (160 loc) · 7.02 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
/*
* Copyright 2024-2024 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.amazonaws.serverless.proxy.spring;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.net.URI;
import java.text.MessageFormat;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.boot.web.server.servlet.context.ServletWebServerApplicationContext;
import org.springframework.cloud.function.serverless.web.ServerlessMVC;
import org.springframework.context.SmartLifecycle;
import org.springframework.core.env.Environment;
import org.springframework.http.RequestEntity;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestTemplate;
import com.amazonaws.serverless.proxy.internal.servlet.AwsProxyHttpServletResponseWriter;
import com.amazonaws.serverless.proxy.model.AwsProxyResponse;
import jakarta.servlet.http.HttpServletRequest;
import tools.jackson.databind.ObjectMapper;
import tools.jackson.databind.SerializationFeature;
import tools.jackson.databind.json.JsonMapper;
/**
* Event loop and necessary configurations to support AWS Lambda Custom Runtime
* - https://docs.aws.amazon.com/lambda/latest/dg/runtimes-custom.html.
*
* @author Oleg Zhurakousky
* @author Mark Sailes
*
*/
public final class AwsSpringWebCustomRuntimeEventLoop implements SmartLifecycle {
private static Log logger = LogFactory.getLog(AwsSpringWebCustomRuntimeEventLoop.class);
static final String LAMBDA_VERSION_DATE = "2018-06-01";
private static final String LAMBDA_ERROR_URL_TEMPLATE = "http://{0}/{1}/runtime/invocation/{2}/error";
private static final String LAMBDA_RUNTIME_URL_TEMPLATE = "http://{0}/{1}/runtime/invocation/next";
private static final String LAMBDA_INVOCATION_URL_TEMPLATE = "http://{0}/{1}/runtime/invocation/{2}/response";
private static final String USER_AGENT_VALUE = String.format("spring-cloud-function/%s-%s",
System.getProperty("java.runtime.version"), AwsSpringHttpProcessingUtils.extractVersion());
private final ServletWebServerApplicationContext applicationContext;
private volatile boolean running;
private final ExecutorService executor = Executors.newSingleThreadExecutor();
public AwsSpringWebCustomRuntimeEventLoop(ServletWebServerApplicationContext applicationContext) {
this.applicationContext = applicationContext;
}
public void run() {
this.running = true;
this.executor.execute(() -> {
eventLoop(this.applicationContext);
});
}
@Override
public void start() {
this.run();
}
@Override
public void stop() {
this.executor.shutdownNow();
this.running = false;
}
@Override
public boolean isRunning() {
return this.running;
}
private void eventLoop(ServletWebServerApplicationContext context) {
ServerlessMVC mvc = ServerlessMVC.INSTANCE(context);
Environment environment = context.getEnvironment();
logger.info("Starting AWSWebRuntimeEventLoop");
String runtimeApi = environment.getProperty("AWS_LAMBDA_RUNTIME_API");
String eventUri = MessageFormat.format(LAMBDA_RUNTIME_URL_TEMPLATE, runtimeApi, LAMBDA_VERSION_DATE);
if (logger.isDebugEnabled()) {
logger.debug("Event URI: " + eventUri);
}
RequestEntity<Void> requestEntity = RequestEntity.get(URI.create(eventUri))
.header("User-Agent", USER_AGENT_VALUE).build();
RestTemplate rest = new RestTemplate();
ObjectMapper mapper = JsonMapper.builder()
.disable(SerializationFeature.FAIL_ON_EMPTY_BEANS)
.build();
AwsProxyHttpServletResponseWriter responseWriter = new AwsProxyHttpServletResponseWriter();
logger.info("Entering event loop");
while (this.isRunning()) {
logger.debug("Attempting to get new event");
ResponseEntity<String> incomingEvent = rest.exchange(requestEntity, String.class);
if (incomingEvent != null && incomingEvent.hasBody()) {
if (logger.isDebugEnabled()) {
logger.debug("New Event received from AWS Gateway: " + incomingEvent.getBody());
}
String requestId = incomingEvent.getHeaders().getFirst("Lambda-Runtime-Aws-Request-Id");
try {
logger.debug("Submitting request to the user's web application");
HttpServletRequest httpServletRequest = AwsSpringHttpProcessingUtils.generateHttpServletRequest(
incomingEvent.getBody(), null, mvc.getServletContext(), mapper);
AwsProxyResponse awsResponse = AwsSpringHttpProcessingUtils.processRequest(
httpServletRequest, mvc, responseWriter);
if (logger.isDebugEnabled()) {
logger.debug("Received response - body: " + awsResponse.getBody() +
"; status: " + awsResponse.getStatusCode() + "; headers: " + awsResponse.getHeaders());
}
String invocationUrl = MessageFormat.format(LAMBDA_INVOCATION_URL_TEMPLATE, runtimeApi,
LAMBDA_VERSION_DATE, requestId);
ResponseEntity<byte[]> result = rest.exchange(RequestEntity.post(URI.create(invocationUrl))
.header("User-Agent", USER_AGENT_VALUE).body(awsResponse), byte[].class);
if (logger.isDebugEnabled()) {
logger.debug("Response sent: body: " + result.getBody() +
"; status: " + result.getStatusCode() + "; headers: " + result.getHeaders());
}
if (logger.isInfoEnabled()) {
logger.info("Result POST status: " + result);
}
}
catch (Exception e) {
logger.error(e);
this.propagateAwsError(requestId, e, mapper, runtimeApi, rest);
}
}
}
}
private void propagateAwsError(String requestId, Exception e, ObjectMapper mapper, String runtimeApi, RestTemplate rest) {
String errorMessage = e.getMessage();
String errorType = e.getClass().getSimpleName();
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
e.printStackTrace(pw);
String stackTrace = sw.toString();
Map<String, String> em = new HashMap<>();
em.put("errorMessage", errorMessage);
em.put("errorType", errorType);
em.put("stackTrace", stackTrace);
try {
byte[] outputBody = mapper.writeValueAsBytes(em);
String errorUrl = MessageFormat.format(LAMBDA_ERROR_URL_TEMPLATE, runtimeApi, LAMBDA_VERSION_DATE, requestId);
ResponseEntity<Object> result = rest.exchange(RequestEntity.post(URI.create(errorUrl))
.header("User-Agent", USER_AGENT_VALUE)
.body(outputBody), Object.class);
if (logger.isInfoEnabled()) {
logger.info("Result ERROR status: " + result.getStatusCode());
}
}
catch (Exception e2) {
throw new IllegalArgumentException("Failed to report error", e2);
}
}
}