HttpApacheDockerService.php 17.4 KB
Newer Older
1 2 3 4 5 6 7 8 9 10
<?php
/**
 * @file
 * The Provision HttpApacheService class.
 *
 * @see \Provision_Service_http_apache
 */

namespace Aegir\Provision\Service\Http;

11
use Aegir\Provision\Configuration;
12
use Aegir\Provision\Context;
13 14
use Aegir\Provision\Robo\ProvisionExecutor;
use Aegir\Provision\Robo\ProvisionTasks;
15
use Aegir\Provision\Robo\Task\Log;
16 17 18
use Aegir\Provision\Service\Http\Apache\Configuration\PlatformConfiguration;
use Aegir\Provision\Service\Http\Apache\Configuration\SiteConfiguration;
use Aegir\Provision\Service\Http\ApacheDocker\Configuration\ServerConfiguration;
19
use Behat\Mink\Exception\Exception;
20
use Psr\Log\LogLevel;
21 22 23 24 25 26 27 28 29 30 31 32 33
use Robo\Task\Base\Exec;
use Robo\Task\Docker\Run;
use Robo\Tasks;

/**
 * Class HttpApacheDockerService
 *
 * @package Aegir\Provision\Service\Http
 */
class HttpApacheDockerService extends HttpApacheService
{
  const SERVICE_TYPE = 'apacheDocker';
  const SERVICE_TYPE_NAME = 'Apache on Docker';
34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59


  /**
   * @var string The name of this server's container.
   */
  private $containerName;


  /**
   * @var string The tag for this server's container.
   */
  private $containerTag;

  /**
   * HttpApacheDockerService constructor.
   * @param $service_config
   * @param Context $provider_context
   */
  function __construct($service_config, Context $provider_context)
  {
      parent::__construct($service_config, $provider_context);

      $this->containerName = "provision_http_{$this->provider->name}";
      $this->containerTag = "provision/http:{$this->provider->name}";
  }

60 61 62 63 64 65 66 67 68 69 70 71 72 73
  /**
   * Returns array of Configuration classes for this service.
   *
   * @see Provision_Service_http_apache::init_server();
   *
   * @return array
   */
  public function getConfigurations()
  {
    $configs['server'][] = ServerConfiguration::class;
    $configs['platform'][] = PlatformConfiguration::class;
    $configs['site'][] = SiteConfiguration::class;
    return $configs;
  }
74

Jon Pugh's avatar
Jon Pugh committed
75 76 77 78 79 80 81
    /**
     * Alter the root path because Provision stores the local path.
     *
     * Apache config must reflect the path inside the container.
     *
     * @param Configuration $config
     */
82 83 84
  public function processConfiguration(Configuration &$config) {

      // Replace platform's stored root with server's root.
85 86 87 88 89 90 91 92 93 94
      if ($this->context instanceof Context\SiteContext) {
          $root_on_host = $this->context->platform->getProperty('root');
      }
      elseif ($this->context instanceof Context\PlatformContext) {
          $root_on_host = $this->context->getProperty('root');
      }
      else {
          return;
      }

95
      $config->data['root'] = $this->mapContainerPath($root_on_host);
96 97 98 99

      if ($this->context instanceof Context\SiteContext) {
          $config->data['site_path'] = $config->data['root'] . '/sites/' . $config->data['uri'];
      }
100 101 102
      
      // When running in docker, internal port is always 80.
      $config->data['http_port'] = 80;
103
  }
104 105 106 107 108 109 110 111 112 113 114 115 116
    
