-
Notifications
You must be signed in to change notification settings - Fork 86
Expand file tree
/
Copy pathLambdaClient.php
More file actions
308 lines (253 loc) · 9.27 KB
/
LambdaClient.php
File metadata and controls
308 lines (253 loc) · 9.27 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
<?php
declare(strict_types=1);
/**
* @author Aaron Francis <aarondfrancis@gmail.com|https://twitter.com/aarondfrancis>
*/
namespace Hammerstone\Sidecar\Clients;
use Aws\Lambda\Exception\LambdaException;
use Aws\Lambda\LambdaClient as BaseClient;
use Aws\Middleware;
use Aws\Result;
use Exception;
use Hammerstone\Sidecar\LambdaFunction;
use Hammerstone\Sidecar\Sidecar;
use Illuminate\Support\Arr;
use Illuminate\Support\Str;
class LambdaClient extends BaseClient
{
const CREATED = 1;
const UPDATED = 2;
const NOOP = 3;
public function __construct(array $args)
{
parent::__construct($args);
$this->addPendingRetryMiddleware();
}
/**
* @return string
*/
public function getLatestVersion(LambdaFunction $function)
{
return last($this->getVersions($function))['Version'];
}
/**
* Test whether the latest deployed version is the one that is aliased.
*
* @return bool
*/
public function latestVersionHasAlias(LambdaFunction $function, $alias)
{
$version = $this->getLatestVersion($function);
$aliased = $this->getAliasWithoutException($function, $alias);
return $aliased && $version === Arr::get($aliased, 'FunctionVersion');
}
/**
* @param null|string $marker
* @return Result
*/
public function getVersions(LambdaFunction $function, $marker = null)
{
$result = $this->listVersionsByFunction([
'FunctionName' => $function->nameWithPrefix(),
'MaxItems' => 50,
'Marker' => $marker,
]);
$versions = $result['Versions'];
if ($marker = Arr::get($result, 'NextMarker')) {
$versions = array_merge($versions, $this->getVersions($function, $marker));
}
return $versions;
}
/**
* @param string $alias
* @param string|null $version
* @return int
*/
public function aliasVersion(LambdaFunction $function, $alias, $version = null)
{
$version = $version ?? $this->getLatestVersion($function);
$aliased = $this->getAliasWithoutException($function, $alias);
// The alias already exists and it's the version we were trying to alias anyway.
if ($aliased && $version === Arr::get($aliased, 'FunctionVersion')) {
return self::NOOP;
}
$args = [
'FunctionName' => $function->nameWithPrefix(),
'Name' => $alias,
'FunctionVersion' => $version,
];
if ($aliased) {
$this->updateAlias($args);
return self::UPDATED;
}
$this->createAlias($args);
return self::CREATED;
}
/**
* @return Result|false
*/
public function getAliasWithoutException(LambdaFunction $function, $name)
{
try {
return $this->getAlias([
'FunctionName' => $function->nameWithPrefix(),
'Name' => $name,
]);
} catch (LambdaException $e) {
if ($e->getStatusCode() !== 404) {
throw $e;
}
}
return false;
}
/**
* @return int
*
* @throws Exception
*/
public function updateExistingFunction(LambdaFunction $function)
{
$config = $function->toDeploymentArray();
// Since the code package has a unique name, this checksum
// encompasses both the code and the configuration.
$checksum = substr(md5(json_encode($config)), 0, 8);
// See if the function already exists with these *exact* parameters.
if ($this->functionExists($function, $checksum)) {
return self::NOOP;
}
// Add the checksum to the description, so we can look for it next time.
$config['Description'] .= " [$checksum]";
// For the updateFunctionCode call, AWS requires that the S3Bucket
// and S3Key be top level instead of nested under `Code`.
$code = [
'FunctionName' => $config['FunctionName'],
'Publish' => $config['Publish'],
'Architectures' => $config['Architectures'],
];
if ($function->packageType() === 'Zip') {
$code['S3Bucket'] = $config['Code']['S3Bucket'];
$code['S3Key'] = $config['Code']['S3Key'];
} else {
$code = array_merge($code, $function->package());
}
$config = Arr::except($config, ['Code', 'Publish']);
$this->updateFunctionConfiguration($config);
$this->updateFunctionCode($code);
}
public function updateFunctionVariables(LambdaFunction $function)
{
$variables = $function->variables();
// Makes the checksum hash more stable.
ksort($variables);
// Add a checksum so that we can easily see later if anything has changed.
$variables['SIDECAR_CHECKSUM'] = substr(md5(json_encode($variables)), 0, 8);
/** @var Result $response */
$response = $this->getFunctionConfiguration([
'FunctionName' => $function->nameWithPrefix(),
]);
// If the variables haven't changed at all, don't waste
// time setting them and activating a new version.
if ($variables['SIDECAR_CHECKSUM'] === Arr::get($response, 'Environment.Variables.SIDECAR_CHECKSUM')) {
Sidecar::log('Environment variables unchanged.');
return;
}
Sidecar::log('Updating environment variables.');
$this->updateFunctionConfiguration([
'FunctionName' => $function->nameWithPrefix(),
'Environment' => [
'Variables' => $variables,
],
]);
Sidecar::log('Publishing new version with new environment variables.');
$this->publishVersion([
'FunctionName' => $function->nameWithPrefix(),
]);
}
/**
* Wait until the function is out of the Pending state, so that
* we don't get 409 conflict errors.
*
* @link https://aws.amazon.com/de/blogs/compute/coming-soon-expansion-of-aws-lambda-states-to-all-functions/
* @link https://aws.amazon.com/blogs/compute/tracking-the-state-of-lambda-functions/
* @link https://github.com/hammerstonedev/sidecar/issues/32
* @link https://github.com/aws/aws-sdk-php/blob/master/src/data/lambda/2015-03-31/waiters-2.json
*
* @param LambdaFunction|string $function
*/
public function waitUntilFunctionUpdated($function)
{
if ($function instanceof LambdaFunction) {
$function = $function->nameWithPrefix();
}
if (is_string($function)) {
// Strip off any aliases.
$function = Str::beforeLast($function, ':');
}
return $this->waitUntil('FunctionUpdated', [
'FunctionName' => $function,
]);
}
/**
* Add a middleware that will retry all requests provided the response
* is a 409 Conflict. We have to do this because AWS puts a function
* in a "Pending" state as they propagate the updates everywhere.
*
* @see LambdaClient::waitUntilFunctionUpdated()
*/
protected function addPendingRetryMiddleware()
{
$middleware = Middleware::retry(function ($attempt, $command, $request, $result, $exception) {
// If the request succeeded, the exception will be null.
return $exception instanceof LambdaException
&& $exception->getStatusCode() === 409
&& Str::contains($exception->getAwsErrorMessage(), [
'The function is currently in the following state: Pending',
'is currently in the following state: \'Pending\'',
'An update is in progress for resource: '
])
&& $this->waitUntilFunctionUpdated($command['FunctionName']);
});
// Add the middleware to the stack in the "sign" section.
$this->getHandlerList()->appendSign($middleware);
}
/**
* Delete a particular version of a function.
*
* @param string $version
*/
public function deleteFunctionVersion(LambdaFunction $function, $version)
{
$this->deleteFunction([
'FunctionName' => $function->nameWithPrefix(),
'Qualifier' => $version
]);
}
/**
* @param null $checksum
* @return bool
*/
public function functionExists(LambdaFunction $function, $checksum = null)
{
try {
$response = $this->getFunction([
'FunctionName' => $function->nameWithPrefix(),
]);
} catch (LambdaException $e) {
// If it's a 404, then that means the function doesn't
// exist, which is what we're trying to figure out.
if ($e->getStatusCode() === 404) {
return false;
}
// If it's some other kind of error, we need to bail.
throw $e;
}
// If the checksum is null, then we're checking to see if any
// version of this function exists, not necessarily a
// particular configuration of the function.
if (is_null($checksum)) {
return true;
}
// See if the description contains the checksum.
return Str::contains(Arr::get($response, 'Configuration.Description', ''), $checksum);
}
}