Skip to content
Commits on Source (31)
<?php <?php
use League\Container\Container;
use Robo\Robo;
use Robo\Common\TimeKeeper;
// We use PWD if available because getcwd() resolves symlinks, which // We use PWD if available because getcwd() resolves symlinks, which
// could take us outside of the Drupal root, making it impossible to find. // could take us outside of the Drupal root, making it impossible to find.
$cwd = empty($_SERVER['PWD']) ? getcwd() : $_SERVER['PWD']; $cwd = empty($_SERVER['PWD']) ? getcwd() : $_SERVER['PWD'];
...@@ -20,16 +16,39 @@ if (file_exists($autoloadFile = __DIR__ . '/vendor/autoload.php') ...@@ -20,16 +16,39 @@ if (file_exists($autoloadFile = __DIR__ . '/vendor/autoload.php')
throw new \Exception("Could not locate autoload.php. cwd is $cwd; __DIR__ is " . __DIR__); throw new \Exception("Could not locate autoload.php. cwd is $cwd; __DIR__ is " . __DIR__);
} }
use Aegir\Provision\Console\ConsoleOutput;
use Aegir\Provision\Console\Config;
use Drupal\Console\Core\Style\DrupalStyle;
use Robo\Common\TimeKeeper;
use Symfony\Component\Console\Input\ArgvInput;
use Symfony\Component\Console\Exception\InvalidOptionException;
use Symfony\Component\Console\Exception\CommandNotFoundException;
// Start Timer. // Start Timer.
$timer = new TimeKeeper(); $timer = new TimeKeeper();
$timer->start(); $timer->start();
$input = new \Symfony\Component\Console\Input\ArgvInput($argv); try {
$output = new \Symfony\Component\Console\Output\ConsoleOutput(); // Create input output objects.
$input = new ArgvInput($argv);
$app = new \Aegir\Provision\Provision($input, $output); $output = new ConsoleOutput();
$io = new DrupalStyle($input, $output);
$status_code = $app->run($input, $output);
// Create a config object.
$config = new Config();
// Create the app.
$app = new \Aegir\Provision\Provision($config, $input, $output);
// Run the app.
$status_code = $app->run($input, $output);
}
catch (InvalidOptionException $e) {
$io->error("There was a problem with your console configuration: " . $e->getMessage(), 1);
$status_code = 1;
}
// Stop timer. // Stop timer.
$timer->stop(); $timer->stop();
......
...@@ -7,9 +7,11 @@ use Aegir\Provision\Command\ServicesCommand; ...@@ -7,9 +7,11 @@ use Aegir\Provision\Command\ServicesCommand;
use Aegir\Provision\Command\ShellCommand; use Aegir\Provision\Command\ShellCommand;
use Aegir\Provision\Command\StatusCommand; use Aegir\Provision\Command\StatusCommand;
use Aegir\Provision\Command\VerifyCommand; use Aegir\Provision\Command\VerifyCommand;
use Aegir\Provision\Common\ProvisionAwareTrait;
use Aegir\Provision\Console\Config; use Aegir\Provision\Console\Config;
use Aegir\Provision\Console\ConsoleOutput; use Aegir\Provision\Console\ConsoleOutput;
use Drupal\Console\Core\Style\DrupalStyle; use Drupal\Console\Core\Style\DrupalStyle;
use Psr\Log\LoggerAwareTrait;
use Psr\Log\LoggerInterface; use Psr\Log\LoggerInterface;
use Psr\Log\LogLevel; use Psr\Log\LogLevel;
use Symfony\Component\Console\Command\HelpCommand; use Symfony\Component\Console\Command\HelpCommand;
...@@ -20,6 +22,7 @@ use Symfony\Component\Console\Input\InputDefinition; ...@@ -20,6 +22,7 @@ use Symfony\Component\Console\Input\InputDefinition;
use Symfony\Component\Console\Logger\ConsoleLogger; use Symfony\Component\Console\Logger\ConsoleLogger;
use Symfony\Component\Console\Output\OutputInterface; use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Application as BaseApplication; use Symfony\Component\Console\Application as BaseApplication;
use Symfony\Component\Console\Command\Command as BaseCommand;
//use Symfony\Component\DependencyInjection\ContainerInterface; //use Symfony\Component\DependencyInjection\ContainerInterface;
//use Drupal\Console\Annotations\DrupalCommandAnnotationReader; //use Drupal\Console\Annotations\DrupalCommandAnnotationReader;
...@@ -43,31 +46,9 @@ class Application extends BaseApplication ...@@ -43,31 +46,9 @@ class Application extends BaseApplication
* @var string * @var string
*/ */
const DEFAULT_TIMEZONE = 'America/New_York'; const DEFAULT_TIMEZONE = 'America/New_York';
/** use ProvisionAwareTrait;
* @var \Aegir\Provision\Tasks use LoggerAwareTrait;
*/
public $robo;
/**
* @var LoggerInterface
*/
public $logger;
/**
* @var DrupalStyle
*/
public $io;
/**
* @var \Symfony\Component\Console\Input\InputInterface
*/
public $input;
/**
* @var \Symfony\Component\Console\Output\OutputInterface
*/
public $output;
/** /**
* @var ConsoleOutput * @var ConsoleOutput
...@@ -88,62 +69,19 @@ class Application extends BaseApplication ...@@ -88,62 +69,19 @@ class Application extends BaseApplication
if (empty(ini_get('date.timezone'))) { if (empty(ini_get('date.timezone'))) {
date_default_timezone_set($this::DEFAULT_TIMEZONE); date_default_timezone_set($this::DEFAULT_TIMEZONE);
} }
//
// // Load Configs
// try {
// $this->config = new Config();
// }
// catch (\Exception $e) {
// throw new \Exception($e->getMessage());
// }
parent::__construct($name, $version);
}
/**
* Prepare input and output arguments. Use this to extend the Application object so that $input and $output is fully populated.
*
* @param \Symfony\Component\Console\Input\InputInterface $input
* @param \Symfony\Component\Console\Output\OutputInterface $output
*/
public function configureIO(InputInterface $input, OutputInterface $output) {
parent::configureIO($input, $output);
$this->io = new DrupalStyle($input, $output);
$this->input = $input; parent::__construct($name, $version);
$this->output = $output;
$this->logger = new ConsoleLogger($output,
[LogLevel::INFO => OutputInterface::VERBOSITY_NORMAL]
);
}
/**
* @var Config
*/
private $config;
/**
* Getter for Configuration.
*
* @return Config
* Configuration object.
*/
public function getConfig()
{
return $this->config;
} }
/** /**
* Setter for Configuration. * Make configureIO public so we can run it before ->run()
* *
* @param Config $config * @param InputInterface $input
* Configuration object. * @param OutputInterface $output
*/ */
public function setConfig(Config $config) public function configureIO(InputInterface $input, OutputInterface $output)
{ {
$this->config = $config; parent::configureIO($input, $output);
} }
/** /**
...@@ -161,7 +99,29 @@ class Application extends BaseApplication ...@@ -161,7 +99,29 @@ class Application extends BaseApplication
return $commands; return $commands;
} }
/**
* Interrupts Command execution to add services like provision and logger.
*
* @param \Symfony\Component\Console\Command\Command $command
* @param \Symfony\Component\Console\Input\InputInterface $input
* @param \Symfony\Component\Console\Output\OutputInterface $output
*
* @return int
*/
protected function doRunCommand( BaseCommand $command, InputInterface $input, OutputInterface $output)
{
// Only setProvision if the command is using the trait.
if (method_exists($command, 'setProvision')) {
$command
->setProvision($this->getProvision())
->setLogger($this->logger)
;
}
$exitCode = parent::doRunCommand($command, $input, $output);
return $exitCode;
}
/** /**
* {@inheritdoc} * {@inheritdoc}
* *
...@@ -181,145 +141,4 @@ class Application extends BaseApplication ...@@ -181,145 +141,4 @@ class Application extends BaseApplication
return $inputDefinition; return $inputDefinition;
} }
/**
* Load all contexts into Context objects.
*
* @return array
*/
static function getAllContexts($name = '', $application = NULL) {
$contexts = [];
$config = new Config();
$context_files = [];
$finder = new \Symfony\Component\Finder\Finder();
$finder->files()->name('*' . $name . '.yml')->in($config->get('config_path') . '/provision');
foreach ($finder as $file) {
list($context_type, $context_name) = explode('.', $file->getFilename());
$context_files[$context_name] = [
'name' => $context_name,
'type' => $context_type,
'file' => $file,
];
}
foreach ($context_files as $context) {
$class = Context::getClassName($context['type']);
$contexts[$context['name']] = new $class($context['name'], $application);
}
if ($name && isset($contexts[$name])) {
return $contexts[$name];
}
elseif ($name && !isset($contexts[$name])) {
return NULL;
}
else {
return $contexts;
}
}
/**
* Load all server contexts.
*
* @param null $service
* @return mixed
* @throws \Exception
*/
static public function getAllServers($service = NULL) {
$servers = [];
$context_files = self::getAllContexts();
if (empty($context_files)) {
throw new \Exception('No server contexts found. Use `provision save` to create one.');
}
foreach ($context_files as $context) {
if ($context->type == 'server') {
$servers[$context->name] = $context;
}
}
return $servers;
}
/**
* Get a simple array of all contexts, for use in an options list.
* @return array
*/
public function getAllContextsOptions($type = NULL) {
$options = [];
foreach ($this->getAllContexts() as $name => $context) {
if ($type) {
if ($context->type == $type) {
$options[$name] = $context->name;
}
}
else {
$options[$name] = $context->type . ' ' . $context->name;
}
}
return $options;
}
/**
* Load the Aegir context with the specified name.
*
* @param $name
*
* @return \Aegir\Provision\Context
* @throws \Exception
*/
static public function getContext($name, Application $application = NULL) {
if (empty($name)) {
throw new \Exception('Context name must not be empty.');
}
if (empty(Application::getAllContexts($name, $application))) {
throw new \Exception('Context not found with name: ' . $name);
}
return Application::getAllContexts($name, $application);
}
/**
* Get a simple array of all servers, optionally specifying the the service_type to filter by ("http", "db" etc.)
* @param string $service_type
* @return array
*/
public function getServerOptions($service_type = '') {
$servers = [];
foreach ($this->getAllServers() as $server) {
if ($service_type && !empty($server->config['services'][$service_type])) {
$servers[$server->name] = $server->name . ': ' . $server->config['services'][$service_type]['type'];
}
elseif ($service_type == '') {
$servers[$server->name] = $server->name . ': ' . $server->config['services'][$service_type]['type'];
}
}
return $servers;
}
/**
* Check that a context type's service requirements are provided by at least 1 server.
*
* @param $type
* @return array
*/
static function checkServiceRequirements($type) {
$class_name = Context::getClassName($type);
// @var $context Context
$service_requirements = $class_name::serviceRequirements();
$services = [];
foreach ($service_requirements as $service) {
try {
if (empty(Application::getAllServers($service))) {
$services[$service] = 0;
}
else {
$services[$service] = 1;
}
} catch (\Exception $e) {
$services[$service] = 0;
}
}
return $services;
}
} }
...@@ -2,7 +2,10 @@ ...@@ -2,7 +2,10 @@
namespace Aegir\Provision; namespace Aegir\Provision;
use Aegir\Provision\Common\ProvisionAwareTrait;
use Drupal\Console\Core\Style\DrupalStyle; use Drupal\Console\Core\Style\DrupalStyle;
use Psr\Log\LoggerAwareTrait;
use Psr\Log\LoggerInterface;
use Psr\Log\LogLevel; use Psr\Log\LogLevel;
use Symfony\Component\Console\Command\Command as BaseCommand; use Symfony\Component\Console\Command\Command as BaseCommand;
use Drupal\Console\Core\Command\Shared\CommandTrait; use Drupal\Console\Core\Command\Shared\CommandTrait;
...@@ -19,7 +22,8 @@ abstract class Command extends BaseCommand ...@@ -19,7 +22,8 @@ abstract class Command extends BaseCommand
{ {
use CommandTrait; use CommandTrait;
use ProvisionAwareTrait;
use LoggerAwareTrait;
/** /**
* @var \Symfony\Component\Console\Input\InputInterface * @var \Symfony\Component\Console\Input\InputInterface
...@@ -50,7 +54,7 @@ abstract class Command extends BaseCommand ...@@ -50,7 +54,7 @@ abstract class Command extends BaseCommand
* @var string * @var string
*/ */
public $context_name; public $context_name;
/** /**
* @param InputInterface $input An InputInterface instance * @param InputInterface $input An InputInterface instance
* @param OutputInterface $output An OutputInterface instance * @param OutputInterface $output An OutputInterface instance
...@@ -70,7 +74,7 @@ abstract class Command extends BaseCommand ...@@ -70,7 +74,7 @@ abstract class Command extends BaseCommand
try { try {
// Load context from context_name argument. // Load context from context_name argument.
$this->context_name = $this->input->getArgument('context_name'); $this->context_name = $this->input->getArgument('context_name');
$this->context = Application::getContext($this->context_name, $this->getApplication()); $this->context = $this->getProvision()->getContext($this->context_name);
} }
catch (\Exception $e) { catch (\Exception $e) {
...@@ -92,7 +96,7 @@ abstract class Command extends BaseCommand ...@@ -92,7 +96,7 @@ abstract class Command extends BaseCommand
$this->input->setArgument('context_name', $this->context_name); $this->input->setArgument('context_name', $this->context_name);
try { try {
$this->context = Application::getContext($this->context_name, $this->getApplication()); $this->context = $this->getProvision()->getContext($this->context_name);
} }
catch (\Exception $e) { catch (\Exception $e) {
$this->context = NULL; $this->context = NULL;
...@@ -104,11 +108,11 @@ abstract class Command extends BaseCommand ...@@ -104,11 +108,11 @@ abstract class Command extends BaseCommand
* Show a list of Contexts to the user for them to choose from. * Show a list of Contexts to the user for them to choose from.
*/ */
public function askForContext($question = 'Choose a context') { public function askForContext($question = 'Choose a context') {
if (empty($this->getApplication()->getAllContextsOptions())) { if (empty($this->getProvision()->getAllContextsOptions())) {
throw new \Exception('No contexts available! use <comment>provision save</comment> to create one.'); throw new \Exception('No contexts available! use <comment>provision save</comment> to create one.');
} }
$this->context_name = $this->io->choice($question, $this->getApplication()->getAllContextsOptions()); $this->context_name = $this->io->choice($question, $this->getProvision()->getAllContextsOptions());
} }
/** /**
......
...@@ -8,6 +8,7 @@ use Aegir\Provision\Context; ...@@ -8,6 +8,7 @@ use Aegir\Provision\Context;
use Aegir\Provision\Context\PlatformContext; use Aegir\Provision\Context\PlatformContext;
use Aegir\Provision\Context\ServerContext; use Aegir\Provision\Context\ServerContext;
use Aegir\Provision\Context\SiteContext; use Aegir\Provision\Context\SiteContext;
use Aegir\Provision\Provision;
use Aegir\Provision\Service; use Aegir\Provision\Service;
use Symfony\Component\Console\Exception\InvalidOptionException; use Symfony\Component\Console\Exception\InvalidOptionException;
use Symfony\Component\Console\Input\ArrayInput; use Symfony\Component\Console\Input\ArrayInput;
...@@ -152,7 +153,7 @@ class SaveCommand extends Command ...@@ -152,7 +153,7 @@ class SaveCommand extends Command
// Check for context type service requirements. // Check for context type service requirements.
$exit = FALSE; $exit = FALSE;
$this->io->comment("Checking service requirements for context type {$context_type}..."); $this->io->comment("Checking service requirements for context type {$context_type}...");
$reqs = Application::checkServiceRequirements($context_type); $reqs = $this->getProvision()->checkServiceRequirements($context_type);
foreach ($reqs as $service => $available) { foreach ($reqs as $service => $available) {
if ($available) { if ($available) {
$this->io->successLite("Service $service: Available"); $this->io->successLite("Service $service: Available");
...@@ -169,9 +170,12 @@ class SaveCommand extends Command ...@@ -169,9 +170,12 @@ class SaveCommand extends Command
} }
$properties = $this->askForContextProperties(); $options = $this->askForContextProperties();
$options['name'] = $this->context_name;
$options['type'] = $this->context_type;
$class = Context::getClassName($this->input->getOption('context_type')); $class = Context::getClassName($this->input->getOption('context_type'));
$this->context = new $class($input->getArgument('context_name'), $this->getApplication(), $properties); $this->context = new $class($input->getArgument('context_name'), $this->getProvision(), $options);
} }
// Delete context config. // Delete context config.
...@@ -227,7 +231,7 @@ class SaveCommand extends Command ...@@ -227,7 +231,7 @@ class SaveCommand extends Command
*/ */
public function askForContext($question = 'Choose a context') public function askForContext($question = 'Choose a context')
{ {
$options = $this->getApplication()->getAllContextsOptions(); $options = $this->getProvision()->getAllContextsOptions();
// If there are options, add "new" to the list. // If there are options, add "new" to the list.
if (count($options)) { if (count($options)) {
...@@ -305,7 +309,7 @@ class SaveCommand extends Command ...@@ -305,7 +309,7 @@ class SaveCommand extends Command
// $context_name = $this->io->ask($all_services[$type]); // $context_name = $this->io->ask($all_services[$type]);
// } // }
// $context = Application::getContext($context_name); // $context = Provision::getContext($context_name);
$this->io->info("Adding required service $type..."); $this->io->info("Adding required service $type...");
...@@ -348,7 +352,7 @@ class SaveCommand extends Command ...@@ -348,7 +352,7 @@ class SaveCommand extends Command
$contexts[$property] = $this->input->getOption($property); $contexts[$property] = $this->input->getOption($property);
try { try {
$context = Application::getContext($contexts[$property]); $context = $this->getProvision()->getContext($contexts[$property]);
} }
catch (\Exception $e) { catch (\Exception $e) {
throw new \Exception("Context set by option --{$property} does not exist."); throw new \Exception("Context set by option --{$property} does not exist.");
...@@ -359,7 +363,7 @@ class SaveCommand extends Command ...@@ -359,7 +363,7 @@ class SaveCommand extends Command
} }
} }
else { else {
$contexts[$property] = $this->io->choice("Select $property context", $this->getApplication()->getAllContextsOptions($context_type)); $contexts[$property] = $this->io->choice("Select $property context", $this->getProvision()->getAllContextsOptions($context_type));
} }
} }
return $contexts; return $contexts;
......
...@@ -219,16 +219,16 @@ class ServicesCommand extends Command ...@@ -219,16 +219,16 @@ class ServicesCommand extends Command
} }
// All other context types are associating with servers that provide the service. // All other context types are associating with servers that provide the service.
else { else {
if (empty($this->getApplication()->getServerOptions($service))) { if (empty($this->getProvision()->getServerOptions($service))) {
throw new \Exception("No servers providing $service service were found. Create one with `provision save` or use `provision services` to add to an existing server."); throw new \Exception("No servers providing $service service were found. Create one with `provision save` or use `provision services` to add to an existing server.");
} }
$server = $this->input->getArgument('server')? $server = $this->input->getArgument('server')?
$this->input->getArgument('server'): $this->input->getArgument('server'):
$this->io->choice('Which server?', $this->getApplication()->getServerOptions($service)); $this->io->choice('Which server?', $this->getProvision()->getServerOptions($service));
// Then ask for all options. // Then ask for all options.
$server_context = $this->getApplication()->getContext($server); $server_context = $this->getProvision()->getContext($server);
$properties = $this->askForServiceProperties($service); $properties = $this->askForServiceProperties($service);
$this->io->info("Using $service service from server $server..."); $this->io->info("Using $service service from server $server...");
......
...@@ -43,6 +43,7 @@ class StatusCommand extends Command ...@@ -43,6 +43,7 @@ class StatusCommand extends Command
*/ */
protected function execute(InputInterface $input, OutputInterface $output) protected function execute(InputInterface $input, OutputInterface $output)
{ {
$this->getProvision();
if ($input->getArgument('context_name')) { if ($input->getArgument('context_name')) {
$rows = [['Configuration File', $this->context->config_path]]; $rows = [['Configuration File', $this->context->config_path]];
...@@ -58,8 +59,9 @@ class StatusCommand extends Command ...@@ -58,8 +59,9 @@ class StatusCommand extends Command
} }
else { else {
$headers = ['Provision CLI Configuration']; $headers = ['Provision CLI Configuration'];
$rows = [['Configuration File', $this->getApplication()->getConfig()->getConfigPath()]]; $rows = [];
$config = $this->getApplication()->getConfig()->all(); $config = $this->getProvision()->getConfig()->toArray();
unset($config['options']);
foreach ($config as $key => $value) { foreach ($config as $key => $value) {
$rows[] = [$key, $value]; $rows[] = [$key, $value];
} }
...@@ -67,14 +69,14 @@ class StatusCommand extends Command ...@@ -67,14 +69,14 @@ class StatusCommand extends Command
// Lookup all contexts // Lookup all contexts
$rows = []; $rows = [];
foreach ($this->getApplication()->getAllContexts() as $context) { foreach ($this->getProvision()->getAllContexts() as $context) {
$rows[] = [$context->name, $context->type]; $rows[] = [$context->name, $context->type];
} }
$headers = ['Contexts']; $headers = ['Contexts'];
$this->io->table($headers, $rows); $this->io->table($headers, $rows);
// Offer to output a context status. // Offer to output a context status.
$options = $this->getApplication()->getAllContextsOptions(); $options = $this->getProvision()->getAllContextsOptions();
$options['none'] = 'none'; $options['none'] = 'none';
$context = $this->io->choiceNoList('Get status for', $options, 'none'); $context = $this->io->choiceNoList('Get status for', $options, 'none');
......
...@@ -60,6 +60,11 @@ class VerifyCommand extends Command ...@@ -60,6 +60,11 @@ class VerifyCommand extends Command
*/ */
protected function execute(InputInterface $input, OutputInterface $output) protected function execute(InputInterface $input, OutputInterface $output)
{ {
if (empty($this->context)) {
throw new \Exception("You must specify a context to verify.");
}
$this->io->title(strtr("Verify %type: %name", [ $this->io->title(strtr("Verify %type: %name", [
'%name' => $this->context_name, '%name' => $this->context_name,
'%type' => $this->context->type, '%type' => $this->context->type,
...@@ -75,8 +80,7 @@ class VerifyCommand extends Command ...@@ -75,8 +80,7 @@ class VerifyCommand extends Command
} }
*/ */
$message = $this->context->verify(); $message = $this->context->verifyCommand();
$this->io->comment($message);
} }
} }
<?php
namespace Aegir\Provision\Common;
use Aegir\Provision\Context;
trait ContextAwareTrait
{
/**
* @var Context
*/
protected $context = NULL;
/**
* @param Context $context
*
* @return $this
*/
public function setContext(Context $context = NULL)
{
$this->context = $context;
return $this;
}
/**
* @return Context
*/
public function getContext()
{
return $this->context;
}
}
<?php
namespace Aegir\Provision\Common;
use Aegir\Provision\Context;
use Symfony\Component\Process\Process;
use Twig\Node\Expression\Unary\NegUnary;
trait ProcessAwareTrait
{
/**
* @var Process
*/
protected $process = NULL;
// /**
// * @var string
// */
// protected $command;
/**
* @param Process $process
*
* @return $this
*/
protected function setProcess(Process $process = NULL)
{
$this->process = $process;
return $this;
}
/**
* @return Process
*/
public function getProcess()
{
if (is_null($this->process)) {
$this->process = new Process($this->command);
}
return $this->process;
}
/**
* @param $command
*
* @return $this
*/
public function setCommand($command) {
$this->command = $command;
return $this;
}
/**
* @return string
*/
public function getCommand() {
return $this->command;
}
public function execute() {
$this->process->run();
}
}
<?php
namespace Aegir\Provision\Common;
use Aegir\Provision\Provision;
trait ProvisionAwareTrait
{
/**
* @var Provision
*/
protected $provision = NULL;
/**
* @param Provision $provision
*
* @return $this
*/
public function setProvision(Provision $provision = NULL)
{
$this->provision = $provision;
return $this;
}
/**
* @return Provision
*/
public function getProvision()
{
if (is_null($this->provision)) {
return Provision::getProvision();
}
return $this->provision;
}
}
...@@ -2,7 +2,7 @@ ...@@ -2,7 +2,7 @@
namespace Aegir\Provision\ConfigDefinition; namespace Aegir\Provision\ConfigDefinition;
use Aegir\Provision\Application; use Aegir\Provision\Common\ProvisionAwareTrait;
use Symfony\Component\Config\Definition\Builder\ScalarNodeDefinition; use Symfony\Component\Config\Definition\Builder\ScalarNodeDefinition;
use Symfony\Component\Config\Definition\Exception\InvalidConfigurationException; use Symfony\Component\Config\Definition\Exception\InvalidConfigurationException;
...@@ -28,6 +28,8 @@ use Symfony\Component\Config\Definition\Exception\InvalidConfigurationException; ...@@ -28,6 +28,8 @@ use Symfony\Component\Config\Definition\Exception\InvalidConfigurationException;
*/ */
class ContextNodeDefinition extends ScalarNodeDefinition class ContextNodeDefinition extends ScalarNodeDefinition
{ {
use ProvisionAwareTrait;
protected function createNode() protected function createNode()
{ {
/** /**
...@@ -50,12 +52,13 @@ class ContextNodeDefinition extends ScalarNodeDefinition ...@@ -50,12 +52,13 @@ class ContextNodeDefinition extends ScalarNodeDefinition
*/ */
public function validateContext($value) public function validateContext($value)
{ {
$this->setProvision($this->getNode()->getAttribute('provision'));
// No need to do anything else. // No need to do anything else.
// If there is no context named $value, getContext() throws an exception for us. // If there is no context named $value, getContext() throws an exception for us.
Application::getContext($value);
// If context_type is specified, Validate that the desired context is the right type. // If context_type is specified, Validate that the desired context is the right type.
if ($this->getNode()->getAttribute('context_type') && Application::getContext($value)->type != $this->getNode()->getAttribute('context_type')) { if ($this->getNode()->getAttribute('context_type') && $this->getProvision()->getContext($value)->type != $this->getNode()->getAttribute('context_type')) {
throw new InvalidConfigurationException(strtr('The context specified for !name must be type !type.', [ throw new InvalidConfigurationException(strtr('The context specified for !name must be type !type.', [
'!name' => $this->name, '!name' => $this->name,
'!type' => $this->getNode()->getAttribute('context_type'), '!type' => $this->getNode()->getAttribute('context_type'),
...@@ -69,8 +72,8 @@ class ContextNodeDefinition extends ScalarNodeDefinition ...@@ -69,8 +72,8 @@ class ContextNodeDefinition extends ScalarNodeDefinition
$this->getNode()->getAttribute('service_requirement'): $this->getNode()->getAttribute('service_requirement'):
$path[2] $path[2]
; ;
Application::getContext($value)->getService($service); $this->getProvision()->getContext($value)->getService($service);
} }
return $value; return $value;
} }
......
...@@ -2,66 +2,48 @@ ...@@ -2,66 +2,48 @@
namespace Aegir\Provision\Console; namespace Aegir\Provision\Console;
use Symfony\Component\Config\Definition\Builder\TreeBuilder; use Symfony\Component\Config\Definition\Exception\Exception;
use Symfony\Component\Config\Definition\ConfigurationInterface; use Symfony\Component\Console\Exception\InvalidOptionException;
use Symfony\Component\Config\Definition\Processor;
use Symfony\Component\Yaml\Dumper;
use Symfony\Component\Filesystem\Filesystem;
use Symfony\Component\Filesystem\Exception\IOExceptionInterface;
use Symfony\Component\Yaml\Yaml;
/** /**
* Class Config. * Class Config
* @package Aegir\Provision\Console
*
* Many thanks to pantheon-systems/terminus. Inspired by DefaultConfig
*/ */
class Config implements ConfigurationInterface class Config extends ProvisionConfig
{ {
/**
* Configuration values array.
*
* @var array
*/
protected $config = [];
/**
* Path to config YML file.
*
* @var string
*/
private $config_path = '';
/**
* Filename of config YML file.
*
* @var string
*/
private $config_filename = '.provision.yml';
const CONFIG_FILENAME = '.provision.yml'; const CONFIG_FILENAME = '.provision.yml';
/** /**
* {@inheritdoc} * DefaultsConfig constructor.
*/ */
public function __construct() public function __construct()
{ {
$this->config_path = $this->getHomeDir().'/'.$this->config_filename; parent::__construct();
try { $this->set('root', $this->getProvisionRoot());
$processor = new Processor(); $this->set('php', $this->getPhpBinary());
$configs = func_get_args(); $this->set('php_version', PHP_VERSION);
if (file_exists($this->config_path)) { $this->set('php_ini', get_cfg_var('cfg_file_path'));
$configs[] = Yaml::parse(file_get_contents($this->config_path)); $this->set('script', $this->getProvisionScript());
} $this->set('os_version', php_uname('v'));
$this->config = $processor->processConfiguration($this, $configs); $this->set('user_home', $this->getHomeDir());
} catch (\Exception $e) {
throw new Exception( $this->set('aegir_root', $this->getHomeDir());
'There is an error with your configuration: '.$e->getMessage() $this->set('script_user', $this->getScriptUser());
); $this->set('config_path', $this->getHomeDir() . '/config');
}
$file = $this->get('user_home') . DIRECTORY_SEPARATOR . Config::CONFIG_FILENAME;
$this->set('console_config_file', $file);
$this->extend(new YamlConfig($this->get('user_home') . DIRECTORY_SEPARATOR . Config::CONFIG_FILENAME));
$this->extend(new DotEnvConfig(getcwd()));
$this->extend(new EnvConfig());
$this->validateConfig(); $this->validateConfig();
} }
/** /**
* Check configuration values against the current system. * Check configuration values against the current system.
* *
...@@ -70,204 +52,108 @@ class Config implements ConfigurationInterface ...@@ -70,204 +52,108 @@ class Config implements ConfigurationInterface
protected function validateConfig() { protected function validateConfig() {
// Check that aegir_root is writable. // Check that aegir_root is writable.
// @TODO: Create some kind of Setup functionality. // @TODO: Create some kind of Setup functionality.
if (!is_writable($this->config['aegir_root'])) { if (!is_writable($this->get('aegir_root'))) {
throw new \Exception( throw new InvalidOptionException(
"There is an error with your configuration. The folder set to 'aegir_root' ({$this->config['aegir_root']}) is not writable. Fix this or change the aegir_root value in the file {$this->config_path}." "The folder set to 'aegir_root' ({$this->get('aegir_root')}) is not writable. Fix this or change the aegir_root value in the file {$this->get('console_config_file')}"
); );
} }
// Check that config_path exists and is writable. // If config_path does not exist and we cannot create it...
if (!file_exists($this->config['config_path'])) { if (!file_exists($this->get('config_path')) && !mkdir($this->get('config_path'))) {
throw new \Exception( throw new InvalidOptionException(
"There is an error with your configuration. The folder set to 'config_path' ({$this->config['config_path']}) does not exist. Create it or change the config_path value in the file {$this->config_path}." "The folder set to 'config_path' ({$this->get('config_path')}) does not exist, and cannot be created. Create it manually or change the 'config_path' value in the file {$this->get('console_config_file')}."
); );
} }
elseif (!is_writable($this->config['config_path'])) { elseif (!is_writable($this->get('config_path'))) {
throw new \Exception( throw new InvalidOptionException(
"There is an error with your configuration. The folder set to 'config_path' ({$this->config['config_path']}) is not writable. Fix this or change the config_path value in the file {$this->config_path}." "The folder set to 'config_path' ({$this->get('config_path')}) is not writable. Fix this or change the config_path value in the file {$this->get('console_config_file')}."
); );
} }
elseif (!file_exists($this->config['config_path'] . '/provision')) { elseif (!file_exists($this->get('config_path') . '/provision')) {
mkdir($this->config['config_path'] . '/provision'); mkdir($this->get('config_path') . '/provision');
} }
// Ensure that script_user is the user. // Ensure that script_user is the user.
$real_script_user = $this->getScriptUser(); $real_script_user = $this->getScriptUser();
if ($this->config['script_user'] != $real_script_user) { if ($this->get('script_user') != $real_script_user) {
throw new \Exception( throw new InvalidOptionException(
"There is an error with your configuration. The user set as 'script_user' ({$this->config['script_user']}) is not the currently running user ({$real_script_user}). Change to user {$this->config['script_user']} or change the script_user value in the file {$this->config_path}." "The user set as 'script_user' ({$this->get('script_user')}) is not the currently running user ({$real_script_user}). Change to user {$this->config->get('script_user')} or change the script_user value in the file {{$this->get('console_config_file')}}."
); );
} }
} }
/**
* {@inheritdoc}
*/
public function getConfigTreeBuilder()
{
$tree_builder = new TreeBuilder();
$root_node = $tree_builder->root('aegir');
$root_node
->children()
->scalarNode('aegir_root')
->defaultValue(Config::getHomeDir())
->end()
->scalarNode('script_user')
->defaultValue(Config::getScriptUser())
->end()
->scalarNode('config_path')
->defaultValue(Config::getHomeDir() . '/config')
->end()
->end();;
return $tree_builder;
}
/**
* Get a config param value.
*
* @param string $key
* Key of the param to get.
*
* @return mixed|null
* Value of the config param, or NULL if not present.
*/
public function get($key, $name = null)
{
if ($name) {
return array_key_exists(
$name,
$this->config[$key]
) ? $this->config[$key][$name] : null;
} else {
return $this->has($key) ? $this->config[$key] : null;
}
}
/**
* Check if config param is present.
*
* @param string $key
* Key of the param to check.
*
* @return bool
* TRUE if key exists.
*/
public function has($key)
{
return array_key_exists($key, $this->config);
}
/** /**
* Set a config param value. * Get the name of the source for this configuration object.
*
* @param string $key
* Key of the param to get.
* @param mixed $val
* Value of the param to set.
* *
* @return bool * @return string
*/ */
public function set($key, $val) public function getSourceName()
{ {
return $this->config[$key] = $val; return 'Default';
} }
/** /**
* Get all config values. * Returns location of PHP with which to run Terminus
* *
* @return array * @return string
* All config galues.
*/ */
public function all() protected function getPhpBinary()
{ {
return $this->config; return defined('PHP_BINARY') ? PHP_BINARY : 'php';
} }
/** /**
* Add a config param value to a config array. * Finds and returns the root directory of Provision
*
* @param string $key
* Key of the group to set to.
* @param string|array $names
* Name of the new object to set.
* @param mixed $val
* Value of the new object to set.
* *
* @return bool * @param string $current_dir Directory to start searching at
* @return string
* @throws \Exception
*/ */
public function add($key, $names, $val) protected function getProvisionRoot($current_dir = null)
{ {
if (is_array($names)) { if (is_null($current_dir)) {
$array_piece = &$this->config[$key]; $current_dir = dirname(__DIR__);
foreach ($names as $name_key) {
$array_piece = &$array_piece[$name_key];
}
return $array_piece = $val;
} else {
return $this->config[$key][$names] = $val;
} }
} if (file_exists($current_dir . DIRECTORY_SEPARATOR . 'composer.json')) {
return $current_dir;
/**
* Remove a config param from a config array.
*
* @param $key
* @param $name
*
* @return bool
*/
public function remove($key, $name)
{
if (isset($this->config[$key][$name])) {
unset($this->config[$key][$name]);
return true;
} else {
return false;
} }
$dir = explode(DIRECTORY_SEPARATOR, $current_dir);
array_pop($dir);
if (empty($dir)) {
throw new \Exception('Could not locate root to set PROVISION_ROOT.');
}
$dir = implode(DIRECTORY_SEPARATOR, $dir);
$root_dir = $this->getProvisionRoot($dir);
return $root_dir;
} }
/** /**
* Saves the config class to file. * Finds and returns the name of the script running Terminus functions
* *
* @return bool * @return string
*/ */
public function save() protected function getProvisionScript()
{ {
$debug = debug_backtrace();
// Create config folder if it does not exist. $script_location = array_pop($debug);
$fs = new Filesystem(); $script_name = str_replace(
$dumper = new Dumper(); $this->getProvisionRoot() . DIRECTORY_SEPARATOR,
'',
try { $script_location['file']
$fs->dumpFile($this->config_path, $dumper->dump($this->config, 10)); );
return $script_name;
return true;
} catch (IOExceptionInterface $e) {
return false;
}
} }
/**
* Determine the user running provision.
*/
static function getScriptUser() {
$real_script_user = posix_getpwuid(posix_geteuid());
return $real_script_user['name'];
}
/** /**
* Returns the appropriate home directory. * Returns the appropriate home directory.
* *
* Adapted from Terminus Package Manager by Ed Reel * Adapted from Terminus Package Manager by Ed Reel
*
* @author Ed Reel <@uberhacker> * @author Ed Reel <@uberhacker>
* @url https://github.com/uberhacker/tpm * @url https://github.com/uberhacker/tpm
* *
* @return string * @return string
*/ */
static function getHomeDir() protected function getHomeDir()
{ {
$home = getenv('HOME'); $home = getenv('HOME');
if (!$home) { if (!$home) {
...@@ -279,14 +165,14 @@ class Config implements ConfigurationInterface ...@@ -279,14 +165,14 @@ class Config implements ConfigurationInterface
$home = getenv('HOMEPATH'); $home = getenv('HOMEPATH');
} }
} }
return $home; return $home;
} }
/** /**
* Determine the user running provision. * Determine the user running provision.
*/ */
public function getConfigPath() { protected function getScriptUser() {
return $this->config_path; $real_script_user = posix_getpwuid(posix_geteuid());
return $real_script_user['name'];
} }
} }
<?php
namespace Aegir\Provision\Console;
use Aegir\Provision\Provision;
/**
* Class DotEnvConfig
* @package Pantheon\Terminus\Config
*/
class DotEnvConfig extends ProvisionConfig
{
/**
* @var string
*/
protected $file;
/**
* DotEnvConfig constructor.
*/
public function __construct($dir)
{
parent::__construct();
$file = $dir . '/.env';
$this->setSourceName($file);
// Load environment variables from __DIR__/.env
if (file_exists($file)) {
// Remove comments (which start with '#')
$lines = file($file);
$lines = array_filter($lines, function ($line) {
return strpos(trim($line), '#') !== 0;
});
$info = parse_ini_string(implode($lines, "\n"));
$this->fromArray($info);
}
}
}
<?php
namespace Aegir\Provision\Console;
/**
* Class EnvConfig
* @package Aegir\Provision\Console
*/
class EnvConfig extends ProvisionConfig
{
protected $source_name = 'Environment Variable';
/**
* EnvConfig constructor.
*/
public function __construct()
{
parent::__construct();
// Add all of the environment vars that match our constant.
foreach ([$_SERVER, $_ENV] as $super) {
foreach ($super as $key => $val) {
if ($this->keyIsConstant($key)) {
$this->set($key, $val);
}
}
}
}
}
<?php
namespace Aegir\Provision\Console;
/**
* Class ProvisionConfig
* @package Aegir\Provision\Console
*
* Many thanks to pantheon-systems/terminus.
*/
class ProvisionConfig extends \Robo\Config
{
/**
* @var string
*/
protected $constant_prefix = 'PROVISION_';
/**
* @var array
*/
protected $sources = [];
/**
* @var string
*/
protected $source_name = 'Unknown';
/**
* Set add all the values in the array to this Config object.
}
* @param array $array
*/
public function fromArray(array $array = [])
{
foreach ($array as $key => $val) {
$this->set($key, $val);
}
}
/**
* Convert the config to an array.
*
* @return array
*/
public function toArray()
{
$out = [];
foreach ($this->keys() as $key) {
$out[$key] = $this->get($key);
}
return $out;
}
/**
* Set a config value. Converts key from Provision constant (PROVISION_XXX) if needed.
*
* @param string $key
* @param mixed $value
*
* @return $this
*/
public function set($key, $value)
{
// Convert Provision constant name to internal key.
if ($this->keyIsConstant($key)) {
$key = $this->getKeyFromConstant($key);
}
return parent::set($key, $value);
}
/**
* Get a configuration value
*
* @param string $key Which config item to look up
* @param string|null $defaultOverride Override usual default value with a different default
*
* @return mixed
*/
public function get($key, $defaultOverride = null)
{
$value = parent::get($key, $defaultOverride);
// Replace placeholders.
if (is_string($value)) {
$value = $this->replacePlaceholders($value);
}
return $value;
}
/**
* Return all of the keys in the Config
* @return array
*/
public function keys()
{
return array_keys($this->export());
}
/**
* Override the values in this Config object with the given input Config
*
* @param \Aegir\Provision\Console\Config $in
*/
public function extend(ProvisionConfig $in)
{
foreach ($in->keys() as $key) {
$this->set($key, $in->get($key));
// Set the source of this variable to make tracking config easier.
$this->setSource($key, $in->getSource($key));
}
}
/**
* Get the name of the source for this configuration object.
*
* @return string
*/
public function getSourceName()
{
return $this->source_name;
}
/**
* Get a description of where this configuration came from.
*
* @param $key
* @return string
*/
public function getSource($key)
{
return isset($this->sources[$key]) ? $this->sources[$key] : $this->getSourceName();
}
/**
* Set the source for a given configuration item.
*
* @param $key
* @param $source
*/
protected function setSource($key, $source)
{
$this->sources[$key] = $source;
}
/**
* Reflects a key name given a PRovision constant name
*
* @param string $constant_name The name of a constant to get a key for
* @return string
*/
protected function getKeyFromConstant($constant_name)
{
$key = strtolower(str_replace($this->constant_prefix, '', $constant_name));
return $key;
}
/**
* Turn an internal key into a constant name
*
* @param string $key The key to get the constant name for.
* @return string
*/
public function getConstantFromKey($key)
{
$key = strtoupper($this->constant_prefix . $key);
return $key;
}
/**
* Determines if a key is a Provision constant name
*
* @param $key
* @return boolean
*/
protected function keyIsConstant($key)
{
return strpos($key, $this->constant_prefix) === 0;
}
/**
* Exchanges values in [[ ]] in the given string with constants
*
* @param string $string The string to perform replacements on
* @return string $string The modified string
*/
protected function replacePlaceholders($string)
{
$regex = '~\[\[(.*?)\]\]~';
preg_match_all($regex, $string, $matches);
if (!empty($matches)) {
foreach ($matches[1] as $id => $value) {
$replacement_key = $this->getKeyFromConstant(trim($value));
$replacement = $this->get($replacement_key);
if ($replacement) {
$string = str_replace($matches[0][$id], $replacement, $string);
}
}
}
$fixed_string = $this->fixDirectorySeparators($string);
return $fixed_string;
}
/**
* Ensures a directory exists
*
* @param string $name The name of the config var
* @param string $value The value of the named config var
* @return boolean|null
*/
public function ensureDirExists($name, $value)
{
if ((strpos($name, $this->constant_prefix) !== false) && (strpos($name, '_DIR') !== false) && ($value != '~')) {
try {
$dir_exists = (is_dir($value) || (!file_exists($value) && @mkdir($value, 0777, true)));
} catch (\Exception $e) {
return false;
}
return $dir_exists;
}
return null;
}
/**
* Ensures that directory paths work in any system
*
* @param string $path A path to set the directory separators for
* @return string
*/
public function fixDirectorySeparators($path)
{
return str_replace(['/', '\\',], DIRECTORY_SEPARATOR, $path);
}
/**
* @param mixed $source_name
*/
public function setSourceName($source_name)
{
$this->source_name = $source_name;
}
}
<?php
namespace Aegir\Provision\Console;
use Symfony\Component\Yaml\Yaml;
/**
* Class YamlConfig
* @package Aegir\Provision\Console
*
* Many thanks to pantheon-systems/terminus.
*/
class YamlConfig extends ProvisionConfig
{
/**
* YamlConfig constructor.
* @param string $yml_path The path to the yaml file.
*/
public function __construct($yml_path)
{
parent::__construct();
$this->setSourceName($yml_path);
$file_config = file_exists($yml_path) ? Yaml::parse(file_get_contents($yml_path)) : [];
if (!is_null($file_config)) {
$this->fromArray($file_config);
}
}
}
...@@ -6,12 +6,15 @@ ...@@ -6,12 +6,15 @@
namespace Aegir\Provision; namespace Aegir\Provision;
use Aegir\Provision\Common\ProvisionAwareTrait;
use Aegir\Provision\Console\Config; use Aegir\Provision\Console\Config;
use Consolidation\AnnotatedCommand\CommandFileDiscovery; use Consolidation\AnnotatedCommand\CommandFileDiscovery;
use Drupal\Console\Core\Style\DrupalStyle; use Drupal\Console\Core\Style\DrupalStyle;
use Psr\Log\LoggerInterface; use Robo\Common\BuilderAwareTrait;
use Robo\Contract\BuilderAwareInterface;
use Symfony\Component\Config\Definition\Builder\TreeBuilder; use Symfony\Component\Config\Definition\Builder\TreeBuilder;
use Symfony\Component\Config\Definition\Processor; use Symfony\Component\Config\Definition\Processor;
use Symfony\Component\Console\Exception\InvalidOptionException;
use Symfony\Component\Filesystem\Exception\IOException; use Symfony\Component\Filesystem\Exception\IOException;
use Symfony\Component\Filesystem\Filesystem; use Symfony\Component\Filesystem\Filesystem;
use Symfony\Component\Yaml\Dumper; use Symfony\Component\Yaml\Dumper;
...@@ -24,9 +27,12 @@ use Symfony\Component\Yaml\Yaml; ...@@ -24,9 +27,12 @@ use Symfony\Component\Yaml\Yaml;
* *
* @package Aegir\Provision * @package Aegir\Provision
*/ */
class Context class Context implements BuilderAwareInterface
{ {
use BuilderAwareTrait;
use ProvisionAwareTrait;
/** /**
* @var string * @var string
* Name for saving aliases and referencing. * Name for saving aliases and referencing.
...@@ -60,27 +66,23 @@ class Context ...@@ -60,27 +66,23 @@ class Context
* init(), set defaults with setProperty(). * init(), set defaults with setProperty().
*/ */
protected $properties = []; protected $properties = [];
/**
* @var \Aegir\Provision\Application;
*/
public $application;
/**
* @var LoggerInterface
*/
public $logger;
/** /**
* Context constructor. * Context constructor.
* *
* @param $name * @param $name
* @param array $options * @param array $options
*/ */
function __construct($name, Application $application = NULL, $options = []) function __construct(
$name,
Provision $provision,
$options = [])
{ {
$this->name = $name; $this->name = $name;
$this->application = $application;
$this->setProvision($provision);
$this->setBuilder($this->getProvision()->getBuilder());
$this->loadContextConfig($options); $this->loadContextConfig($options);
$this->prepareServices(); $this->prepareServices();
} }
...@@ -94,8 +96,8 @@ class Context ...@@ -94,8 +96,8 @@ class Context
*/ */
private function loadContextConfig($options = []) { private function loadContextConfig($options = []) {
if ($this->application) { if ($this->getProvision()) {
$this->config_path = $this->application->getConfig()->get('config_path') . '/provision/' . $this->type . '.' . $this->name . '.yml'; $this->config_path = $this->getProvision()->getConfig()->get('config_path') . '/provision/' . $this->type . '.' . $this->name . '.yml';
} }
else { else {
$config = new Config(); $config = new Config();
...@@ -115,14 +117,16 @@ class Context ...@@ -115,14 +117,16 @@ class Context
$this->properties[$option] = $options[$option]; $this->properties[$option] = $options[$option];
} }
} }
$this->properties['type'] = $this->type;
$this->properties['name'] = $this->name;
$configs[] = $this->properties; $configs[] = $this->properties;
$this->properties['context_type'] = $this->type;
$this->config = $processor->processConfiguration($this, $configs); $this->config = $processor->processConfiguration($this, $configs);
} catch (\Exception $e) { } catch (\Exception $e) {
throw new \Exception( throw new InvalidOptionException(
strtr("There is an error with the configuration for !type '!name'. Check the file !file and try again. \n \nError: !message", [ strtr("There is an error with the configuration for !type '!name'. Check the file !file and try again. \n \nError: !message", [
'!type' => $this->type, '!type' => $this->type,
'!name' => $this->name, '!name' => $this->name,
...@@ -269,6 +273,11 @@ class Context ...@@ -269,6 +273,11 @@ class Context
->children() ->children()
->scalarNode('name') ->scalarNode('name')
->defaultValue($this->name) ->defaultValue($this->name)
->isRequired()
->end()
->scalarNode('type')
->defaultValue($this->type)
->isRequired()
->end() ->end()
->end(); ->end();
...@@ -293,6 +302,7 @@ class Context ...@@ -293,6 +302,7 @@ class Context
->node($property, 'context') ->node($property, 'context')
->isRequired() ->isRequired()
->attribute('context_type', $type) ->attribute('context_type', $type)
->attribute('provision', $this->getProvision())
->end() ->end()
->end(); ->end();
} }
...@@ -323,7 +333,7 @@ class Context ...@@ -323,7 +333,7 @@ class Context
// If type is empty, it's because it's in the ServerContext // If type is empty, it's because it's in the ServerContext
if (empty($info['type'])) { if (empty($info['type'])) {
$server = Application::getContext($info['server']); $server = $this->getProvision()->getContext($info['server']);
$service_type = ucfirst($server->getService($service)->type); $service_type = ucfirst($server->getService($service)->type);
} }
else { else {
...@@ -466,32 +476,33 @@ class Context ...@@ -466,32 +476,33 @@ class Context
* *
* If this context is a Service Subscriber, the provider service will be verified first. * If this context is a Service Subscriber, the provider service will be verified first.
*/ */
public function verify() { public function verifyCommand() {
$return_codes = []; $return_codes = [];
// Run verify method on all services. // Run verify method on all services.
foreach ($this->getServices() as $type => $service) { foreach ($this->getServices() as $type => $service) {
$friendlyName = $service->getFriendlyName(); $return_codes[] = $service->verify() ? 0 : 1;
if ($this->isProvider()) {
$this->application->io->section("Verify service: {$friendlyName}");
foreach ($service->verify() as $type => $verify_success) {
$return_codes[] = $verify_success? 0: 1;
}
}
else {
$this->application->io->section("Verify service: {$friendlyName} on {$service->provider->name}");
// First verify the service provider.
foreach ($service->verifyProvider() as $verify_part => $verify_success) {
$return_codes[] = $verify_success? 0: 1;
}
// Then run "verify" on the subscriptions.
foreach ($this->getSubscription($type)->verify() as $type => $verify_success) {
$return_codes[] = $verify_success? 0: 1;
}
}
} }
//
// if ($this->isProvider()) {
// $this->getProvision()->io()->section("Verify service: {$friendlyName}");
// foreach ($service->verify() as $type => $verify_success) {
// $return_codes[] = $verify_success? 0: 1;
// }
// }
// else {
// $this->getProvision()->io()->section("Verify service: {$friendlyName} on {$service->provider->name}");
//
// // First verify the service provider.
// foreach ($service->verifyProvider() as $verify_part => $verify_success) {
// $return_codes[] = $verify_success? 0: 1;
// }
//
// // Then run "verify" on the subscriptions.
// foreach ($this->getSubscription($type)->verify() as $type => $verify_success) {
// $return_codes[] = $verify_success? 0: 1;
// }
// }
// }
// If any service verify failed, exit with a non-zero code. // If any service verify failed, exit with a non-zero code.
if (count(array_filter($return_codes))) { if (count(array_filter($return_codes))) {
......
...@@ -4,6 +4,7 @@ namespace Aegir\Provision\Context; ...@@ -4,6 +4,7 @@ namespace Aegir\Provision\Context;
use Aegir\Provision\Application; use Aegir\Provision\Application;
use Aegir\Provision\ContextSubscriber; use Aegir\Provision\ContextSubscriber;
use Aegir\Provision\Provision;
use Symfony\Component\Config\Definition\ConfigurationInterface; use Symfony\Component\Config\Definition\ConfigurationInterface;
/** /**
...@@ -30,12 +31,15 @@ class PlatformContext extends ContextSubscriber implements ConfigurationInterfac ...@@ -30,12 +31,15 @@ class PlatformContext extends ContextSubscriber implements ConfigurationInterfac
* PlatformContext constructor. * PlatformContext constructor.
* *
* @param $name * @param $name
* @param Application $application * @param Provision $provision
* @param array $options * @param array $options
*/ */
function __construct($name, Application $application = NULL, array $options = []) function __construct(
{ $name,
parent::__construct($name, $application, $options); Provision $provision = NULL,
$options = []
) {
parent::__construct($name, $provision, $options);
// Load "web_server" context. // Load "web_server" context.
// There is no need to validate for $this->properties['web_server'] because the config system does that. // There is no need to validate for $this->properties['web_server'] because the config system does that.
...@@ -71,8 +75,15 @@ class PlatformContext extends ContextSubscriber implements ConfigurationInterfac ...@@ -71,8 +75,15 @@ class PlatformContext extends ContextSubscriber implements ConfigurationInterfac
*/ */
public function verify() public function verify()
{ {
$this->application->io->customLite($this->getProperty('root'), 'Root: ', 'info'); $this->getProvision()->io()->customLite($this->getProperty('root'), 'Root: ', 'info');
$this->application->io->customLite($this->config_path, 'Configuration File: ', 'info'); $this->getProvision()->io()->customLite($this->config_path, 'Configuration File: ', 'info');
// This is how you can use Robo Tasks in a platform verification call.
// The "silent" method actually works here.
// It only partially works in Service::restartServices()!
$this->getBuilder()->taskExec('env')
->silent(!$this->getProvision()->io()->isVerbose())
->run();
return parent::verify(); return parent::verify();
} }
......
...@@ -3,7 +3,9 @@ ...@@ -3,7 +3,9 @@
namespace Aegir\Provision\Context; namespace Aegir\Provision\Context;
use Aegir\Provision\Application; use Aegir\Provision\Application;
use Aegir\Provision\Context;
use Aegir\Provision\ContextSubscriber; use Aegir\Provision\ContextSubscriber;
use Aegir\Provision\Provision;
use Symfony\Component\Config\Definition\ConfigurationInterface; use Symfony\Component\Config\Definition\ConfigurationInterface;
/** /**
...@@ -34,17 +36,20 @@ class SiteContext extends ContextSubscriber implements ConfigurationInterface ...@@ -34,17 +36,20 @@ class SiteContext extends ContextSubscriber implements ConfigurationInterface
* @param Application $application * @param Application $application
* @param array $options * @param array $options
*/ */
function __construct($name, Application $application = NULL, array $options = []) function __construct(
{ $name,
parent::__construct($name, $application, $options); Provision $provision = NULL,
$options = []
) {
parent::__construct($name, $provision, $options);
// Load "web_server" and "platform" contexts. // Load "web_server" and "platform" contexts.
// There is no need to check if the property exists because the config system does that. // There is no need to check if the property exists because the config system does that.
// $this->db_server = $application->getContext($this->properties['db_server']); // $this->db_server = $application->getContext($this->properties['db_server']);
$this->platform = Application::getContext($this->properties['platform'], $application); // Load platform context... @TODO: Automatically do this for required contexts?
$this->platform = $this->getProvision()->getContext($this->properties['platform']);
// Add platform http service subscription. // Add platform http service subscription.
$this->serviceSubscriptions['http'] = $this->platform->getSubscription('http'); $this->serviceSubscriptions['http'] = $this->platform->getSubscription('http');
$this->serviceSubscriptions['http']->context = $this; $this->serviceSubscriptions['http']->context = $this;
...@@ -82,9 +87,9 @@ class SiteContext extends ContextSubscriber implements ConfigurationInterface ...@@ -82,9 +87,9 @@ class SiteContext extends ContextSubscriber implements ConfigurationInterface
*/ */
public function verify() public function verify()
{ {
$this->application->io->customLite($this->getProperty('uri'), 'Site URL: ', 'info'); $this->getProvision()->io()->customLite($this->getProperty('uri'), 'Site URL: ', 'info');
$this->application->io->customLite($this->platform->getProperty('root'), 'Root: ', 'info'); $this->getProvision()->io()->customLite($this->platform->getProperty('root'), 'Root: ', 'info');
$this->application->io->customLite($this->config_path, 'Configuration File: ', 'info'); $this->getProvision()->io()->customLite($this->config_path, 'Configuration File: ', 'info');
return parent::verify(); return parent::verify();
} }
......
...@@ -93,6 +93,7 @@ class ContextSubscriber extends Context ...@@ -93,6 +93,7 @@ class ContextSubscriber extends Context
->node('server', 'context') ->node('server', 'context')
->isRequired() ->isRequired()
->attribute('context_type', 'server') ->attribute('context_type', 'server')
->attribute('provision', $this->getProvision())
->end() ->end()
->append($this->addServiceProperties('service_subscriptions')) ->append($this->addServiceProperties('service_subscriptions'))
->end() ->end()
......