This repository was archived by the owner on Apr 27, 2026. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 128
Expand file tree
/
Copy pathProjectCreateCommand.php
More file actions
435 lines (389 loc) · 16 KB
/
ProjectCreateCommand.php
File metadata and controls
435 lines (389 loc) · 16 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
430
431
432
433
434
435
<?php
namespace Platformsh\Cli\Command\Project;
use GuzzleHttp\Exception\ConnectException;
use Platformsh\Cli\Command\CommandBase;
use Platformsh\Cli\Console\Bot;
use Platformsh\ConsoleForm\Field\Field;
use Platformsh\ConsoleForm\Field\OptionsField;
use Platformsh\ConsoleForm\Field\BooleanField;
use Platformsh\ConsoleForm\Field\UrlField;
use Platformsh\ConsoleForm\Form;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;
class ProjectCreateCommand extends CommandBase
{
/** @var Form */
protected $form;
/**
* {@inheritdoc}
*/
protected function configure()
{
$this
->setName('project:create')
->setAliases(['create'])
->setDescription('Create a new project');
$this->form = Form::fromArray($this->getFields());
$this->form->configureInputDefinition($this->getDefinition());
$this->addOption('check-timeout', null, InputOption::VALUE_REQUIRED, 'The API timeout while checking the project status', 30)
->addOption('timeout', null, InputOption::VALUE_REQUIRED, 'The total timeout for all API checks (0 to disable the timeout)', 900)
->addOption('template', null, InputOption::VALUE_OPTIONAL, 'Choose a starting template or provide a url of one.', false);
$this->setHelp(<<<EOF
Use this command to create a new project.
An interactive form will be presented with the available options. But if the
command is run non-interactively (with --yes), the form will not be displayed,
and the --region option will be required.
A project subscription will be requested, and then checked periodically (every 3
seconds) until the project has been activated, or until the process times out
(after 15 minutes by default).
If known, the project ID will be output to STDOUT. All other output will be sent
to STDERR.
EOF
);
}
/**
* {@inheritdoc}
*/
protected function execute(InputInterface $input, OutputInterface $output)
{
/** @var \Platformsh\Cli\Service\QuestionHelper $questionHelper */
$questionHelper = $this->getService('question_helper');
$options = $this->form->resolveOptions($input, $output, $questionHelper);
$template = $input->getOption('template');
// This will present the user with an additional form that will allow
// them to choose from a catalog if they add only --template with a url.
if ($template !== false) {
$this->template_form = Form::fromArray($this->getTemplateFields($template));
$template_options = $this->template_form->resolveOptions($input, $output, $questionHelper);
}
$estimate = $this->api()
->getClient()
->getSubscriptionEstimate($options['plan'], $options['storage'], $options['environments'], 1);
$costConfirm = sprintf(
'The estimated monthly cost of this project is: <comment>%s</comment>',
$estimate['total']
);
if ($this->config()->has('service.pricing_url')) {
$costConfirm .= sprintf(
"\nPricing information: <comment>%s</comment>",
$this->config()->get('service.pricing_url')
);
}
$costConfirm .= "\n\nAre you sure you want to continue?";
if (!$questionHelper->confirm($costConfirm)) {
return 1;
}
if (isset($template_options['template_url_from_catalog'])) {
$options['template'] = $template_options['template_url_from_catalog'];
}
else if (isset($template)) {
$options['template'] = $template;
}
$subscription = $this->api()->getClient()
->createSubscription(
$options['region'],
$options['plan'],
$options['title'],
$options['storage'] * 1024,
$options['environments'],
$options['activationCallback'],
$options['template']
);
$this->api()->clearProjectsCache();
$this->stdErr->writeln(sprintf(
'Your %s project has been requested (subscription ID: <comment>%s</comment>)',
$this->config()->get('service.name'),
$subscription->id
));
$this->stdErr->writeln(sprintf(
"\nThe %s Bot is activating your project\n",
$this->config()->get('service.name')
));
$bot = new Bot($this->stdErr);
$timedOut = false;
$start = $lastCheck = time();
$checkInterval = 3;
$checkTimeout = $this->getTimeOption($input, 'check-timeout', 1, 3600);
$totalTimeout = $this->getTimeOption($input, 'timeout', 0, 3600);
while ($subscription->isPending() && !$timedOut) {
$bot->render();
// Attempt to check the subscription every $checkInterval seconds.
// This also waits $checkInterval seconds before the first check,
// which allows the server a little more leeway to act on the
// initial request.
if (time() - $lastCheck >= $checkInterval) {
$lastCheck = time();
try {
// The API call will timeout after $checkTimeout seconds.
$subscription->refresh(['timeout' => $checkTimeout, 'exceptions' => false]);
} catch (ConnectException $e) {
if (strpos($e->getMessage(), 'timed out') !== false) {
$this->debug($e->getMessage());
} else {
throw $e;
}
}
}
// Check the total timeout.
$timedOut = $totalTimeout ? time() - $start > $totalTimeout : false;
}
$this->stdErr->writeln('');
if (!$subscription->isActive()) {
if ($timedOut) {
$this->stdErr->writeln('<error>The project failed to activate on time</error>');
} else {
$this->stdErr->writeln('<error>The project failed to activate</error>');
}
if (!empty($subscription->project_id)) {
$output->writeln($subscription->project_id);
}
$this->stdErr->writeln(sprintf('View your active projects with: <info>%s project:list</info>', $this->config()->get('application.executable')));
return 1;
}
if (isset($subscription->project_options['initialize']['profile']) && isset($subscription->project_options['initialize']['repository'])) {
$project = $this->api()->getProject($subscription->project_id);
$environment = $this->api()->getEnvironment('master', $project);
if (isset($project) && isset($environment)) {
$environment->initialize($subscription->project_options['initialize']['profile'], $subscription->project_options['initialize']['repository']);
$this->api()->clearEnvironmentsCache($environment->project);
$this->stdErr->writeln("The project has been initialized and is ready!");
}
else {
$this->stdErr->writeln("The project could not be initialized at this time due to missing profile and repository information.");
}
}
else {
$this->stdErr->writeln("The project is now ready!");
}
$output->writeln($subscription->project_id);
$this->stdErr->writeln('');
if (!empty($subscription->project_options['initialize'])) {
$this->stdErr->writeln(" Template: <info>{$subscription->project_options[initialize][repository] }</info>");
}
$this->stdErr->writeln(" Region: <info>{$subscription->project_region}</info>");
$this->stdErr->writeln(" Project ID: <info>{$subscription->project_id}</info>");
$this->stdErr->writeln(" Project title: <info>{$subscription->project_title}</info>");
$this->stdErr->writeln(" URL: <info>{$subscription->project_ui}</info>");
return 0;
}
/**
* Return a list of plans.
*
* The default list is in the config `service.available_plans`. This is
* replaced at runtime by an API call.
*
* @param bool $runtime
*
* @return array
*/
protected function getAvailablePlans($runtime = false)
{
static $plans;
// First look to the setup/options API for a plan list.
$account = $this->api()->getMyAccount(true);
$setupOptions = $this->api()->getClient()->getSetupOptions(NULL, NULL, NULL, $account['username'], NULL);
if (isset($setupOptions) && !empty($setupOptions['plans'])) {
$plans = $setupOptions['plans'];
}
else {
if (is_array($plans)) {
return $plans;
}
if (!$runtime) {
return (array) $this->config()->get('service.available_plans');
}
$plans = [];
foreach ($this->api()->getClient()->getPlans() as $plan) {
if ($plan->hasProperty('price', false)) {
$plans[$plan->name] = sprintf('%s (%s)', $plan->label, $plan->price->__toString());
} else {
$plans[$plan->name] = $plan->label;
}
}
}
return $plans;
}
/**
* Return a list of regions.
*
* The default list is in the config `service.available_regions`. This is
* replaced at runtime by an API call.
*
* @param bool $runtime
*
* @return array
*/
protected function getAvailableRegions($runtime = false)
{
if ($runtime) {
// First look to the setup/options API for a region list.
$account = $this->api()->getMyAccount(true);
$setupOptions = $this->api()->getClient()->getSetupOptions(NULL, NULL, NULL, $account['username'], NULL);
if (isset($setupOptions) && !empty($setupOptions['regions'])) {
$regions = $setupOptions['regions'];
}
else {
// Fallback to the regions api.
$regions = [];
foreach ($this->api()->getClient()->getRegions() as $region) {
if ($region->available) {
$regions[$region->id] = $region->label;
}
}
}
} else {
$regions = (array) $this->config()->get('service.available_regions');
}
return $regions;
}
/**
* Return the catalog.
*
* The default list is in the config `service.catalog`. This is
* replaced at runtime by an API call.
*
* @param bool $runtime
*
* @return array
*/
protected function getDefaultCatalog($runtime = false)
{
if ($runtime) {
$catalog = [];
$catalog_items = $this->api()->getClient()->getCatalog()->getData();
if (!empty($catalog_items)) {
foreach ($catalog_items as $item) {
if (isset($item['info']) && isset($item['template'])) {
$catalog[] = $item['template'];
}
}
}
} else {
$catalog = (array) $this->config()->get('service.catalog');
}
if (empty($catalog)) {
// Should we throw an error here? Do we want to kill the process?
}
return $catalog;
}
/**
* Returns a list of ConsoleForm form fields for this command.
*
* @return Field[]
*/
protected function getFields()
{
return [
'title' => new Field('Project title', [
'optionName' => 'title',
'description' => 'The initial project title',
'questionLine' => '',
'default' => 'Untitled Project',
]),
'region' => new OptionsField('Region', [
'optionName' => 'region',
'description' => 'The region where the project will be hosted',
'options' => $this->getAvailableRegions(),
'optionsCallback' => function () {
return $this->getAvailableRegions(true);
},
]),
'plan' => new OptionsField('Plan', [
'optionName' => 'plan',
'description' => 'The subscription plan',
'options' => $this->getAvailablePlans(),
'optionsCallback' => function () {
return $this->getAvailablePlans(true);
},
'default' => in_array('development', $this->getAvailablePlans()) ? 'development' : null,
'allowOther' => true,
]),
'environments' => new Field('Environments', [
'optionName' => 'environments',
'description' => 'The number of environments',
'default' => 3,
'validator' => function ($value) {
return is_numeric($value) && $value > 0 && $value < 50;
},
]),
'storage' => new Field('Storage', [
'description' => 'The amount of storage per environment, in GiB',
'default' => 5,
'validator' => function ($value) {
return is_numeric($value) && $value > 0 && $value < 1024;
},
]),
];
}
/**
* Returns a list of ConsoleForm form fields for this command.
*
* @return Field[]
*/
protected function getTemplateFields($url)
{
$fields = [];
// If provided, check the template is valid.
if ($url != false) {
$this->api()->getClient()->getSetupOptions(NULL, NULL, $url, NULL, NULL);
}
if ($url == false) {
$fields['template_option'] = new OptionsField('Template Options', [
'optionName' => 'template_option',
'options' => [
'Provide your own template url.',
'Choose a template from the catalog.',
'No template at this time.',
],
'description' => 'Choose a template, provide a url or choose not to use one.',
'includeAsOption' => false,
]);
$fields['template_url_from_catalog'] = new OptionsField('Template (from a catalog)', [
'optionName' => 'template_url_from_catalog',
'conditions' => [
'template_option' => [
'Choose a template from the catalog.'
],
],
'description' => 'The template from which to create your project or your own blank project.',
'options' => $this->getDefaultCatalog(),
'asChoice' => FALSE,
'optionsCallback' => function () {
return $this->getDefaultCatalog(true);
},
]);
$fields['template_url'] = new UrlField('Template URL', [
'optionName' => 'template_url',
'conditions' => [
'template_option' => [
'Provide your own template url.'
],
],
'description' => 'The template url',
'questionLine' => 'What is the URL of the template?',
]);
}
return $fields;
}
/**
* Get a numeric option value while ensuring it's a reasonable number.
*
* @param \Symfony\Component\Console\Input\InputInterface $input
* @param string $optionName
* @param int $min
* @param int $max
*
* @return float|int
*/
private function getTimeOption(InputInterface $input, $optionName, $min = 0, $max = 3600)
{
$value = $input->getOption($optionName);
if ($value <= $min) {
$value = $min;
} elseif ($value > $max) {
$value = $max;
}
return $value;
}
}