    /**
     * Convert a path on the host like /home/jon/hostmaster to /var/aegir/hostmaster
     *
     * @param $root_on_host
     *
     * @return string
     */
    function mapContainerPath($root_on_host) {
        $path_parts = explode(DIRECTORY_SEPARATOR, $root_on_host);
        $directory = array_pop($path_parts);
        return $this->provider->getProperty('aegir_root') . DIRECTORY_SEPARATOR . 'platforms' . DIRECTORY_SEPARATOR . $directory;
    }
117
  
118
  public function verifyServer() {
119 120
      $tasks = [];

121
      $provision = $this->getProvision();
122
      $robo = $this->getProvision()->getTasks();
123
      $provider = $this->provider;
124
      $build_dir = __DIR__ . DIRECTORY_SEPARATOR . '/ApacheDocker/';
125 126
      
      // Write Apache configuration files.
127
      $tasks['Saved Apache configuration files.'] = function () use ($provision) {
128 129 130 131
          $this->writeConfigurations();
      };
      
      // Build Docker image.
132
      $tasks['http.docker.build'] = $this->getProvision()->newTask()
133 134 135
          ->success('Built new Docker image for Apache: ' . $this->containerTag)
          ->failure('Unable to build docker container with tag: ' . $this->containerTag)
          ->execute(function () use ($provision, $build_dir) {
136
          $this->getProvision()->getTasks()->taskDockerBuild($build_dir)
137
              ->tag($this->containerTag)
138 139 140 141 142 143 144 145 146
              ->option(
                  '-f',
                  __DIR__.DIRECTORY_SEPARATOR.'/ApacheDocker/http.Dockerfile'
              )
              ->option(
                  '--build-arg',
                  "AEGIR_SERVER_NAME={$this->provider->name}"
              )
              ->option('--build-arg', "AEGIR_UID=".posix_getuid())
147
              ->silent(!$this->getProvision()->getOutput()->isVerbose())
148 149
              ->run()
          ;
150
      });
151
      
152
      // Docker run
153
      $tasks['Run docker image.'] = function () use ($provision,$provider) {
154
        
155 156
          // Check for existing container.
          $containerExists = $provision->getTasks()
157
              ->taskExec("docker ps -a -q -f name={$this->containerName}")
158 159 160
              ->silent(!$this->getProvision()->getOutput()->isVerbose())
              ->printOutput(false)
              ->storeState('container_id')
161
              ->taskFileSystemStack()
162
              ->defer(
163
                  function ($task, $state) use ($provision, $provider) {
164 165 166 167 168
                      $container = $state['container_id'];
                      if ($container) {
                        
                          //Check that it is running
                          $provision->getTasks()
169
                              ->taskExec("docker inspect -f '{{.State.Running}}' {$this->containerName}")
170 171 172 173 174
                              ->silent(!$provision->getOutput()->isVerbose())
                              ->printOutput(false)
                              ->storeState('running')
                              ->taskFileSystemStack()
                              ->defer(
175
                                  function ($task, $state) use ($provision, $provider) {
176 177
                                    
                                      if ($state['running'] == 'true') {
178
                                          $provision->io()->successLite('Container is already running: ' . $this->containerName);
179 180 181 182
                                      }
                                      // If not running, try to start it.
                                      else {
                                          $startResult = $provision->getTasks()
183
                                              ->taskExec("docker start {$this->containerName}")
184 185 186 187 188
                                              ->silent(!$provision->getOutput()->isVerbose())
                                              ->run()
                                          ;
                                        
                                          if ($startResult->wasSuccessful()) {
189
                                              $provision->io()->successLite('Existing container found. Restarted container ' . $this->containerName);
190 191
                                          }
                                          else {
192 193
                                              $provision->io()->errorLite('Unable to restart docker container: ' . $this->containerName);
                                              throw new \Exception('Unable to restart docker container: ' . $this->containerName);
194 195 196 197 198 199 200 201 202
                                          }
                                      }
                                  })
                              ->run();
                        
                      }
                    
                      # Docker container not found. Start it.
                      else {
203 204
                          $configVolumeHost = $provision->getConfig()->get('config_path') . DIRECTORY_SEPARATOR . $this->provider->name;
                          $configVolumeGuest = $this->provider->getProperty('aegir_root') . '/config/' . $this->provider->name;
205
                        
206
                          $container = $provision->getTasks()->taskDockerRun($this->containerTag)
207
                              ->detached()
208
                              ->publish($this->getProperty('http_port'), 80)
209
                              ->name($this->containerName)
210 211
                              ->volume($configVolumeHost, $configVolumeGuest)
                              ->silent(!$provision->getOutput()->isVerbose())
212
                              ->option('rm')
213 214
                              ->interactive();

215 216 217 218 219
                          // Lookup all subscribers (all platforms that use this web service) and map volumes for root.
                          foreach ($this->getAllSubscribers() as $platform) {
                              if (!empty($platform->getProperty('root'))) {
                                  $container->volume($platform->getProperty('root'), $this->mapContainerPath($platform->getProperty('root')));
                              }
220 221 222
                          }

                          $result = $container->run();
223 224
                        
                          if ($result->wasSuccessful()) {
225
                              $provision->io()->successLite('Running Docker image ' . $this->containerTag);
226 227
                          }
                          else {
228 229
                              $provision->io()->errorLite('Unable to run docker container: ' . $this->containerName);
                              throw new \Exception('Unable to run docker container: ' . $this->containerName);
230 231
                          }
                      }
232 233
                  }
              )
234 235 236 237 238 239 240
              ->run();
          if ($containerExists->wasSuccessful()) {
              $this->getProvision()->getLogger()->info('All processes completed successfully.');
          }
          else {
              throw new \Exception('Something went wrong.');
          }
241 242
      };
      
243
      $tasks['http.restart'] = $this->getProvision()->newTask()
244
          ->execute(function() {
245 246 247 248 249
              $this->restartService();
          })
          ->success('Restarted web service.')
          ->failure('Unable to restart web service.');
      
250
      return $tasks;
251
  }
252 253 254 255 256 257

