-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathbootstrap
More file actions
379 lines (379 loc) · 11.8 KB
/
Copy pathbootstrap
File metadata and controls
379 lines (379 loc) · 11.8 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
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
#!/opt/php/bin/php
<?php
ini_set('display_errors', '1');
error_reporting(E_ALL);
$bootstrap = new CLIBootstrap();
require_once $bootstrap->taskPath;
while (true) {
try {
$bootstrap->handleInvocation();
} catch (Exception $e) {
CLIBootstrap::consoleLog($e->getMessage());
CLIBootstrap::consoleLog($e->getTraceAsString());
exit(1);
}
}
/**
* Class CLIBootstrap
* All about managing that Lambda bootstrap
*/
class CLIBootstrap
{
/**
* The path to the user file entrypoint.
* @var string
*/
public $taskPath;
/**
* The name of the Lambda function itself.
* @var string
*/
private $lambdaFunction;
/**
* AWS Runtime Version we are using.
* @var string
*/
private $rumtimeAPI;
/**
* The invocation ID of the event being processed.
* @var string
*/
private $requestId;
/**
* The body of the invocation, the event.
* @var string
*/
private $requestBody;
/**
* A cURL handle for retrieving the next task.
* @var resource
*/
private $next;
/**
* A cURL handle for reporting errors.
* @var resource
*/
private $error;
/**
* A cURL handle for reporting results.
* @var resource
*/
private $result;
/**
* A place to store a lot of context information.
* @var array
*/
private $context;
/**
* CLIBootstrap constructor.
* Handle all the initialization here. This is where all the "cold start"
* logic should be.
*/
public function __construct()
{
self::consoleLog('Cold Start');
list($lambdaFileName, $lambdaFunction) = explode('.', getenv('_HANDLER'));
$this->taskPath = sprintf('%s/%s.php', getenv('LAMBDA_TASK_ROOT'), $lambdaFileName);
$this->rumtimeAPI = (string)getenv('AWS_LAMBDA_RUNTIME_API');
$this->lambdaFunction = $lambdaFunction;
$this->initInvocationFetcher();
$this->initInvocationError();
}
/**
* Helper function to template writing to the console from
* the bootstrap.
* @param String $message
*/
public static function consoleLog(String $message): void
{
echo $message . PHP_EOL;
}
/**
* Initialize the cURL handle for getting the next task.
*/
protected function initInvocationFetcher(): void
{
$this->next = curl_init(sprintf('http://%s/2018-06-01/runtime/invocation/next', $this->rumtimeAPI));
curl_setopt($this->next, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($this->next, CURLOPT_FAILONERROR, true);
curl_setopt($this->next, CURLOPT_HEADERFUNCTION, [$this, 'writeHeader']);
curl_setopt($this->next, CURLOPT_WRITEFUNCTION, [$this, 'writeData']);
}
/**
* Initialize the cURL handle for reporting errors.
*/
protected function initInvocationError(): void
{
$this->error = curl_init();
curl_setopt($this->error, CURLOPT_CUSTOMREQUEST, 'POST');
curl_setopt($this->error, CURLOPT_RETURNTRANSFER, true);
}
/**
* Initialize the cURL handle for reporting results.
*/
protected function initInvocationResult(): void
{
$this->result = curl_init();
curl_setopt($this->result, CURLOPT_CUSTOMREQUEST, 'POST');
curl_setopt($this->result, CURLOPT_RETURNTRANSFER, true);
}
/**
* Handles fetching the next task;
* @return array
*/
public function getNextTask(): void
{
// Politely ask cURL to fetch
curl_exec($this->next);
// Check for any errors while fetching.
if (curl_error($this->next)) {
self::consoleLog('Failed to fetch next Lambda invocation: ' . curl_error($this->next));
throw new RuntimeException(curl_error($this->next));
}
// Check to ensure that we figured out what the Invocation ID is.
if (empty($this->requestId)) {
self::consoleLog('Failed to determine Lambda invocation ID');
throw new RuntimeException('Failed to determine Lambda invocation ID');
} else {
curl_setopt($this->error, CURLOPT_URL,
sprintf('http://%s/2018-06-01/runtime/invocation/%s/response',
$this->rumtimeAPI, $this->requestId));
}
// We also need the invocation body, which is where the actual event is.
if (empty($this->requestBody)) {
self::consoleLog('Empty Event');
$response = [
"statusCode" => 500,
"message" => "An empty event was received",
"errorType" => "InvalidEvent",
"requestId" => $this->requestId
];
$response_json = json_encode($response);
curl_setopt($this->error, CURLOPT_POSTFIELDS, $response_json);
curl_setopt($this->error, CURLOPT_HTTPHEADER, [
'Content-Type: application/json',
'Content-Length: ' . strlen($response_json),
]);
curl_exec($this->error);
throw new RuntimeException('Failed to determine Lambda invocation ID');
}
}
public function executeLambda(): void
{
try {
$store = new Threaded();
$thread = new LambdaRunner($store, $this->lambdaFunction, $this->requestBody, json_encode($this->context));
$thread->start() && $thread->join();
} catch (Exception $e) {
self::consoleLog('ERROR: ' . $e->getMessage());
$response = [
"statusCode" => 500,
"message" => $e->getMessage(),
"errorType" => "FailedFunction",
"requestId" => $this->requestId
];
$response_json = json_encode($response);
curl_setopt($this->error, CURLOPT_POSTFIELDS, $response_json);
curl_setopt($this->error, CURLOPT_HTTPHEADER, [
'Content-Type: application/json',
'Content-Length: ' . strlen($response_json),
]);
curl_exec($this->error);
throw new RuntimeException('Failed to execute the Lambda Function.');
}
$this->reportResult($store[0]);
}
/**
* Send the result of the lambda back.
* @param $response
*/
public function reportResult(array $response): void
{
self::consoleLog('reportResult');
// Initialize a new cURL resource for reporting.
$this->initInvocationResult();
// If we have a body, it needs to be encoded within the response.
if (array_key_exists('body', $response)) {
$response['body'] = json_encode($response['body']);
}
// Now we can encode everything.
$response_json = json_encode($response);
// Set up curl
curl_setopt($this->result, CURLOPT_URL,
sprintf('http://%s/2018-06-01/runtime/invocation/%s/response',
$this->rumtimeAPI, $this->requestId));
curl_setopt($this->result, CURLOPT_POSTFIELDS, $response_json);
curl_setopt($this->result, CURLOPT_HTTPHEADER, [
'Content-Type: application/json',
'Content-Length: ' . strlen($response_json),
]);
// Send the results
curl_exec($this->result);
// Check for any errors while sending.
if (curl_error($this->result)) {
self::consoleLog('Failed to report lambda results: ' . curl_error($this->result));
throw new RuntimeException(curl_error($this->result));
}
}
/**
* Callback for processing headers when getting a new task.
*
* @param cURL $ch
* @param String $header
* @return int
*/
protected function writeHeader($ch, String $header): int
{
$headerLength = strlen($header);
if (!preg_match('/:\s*/', $header)) {
return $headerLength;
}
[$name, $value] = preg_split('/:\s*/', $header, 2);
$this->context[trim($name)] = trim($value);
if (strtolower($name) == 'lambda-runtime-aws-request-id') {
$this->requestId = trim($value);
}
return $headerLength;
}
/**
* Callback for handling the response body of the get new task.
*
* @param cURL $ch
* @param String $chunk
* @return int
*/
protected function writeData($ch, String $chunk): int
{
$this->requestBody .= $chunk;
return strlen($chunk);
}
/**
* Ensures we start every task with no data from
* the last task.
*/
protected function clearTaskParams(): void
{
$this->requestId = '';
$this->requestBody = '';
$this->context = [];
}
/**
* This is where the magic happens.
*/
public function handleInvocation(): void
{
self::consoleLog('handleInvocation');
// Reset all our task specific variables.
$this->clearTaskParams();
try {
$this->getNextTask();
} catch (Exception $e) {
self::consoleLog('No task, or other error');
// An exception here simply trigger a return.
return;
}
// Execute the users lambda.
$this->executeLambda();
}
}
class LambdaRunner extends Thread
{
/**
* The function to call
* @var callable
*/
private $method;
/**
* Any parameters for the object
* @var array|mixed[]
*/
private $params;
/**
* Results from the function
* @var mixed
*/
private $store;
/**
* Whether the thread has joined or not.
* @var bool
*/
private $joined;
/**
* Caller constructor
*
* Provide a passthrough to call_user_func_array
*
* @param Threaded $store
* @param callable $method
* @param mixed ...$params
*/
public function __construct(Threaded $store, callable $method, ...$params)
{
$this->method = $method;
$this->params = $params;
$this->store = $store;
$this->joined = false;
}
/**
* Run the function and catch the results.
* This is where the thread magic happens,
* anything done here, is completely separate
* from our main thread.
**/
public function run(): void
{
/*
The following array cast is necessary to prevent implicit coercion to a
Volatile object. Without it, accessing $store in the main thread after
this thread has been destroyed would lead to RuntimeException of:
"pthreads detected an attempt to connect to an object which has already
been destroyed in %s:%d"
See this StackOverflow post for additional information:
https://stackoverflow.com/a/44852650/4530326
*/
$this->store[] = (array)($this->method)(...$this->params);
}
/**
* Static method to create our threads
* @param Threaded $store
* @param callable $method
* @param mixed ...$params
* @return LambdaRunner
*/
public static function call(Threaded $store, $method, ...$params): LambdaRunner
{
$thread = new LambdaRunner($store, $method, ...$params);
if ($thread->start()) {
return $thread;
}
}
/**
* Causes the calling context to wait for the referenced Thread to finish executing
* @link http://www.php.net/manual/en/thread.join.php
* @return boolean <p>A boolean indication of success</p>
*/
public function join(): void
{
// Make certain we do not attempt to join twice.
if (!$this->joined) {
$this->joined = true;
parent::join();
}
}
/**
* Fetch the results.
* @return string
*/
public function getStore()
{
$this->join();
return $this->store;
}
/**
* Ensure we are joined, and then return the result.
**/
public function __toString(): string
{
return print_r($this->store, true);
}
}