diff options
author | John Molakvoæ <skjnldsv@users.noreply.github.com> | 2021-10-27 15:52:30 +0200 |
---|---|---|
committer | GitHub <noreply@github.com> | 2021-10-27 15:52:30 +0200 |
commit | cf58d5ff512a6af96f81c7911532fdcb176e6867 (patch) | |
tree | cdffbf3e484541c03becea0eedabaa4a8b1b3e9d /apps | |
parent | 799b77208e9544cd0a88e25ff90b6b7536673ef0 (diff) | |
parent | cf6da08f0093a9ade4a45a60dedba354f47f7394 (diff) | |
download | nextcloud-server-cf58d5ff512a6af96f81c7911532fdcb176e6867.tar.gz nextcloud-server-cf58d5ff512a6af96f81c7911532fdcb176e6867.zip |
Merge pull request #29447 from nextcloud/backport/29220/stable21
Diffstat (limited to 'apps')
-rw-r--r-- | apps/files_external/lib/Lib/Storage/AmazonS3.php | 335 | ||||
-rw-r--r-- | apps/files_external/tests/Storage/Amazons3Test.php | 6 | ||||
-rw-r--r-- | apps/files_external/tests/Storage/VersionedAmazonS3Test.php | 43 |
3 files changed, 240 insertions, 144 deletions
diff --git a/apps/files_external/lib/Lib/Storage/AmazonS3.php b/apps/files_external/lib/Lib/Storage/AmazonS3.php index 7ae9003c721..df13603de23 100644 --- a/apps/files_external/lib/Lib/Storage/AmazonS3.php +++ b/apps/files_external/lib/Lib/Storage/AmazonS3.php @@ -50,6 +50,10 @@ use OC\Files\Cache\CacheEntry; use OC\Files\ObjectStore\S3ConnectionTrait; use OC\Files\ObjectStore\S3ObjectTrait; use OCP\Constants; +use OCP\Files\FileInfo; +use OCP\Files\IMimeTypeDetector; +use OCP\ICacheFactory; +use OCP\IMemcache; class AmazonS3 extends \OC\Files\Storage\Common { use S3ConnectionTrait; @@ -68,12 +72,25 @@ class AmazonS3 extends \OC\Files\Storage\Common { /** @var CappedMemoryCache|array */ private $filesCache; + /** @var IMimeTypeDetector */ + private $mimeDetector; + + /** @var bool|null */ + private $versioningEnabled = null; + + /** @var IMemcache */ + private $memCache; + public function __construct($parameters) { parent::__construct($parameters); $this->parseParams($parameters); $this->objectCache = new CappedMemoryCache(); $this->directoryCache = new CappedMemoryCache(); $this->filesCache = new CappedMemoryCache(); + $this->mimeDetector = \OC::$server->get(IMimeTypeDetector::class); + /** @var ICacheFactory $cacheFactory */ + $cacheFactory = \OC::$server->get(ICacheFactory::class); + $this->memCache = $cacheFactory->createLocal('s3-external'); } /** @@ -116,12 +133,20 @@ class AmazonS3 extends \OC\Files\Storage\Common { unset($this->objectCache[$existingKey]); } } - unset($this->directoryCache[$key], $this->filesCache[$key]); + unset($this->filesCache[$key]); + $keys = array_keys($this->directoryCache->getData()); + $keyLength = strlen($key); + foreach ($keys as $existingKey) { + if (substr($existingKey, 0, $keyLength) === $key) { + unset($this->directoryCache[$existingKey]); + } + } + unset($this->directoryCache[$key]); } /** * @param $key - * @return Result|boolean + * @return array|false */ private function headObject($key) { if (!isset($this->objectCache[$key])) { @@ -129,7 +154,7 @@ class AmazonS3 extends \OC\Files\Storage\Common { $this->objectCache[$key] = $this->getConnection()->headObject([ 'Bucket' => $this->bucket, 'Key' => $key - ]); + ])->toArray(); } catch (S3Exception $e) { if ($e->getStatusCode() >= 500) { throw $e; @@ -138,6 +163,9 @@ class AmazonS3 extends \OC\Files\Storage\Common { } } + if (is_array($this->objectCache[$key]) && !isset($this->objectCache[$key]["Key"])) { + $this->objectCache[$key]["Key"] = $key; + } return $this->objectCache[$key]; } @@ -155,63 +183,45 @@ class AmazonS3 extends \OC\Files\Storage\Common { * @throws \Exception */ private function doesDirectoryExist($path) { - if (!isset($this->directoryCache[$path])) { + if ($path === '.' || $path === '') { + return true; + } + $path = rtrim($path, '/') . '/'; + + if (isset($this->directoryCache[$path])) { + return $this->directoryCache[$path]; + } + try { // Maybe this isn't an actual key, but a prefix. // Do a prefix listing of objects to determine. - try { - $result = $this->getConnection()->listObjects([ - 'Bucket' => $this->bucket, - 'Prefix' => rtrim($path, '/'), - 'MaxKeys' => 1, - 'Delimiter' => '/', - ]); + $result = $this->getConnection()->listObjectsV2([ + 'Bucket' => $this->bucket, + 'Prefix' => $path, + 'MaxKeys' => 1, + ]); - if ((isset($result['Contents'][0]['Key']) && $result['Contents'][0]['Key'] === rtrim($path, '/') . '/') - || isset($result['CommonPrefixes'])) { - $this->directoryCache[$path] = true; - } else { - $this->directoryCache[$path] = false; - } - } catch (S3Exception $e) { - if ($e->getStatusCode() === 403) { - $this->directoryCache[$path] = false; - } - throw $e; + if (isset($result['Contents'])) { + $this->directoryCache[$path] = true; + return true; } - } - return $this->directoryCache[$path]; - } - - /** - * Updates old storage ids (v0.2.1 and older) that are based on key and secret to new ones based on the bucket name. - * TODO Do this in a repair step. requires iterating over all users and loading the mount.json from their home - * - * @param array $params - */ - public function updateLegacyId(array $params) { - $oldId = 'amazon::' . $params['key'] . md5($params['secret']); + // empty directories have their own object + $object = $this->headObject($path); - // find by old id or bucket - $stmt = \OC::$server->getDatabaseConnection()->prepare( - 'SELECT `numeric_id`, `id` FROM `*PREFIX*storages` WHERE `id` IN (?, ?)' - ); - $stmt->execute([$oldId, $this->id]); - while ($row = $stmt->fetch()) { - $storages[$row['id']] = $row['numeric_id']; + if ($object) { + $this->directoryCache[$path] = true; + return true; + } + } catch (S3Exception $e) { + if ($e->getStatusCode() >= 400 && $e->getStatusCode() < 500) { + $this->directoryCache[$path] = false; + } + throw $e; } - if (isset($storages[$this->id]) && isset($storages[$oldId])) { - // if both ids exist, delete the old storage and corresponding filecache entries - \OC\Files\Cache\Storage::remove($oldId); - } elseif (isset($storages[$oldId])) { - // if only the old id exists do an update - $stmt = \OC::$server->getDatabaseConnection()->prepare( - 'UPDATE `*PREFIX*storages` SET `id` = ? WHERE `id` = ?' - ); - $stmt->execute([$this->id, $oldId]); - } - // only the bucket based id may exist, do nothing + + $this->directoryCache[$path] = false; + return false; } /** @@ -244,7 +254,7 @@ class AmazonS3 extends \OC\Files\Storage\Common { 'Bucket' => $this->bucket, 'Key' => $path . '/', 'Body' => '', - 'ContentType' => 'httpd/unix-directory' + 'ContentType' => FileInfo::MIMETYPE_FOLDER ]); $this->testTimeout(); } catch (S3Exception $e) { @@ -280,7 +290,9 @@ class AmazonS3 extends \OC\Files\Storage\Common { protected function clearBucket() { $this->clearCache(); try { - $this->getConnection()->clearBucket($this->bucket); + $this->getConnection()->clearBucket([ + "Bucket" => $this->bucket + ]); return true; // clearBucket() is not working with Ceph, so if it fails we try the slower approach } catch (\Exception $e) { @@ -314,7 +326,9 @@ class AmazonS3 extends \OC\Files\Storage\Common { } // we reached the end when the list is no longer truncated } while ($objects['IsTruncated']); - $this->deleteObject($path); + if ($path !== '' && $path !== null) { + $this->deleteObject($path); + } } catch (S3Exception $e) { \OC::$server->getLogger()->logException($e, ['app' => 'files_external']); return false; @@ -323,54 +337,12 @@ class AmazonS3 extends \OC\Files\Storage\Common { } public function opendir($path) { - $path = $this->normalizePath($path); - - if ($this->isRoot($path)) { - $path = ''; - } else { - $path .= '/'; - } - try { - $files = []; - $results = $this->getConnection()->getPaginator('ListObjects', [ - 'Bucket' => $this->bucket, - 'Delimiter' => '/', - 'Prefix' => $path, - ]); - - foreach ($results as $result) { - // sub folders - if (is_array($result['CommonPrefixes'])) { - foreach ($result['CommonPrefixes'] as $prefix) { - $directoryName = trim($prefix['Prefix'], '/'); - $files[] = substr($directoryName, strlen($path)); - $this->directoryCache[$directoryName] = true; - } - } - if (is_array($result['Contents'])) { - foreach ($result['Contents'] as $object) { - if (isset($object['Key']) && $object['Key'] === $path) { - // it's the directory itself, skip - continue; - } - $file = basename( - isset($object['Key']) ? $object['Key'] : $object['Prefix'] - ); - $files[] = $file; - - // store this information for later usage - $this->filesCache[$path . $file] = [ - 'ContentLength' => $object['Size'], - 'LastModified' => (string)$object['LastModified'], - ]; - } - } - } - - return IteratorDirectory::wrap($files); + $content = iterator_to_array($this->getDirectoryContent($path)); + return IteratorDirectory::wrap(array_map(function (array $item) { + return $item['name']; + }, $content)); } catch (S3Exception $e) { - \OC::$server->getLogger()->logException($e, ['app' => 'files_external']); return false; } } @@ -378,33 +350,18 @@ class AmazonS3 extends \OC\Files\Storage\Common { public function stat($path) { $path = $this->normalizePath($path); - try { - $stat = []; - if ($this->is_dir($path)) { - $cacheEntry = $this->getCache()->get($path); - if ($cacheEntry instanceof CacheEntry) { - $stat['size'] = $cacheEntry->getSize(); - $stat['mtime'] = $cacheEntry->getMTime(); - } else { - // Use dummy values - $stat['size'] = -1; // Pending - $stat['mtime'] = time(); - } - } else { - $stat['size'] = $this->getContentLength($path); - $stat['mtime'] = strtotime($this->getLastModified($path)); + if ($this->is_dir($path)) { + $stat = $this->getDirectoryMetaData($path); + } else { + $object = $this->headObject($path); + if ($object === false) { + return false; } - $stat['atime'] = time(); - - return $stat; - } catch (S3Exception $e) { - \OC::$server->getLogger()->logException($e, ['app' => 'files_external']); - return false; + $stat = $this->objectToMetaData($object); } - } + $stat['atime'] = time(); - public function hasUpdated($path, $time) { - return $this->getMountOption('filesystem_check_changes', 1) === 1 || parent::hasUpdated($path, $time); + return $stat; } /** @@ -459,7 +416,7 @@ class AmazonS3 extends \OC\Files\Storage\Common { } try { - return $this->isRoot($path) || $this->doesDirectoryExist($path); + return $this->doesDirectoryExist($path); } catch (S3Exception $e) { \OC::$server->getLogger()->logException($e, ['app' => 'files_external']); return false; @@ -474,6 +431,9 @@ class AmazonS3 extends \OC\Files\Storage\Common { } try { + if (isset($this->directoryCache[$path]) && $this->directoryCache[$path]) { + return 'dir'; + } if (isset($this->filesCache[$path]) || $this->headObject($path)) { return 'file'; } @@ -599,11 +559,11 @@ class AmazonS3 extends \OC\Files\Storage\Common { return true; } - public function copy($path1, $path2) { + public function copy($path1, $path2, $isFile = null) { $path1 = $this->normalizePath($path1); $path2 = $this->normalizePath($path2); - if ($this->is_file($path1)) { + if ($isFile === true || $this->is_file($path1)) { try { $this->getConnection()->copyObject([ 'Bucket' => $this->bucket, @@ -619,28 +579,17 @@ class AmazonS3 extends \OC\Files\Storage\Common { $this->remove($path2); try { - $this->getConnection()->copyObject([ - 'Bucket' => $this->bucket, - 'Key' => $path2 . '/', - 'CopySource' => S3Client::encodeKey($this->bucket . '/' . $path1 . '/') - ]); + $this->mkdir($path2); $this->testTimeout(); } catch (S3Exception $e) { \OC::$server->getLogger()->logException($e, ['app' => 'files_external']); return false; } - $dh = $this->opendir($path1); - if (is_resource($dh)) { - while (($file = readdir($dh)) !== false) { - if (\OC\Files\Filesystem::isIgnoredDir($file)) { - continue; - } - - $source = $path1 . '/' . $file; - $target = $path2 . '/' . $file; - $this->copy($source, $target); - } + foreach ($this->getDirectoryContent($path1) as $item) { + $source = $path1 . '/' . $item['name']; + $target = $path2 . '/' . $item['name']; + $this->copy($source, $target, $item['mimetype'] !== FileInfo::MIMETYPE_FOLDER); } } @@ -707,4 +656,102 @@ class AmazonS3 extends \OC\Files\Storage\Common { public static function checkDependencies() { return true; } + + public function getDirectoryContent($directory): \Traversable { + $path = $this->normalizePath($directory); + + if ($this->isRoot($path)) { + $path = ''; + } else { + $path .= '/'; + } + + $results = $this->getConnection()->getPaginator('ListObjectsV2', [ + 'Bucket' => $this->bucket, + 'Delimiter' => '/', + 'Prefix' => $path, + ]); + + foreach ($results as $result) { + // sub folders + if (is_array($result['CommonPrefixes'])) { + foreach ($result['CommonPrefixes'] as $prefix) { + $dir = $this->getDirectoryMetaData($prefix['Prefix']); + if ($dir) { + yield $dir; + } + } + } + if (is_array($result['Contents'])) { + foreach ($result['Contents'] as $object) { + $this->objectCache[$object['Key']] = $object; + if ($object['Key'] !== $path) { + yield $this->objectToMetaData($object); + } + } + } + } + } + + private function objectToMetaData(array $object): array { + return [ + 'name' => basename($object['Key']), + 'mimetype' => $this->mimeDetector->detectPath($object['Key']), + 'mtime' => strtotime($object['LastModified']), + 'storage_mtime' => strtotime($object['LastModified']), + 'etag' => $object['ETag'], + 'permissions' => Constants::PERMISSION_ALL - Constants::PERMISSION_CREATE, + 'size' => (int)($object['Size'] ?? $object['ContentLength']), + ]; + } + + private function getDirectoryMetaData(string $path): ?array { + $path = trim($path, '/'); + // when versioning is enabled, delete markers are returned as part of CommonPrefixes + // resulting in "ghost" folders, verify that each folder actually exists + if ($this->versioningEnabled() && !$this->doesDirectoryExist($path)) { + return null; + } + $cacheEntry = $this->getCache()->get($path); + if ($cacheEntry instanceof CacheEntry) { + return $cacheEntry->getData(); + } else { + return [ + 'name' => basename($path), + 'mimetype' => FileInfo::MIMETYPE_FOLDER, + 'mtime' => time(), + 'storage_mtime' => time(), + 'etag' => uniqid(), + 'permissions' => Constants::PERMISSION_ALL, + 'size' => -1, + ]; + } + } + + public function versioningEnabled(): bool { + if ($this->versioningEnabled === null) { + $cached = $this->memCache->get('versioning-enabled::' . $this->getBucket()); + if ($cached === null) { + $result = $this->getConnection()->getBucketVersioning(['Bucket' => $this->getBucket()]); + $this->versioningEnabled = $result->get('Status') === 'Enabled'; + $this->memCache->set('versioning-enabled::' . $this->getBucket(), $this->versioningEnabled, 60); + } else { + $this->versioningEnabled = $cached; + } + } + return $this->versioningEnabled; + } + + public function hasUpdated($path, $time) { + // for files we can get the proper mtime + if ($path !== '' && $object = $this->headObject($path)) { + $stat = $this->objectToMetaData($object); + return $stat['mtime'] > $time; + } else { + // for directories, the only real option we have is to do a prefix listing and iterate over all objects + // however, since this is just as expensive as just re-scanning the directory, we can simply return true + // and have the scanner figure out if anything has actually changed + return true; + } + } } diff --git a/apps/files_external/tests/Storage/Amazons3Test.php b/apps/files_external/tests/Storage/Amazons3Test.php index 728db46e16d..aad84ff6a2c 100644 --- a/apps/files_external/tests/Storage/Amazons3Test.php +++ b/apps/files_external/tests/Storage/Amazons3Test.php @@ -40,6 +40,8 @@ use OCA\Files_External\Lib\Storage\AmazonS3; */ class Amazons3Test extends \Test\Files\Storage\Storage { private $config; + /** @var AmazonS3 */ + protected $instance; protected function setUp(): void { parent::setUp(); @@ -62,4 +64,8 @@ class Amazons3Test extends \Test\Files\Storage\Storage { public function testStat() { $this->markTestSkipped('S3 doesn\'t update the parents folder mtime'); } + + public function testHashInFileName() { + $this->markTestSkipped('Localstack has a bug with hashes in filename'); + } } diff --git a/apps/files_external/tests/Storage/VersionedAmazonS3Test.php b/apps/files_external/tests/Storage/VersionedAmazonS3Test.php new file mode 100644 index 00000000000..a16a9944d57 --- /dev/null +++ b/apps/files_external/tests/Storage/VersionedAmazonS3Test.php @@ -0,0 +1,43 @@ +<?php + +declare(strict_types=1); +/** + * @copyright Copyright (c) 2021 Robin Appelman <robin@icewind.nl> + * + * @license GNU AGPL version 3 or any later version + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see <http://www.gnu.org/licenses/>. + * + */ + +namespace OCA\Files_External\Tests\Storage; + +/** + * @group DB + */ +class VersionedAmazonS3Test extends Amazons3Test { + protected function setUp(): void { + parent::setUp(); + try { + $this->instance->getConnection()->putBucketVersioning([ + 'Bucket' => $this->instance->getBucket(), + 'VersioningConfiguration' => [ + 'Status' => 'Enabled', + ], + ]); + } catch (\Exception $e) { + $this->markTestSkipped("s3 backend doesn't seem to support versioning"); + } + } +} |