View source
<?php
namespace Drupal\automatic_updates\Services;
use Drupal\automatic_updates\Event\PostUpdateEvent;
use Drupal\automatic_updates\Event\UpdateEvents;
use Drupal\automatic_updates\ProjectInfoTrait;
use Drupal\automatic_updates\ReadinessChecker\ReadinessCheckerManagerInterface;
use Drupal\automatic_updates\UpdateMetadata;
use Drupal\Component\FileSystem\FileSystem;
use Drupal\Core\Archiver\ArchiverInterface;
use Drupal\Core\Archiver\ArchiverManager;
use Drupal\Core\Config\ConfigFactoryInterface;
use Drupal\Core\File\Exception\FileException;
use Drupal\Core\File\FileSystemInterface;
use Drupal\Core\Url;
use Drupal\Signify\ChecksumList;
use Drupal\Signify\FailedCheckumFilter;
use Drupal\Signify\Verifier;
use GuzzleHttp\ClientInterface;
use GuzzleHttp\Exception\RequestException;
use Psr\Log\LoggerInterface;
class InPlaceUpdate implements UpdateInterface {
use ProjectInfoTrait;
const DELETION_MANIFEST = 'DELETION_MANIFEST.txt';
const ARCHIVE_DIRECTORY = 'files/';
protected $logger;
protected $archiveManager;
protected $configFactory;
protected $fileSystem;
protected $httpClient;
protected $rootPath;
protected $vendorPath;
protected $backup;
protected $tempDirectory;
public function __construct(LoggerInterface $logger, ArchiverManager $archive_manager, ConfigFactoryInterface $config_factory, FileSystemInterface $file_system, ClientInterface $http_client, $app_root) {
$this->logger = $logger;
$this->archiveManager = $archive_manager;
$this->configFactory = $config_factory;
$this->fileSystem = $file_system;
$this->httpClient = $http_client;
$this->rootPath = (string) $app_root;
$this->vendorPath = $this->rootPath . DIRECTORY_SEPARATOR . 'vendor' . DIRECTORY_SEPARATOR;
$project_root = drupal_get_path('module', 'automatic_updates');
require_once $project_root . DIRECTORY_SEPARATOR . 'vendor' . DIRECTORY_SEPARATOR . 'autoload.php';
}
public function update(UpdateMetadata $metadata) {
$checker = \Drupal::service('automatic_updates.readiness_checker');
if ($checker
->run(ReadinessCheckerManagerInterface::ERROR)) {
return FALSE;
}
$success = FALSE;
if ($metadata
->getProjectName() === 'drupal') {
$project_root = $this->rootPath;
}
else {
$project_root = drupal_get_path($metadata
->getProjectType(), $metadata
->getProjectName());
}
if ($archive = $this
->getArchive($metadata)) {
$modified = $this
->checkModifiedFiles($metadata, $archive);
if (!$modified && $this
->backup($archive, $project_root)) {
$this->logger
->info('In place update has started.');
try {
$success = $this
->processUpdate($archive, $project_root);
$this->logger
->info('In place update has finished.');
} catch (\Throwable $throwable) {
$this->logger
->info('In place update failed.');
watchdog_exception($throwable);
} catch (\Exception $exception) {
$this->logger
->info('In place update failed.');
watchdog_exception($exception);
}
if ($success) {
$process = automatic_updates_console_command('updatedb:status');
if ($success && $process
->getOutput()) {
$this->logger
->info('Database update handling has started.');
$success = $this
->handleDatabaseUpdates();
$this->logger
->info('Database update handling has finished.');
}
}
if (!$success) {
$this->logger
->info('Rollback has started.');
$this
->rollback($project_root);
$this->logger
->info('Rollback has finished.');
}
if ($success) {
$this->logger
->info('Cache clear has started.');
$this
->cacheRebuild();
$this->logger
->info('Cache clear has finished.');
}
}
}
$event_dispatcher = \Drupal::service('event_dispatcher');
$event = new PostUpdateEvent($metadata, $success);
$event_dispatcher
->dispatch(UpdateEvents::POST_UPDATE, $event);
return $success;
}
protected function getArchive(UpdateMetadata $metadata) {
$quasi_patch = $this
->getQuasiPatchFileName($metadata);
$url = $this
->buildUrl($metadata
->getProjectName(), $quasi_patch);
$temp_directory = FileSystem::getOsTemporaryDirectory() . DIRECTORY_SEPARATOR;
$destination = $this->fileSystem
->getDestinationFilename($temp_directory . $quasi_patch, FileSystemInterface::EXISTS_REPLACE);
$this
->doGetResource($url, $destination);
$csig_file = $quasi_patch . '.csig';
$csig_url = $this
->buildUrl($metadata
->getProjectName(), $csig_file);
$csig_destination = $this->fileSystem
->getDestinationFilename(FileSystem::getOsTemporaryDirectory() . DIRECTORY_SEPARATOR . $csig_file, FileSystemInterface::EXISTS_REPLACE);
$this
->doGetResource($csig_url, $csig_destination);
$csig = file_get_contents($csig_destination);
$this
->validateArchive($temp_directory, $csig);
return $this->archiveManager
->getInstance([
'filepath' => $destination,
]);
}
protected function checkModifiedFiles(UpdateMetadata $metadata, ArchiverInterface $archive) {
if ($metadata
->getProjectType() === 'core') {
$metadata
->setProjectType('module');
}
$extensions = $this
->getInfos($metadata
->getProjectType());
$modified_files = \Drupal::service('automatic_updates.modified_files');
try {
$files = iterator_to_array($modified_files
->getModifiedFiles([
$extensions[$metadata
->getProjectName()],
]));
} catch (RequestException $exception) {
return TRUE;
}
$files = array_unique($files);
$archive_files = $archive
->listContents();
foreach ($archive_files as $index => &$archive_file) {
$skipped_files = [
self::DELETION_MANIFEST,
];
if (in_array($archive_file, $skipped_files, TRUE) || substr($archive_file, -1) === '/') {
unset($archive_files[$index]);
continue;
}
$this
->stripFileDirectoryPath($archive_file);
}
unset($archive_file);
if ($intersection = array_intersect($files, $archive_files)) {
$this->logger
->error('Can not update because %count files are modified: %paths', [
'%count' => count($intersection),
'%paths' => implode(', ', $intersection),
]);
return TRUE;
}
return FALSE;
}
protected function doGetResource($url, $destination, $delay = NULL) {
try {
$this->httpClient
->get($url, [
'sink' => $destination,
'delay' => $delay,
'timeout' => 120,
]);
} catch (RequestException $exception) {
$response = $exception
->getResponse();
if ($response && $response
->getStatusCode() === 429) {
$delay = 1000 * (isset($response
->getHeader('Retry-After')[0]) ? $response
->getHeader('Retry-After')[0] : 10);
$this
->doGetResource($url, $destination, $delay);
}
else {
$this->logger
->error('Retrieval of "@url" failed with: @message', [
'@url' => $exception
->getRequest()
->getUri(),
'@message' => $exception
->getMessage(),
]);
throw $exception;
}
}
}
protected function processUpdate(ArchiverInterface $archive, $project_root) {
$archive
->extract($this
->getTempDirectory());
foreach ($this
->getFilesList($this
->getTempDirectory()) as $file) {
$file_real_path = $this
->getFileRealPath($file);
$file_path = substr($file_real_path, strlen($this
->getTempDirectory() . self::ARCHIVE_DIRECTORY));
$project_real_path = $this
->getProjectRealPath($file_path, $project_root);
try {
$directory = dirname($project_real_path);
$this->fileSystem
->prepareDirectory($directory, FileSystemInterface::CREATE_DIRECTORY);
$this->fileSystem
->copy($file_real_path, $project_real_path, FileSystemInterface::EXISTS_REPLACE);
$this->logger
->info('"@file" was updated.', [
'@file' => $project_real_path,
]);
} catch (FileException $exception) {
return FALSE;
}
}
foreach ($this
->getDeletions() as $deletion) {
try {
$file_deletion = $this
->getProjectRealPath($deletion, $project_root);
$this->fileSystem
->delete($file_deletion);
$this->logger
->info('"@file" was deleted.', [
'@file' => $file_deletion,
]);
} catch (FileException $exception) {
return FALSE;
}
}
return TRUE;
}
protected function validateArchive($directory, $csig) {
$module_path = drupal_get_path('module', 'automatic_updates');
$key = file_get_contents($module_path . '/artifacts/keys/root.pub');
$verifier = new Verifier($key);
$files = $verifier
->verifyCsigMessage($csig);
$checksums = new ChecksumList($files, TRUE);
$failed_checksums = new FailedCheckumFilter($checksums, $directory);
if (iterator_count($failed_checksums)) {
throw new \RuntimeException('The downloaded files did not match what was expected.');
}
}
protected function backup(ArchiverInterface $archive, $project_root) {
$backup = $this->fileSystem
->createFilename('automatic_updates-backup', 'temporary://');
$this->fileSystem
->prepareDirectory($backup, FileSystemInterface::CREATE_DIRECTORY);
$this->backup = $this->fileSystem
->realpath($backup) . DIRECTORY_SEPARATOR;
if (!$this->backup) {
return FALSE;
}
foreach ($archive
->listContents() as $file) {
if (!$this
->stripFileDirectoryPath($file)) {
continue;
}
$success = $this
->doBackup($file, $project_root);
if (!$success) {
return FALSE;
}
}
$archive
->extract($this
->getTempDirectory(), [
self::DELETION_MANIFEST,
]);
foreach ($this
->getDeletions() as $deletion) {
$success = $this
->doBackup($deletion, $project_root);
if (!$success) {
return FALSE;
}
}
return TRUE;
}
protected function stripFileDirectoryPath(&$file) {
if (strpos($file, self::ARCHIVE_DIRECTORY) === 0) {
$file = substr($file, 6);
return TRUE;
}
return FALSE;
}
protected function doBackup($file, $project_root) {
$directory = $this->backup . dirname($file);
if (!file_exists($directory) && !$this->fileSystem
->mkdir($directory, NULL, TRUE)) {
return FALSE;
}
$project_real_path = $this
->getProjectRealPath($file, $project_root);
if (file_exists($project_real_path) && !is_dir($project_real_path)) {
try {
$this->fileSystem
->copy($project_real_path, $this->backup . $file, FileSystemInterface::EXISTS_REPLACE);
$this->logger
->info('"@file" was backed up in preparation for an update.', [
'@file' => $project_real_path,
]);
} catch (FileException $exception) {
return FALSE;
}
}
return TRUE;
}
protected function rollback($project_root) {
if (!$this->backup) {
return;
}
foreach ($this
->getFilesList($this
->getTempDirectory()) as $file) {
$file_real_path = $this
->getFileRealPath($file);
$file_path = substr($file_real_path, strlen($this
->getTempDirectory() . self::ARCHIVE_DIRECTORY));
$project_real_path = $this
->getProjectRealPath($file_path, $project_root);
try {
$this->fileSystem
->delete($project_real_path);
$this->logger
->info('"@file" was successfully removed during rollback.', [
'@file' => $project_real_path,
]);
} catch (FileException $exception) {
$this->logger
->error('"@file" failed removal on rollback.', [
'@file' => $project_real_path,
]);
}
}
foreach ($this
->getFilesList($this->backup) as $file) {
$this
->doRestore($file, $project_root);
}
}
protected function doRestore(\SplFileInfo $file, $project_root) {
$file_real_path = $this
->getFileRealPath($file);
$file_path = substr($file_real_path, strlen($this->backup));
try {
$this->fileSystem
->copy($file_real_path, $this
->getProjectRealPath($file_path, $project_root), FileSystemInterface::EXISTS_REPLACE);
$this->logger
->info('"@file" was successfully restored.', [
'@file' => $file_path,
]);
} catch (FileException $exception) {
$this->logger
->error('"@file" failed restoration during rollback.', [
'@file' => $file_real_path,
]);
}
}
protected function getFilesList($directory) {
$filter = static function ($file, $file_name, $iterator) {
if ($iterator
->hasChildren() && $file
->getFilename() !== '.git') {
return TRUE;
}
$skipped_files = [
self::DELETION_MANIFEST,
];
return $file
->isFile() && !in_array($file
->getFilename(), $skipped_files, TRUE);
};
$innerIterator = new \RecursiveDirectoryIterator($directory, \RecursiveDirectoryIterator::SKIP_DOTS);
return new \RecursiveIteratorIterator(new \RecursiveCallbackFilterIterator($innerIterator, $filter));
}
protected function buildUrl($project_name, $file_name) {
$uri = $this->configFactory
->get('automatic_updates.settings')
->get('download_uri');
return Url::fromUri("{$uri}/{$project_name}/{$file_name}")
->toString();
}
protected function getQuasiPatchFileName(UpdateMetadata $metadata) {
return "{$metadata->getProjectName()}-{$metadata->getFromVersion()}-to-{$metadata->getToVersion()}.zip";
}
protected function getFileRealPath(\SplFileInfo $file) {
$real_path = $file
->getRealPath();
if (!$real_path) {
throw new FileException(sprintf('Could not get real path for "%s"', $file
->getFilename()));
}
return $real_path;
}
protected function getProjectRealPath($file_path, $project_root) {
if (strpos($file_path, 'vendor' . DIRECTORY_SEPARATOR) === 0) {
return $this->vendorPath . substr($file_path, 7);
}
return rtrim($project_root, '/\\') . DIRECTORY_SEPARATOR . $file_path;
}
protected function getTempDirectory() {
if (!$this->tempDirectory) {
$this->tempDirectory = $this->fileSystem
->createFilename('automatic_updates-update', FileSystem::getOsTemporaryDirectory());
$this->fileSystem
->prepareDirectory($this->tempDirectory, FileSystemInterface::CREATE_DIRECTORY);
$this->tempDirectory .= DIRECTORY_SEPARATOR;
}
return $this->tempDirectory;
}
protected function getDeletions() {
$deletions = [];
if (!file_exists($this
->getTempDirectory() . self::DELETION_MANIFEST)) {
return new \ArrayIterator($deletions);
}
$handle = fopen($this
->getTempDirectory() . self::DELETION_MANIFEST, 'r');
if ($handle) {
while (($deletion = fgets($handle)) !== FALSE) {
if ($result = trim($deletion)) {
$deletions[] = $result;
}
}
fclose($handle);
}
return new \ArrayIterator($deletions);
}
protected function cacheRebuild() {
if (function_exists('opcache_reset')) {
opcache_reset();
}
automatic_updates_console_command('cache:rebuild');
}
protected function handleDatabaseUpdates() {
$result = TRUE;
$database_update_handler = \Drupal::service('plugin.manager.database_update_handler');
foreach ($this->configFactory
->get('automatic_updates.settings')
->get('database_update_handling') as $plugin_id) {
$result = $result && $database_update_handler
->createInstance($plugin_id)
->execute();
}
return $result;
}
}