Skip to content
Commits on Source (18)
......@@ -11,6 +11,7 @@ use Aegir\Provision\Common\ProvisionAwareTrait;
use Aegir\Provision\Console\Config;
use Aegir\Provision\Console\ConsoleOutput;
use Drupal\Console\Core\Style\DrupalStyle;
use Psr\Log\LoggerAwareTrait;
use Psr\Log\LoggerInterface;
use Psr\Log\LogLevel;
use Symfony\Component\Console\Command\HelpCommand;
......@@ -21,6 +22,7 @@ use Symfony\Component\Console\Input\InputDefinition;
use Symfony\Component\Console\Logger\ConsoleLogger;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Application as BaseApplication;
use Symfony\Component\Console\Command\Command as BaseCommand;
//use Symfony\Component\DependencyInjection\ContainerInterface;
//use Drupal\Console\Annotations\DrupalCommandAnnotationReader;
......@@ -46,6 +48,7 @@ class Application extends BaseApplication
const DEFAULT_TIMEZONE = 'America/New_York';
use ProvisionAwareTrait;
use LoggerAwareTrait;
/**
* @var ConsoleOutput
......@@ -66,46 +69,19 @@ class Application extends BaseApplication
if (empty(ini_get('date.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;
$this->output = $output;
$this->logger = new ConsoleLogger($output,
[LogLevel::INFO => OutputInterface::VERBOSITY_NORMAL]
);
parent::__construct($name, $version);
}
/**
* Getter for Configuration.
* Make configureIO public so we can run it before ->run()
*
* @return \Aegir\Provision\Console\ProvisionConfig
* Configuration object.
* @param InputInterface $input
* @param OutputInterface $output
*/
public function getConfig()
public function configureIO(InputInterface $input, OutputInterface $output)
{
return $this->getProvision()->getConfig();
parent::configureIO($input, $output);
}
/**
......@@ -115,15 +91,37 @@ class Application extends BaseApplication
{
$commands[] = new HelpCommand();
$commands[] = new ListCommand();
$commands[] = new SaveCommand($this->getProvision());
$commands[] = new ServicesCommand($this->getProvision());
$commands[] = new SaveCommand();
$commands[] = new ServicesCommand();
// $commands[] = new ShellCommand();
$commands[] = new StatusCommand($this->getProvision());
$commands[] = new VerifyCommand($this->getProvision());
$commands[] = new StatusCommand();
$commands[] = new VerifyCommand();
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}
*
......
......@@ -4,6 +4,8 @@ namespace Aegir\Provision;
use Aegir\Provision\Common\ProvisionAwareTrait;
use Drupal\Console\Core\Style\DrupalStyle;
use Psr\Log\LoggerAwareTrait;
use Psr\Log\LoggerInterface;
use Psr\Log\LogLevel;
use Symfony\Component\Console\Command\Command as BaseCommand;
use Drupal\Console\Core\Command\Shared\CommandTrait;
......@@ -21,6 +23,7 @@ abstract class Command extends BaseCommand
use CommandTrait;
use ProvisionAwareTrait;
use LoggerAwareTrait;
/**
* @var \Symfony\Component\Console\Input\InputInterface
......@@ -52,18 +55,6 @@ abstract class Command extends BaseCommand
*/
public $context_name;
/**
* Command constructor.
*
* @param \Aegir\Provision\Provision $provision
*/
function __construct(Provision $provision)
{
$this->setProvision($provision);
parent::__construct();
}
/**
* @param InputInterface $input An InputInterface instance
* @param OutputInterface $output An OutputInterface instance
......@@ -83,7 +74,7 @@ abstract class Command extends BaseCommand
try {
// Load context from context_name argument.
$this->context_name = $this->input->getArgument('context_name');
$this->context = Provision::getContext($this->context_name, $this->getProvision());
$this->context = $this->getProvision()->getContext($this->context_name);
}
catch (\Exception $e) {
......@@ -105,7 +96,7 @@ abstract class Command extends BaseCommand
$this->input->setArgument('context_name', $this->context_name);
try {
$this->context = Provision::getContext($this->context_name, $this->getProvision());
$this->context = $this->getProvision()->getContext($this->context_name);
}
catch (\Exception $e) {
$this->context = NULL;
......@@ -117,11 +108,11 @@ abstract class Command extends BaseCommand
* Show a list of Contexts to the user for them to choose from.
*/
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.');
}
$this->context_name = $this->io->choice($question, $this->getApplication()->getAllContextsOptions());
$this->context_name = $this->io->choice($question, $this->getProvision()->getAllContextsOptions());
}
/**
......
......@@ -153,7 +153,7 @@ class SaveCommand extends Command
// Check for context type service requirements.
$exit = FALSE;
$this->io->comment("Checking service requirements for context type {$context_type}...");
$reqs = Provision::checkServiceRequirements($context_type);
$reqs = $this->getProvision()->checkServiceRequirements($context_type);
foreach ($reqs as $service => $available) {
if ($available) {
$this->io->successLite("Service $service: Available");
......@@ -170,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'));
$this->context = new $class($input->getArgument('context_name'), $this->getProvision(), $properties);
$this->context = new $class($input->getArgument('context_name'), $this->getProvision(), $options);
}
// Delete context config.
......@@ -228,7 +231,7 @@ class SaveCommand extends Command
*/
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 (count($options)) {
......@@ -349,7 +352,7 @@ class SaveCommand extends Command
$contexts[$property] = $this->input->getOption($property);
try {
$context = Provision::getContext($contexts[$property]);
$context = $this->getProvision()->getContext($contexts[$property]);
}
catch (\Exception $e) {
throw new \Exception("Context set by option --{$property} does not exist.");
......@@ -360,7 +363,7 @@ class SaveCommand extends Command
}
}
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;
......
......@@ -219,16 +219,16 @@ class ServicesCommand extends Command
}
// All other context types are associating with servers that provide the service.
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.");
}
$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.
$server_context = $this->getApplication()->getContext($server);
$server_context = $this->getProvision()->getContext($server);
$properties = $this->askForServiceProperties($service);
$this->io->info("Using $service service from server $server...");
......
......@@ -43,6 +43,7 @@ class StatusCommand extends Command
*/
protected function execute(InputInterface $input, OutputInterface $output)
{
$this->getProvision();
if ($input->getArgument('context_name')) {
$rows = [['Configuration File', $this->context->config_path]];
......
......@@ -60,6 +60,11 @@ class VerifyCommand extends Command
*/
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", [
'%name' => $this->context_name,
'%type' => $this->context->type,
......@@ -75,7 +80,7 @@ class VerifyCommand extends Command
}
*/
$message = $this->context->verify();
$message = $this->context->verifyCommand();
}
}
<?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();
}
}
......@@ -28,6 +28,11 @@ trait ProvisionAwareTrait
*/
public function getProvision()
{
if (is_null($this->provision)) {
return Provision::getProvision();
}
return $this->provision;
}
}
......@@ -2,8 +2,7 @@
namespace Aegir\Provision\ConfigDefinition;
use Aegir\Provision\Application;
use Aegir\Provision\Provision;
use Aegir\Provision\Common\ProvisionAwareTrait;
use Symfony\Component\Config\Definition\Builder\ScalarNodeDefinition;
use Symfony\Component\Config\Definition\Exception\InvalidConfigurationException;
......@@ -29,6 +28,8 @@ use Symfony\Component\Config\Definition\Exception\InvalidConfigurationException;
*/
class ContextNodeDefinition extends ScalarNodeDefinition
{
use ProvisionAwareTrait;
protected function createNode()
{
/**
......@@ -51,12 +52,13 @@ class ContextNodeDefinition extends ScalarNodeDefinition
*/
public function validateContext($value)
{
$this->setProvision($this->getNode()->getAttribute('provision'));
// No need to do anything else.
// If there is no context named $value, getContext() throws an exception for us.
Provision::getContext($value);
// If context_type is specified, Validate that the desired context is the right type.
if ($this->getNode()->getAttribute('context_type') && Provision::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.', [
'!name' => $this->name,
'!type' => $this->getNode()->getAttribute('context_type'),
......@@ -70,8 +72,8 @@ class ContextNodeDefinition extends ScalarNodeDefinition
$this->getNode()->getAttribute('service_requirement'):
$path[2]
;
Provision::getContext($value)->getService($service);
$this->getProvision()->getContext($value)->getService($service);
}
return $value;
}
......
......@@ -10,11 +10,11 @@ use Aegir\Provision\Common\ProvisionAwareTrait;
use Aegir\Provision\Console\Config;
use Consolidation\AnnotatedCommand\CommandFileDiscovery;
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\Processor;
use Symfony\Component\Console\Exception\InvalidOptionException;
use Symfony\Component\Filesystem\Exception\IOException;
use Symfony\Component\Filesystem\Filesystem;
use Symfony\Component\Yaml\Dumper;
......@@ -67,11 +67,6 @@ class Context implements BuilderAwareInterface
*/
protected $properties = [];
/**
* @var LoggerInterface
*/
public $logger;
/**
* Context constructor.
*
......@@ -80,17 +75,16 @@ class Context implements BuilderAwareInterface
*/
function __construct(
$name,
Provision $provision = NULL,
Provision $provision,
$options = [])
{
$this->name = $name;
$this->setProvision($provision);
$this->setBuilder($this->getProvision()->getBuilder());
$this->loadContextConfig($options);
$this->prepareServices();
if ($provision) {
$this->setProvision($provision);
$this->setBuilder($this->getProvision()->getBuilder());
}
}
/**
......@@ -123,14 +117,16 @@ class Context implements BuilderAwareInterface
$this->properties[$option] = $options[$option];
}
}
$this->properties['type'] = $this->type;
$this->properties['name'] = $this->name;
$configs[] = $this->properties;
$this->properties['context_type'] = $this->type;
$this->config = $processor->processConfiguration($this, $configs);
} 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", [
'!type' => $this->type,
'!name' => $this->name,
......@@ -277,6 +273,11 @@ class Context implements BuilderAwareInterface
->children()
->scalarNode('name')
->defaultValue($this->name)
->isRequired()
->end()
->scalarNode('type')
->defaultValue($this->type)
->isRequired()
->end()
->end();
......@@ -301,6 +302,7 @@ class Context implements BuilderAwareInterface
->node($property, 'context')
->isRequired()
->attribute('context_type', $type)
->attribute('provision', $this->getProvision())
->end()
->end();
}
......@@ -331,7 +333,7 @@ class Context implements BuilderAwareInterface
// If type is empty, it's because it's in the ServerContext
if (empty($info['type'])) {
$server = Provision::getContext($info['server']);
$server = $this->getProvision()->getContext($info['server']);
$service_type = ucfirst($server->getService($service)->type);
}
else {
......@@ -474,32 +476,33 @@ class Context implements BuilderAwareInterface
*
* If this context is a Service Subscriber, the provider service will be verified first.
*/
public function verify() {
public function verifyCommand() {
$return_codes = [];
// Run verify method on all services.
foreach ($this->getServices() as $type => $service) {
$friendlyName = $service->getFriendlyName();
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;
}
}
$return_codes[] = $service->verify() ? 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 (count(array_filter($return_codes))) {
......
......@@ -75,14 +75,14 @@ class PlatformContext extends ContextSubscriber implements ConfigurationInterfac
*/
public function verify()
{
$this->application->io->customLite($this->getProperty('root'), 'Root: ', 'info');
$this->application->io->customLite($this->config_path, 'Configuration File: ', 'info');
$this->getProvision()->io()->customLite($this->getProperty('root'), 'Root: ', '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->application->io->isVerbose())
->silent(!$this->getProvision()->io()->isVerbose())
->run();
return parent::verify();
......
......@@ -3,6 +3,7 @@
namespace Aegir\Provision\Context;
use Aegir\Provision\Application;
use Aegir\Provision\Context;
use Aegir\Provision\ContextSubscriber;
use Aegir\Provision\Provision;
use Symfony\Component\Config\Definition\ConfigurationInterface;
......@@ -46,9 +47,9 @@ class SiteContext extends ContextSubscriber implements ConfigurationInterface
// 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->platform = Provision::getContext($this->properties['platform'], $provision);
// Load platform context... @TODO: Automatically do this for required contexts?
$this->platform = $this->getProvision()->getContext($this->properties['platform']);
// Add platform http service subscription.
$this->serviceSubscriptions['http'] = $this->platform->getSubscription('http');
$this->serviceSubscriptions['http']->context = $this;
......@@ -86,9 +87,9 @@ class SiteContext extends ContextSubscriber implements ConfigurationInterface
*/
public function verify()
{
$this->application->io->customLite($this->getProperty('uri'), 'Site URL: ', 'info');
$this->application->io->customLite($this->platform->getProperty('root'), 'Root: ', 'info');
$this->application->io->customLite($this->config_path, 'Configuration File: ', 'info');
$this->getProvision()->io()->customLite($this->getProperty('uri'), 'Site URL: ', 'info');
$this->getProvision()->io()->customLite($this->platform->getProperty('root'), 'Root: ', 'info');
$this->getProvision()->io()->customLite($this->config_path, 'Configuration File: ', 'info');
return parent::verify();
}
......
......@@ -93,6 +93,7 @@ class ContextSubscriber extends Context
->node('server', 'context')
->isRequired()
->attribute('context_type', 'server')
->attribute('provision', $this->getProvision())
->end()
->append($this->addServiceProperties('service_subscriptions'))
->end()
......
......@@ -6,25 +6,28 @@ namespace Aegir\Provision;
use Aegir\Provision\Console\Config;
use Aegir\Provision\Commands\ExampleCommands;
use Aegir\Provision\Console\ConsoleOutput;
use Aegir\Provision\Robo\ProvisionCollectionBuilder;
use Aegir\Provision\Robo\ProvisionExecutor;
use Aegir\Provision\Robo\ProvisionTasks;
use Drupal\Console\Core\Style\DrupalStyle;
use League\Container\Container;
use League\Container\ContainerAwareInterface;
use League\Container\ContainerAwareTrait;
use Psr\Log\LoggerAwareInterface;
use Psr\Log\LoggerAwareTrait;
use Robo\Collection\CollectionBuilder;
use Psr\Log\LogLevel;
use Robo\Common\BuilderAwareTrait;
use Robo\Common\ConfigAwareTrait;
use Robo\Common\IO;
use Robo\Contract\BuilderAwareInterface;
use Robo\Contract\ConfigAwareInterface;
use Robo\Contract\IOAwareInterface;
use Robo\Log\RoboLogger;
use Robo\Robo;
use Robo\Runner as RoboRunner;
use Symfony\Component\Console\Input\ArgvInput;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Logger\ConsoleLogger;
use Symfony\Component\Console\Output\OutputInterface;
/**
......@@ -59,6 +62,16 @@ class Provision implements ConfigAwareInterface, ContainerAwareInterface, Logger
*/
private $commands = [];
/**
* @var \Aegir\Provision\Context[]
*/
private $contexts = [];
/**
* @var array[]
*/
private $context_files = [];
/**
* Provision constructor.
*
......@@ -71,21 +84,28 @@ class Provision implements ConfigAwareInterface, ContainerAwareInterface, Logger
InputInterface $input = NULL,
OutputInterface $output = NULL
) {
$this->setConfig($config);
$this->setInput($input);
$this->setOutput($output);
$logger = new ConsoleLogger($output);
$this
->setConfig($config)
;
// Create Application.
$application = new Application(self::APPLICATION_NAME, self::VERSION);
$application->setProvision($this);
// $application->setConfig($consoleConfig);
$application
->setProvision($this)
->setLogger($logger)
;
$application->configureIO($input, $output);
$this->setInput($input);
$this->setOutput($output);
// Create and configure container.
$container = Robo::createDefaultContainer($input, $output, $application, $config);
$this->setContainer($container);
$this->configureContainer($container);
// Instantiate Robo Runner.
$this->runner = new RoboRunner([
ExampleCommands::class
......@@ -96,11 +116,51 @@ class Provision implements ConfigAwareInterface, ContainerAwareInterface, Logger
$this->setBuilder($container->get('builder'));
$this->setLogger($container->get('logger'));
$this->loadAllContexts();
}
/**
* Lookup all context yml files and load into Context classes.
*/
private function loadAllContexts()
{
$folder = $this->getConfig()->get('config_path') . '/provision';
$finder = new \Symfony\Component\Finder\Finder();
$finder->files()->name("*.yml")->in($folder);
foreach ($finder as $file) {
$context_type = substr($file->getFilename(), 0, strpos($file->getFilename(), '.'));
$context_name = substr($file->getFilename(), strpos($file->getFilename(), '.') + 1, strlen($file->getFilename()) - strlen($context_type) - 5);
$this->context_files[$context_name] = [
'name' => $context_name,
'type' => $context_type,
'file' => $file,
];
}
// Load Context classes from files metadata.
foreach ($this->context_files as $context) {
$class = Context::getClassName($context['type']);
$this->contexts[$context['name']] = new $class($context['name'], $this);
}
}
/**
* Loads a single context from file into $this->contexts[$name].
*
* Used to load dependant contexts that might not be instantiated yet.
*
* @param $name
*/
public function loadContext($name) {
$class = Context::getClassName($this->context_files[$name]['type']);
$this->contexts[$this->context_files[$name]['name']] = new $class($this->context_files[$name]['name'], $this);
}
public function run(InputInterface $input, OutputInterface $output) {
$status_code = $this->runner->run($input, $output);
return $status_code;
}
......@@ -142,41 +202,55 @@ class Provision implements ConfigAwareInterface, ContainerAwareInterface, Logger
return $this->input();
}
/**
* Gets Logger object.
* Returns the currently active Logger instance.
*
* @return \Psr\Log\LoggerInterface
*/
public function getLogger()
{
return $this->logger;
}
/**
* Load all contexts into Context objects.
* Provide access to DrupalStyle object.
*
* @return array
* @return \Drupal\Console\Core\Style\DrupalStyle
*/
static function getAllContexts($name = '', Provision $provision = 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'], $provision);
public function io()
{
if (!$this->io) {
$this->io = new DrupalStyle($this->input(), $this->output());
}
if ($name && isset($contexts[$name])) {
return $contexts[$name];
return $this->io;
}
/**
* Get a new Provision
* @return \Aegir\Provision\Provision
*/
static function getProvision() {
$input = new ArgvInput();
$output = new ConsoleOutput();
$config = new Config();
return new Provision($config, $input, $output);
}
/**
* Return all available contexts.
*
* @return array|Context
*/
public function getAllContexts($name = '') {
if ($name && isset($this->contexts[$name])) {
return $this->contexts[$name];
}
elseif ($name && !isset($contexts[$name])) {
elseif ($name && !isset($this->contexts[$name])) {
return NULL;
}
else {
return $contexts;
return $this->contexts;
}
}
......@@ -187,9 +261,9 @@ class Provision implements ConfigAwareInterface, ContainerAwareInterface, Logger
* @return mixed
* @throws \Exception
*/
static public function getAllServers($service = NULL) {
protected function getAllServers($service = NULL) {
$servers = [];
$context_files = self::getAllContexts();
$context_files = $this->getAllContexts();
if (empty($context_files)) {
throw new \Exception('No server contexts found. Use `provision save` to create one.');
}
......@@ -225,17 +299,39 @@ class Provision implements ConfigAwareInterface, ContainerAwareInterface, Logger
*
* @param $name
*
* @return \Aegir\Provision\Context
* @return array|\Aegir\Provision\Context
* @throws \Exception
*/
static public function getContext($name, Provision $provision = NULL) {
public function getContext($name) {
// Check if $name is empty.
if (empty($name)) {
throw new \Exception('Context name must not be empty.');
}
// If context exists but hasn't been loaded, load it.
if (empty($this->contexts[$name]) && !empty($this->context_files[$name])) {
$this->loadContext($name);
}
// Check if context still isn't found.
if (empty($this->contexts[$name])) {
throw new \Exception('Context not found with name: ' . $name);
}
return $this->contexts[$name];
}
/**
* Look for a context file being present. This is available before Context
* objects are bootstrapped.
*/
public function getContextFile($name) {
if (empty($name)) {
throw new \Exception('Context name must not be empty.');
}
if (empty(Provision::getAllContexts($name, $provision))) {
if (empty($this->context_files[$name])) {
throw new \Exception('Context not found with name: ' . $name);
}
return Provision::getAllContexts($name, $provision);
return$this->context_files[$name];
}
/**
......@@ -262,7 +358,7 @@ class Provision implements ConfigAwareInterface, ContainerAwareInterface, Logger
* @param $type
* @return array
*/
static function checkServiceRequirements($type) {
public function checkServiceRequirements($type) {
$class_name = Context::getClassName($type);
// @var $context Context
......@@ -271,7 +367,7 @@ class Provision implements ConfigAwareInterface, ContainerAwareInterface, Logger
$services = [];
foreach ($service_requirements as $service) {
try {
if (empty(Provision::getAllServers($service))) {
if (empty($this->getAllServers($service))) {
$services[$service] = 0;
}
else {
......
......@@ -8,17 +8,20 @@
namespace Aegir\Provision;
use Aegir\Provision\Common\ContextAwareTrait;
use Aegir\Provision\Common\ProvisionAwareTrait;
use Psr\Log\LoggerAwareTrait;
use Robo\Common\BuilderAwareTrait;
use Robo\Common\OutputAdapter;
use Robo\Contract\BuilderAwareInterface;
class Service implements BuilderAwareInterface
{
use BuilderAwareTrait;
use ProvisionAwareTrait;
use ContextAwareTrait;
use LoggerAwareTrait;
public $type;
public $properties;
......@@ -46,7 +49,9 @@ class Service implements BuilderAwareInterface
function __construct($service_config, Context $provider_context)
{
$this->provider = $provider_context;
$this->setContext($provider_context);
$this->setProvision($provider_context->getProvision());
$this->setLogger($provider_context->getProvision()->getLogger());
$this->type = $service_config['type'];
$this->properties = $service_config['properties'];
......@@ -77,30 +82,54 @@ class Service implements BuilderAwareInterface
return "\Aegir\Provision\Service\\{$service}Service";
}
}
/**
* React to the `provision verify` command.
*/
function verify()
{
return [
'configuration' => $this->writeConfigurations(),
'service' => $this->restartService(),
];
}
/**
* React to `provision verify` command when run on a subscriber, to verify the service's provider.
*
* This is used to allow skipping of the service restart.
* React to the verify command. Passes off to the method verifySite, verifyServer, verifyPlatform.
* @return mixed
*/
function verifyProvider()
{
return [
'configuration' => $this->writeConfigurations(),
];
public function verify() {
$method = 'verify' . ucfirst($this->getContext()->type);
$this->getProvision()->getLogger()->info("Running {method}", [
'method' => $method
]);
return $this::$method();
}
//
// /**
// * React to the `provision verify` command.
// */
// function verifySite()
// {
// return [
// 'configuration' => $this->writeConfigurations(),
// 'service' => $this->restartService(),
// ];
// }
//
// /**
// * React to the `provision verify` command.
// */
// function verifyPlatform()
// {
// return [
// 'configuration' => $this->writeConfigurations(),
// 'service' => $this->restartService(),
// ];
// }
//
// /**
// * React to `provision verify` command when run on a subscriber, to verify the service's provider.
// *
// * This is used to allow skipping of the service restart.
// */
// function verifyServer()
// {
// return [
// 'configuration' => $this->writeConfigurations(),
// ];
// }
/**
* Run the services "restart_command".
* @return bool
......@@ -110,19 +139,19 @@ class Service implements BuilderAwareInterface
return TRUE;
}
else {
$task = $this->application->getProvision()->getBuilder()->taskExec($this->properties['restart_command'])
->silent(!$this->application->io->isVerbose())
$task = $this->getProvision()->getBuilder()->taskExec($this->properties['restart_command'])
->silent(!$this->getProvision()->io()->isVerbose())
;
/** @var \Robo\Result $result */
$result = $task->run();
if ($result->wasSuccessful()) {
$this->application->io->successLite('Service restarted.');
$this->getProvision()->io()->successLite('Service restarted.');
sleep(1);
return TRUE;
}
else {
$this->application->io->errorLite('Unable to restart service:' . $result->getOutputData());
$this->getProvision()->io()->errorLite('Unable to restart service:' . $result->getOutputData());
}
}
return FALSE;
......@@ -174,12 +203,12 @@ class Service implements BuilderAwareInterface
try {
$config = new $configuration_class($context, $this);
$config->write();
$context->application->io->successLite(
$context->getProvision()->io()->successLite(
'Wrote '.$config->description.' to '.$config->filename()
);
}
catch (\Exception $e) {
$context->application->io->errorLite(
$context->getProvision()->io()->errorLite(
'Unable to write '.$config->description.' to '.$config->filename() . ': ' . $e->getMessage()
);
$success = FALSE;
......
......@@ -34,7 +34,7 @@ class DbMysqlService extends DbService
if ($this->database_exists($test)) {
if (!$this->drop_database($test)) {
$this->provider->application->io->errorLite(strtr("Failed to drop database @dbname", ['@dbname' => $test]));
$this->provider->getProvision()->io()->errorLite(strtr("Failed to drop database @dbname", ['@dbname' => $test]));
}
return TRUE;
}
......
......@@ -12,6 +12,7 @@ namespace Aegir\Provision\Service;
use Aegir\Provision\Context\SiteContext;
use Aegir\Provision\Service;
use Aegir\Provision\ServiceInterface;
use Aegir\Provision\ServiceSubscription;
use Symfony\Component\Console\Output\OutputInterface;
......@@ -20,7 +21,7 @@ use Symfony\Component\Console\Output\OutputInterface;
*
* @package Aegir\Provision\Service
*/
class DbService extends Service
class DbService extends Service implements ServiceInterface
{
const SERVICE = 'db';
......@@ -89,7 +90,7 @@ class DbService extends Service
/**
* React to the `provision verify` command on Server contexts
*/
function verify() {
function verifyServer() {
$this->creds = array_map('urldecode', parse_url($this->properties['master_db']));
if (!isset($this->creds['port'])) {
......@@ -105,18 +106,18 @@ class DbService extends Service
try {
$this->connect();
$return = TRUE;
$this->provider->application->io->successLite('Successfully connected to database server!');
$this->provider->getProvision()->io()->successLite('Successfully connected to database server!');
if ($this->can_create_database()) {
$this->provider->application->io->successLite('Provision can create new databases.');
$this->provider->getProvision()->io()->successLite('Provision can create new databases.');
} else {
$this->provider->application->io->errorLite('Provision is unable to create databases.');
$this->provider->getProvision()->io()->errorLite('Provision is unable to create databases.');
$return = FALSE;
}
if ($this->can_grant_privileges()) {
$this->provider->application->io->successLite('Provision can grant privileges on database users.');
$this->provider->getProvision()->io()->successLite('Provision can grant privileges on database users.');
} else {
$this->provider->application->io->errorLite('Provision is unable to grant privileges on database users.');
$this->provider->getProvision()->io()->errorLite('Provision is unable to grant privileges on database users.');
$return = FALSE;
}
......@@ -125,7 +126,7 @@ class DbService extends Service
];
}
catch (\PDOException $e) {
$this->provider->application->io->errorLite($e->getMessage());
$this->provider->getProvision()->io()->errorLite($e->getMessage());
return [
'service' => FALSE
];
......@@ -135,11 +136,11 @@ class DbService extends Service
/**
* React to the `provision verify` command on subscriber contexts (sites and platforms)
*/
function verifySubscription(ServiceSubscription $serviceSubscription) {
$this->subscription = $serviceSubscription;
function verifySite() {
$this->subscription = $this->getContext()->getSubscription($this->type);
// Check for database
$this->create_site_database($serviceSubscription->context);
$this->create_site_database($this->getContext());
$this->creds_root = array_map('urldecode', parse_url($this->properties['master_db']));
......@@ -156,19 +157,23 @@ class DbService extends Service
try {
$this->connect();
$this->subscription->context->application->io->successLite('Successfully connected to database server.');
$this->subscription->context->getProvision()->io()->successLite('Successfully connected to database server.');
return [
'service' => TRUE
];
}
catch (\PDOException $e) {
$this->subscription->context->application->io->errorLite($e->getMessage());
$this->subscription->context->getProvision()->io()->errorLite($e->getMessage());
return [
'service' => FALSE
];
}
}
public function verifyPlatform() {
}
/**
* React to `provision verify` command when run on a subscriber, to verify the service's provider.
*
......@@ -215,11 +220,11 @@ class DbService extends Service
$query = preg_replace_callback($this::PROVISION_QUERY_REGEXP, array($this, 'query_callback'), $query);
try {
$this->provider->application->logger->notice("Running Query: {$query}");
$this->provider->getProvision()->getLogger()->info("Running Query: {$query}");
$result = $this->conn->query($query);
}
catch (\PDOException $e) {
$this->provider->application->io->errorLite($e->getMessage());
$this->provider->getProvision()->getLogger()->error($e->getMessage());
return FALSE;
}
......@@ -381,13 +386,13 @@ class DbService extends Service
}
if ($this->database_exists($db_name)) {
$this->application->io->successLite(strtr("Database '@name' already exists.", [
$this->getProvision()->io()->successLite(strtr("Database '@name' already exists.", [
'@name' => $db_name
]));
}
else {
$this->create_database($db_name);
$this->application->io->successLite(strtr("Created database '@name'.", [
$this->getProvision()->io()->successLite(strtr("Created database '@name'.", [
'@name' => $db_name,
]));
}
......@@ -398,7 +403,7 @@ class DbService extends Service
'@user' => $db_user
]));
}
$this->application->io->successLite(strtr("Granted privileges to user '@user@@host' for database '@name'.", [
$this->getProvision()->io()->successLite(strtr("Granted privileges to user '@user@@host' for database '@name'.", [
'@user' => $db_user,
'@host' => $db_grant_host,
'@name' => $db_name,
......@@ -408,7 +413,7 @@ class DbService extends Service
$status = $this->database_exists($db_name);
if ($status) {
$this->application->io->successLite(strtr("Database service configured for site @name.", [
$this->getProvision()->io()->successLite(strtr("Database service configured for site @name.", [
'@name' => $site->name,
]));
}
......
......@@ -21,7 +21,7 @@ class PlatformConfiguration extends Configuration {
function filename() {
$file = $this->context->name . '.conf';
return $this->context->application->getConfig()->get('config_path') . '/' . $this->service->provider->name . '/' . $this->service->getType() . '/platform.d/' . $file;
return $this->context->getProvision()->getConfig()->get('config_path') . '/' . $this->service->provider->name . '/' . $this->service->getType() . '/platform.d/' . $file;
}
function process()
......
......@@ -26,7 +26,7 @@ class ServerConfiguration extends Configuration {
function filename() {
if ($this->service->getType()) {
$file = $this->service->getType() . '.conf';
return $this->service->provider->application->getConfig()->get('config_path') . '/' . $this->service->provider->name . '/' . $file;
return $this->service->provider->getProvision()->getConfig()->get('config_path') . '/' . $this->service->provider->name . '/' . $file;
}
else {
return FALSE;
......@@ -35,7 +35,7 @@ class ServerConfiguration extends Configuration {
function process()
{
parent::process();
$app_dir = $this->context->application->getConfig()->get('config_path') . '/' . $this->context->name . '/' . $this->service->getType();
$app_dir = $this->context->getProvision()->getConfig()->get('config_path') . '/' . $this->context->name . '/' . $this->service->getType();
$this->data['http_port'] = $this->service->properties['http_port'];
$this->data['include_statement'] = '# INCLUDE STATEMENT';
$this->data['http_pred_path'] = "{$app_dir}/pre.d";
......