forked from brefphp/bref
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbref
executable file
·423 lines (360 loc) · 14.5 KB
/
bref
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
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
#!/usr/bin/env php
<?php
declare(strict_types=1);
use Aws\CloudFormation\CloudFormationClient;
use Aws\CloudFormation\Exception\CloudFormationException;
use Bref\Console\LoadingAnimation;
use Bref\Console\OpenUrl;
use Bref\Lambda\InvocationFailed;
use Bref\Lambda\SimpleLambdaClient;
use Symfony\Component\Console\Style\SymfonyStyle;
use Symfony\Component\Filesystem\Filesystem;
use Symfony\Component\Process\ExecutableFinder;
use Symfony\Component\Process\Process;
if (file_exists(__DIR__ . '/vendor/autoload.php')) {
require_once __DIR__ . '/vendor/autoload.php';
} elseif (file_exists(__DIR__ . '/../autoload.php')) {
/** @noinspection PhpIncludeInspection */
require_once __DIR__ . '/../autoload.php';
} else {
/** @noinspection PhpIncludeInspection */
require_once __DIR__ . '/../../autoload.php';
}
$app = new Silly\Application('Deploy serverless PHP applications');
$app->command('init', function (SymfonyStyle $io) {
$exeFinder = new ExecutableFinder();
if (! $exeFinder->find('serverless')) {
$io->error(
'The `serverless` command is not installed.' . PHP_EOL .
'Please follow the instructions at https://bref.sh/docs/installation.html'
);
return 1;
}
if (file_exists('serverless.yml') || file_exists('index.php')) {
$io->error('The directory already contains a `serverless.yml` and/or `index.php` file.');
return 1;
}
$choice = $io->choice(
'What kind of lambda do you want to create? (you will be able to add more functions later by editing `serverless.yml`)',
[
'PHP function',
'HTTP application',
'Console application',
],
'PHP function'
);
$templateDirectory = [
'PHP function' => 'default',
'HTTP application' => 'http',
'Console application' => 'console',
][$choice];
$fs = new Filesystem;
$rootPath = __DIR__ . "/template/$templateDirectory";
$filesToGitAdd = [];
foreach (scandir($rootPath, SCANDIR_SORT_NONE) as $file) {
if (in_array($file, ['.', '..'])) {
continue;
}
$io->writeln("Creating $file");
$fs->copy("$rootPath/$file", $file);
$filesToGitAdd[] = $file;
}
/*
* We check if this is a git repository to automatically add files to git.
*/
if ((new Process(['git', 'rev-parse', '--is-inside-work-tree']))->run() === 0) {
foreach ($filesToGitAdd as $file) {
(new Process(['git', 'add', $file]))->run();
}
$io->success([
'Project initialized and ready to test or deploy.',
'The files created were automatically added to git.',
]);
} else {
$io->success('Project initialized and ready to test or deploy.');
}
return 0;
});
/**
* Run a CLI command in the remote environment.
*/
$app->command('cli function [--region=] [arguments]*', function (string $function, ?string $region, array $arguments, SymfonyStyle $io) {
$lambda = new SimpleLambdaClient(($region ?: getenv('AWS_DEFAULT_REGION')) ?: 'us-east-1');
// Because arguments may contain spaces, and are going to be executed remotely
// as a separate process, we need to escape all arguments.
$arguments = array_map(static function (string $arg): string {
return escapeshellarg($arg);
}, $arguments);
try {
$result = $lambda->invoke($function, json_encode([
'cli' => implode(' ', $arguments),
]));
} catch (InvocationFailed $e) {
$io->getErrorStyle()->writeln('<info>' . $e->getInvocationLogs() . '</info>');
$io->error($e->getMessage());
return 1;
}
$payload = $result->getPayload();
if (isset($payload['output'])) {
$io->writeln($payload['output']);
} else {
$io->error('The command did not return a valid response.');
$io->writeln('<info>Logs:</info>');
$io->write('<comment>' . $result->getLogs() . '</comment>');
$io->writeln('<info>Lambda result payload:</info>');
$io->writeln(json_encode($payload, JSON_PRETTY_PRINT));
return 1;
}
return (int) ($payload['exitCode'] ?? 1);
});
$app->command('invoke function [--region=] [-e|--event=]', function (string $function, ?string $region, ?string $event, SymfonyStyle $io) {
$io->warning([
'The `bref invoke` command is deprecated in favor of the `serverless invoke` command.',
'Run `serverless invoke --help` to learn how to use it, or read the documentation here: https://bref.sh/docs/runtimes/function.html#cli',
]);
$lambda = new SimpleLambdaClient(($region ?: getenv('AWS_DEFAULT_REGION')) ?: 'us-east-1');
try {
$result = $lambda->invoke($function, $event);
} catch (InvocationFailed $e) {
$io->getErrorStyle()->writeln('<info>' . $e->getInvocationLogs() . '</info>');
$io->error($e->getMessage());
return 1;
}
$io->getErrorStyle()->writeln('<info>' . $result->getLogs() . '</info>');
$io->writeln(json_encode($result->getPayload(), JSON_PRETTY_PRINT));
return 0;
})->descriptions('Invoke the lambda on the serverless provider', [
'--event' => 'Event data as JSON, e.g. `--event \'{"name":"matt"}\'`',
]);
$app->command('deployment stack-name [--region=]', function (string $stackName, ?string $region, SymfonyStyle $io) {
$region = ($region ?: getenv('AWS_DEFAULT_REGION')) ?: 'us-east-1';
$cloudFormation = new CloudFormationClient([
'version' => 'latest',
'region' => $region,
]);
try {
$result = $cloudFormation->describeStacks([
'StackName' => $stackName,
]);
$stacks = $result->get('Stacks');
if (!isset($stacks[0])) {
$io->error(sprintf('The stack %s cannot be found in region %s', $stackName, $region));
return 1;
}
$stack = $stacks[0];
} catch (CloudFormationException $e) {
$io->error([
"Error while fetching information about the stack `$stackName` in region `$region`:",
sprintf('"%s"', $e->getAwsErrorMessage()),
"In case the stack was not found make sure that `$region` is the correct region.",
]);
return 1;
}
$io->section('Events');
$result = $cloudFormation->describeStackEvents([
'StackName' => $stackName,
]);
$events = $result->get('StackEvents');
// Last events last
$events = array_reverse($events);
// Keep only events from the last 24 hours
$oneDayAgo = new DateTimeImmutable('-1 day');
$events = array_filter($events, function (array $event) use ($oneDayAgo) {
return $event['Timestamp'] >= $oneDayAgo;
});
if (empty($events)) {
$io->text('No events were found in the last 24 hours.');
} else {
$errors = [];
foreach ($events as $event) {
/** @var DateTimeInterface $time */
$time = $event['Timestamp'];
$status = $event['ResourceStatus'];
$error = false;
if (strpos($status, 'FAILED') !== false) {
$error = true;
$errors[] = $event;
}
$io->write(sprintf(
'<comment>%s</comment> %s %s',
$time->format('M j G:H'),
$error ? "<error>$status</error>" : $status,
$event['ResourceType']
));
if (isset($event['ResourceStatusReason'])) {
$io->write(" <info>{$event['ResourceStatusReason']}</info>");
}
$io->writeln('');
}
$io->writeln('');
if (empty($errors)) {
$io->writeln('<info>No errors found.</info>');
} else {
$io->writeln('<error>Summary of the errors found:</error>');
foreach ($errors as $event) {
/** @var DateTimeInterface $time */
$time = $event['Timestamp'];
$io->writeln(sprintf(
'<comment>%s</comment> <info>%s</info> %s',
$time->format('M j G:H'),
$event['ResourceType'],
$event['ResourceStatusReason'] ?? ''
));
}
}
}
if (isset($stack['Outputs']) && !empty($stack['Outputs'])) {
$io->section('Outputs');
$io->listing(array_map(function (array $output): string {
return sprintf(
'%s: <info>%s</info>',
$output['Description'] ?? $output['OutputKey'],
$output['OutputValue']
);
}, $stack['Outputs']));
}
return 0;
})->descriptions('Displays the latest deployment logs from CloudFormation. Only the logs from the last 24 hours are displayed. Use these logs to debug why a deployment failed.');
$app->command('dashboard [--host=] [--port=] [--profile=] [--stage=]', function (string $host = 'localhost', int $port = 8000, string $profile = null, string $stage = null, SymfonyStyle $io) {
if ($host === 'localhost') {
$host = '127.0.0.1';
}
if ($profile === null) {
$profile = getenv('AWS_PROFILE') ?: 'default';
}
if (! file_exists('serverless.yml')) {
$io->error('No `serverless.yml` file found.');
return 1;
}
$exeFinder = new ExecutableFinder();
if (! $exeFinder->find('docker')) {
$io->error(
'The `docker` command is not installed.' . PHP_EOL .
'Please follow the instructions at https://docs.docker.com/install/'
);
return 1;
}
if (! $exeFinder->find('serverless')) {
$io->error(
'The `serverless` command is not installed.' . PHP_EOL .
'Please follow the instructions at https://bref.sh/docs/installation.html'
);
return 1;
}
$serverlessInfo = new Process(['serverless', 'info', '--stage', $stage, '--aws-profile', $profile]);
$serverlessInfo->start();
$animation = new LoadingAnimation($io);
do {
$animation->tick('Retrieving the stack');
usleep(100*1000);
} while ($serverlessInfo->isRunning());
$animation->clear();
if (!$serverlessInfo->isSuccessful()) {
$io->error('The command `serverless info` failed' . PHP_EOL . $serverlessInfo->getOutput());
return 1;
}
$servelessInfoOutput = $serverlessInfo->getOutput();
$region = [];
preg_match('/region: ([a-z0-9-]*)/', $servelessInfoOutput, $region);
$region = $region[1];
$stack = [];
preg_match('/stack: ([a-zA-Z0-9-]*)/', $servelessInfoOutput, $stack);
$stack = $stack[1];
$io->writeln("Stack: <fg=yellow>$stack ($region)</>");
$dockerPull = new Process(['docker', 'pull', 'bref/dashboard']);
$dockerPull->setTimeout(null);
$dockerPull->start();
do {
$animation->tick('Retrieving the latest version of the dashboard');
usleep(100*1000);
} while ($dockerPull->isRunning());
$animation->clear();
if (! $dockerPull->isSuccessful()) {
$io->error([
'The command `docker pull bref/dashboard` failed',
$dockerPull->getErrorOutput(),
]);
return 1;
}
$process = new Process(['docker', 'run', '--rm', '-p', $host . ':' . $port.':8000', '-v', getenv('HOME').'/.aws:/root/.aws:ro', '--env', 'STACKNAME='.$stack, '--env', 'REGION='.$region, '--env', 'AWS_PROFILE='.$profile, 'bref/dashboard']);
$process->setTimeout(null);
$process->start();
do {
$animation->tick('Starting the dashboard');
usleep(100*1000);
$serverOutput = $process->getOutput();
$hasStarted = (strpos($serverOutput, 'Development Server started') !== false);
} while ($process->isRunning() && !$hasStarted);
$animation->clear();
if (!$process->isRunning()) {
$io->error([
'The dashboard failed to start',
$process->getErrorOutput(),
]);
return 1;
}
$url = "http://$host:$port";
$io->writeln("Dashboard started: <fg=green;options=bold,underscore>$url</>");
OpenUrl::open($url);
$process->wait(function ($type, $buffer) {
if (Process::ERR === $type) {
echo 'ERR > '.$buffer;
} else {
echo 'OUT > '.$buffer;
}
});
return $process->getExitCode();
})->descriptions('Start the dashboard');
$app->command('bref.dev [--profile=] [--stage=]', function (string $profile = 'default', string $stage = null, SymfonyStyle $io) {
if (! file_exists('serverless.yml')) {
$io->error('No `serverless.yml` file found.');
return 1;
}
if (! (new ExecutableFinder)->find('serverless')) {
$io->error(
'The `serverless` command is not installed.' . PHP_EOL .
'Please follow the instructions at https://bref.sh/docs/installation.html'
);
return 1;
}
$serverlessInfo = new Process(['serverless', 'info', '--stage', $stage, '--aws-profile', $profile]);
$serverlessInfo->start();
$animation = new LoadingAnimation($io);
do {
$animation->tick('Retrieving the API Gateway URL');
usleep(100*1000);
} while ($serverlessInfo->isRunning());
$animation->clear();
if (!$serverlessInfo->isSuccessful()) {
$io->error('The command `serverless info` failed' . PHP_EOL . $serverlessInfo->getErrorOutput());
return 1;
}
$serverlessInfoOutput = $serverlessInfo->getOutput();
// Region
$regionMatches = [];
preg_match('/region: ([a-z0-9-]*)/', $serverlessInfoOutput, $regionMatches);
$region = $regionMatches[1];
// Stage
$stageMatches = [];
preg_match('/stage: ([a-z0-9-]*)/', $serverlessInfoOutput, $stageMatches);
$stage = $stageMatches[1];
// API ID
$apiIdMatches = [];
preg_match('# - https://([^.]+)\.execute-api\.#', $serverlessInfoOutput, $apiIdMatches);
$apiId = $apiIdMatches[1];
$io->writeln("Creating a short URL for <info>https://$apiId.execute-api.$region.amazonaws.com/$stage</info>");
$client = new GuzzleHttp\Client();
$response = $client->request('POST', 'https://api.bref.dev/site', [
'json' => [
'apiId' => $apiId,
'region' => $region,
'stage' => $stage,
],
]);
$response = json_decode((string) $response->getBody(), true);
$shortUrl = $response['url'];
$io->writeln("Short URL created and active for 7 days: <info>$shortUrl</info>");
$io->writeln('<comment>Please use this URL for development only and avoid load testing it with a lot of traffic. That helps us provide the service for free. The service is currently in beta and can change at any moment.</comment>');
return 0;
})->descriptions('Create a short URL on bref.dev');
$app->run();