  /**
   * Override HttpService by adding 'docker exec' in front of it.
   */
  public function restartService() {
      $this->properties['restart_command'] = "docker exec {$this->containerName}  {$this->properties['restart_command']}";
258
      return parent::restartService();
259
  }
260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413
//
//  public function verify2()
//  {
//      $provision = $this->getProvision();
//      $provider = $this->provider;
//      $logger = $this->getProvision()->getLogger();
//      $collection = $this->getProvision()->getBuilder();
//      $collection->addCode(
//          function () use ($logger) {
//              $this->writeConfigurations();
//          }
//      );
//
//      $tag = "provision/http:{$this->provider->name}";
//      $name = "provision_http_{$this->provider->name}";
//      $build_dir = __DIR__ . DIRECTORY_SEPARATOR . '/ApacheDocker/';
//
//      # Build Docker Image
//      $collection->getCollection()->addCode(function () use ($provision, $tag, $name, $provider, $build_dir) {
//          $buildResult = $this->getProvision()->getTasks()->taskDockerBuild($build_dir)
//              ->tag($tag)
//              ->option(
//                  '-f',
//                  __DIR__.DIRECTORY_SEPARATOR.'/ApacheDocker/http.Dockerfile'
//              )
//              ->option(
//                  '--build-arg',
//                  "AEGIR_SERVER_NAME={$this->provider->name}"
//              )
//              ->option('--build-arg', "AEGIR_UID=".posix_getuid())
//              ->silent(!$this->getProvision()->getOutput()->isVerbose())
//              ->run()
//          ;
//
//          if ($buildResult->wasSuccessful()) {
//              $provision->io()->successLite('Built new Docker image for Apache: ' . $tag);
//          }
//          else {
//              $provision->io()->errorLite('Unable to build docker container with tag: ' . $tag);
//              throw new \Exception('Unable to build docker container with tag: ' . $tag);
//          }
//      }, 'docker-build');
//
//      # Run Docker Image
//      $collection->getCollection()->addCode(function () use ($provision, $tag, $name, $provider) {
//
//          // Check for existing container.
//          $containerExists = $provision->getTasks()
//              ->taskExec("docker ps -a -q -f name={$name}")
//                    ->silent(!$this->getProvision()->getOutput()->isVerbose())
//                  ->printOutput(false)
//                  ->storeState('container_id')
//              ->taskFileSystemStack()
//                  ->defer(
//                      function ($task, $state) use ($provision, $tag, $name, $provider) {
//                          $container = $state['container_id'];
//                          if ($container) {
//
//                              //Check that it is running
//                              $provision->getTasks()
//                                  ->taskExec("docker inspect -f '{{.State.Running}}' {$name}")
//                                      ->silent(!$provision->getOutput()->isVerbose())
//                                      ->printOutput(false)
//                                      ->storeState('running')
//                                  ->taskFileSystemStack()
//                                      ->defer(
//                                          function ($task, $state) use ($provision, $tag, $name, $provider) {
//
//                                              if ($state['running'] == 'true') {
//                                                  $provision->io()->successLite('Container is already running: ' . $name);
//                                              }
//                                              // If not running, try to start it.
//                                              else {
//                                                  $startResult = $provision->getTasks()
//                                                      ->taskExec("docker start {$name}")
//                                                      ->silent(!$provision->getOutput()->isVerbose())
//                                                      ->run()
//                                                  ;
//
//                                                  if ($startResult->wasSuccessful()) {
//                                                      $provision->io()->successLite('Existing container found. Restarted container ' . $name);
//                                                  }
//                                                  else {
//                                                      $provision->io()->errorLite('Unable to restart docker container: ' . $name);
//                                                      throw new \Exception('Unable to restart docker container: ' . $name);
//                                                  }
//                                              }
//                                          })
//                                  ->run();
//
//                          }
//
//                          # Docker container not found. Start it.
//                          else {
//                              $configVolumeHost = $provision->getConfig()->get('config_path') . DIRECTORY_SEPARATOR . $this->provider->name . DIRECTORY_SEPARATOR . '/apache';
//                              $configVolumeGuest = $this->provider->getProperty('aegir_root') . '/config/' . $this->provider->name . DIRECTORY_SEPARATOR . '/apache';
//
//                              $result = $provision->getTasks()->taskDockerRun($tag)
//                                  ->detached()
//                                  ->publish(80)
//                                  ->name($name)
//                                  ->volume($configVolumeHost, $configVolumeGuest)
//                                  ->silent(!$provision->getOutput()->isVerbose())
//                                  ->interactive()
//                                  ->run();
//
//                              if ($result->wasSuccessful()) {
//                                  $provision->io()->successLite('Running Docker image ' . $tag);
//                              }
//                              else {
//                                  $provision->io()->errorLite('Unable to run docker container: ' . $name);
//                                  throw new \Exception('Unable to run docker container: ' . $name);
//                              }
//                          }
//                      }
//                  )
//              ->run();
//          if ($containerExists->wasSuccessful()) {
//              $this->getProvision()->getLogger()->info('All processes completed successfully.');
//          }
//          else {
//              throw new \Exception('Something went wrong.');
//          }
//      });
//
//      $collection->getCollection()->addCode(function () use ($provision, $tag, $name, $provider) {
          
//          $this->getProvision()->application->console->runCollection($);
//          $provision->io()->customLite('Waiting for godot...', '𝙋');
//          $provision->io()->progressStart();
//
//
//          sleep(1);
//          $provision->io()->progressAdvance();
//
//          sleep(1);
//          $provision->io()->progressAdvance();
//
//          sleep(1);
//          $provision->io()->progressAdvance();
//
//          sleep(1);
//          $provision->io()->progressAdvance();
//
//          sleep(1);
//          $provision->io()->progressAdvance();
//          sleep(1);
//
//          $provision->io()->progressFinish();
//
    
//      });
//      return $collection;
//  }
414
}