This repository has been archived by the owner on Feb 3, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 8
/
GetCommand.php
265 lines (237 loc) · 7.89 KB
/
GetCommand.php
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
<?php
namespace Meanbee\Magedbm\Command;
use Aws\Common\Exception\InstanceProfileCredentialsException;
use Aws\S3\Exception\NoSuchKeyException;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\ArrayInput;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;
class GetCommand extends BaseCommand
{
protected $filename;
/**
* Configure the command parameters.
*/
protected function configure()
{
parent::configure();
$this
->setName('get')
->setDescription('Get database from Amazon S3')
->addArgument(
'name',
InputArgument::REQUIRED,
'Project identifier'
)
->addOption(
'file',
null,
InputOption::VALUE_REQUIRED,
'File to import, otherwise latest downloaded'
)
->addOption(
'download-only',
'-o',
InputOption::VALUE_NONE,
'Only download the backup to the current directory'
)
->addOption(
'--force',
'-f',
InputOption::VALUE_NONE,
'Force import without interaction'
)
->addOption(
'--drop-tables',
'-d',
InputOption::VALUE_NONE,
'Drop tables before import. Deprecated since 1.4.0 as all exports now drop tables automatically.'
)
->addOption(
'--region',
'-r',
InputOption::VALUE_REQUIRED,
'Optionally specify region, otherwise default configuration will be used.'
)
->addOption(
'--bucket',
'-b',
InputOption::VALUE_REQUIRED,
'Optionally specify bucket, otherwise default configuration will be used. '
);
}
/**
* Execute the command.
*
* @param InputInterface $input
* @param OutputInterface $output
*
* @throws \Exception
* @return int
*/
protected function execute(InputInterface $input, OutputInterface $output)
{
// Import overwrites databases so ask for confirmation.
$dialog = $this->getHelper('dialog');
if (!$input->getOption('force') && !$input->getOption('download-only')) {
if (!$dialog->askConfirmation(
$output,
'<question>Are you sure you wish to overwrite local database [y/n]?</question>',
false
)
) {
return;
}
}
$s3 = $this->getS3Client($input->getOption('region'));
$config = $this->getConfig($input);
$file = $input->getOption('file');
if (!$file) {
$file = $this->getLatestFile($s3, $config, $input);
}
$this->downloadBackup($file, $s3, $config, $input);
if ($input->getOption('download-only')) {
$this->backupMove($file);
} else {
$this->backupImport($file, $input);
}
}
/**
* Get latest file for a project
*
* @param \Aws\S3\S3Client $s3
* @param Array $config
* @param InputInterface $input
*
* @return mixed
*/
protected function getLatestFile($s3, $config, $input)
{
try {
// Download latest available backup
$results = $s3->getIterator(
'ListObjects',
array('Bucket' => $config['bucket'], 'Prefix' => $input->getArgument('name'))
);
$newest = null;
foreach ($results as $item) {
if (is_null($newest) || $item['LastModified'] > $newest['LastModified']) {
$newest = $item;
}
}
if (!$results->count()) {
// Credentials Exception would have been thrown by now, so now we can safely check for item count.
throw new \Exception('No backups found for ' . $input->getArgument('name'));
}
} catch (InstanceProfileCredentialsException $e) {
$this->getOutput()->writeln('<error>AWS credentials not found. Please run `configure` command.</error>');
exit;
} catch (\Exception $e) {
$this->getOutput()->writeln('<error>' . $e->getMessage() . '</error>');
exit;
}
$itemKeyChunks = explode('/', $newest['Key']);
return array_pop($itemKeyChunks);
}
/**
* Download from S3 to tmp directory
*
* @param $s3
* @param $config
* @param $input
*/
protected function downloadBackup($file, $s3, $config, $input)
{
$this->getOutput()->writeln(sprintf('<info>Downloading database %s</info>', $file));
try {
$s3->getObject(array(
'Bucket' => $config['bucket'],
'Key' => $input->getArgument('name') . '/' . $file,
'SaveAs' => $this->getFilePath($file)
));
} catch (NoSuchKeyException $e) {
$this->getOutput()->writeln('<error>No such file found in S3 bucket.</error>');
exit;
}
if (!file_exists($this->getFilePath($file))) {
$this->getOutput()->writeln('<error>Failed to save file to local tmp directory.</error>');
exit;
}
}
/**
* Import backup from tmp directory to local database
*
* @param $file
* @param $input
*
* @throws \Exception
*/
protected function backupImport($file, $input)
{
try {
/** @var \N98\Magento\Command\Database\ImportCommand $dump */
$importCommand = $this->getMagerun()->find("db:import");
} catch (\InvalidArgumentException $e) {
throw new \Exception("'magerun db:import' command not found. Missing dependencies?");
}
$params = array(
'filename' => $this->getFilePath($file),
'--compression' => 'gzip',
);
try {
if ($returnCode = $importCommand->run(new ArrayInput($params), $this->getOutput())) {
$this->getOutput()->writeln('<error>magerun db:import failed to import database.</error>');
}
} catch (\Exception $e) {
$this->cleanUp();
$this->getOutput()->writeln($e->getMessage());
exit(1);
}
$this->cleanUp();
}
/**
* Move backup from tmp directory to current working directory
*
* @param $file
*/
protected function backupMove($file)
{
$filename = $this->getFilePath($file);
$newFilename = getcwd() . '/' . $file;
if (!is_writable(getcwd())) {
$this->getOutput()->writeln("<info>Unable to write to current working directory. Check $filename</info>");
return;
}
$result = rename($filename, $newFilename);
if ($result && file_exists($newFilename)) {
$this->getOutput()->writeln("<info>Downloaded to $newFilename</info>");
} else {
$this->getOutput()->writeln(
"<error>Failed to move backup to current working directory. Check $filename</error>"
);
}
}
/**
* Get filepath in tmp directory
*
* @param $file
*
* @return string
*/
protected function getFilePath($file)
{
// Create tmp directory if doesn't exist
if (!file_exists(self::TMP_PATH) && !is_dir(self::TMP_PATH)) {
mkdir(self::TMP_PATH, 0700);
}
return sprintf('%s/%s', self::TMP_PATH, $file);
}
/**
* Cleanup tmp directory
*/
protected function cleanUp()
{
array_map('unlink', glob(self::TMP_PATH . '/*'));
}
}