forked from platformsh/legacy-cli
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRelationships.php
More file actions
429 lines (390 loc) · 15.7 KB
/
Relationships.php
File metadata and controls
429 lines (390 loc) · 15.7 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
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
424
425
426
427
428
429
<?php
namespace Platformsh\Cli\Service;
use GuzzleHttp\Query;
use Platformsh\Cli\Model\Host\HostInterface;
use Platformsh\Cli\Model\Host\LocalHost;
use Platformsh\Cli\Util\OsUtil;
use Platformsh\Client\Model\Deployment\Service;
use Symfony\Component\Console\Input\InputDefinition;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\ConsoleOutputInterface;
use Symfony\Component\Console\Output\OutputInterface;
class Relationships implements InputConfiguringInterface
{
protected $envVarService;
/**
* @param RemoteEnvVars $envVarService
*/
public function __construct(RemoteEnvVars $envVarService)
{
$this->envVarService = $envVarService;
}
/**
* @param \Symfony\Component\Console\Input\InputDefinition $definition
*/
public static function configureInput(InputDefinition $definition)
{
$definition->addOption(
new InputOption('relationship', 'r', InputOption::VALUE_REQUIRED, 'The service relationship to use')
);
}
/**
* Choose a database for the user.
*
* @param HostInterface $host
* @param InputInterface $input
* @param OutputInterface $output
*
* @return array|false
*/
public function chooseDatabase(HostInterface $host, InputInterface $input, OutputInterface $output, $types = ['mysql', 'pgsql'])
{
return $this->chooseService($host, $input, $output, $types);
}
/**
* Choose a service for the user.
*
* @param HostInterface $host
* @param InputInterface $input
* @param OutputInterface $output
* @param string[] $schemes Filter by scheme.
*
* @return array|false
*/
public function chooseService(HostInterface $host, InputInterface $input, OutputInterface $output, $schemes = [])
{
$stdErr = $output instanceof ConsoleOutputInterface ? $output->getErrorOutput() : $output;
$relationships = $this->getRelationships($host);
// Filter to find services matching the schemes.
if (!empty($schemes)) {
$relationships = array_filter($relationships, function (array $relationship) use ($schemes) {
foreach ($relationship as $service) {
if (isset($service['scheme']) && in_array($service['scheme'], $schemes, true)) {
return true;
}
}
return false;
});
}
if (empty($relationships)) {
if (!empty($schemes)) {
$stdErr->writeln(sprintf('No relationships found matching scheme(s): <error>%s</error>.', implode(', ', $schemes)));
} else {
$stdErr->writeln(sprintf('No relationships found'));
}
return false;
}
// Collapse relationships and services into a flat list.
$choices = [];
foreach ($relationships as $name => $relationship) {
$serviceCount = count($relationship);
foreach ($relationship as $key => $info) {
$identifier = $name . ($serviceCount > 1 ? '.' . $key : '');
if (isset($info['username']) && (!isset($info['host']) || $info['host'] === '127.0.0.1')) {
$choices[$identifier] = sprintf('%s (%s)', $identifier, $info['username']);
} elseif (isset($info['username'], $info['host'])) {
$choices[$identifier] = sprintf('%s (%s@%s)', $identifier, $info['username'], $info['host']);
} else {
$choices[$identifier] = $identifier;
}
}
}
// Use the --relationship option, if specified.
$identifier = false;
if ($input->hasOption('relationship')
&& ($relationshipName = $input->getOption('relationship'))) {
// Normalise the relationship name to remove a trailing ".0".
if (substr($relationshipName, -2) === '.0'
&& isset($relationships[$relationshipName]) && count($relationships[$relationshipName]) ===1) {
$relationshipName = substr($relationshipName, 0, strlen($relationshipName) - 2);
}
if (!isset($choices[$relationshipName])) {
$stdErr->writeln('Relationship not found: <error>' . $relationshipName . '</error>');
return false;
}
$identifier = $relationshipName;
}
if (!$identifier && count($choices) === 1) {
$identifier = key($choices);
}
if (!$identifier && !$input->isInteractive()) {
$stdErr->writeln('More than one relationship found.');
if ($input->hasOption('relationship')) {
$stdErr->writeln('Use the <error>--relationship</error> (-r) option to specify a relationship. Options:');
foreach (array_keys($choices) as $identifier) {
$stdErr->writeln(' ' . $identifier);
}
}
return false;
}
if (!$identifier) {
$questionHelper = new QuestionHelper($input, $output);
$identifier = $questionHelper->choose($choices, 'Enter a number to choose a relationship:');
}
if (strpos($identifier, '.') !== false) {
list($name, $key) = explode('.', $identifier, 2);
} else {
$name = $identifier;
$key = 0;
}
$relationship = $relationships[$name][$key];
// Ensure the service name is included in the relationship info.
// This is for backwards compatibility with projects that do not have
// this information.
if (!isset($relationship['service'])) {
$appConfig = $this->envVarService->getArrayEnvVar('APPLICATION', $host);
if (!empty($appConfig['relationships'][$name]) && is_string($appConfig['relationships'][$name])) {
list($serviceName, ) = explode(':', $appConfig['relationships'][$name], 2);
$relationship['service'] = $serviceName;
}
}
// Add metadata about the service.
$relationship['_relationship_name'] = $name;
$relationship['_relationship_key'] = $key;
return $relationship;
}
/**
* Get the relationships deployed on the application.
*
* @param HostInterface $host
* @param bool $refresh
*
* @return array
*/
public function getRelationships(HostInterface $host, $refresh = false)
{
return $this->normalizeRelationships(
$this->envVarService->getArrayEnvVar('RELATIONSHIPS', $host, $refresh)
);
}
/**
* Normalizes relationships that have weird output in the API.
*
* If only real-life relationships were this simple.
*
* @param array $relationships
*
* @return array
*/
private function normalizeRelationships(array $relationships)
{
foreach ($relationships as &$relationship) {
foreach ($relationship as &$instance) {
// If there is a "host" which is actually a full MongoDB
// multi-instance URI such a mongodb://hostname1,hostname2,hostname3:1234/path?query
// then this converts it into a valid URL (selecting just the
// first hostname), and parses that to populate the instance
// definition.
if (isset($instance['scheme']) && isset($instance['host'])
&& $instance['scheme'] === 'mongodb' && strpos($instance['host'], 'mongodb://') === 0) {
$mongodbUri = $instance['host'];
$url = \preg_replace_callback('#^(mongodb://)([^/?]+)([/?]|$)#', function ($matches) {
return $matches[1] . \explode(',', $matches[2])[0] . $matches[3];
}, $mongodbUri);
$urlParts = \parse_url($url);
if ($urlParts) {
$instance = array_merge($urlParts, $instance);
// Fix the "host" to be a hostname.
$instance['host'] = $urlParts['host'];
// Set the "url" as the original "host".
$instance['url'] = $mongodbUri;
}
}
}
}
return $relationships;
}
/**
* Returns whether the database is MariaDB.
*
* @param array $database The database definition from the relationships.
* @return bool
*/
public function isMariaDB(array $database)
{
return isset($database['type']) && (\strpos($database['type'], 'mariadb:') === 0 || \strpos($database['type'], 'mysql:') === 0);
}
/**
* Returns whether the database is OracleDB.
*
* @param array $database The database definition from the relationships.
* @return bool
*/
public function isOracleDB(array $database)
{
return isset($database['type']) && \strpos($database['type'], 'oracle-mysql:') === 0;
}
/**
* Returns the correct command to use with a MariaDB client.
*
* MariaDB now needs MariaDB-specific command names. But these were added
* in the MariaDB client 10.4.6, and we cannot efficiently check the client
* version, at least not before we are already running the command.
* See: https://jira.mariadb.org/browse/MDEV-21303
*
* @param string $cmd
*
* @return string
*/
public function mariaDbCommandWithFallback($cmd)
{
if ($cmd === 'mariadb') {
return 'cmd="$(command -v mariadb || echo -n mysql)"; "$cmd"';
}
if ($cmd === 'mariadb-dump') {
return 'cmd="$(command -v mariadb-dump || echo -n mysqldump)"; "$cmd"';
}
return $cmd;
}
/**
* Returns command-line arguments to connect to a database.
*
* @param string $command The command that will need arguments
* (one of 'psql', 'pg_dump', 'mysql',
* 'mysqldump', 'mariadb' or
* 'mariadb-dump').
* @param array $database The database definition from the
* relationship.
* @param string|null $schema The name of a database schema, or
* null to use the default schema, or
* an empty string to not select a
* schema.
*
* @return string
* The command line arguments (excluding the $command).
*/
public function getDbCommandArgs($command, array $database, $schema = null)
{
if ($schema === null) {
$schema = $database['path'];
}
switch ($command) {
case 'psql':
case 'pg_dump':
$url = sprintf(
'postgresql://%s:%s@%s:%d',
$database['username'],
$database['password'],
$database['host'],
$database['port']
);
if ($schema !== '') {
$url .= '/' . rawurlencode($schema);
}
return OsUtil::escapePosixShellArg($url);
case 'mariadb':
case 'mariadb-dump':
case 'mysql':
case 'mysqldump':
$args = sprintf(
'--user=%s --password=%s --host=%s --port=%d',
OsUtil::escapePosixShellArg($database['username']),
OsUtil::escapePosixShellArg($database['password']),
OsUtil::escapePosixShellArg($database['host']),
$database['port']
);
if ($schema !== '') {
$args .= ' ' . OsUtil::escapePosixShellArg($schema);
}
return $args;
case 'mongo':
case 'mongodump':
case 'mongoexport':
case 'mongorestore':
if (isset($database['url'])) {
if ($command === 'mongo') {
return $database['url'];
}
return sprintf('--uri %s', OsUtil::escapePosixShellArg($database['url']));
}
$args = sprintf(
'--username %s --password %s --host %s --port %d',
OsUtil::escapePosixShellArg($database['username']),
OsUtil::escapePosixShellArg($database['password']),
OsUtil::escapePosixShellArg($database['host']),
$database['port']
);
if ($schema !== '') {
$args .= ' --authenticationDatabase ' . OsUtil::escapePosixShellArg($schema);
if ($command === 'mongo') {
$args .= ' ' . OsUtil::escapePosixShellArg($schema);
} else {
$args .= ' --db ' . OsUtil::escapePosixShellArg($schema);
}
}
return $args;
}
throw new \InvalidArgumentException('Unrecognised command: ' . $command);
}
/**
* @return bool
*/
public function hasLocalEnvVar()
{
return $this->envVarService->getEnvVar('RELATIONSHIPS', new LocalHost()) !== '';
}
/**
* Builds a URL from the parts included in a relationship array.
*
* @param array $instance
*
* @return string
*/
public function buildUrl(array $instance)
{
$parts = $instance;
// Convert to parse_url parts.
if (isset($parts['username'])) {
$parts['user'] = $parts['username'];
}
if (isset($parts['password'])) {
$parts['pass'] = $parts['password'];
}
unset($parts['username'], $parts['password']);
// The 'query' is expected to be a string.
if (isset($parts['query']) && is_array($parts['query'])) {
unset($parts['query']['is_master']);
$parts['query'] = (new Query($parts['query']))->__toString();
}
// Special case #1: Solr.
if (isset($parts['scheme']) && $parts['scheme'] === 'solr') {
$parts['scheme'] = 'http';
if (isset($parts['path']) && \dirname($parts['path']) === '/solr') {
$parts['path'] = '/solr/';
}
}
// Special case #2: PostgreSQL.
if (isset($parts['scheme']) && $parts['scheme'] === 'pgsql') {
$parts['scheme'] = 'postgresql';
}
return \GuzzleHttp\Url::buildUrl($parts);
}
/**
* Returns a list of schemas (database names/paths) for a service.
*
* The MySQL, MariaDB and Oracle MySQL services allow specifying custom
* schemas. The PostgreSQL service has the same feature, but they are
* unfortunately named differently: "databases" not "schemas". If nothing
* is configured, all four service types default to having one schema named
* "main".
*
* See https://docs.upsun.com/anchors/fixed/services/postgresql/
* and https://docs.upsun.com/anchors/fixed/services/mysql/
*
* @return string[]
*/
public function getServiceSchemas(Service $service)
{
if (!empty($service->configuration['schemas'])) {
return $service->configuration['schemas'];
}
if (!empty($service->configuration['databases'])) {
return $service->configuration['databases'];
}
if (preg_match('/^(postgresql|mariadb|mysql|oracle-mysql):/', $service->type) === 1) {
return ['main'];
}
return [];
}
}