def test_get_non_existing(self): """ Test that trying to retrieve a s3 that doesn't exist raises an error """ uri = "s3://user:key@auth_address/badbucket/%s" % FAKE_UUID loc = get_location_from_uri(uri) self.assertRaises(exception.NotFound, self.store.get, loc) uri = "s3://user:key@auth_address/glance/noexist" loc = get_location_from_uri(uri) self.assertRaises(exception.NotFound, self.store.get, loc)
def test_get_non_existing(self): """ Test that trying to retrieve a file that doesn't exist raises an error """ loc = get_location_from_uri("file:///%s/non-existing" % self.test_dir) self.assertRaises(exception.NotFound, self.store.get, loc)
def test_add(self): """Test that we can add an image via the s3 backend""" expected_image_id = utils.generate_uuid() expected_s3_size = FIVE_KB expected_s3_contents = "*" * expected_s3_size expected_checksum = hashlib.md5(expected_s3_contents).hexdigest() expected_location = format_s3_location( S3_OPTIONS["s3_store_access_key"], S3_OPTIONS["s3_store_secret_key"], S3_OPTIONS["s3_store_host"], S3_OPTIONS["s3_store_bucket"], expected_image_id, ) image_s3 = StringIO.StringIO(expected_s3_contents) location, size, checksum = self.store.add(expected_image_id, image_s3, expected_s3_size) self.assertEquals(expected_location, location) self.assertEquals(expected_s3_size, size) self.assertEquals(expected_checksum, checksum) loc = get_location_from_uri(expected_location) (new_image_s3, new_image_size) = self.store.get(loc) new_image_contents = StringIO.StringIO() for chunk in new_image_s3: new_image_contents.write(chunk) new_image_s3_size = new_image_contents.len self.assertEquals(expected_s3_contents, new_image_contents.getvalue()) self.assertEquals(expected_s3_size, new_image_s3_size)
def test_delete_non_existing(self): """ Test that trying to delete a swift that doesn't exist raises an error """ loc = get_location_from_uri("swift://%s:key@authurl/glance/noexist" % (self.swift_store_user)) self.assertRaises(exception.NotFound, self.store.delete, loc)
def test_add(self): """Test that we can add an image via the swift backend""" swift_store_utils.is_multiple_swift_store_accounts_enabled = mock.Mock(return_value=False) reload(swift) self.store = Store() expected_swift_size = FIVE_KB expected_swift_contents = "*" * expected_swift_size expected_checksum = hashlib.md5(expected_swift_contents).hexdigest() expected_image_id = str(uuid.uuid4()) loc = "swift+https://tenant%%3Auser1:key@localhost:8080/glance/%s" expected_location = loc % (expected_image_id) image_swift = six.StringIO(expected_swift_contents) global SWIFT_PUT_OBJECT_CALLS SWIFT_PUT_OBJECT_CALLS = 0 location, size, checksum, _ = self.store.add(expected_image_id, image_swift, expected_swift_size) self.assertEqual(expected_location, location) self.assertEqual(expected_swift_size, size) self.assertEqual(expected_checksum, checksum) # Expecting a single object to be created on Swift i.e. no chunking. self.assertEqual(SWIFT_PUT_OBJECT_CALLS, 1) loc = get_location_from_uri(expected_location) (new_image_swift, new_image_size) = self.store.get(loc) new_image_contents = "".join([chunk for chunk in new_image_swift]) new_image_swift_size = len(new_image_swift) self.assertEqual(expected_swift_contents, new_image_contents) self.assertEqual(expected_swift_size, new_image_swift_size)
def get_from_backend(uri, **kwargs): """Yields chunks of data from backend specified by uri""" loc = location.get_location_from_uri(uri) backend_class = get_backend_class(loc.store_name) return backend_class.get(loc, **kwargs)
def test_https_get(self): uri = "https://netloc/path/to/file.tar.gz" expected_returns = [ "I ", "am", " a", " t", "ea", "po", "t,", " s", "ho", "rt", " a", "nd", " s", "to", "ut", "\n", ] loc = get_location_from_uri(uri) image_file = self.store.get(loc) chunks = [c for c in image_file] self.assertEqual(chunks, expected_returns)
def test_get_non_existing(self): """ Test that trying to retrieve a s3 that doesn't exist raises an error """ loc = get_location_from_uri( "s3://user:key@auth_address/badbucket/2") self.assertRaises(exception.NotFound, S3Backend.get, loc) loc = get_location_from_uri( "s3://user:key@auth_address/glance/noexist") self.assertRaises(exception.NotFound, S3Backend.get, loc)
def test_add(self): """Test that we can add an image via the filesystem backend""" ChunkedFile.CHUNKSIZE = 1024 expected_image_id = utils.generate_uuid() expected_file_size = 1024 * 5 # 5K expected_file_contents = "*" * expected_file_size expected_checksum = hashlib.md5(expected_file_contents).hexdigest() expected_location = "file://%s/%s" % (self.test_dir, expected_image_id) image_file = StringIO.StringIO(expected_file_contents) location, size, checksum = self.store.add(expected_image_id, image_file, expected_file_size) self.assertEquals(expected_location, location) self.assertEquals(expected_file_size, size) self.assertEquals(expected_checksum, checksum) uri = "file:///%s/%s" % (self.test_dir, expected_image_id) loc = get_location_from_uri(uri) (new_image_file, new_image_size) = self.store.get(loc) new_image_contents = "" new_image_file_size = 0 for chunk in new_image_file: new_image_file_size += len(chunk) new_image_contents += chunk self.assertEquals(expected_file_contents, new_image_contents) self.assertEquals(expected_file_size, new_image_file_size)
def test_http_get_not_found(self): not_found_resp = utils.FakeHTTPResponse(status=404, data="404 Not Found") FAKE_RESPONSE_STACK.append(not_found_resp) uri = "http://netloc/path/to/file.tar.gz" loc = get_location_from_uri(uri) self.assertRaises(exception.BadStoreUri, self.store.get, loc)
def test_get_location_from_uri_back_to_uri(self): """ Test that for various URIs, the correct Location object can be constructed and then the original URI returned via the get_store_uri() method. """ good_store_uris = [ "https://*****:*****@example.com:80/images/some-id", "http://images.oracle.com/123456", "swift://account%3Auser:[email protected]/container/obj-id", "swift://storeurl.com/container/obj-id", "swift+https://account%3Auser:[email protected]/container/obj-id", "s3://accesskey:[email protected]/bucket/key-id", "s3://accesskey:secretwith/[email protected]/bucket/key-id", "s3+http://accesskey:[email protected]/bucket/key-id", "s3+https://accesskey:[email protected]/bucket/key-id", "file:///var/lib/glance/images/1", "rbd://imagename", "rbd://fsid/pool/image/snap", "rbd://%2F/%2F/%2F/%2F", "sheepdog://244e75f1-9c69-4167-9db7-1aa7d1973f6c", "cinder://12345678-9012-3455-6789-012345678901", "vsphere://ip/folder/openstack_glance/2332298?dcPath=dc&dsName=ds", ] for uri in good_store_uris: loc = location.get_location_from_uri(uri) # The get_store_uri() method *should* return an identical URI # to the URI that is passed to get_location_from_uri() self.assertEqual(loc.get_store_uri(), uri)
def test_http_get_not_found(self): fake = utils.FakeHTTPResponse(status=404, data="404 Not Found") self.response.return_value = fake uri = "http://netloc/path/to/file.tar.gz" loc = get_location_from_uri(uri) self.assertRaises(exceptions.BadStoreUri, self.store.get, loc)
def test_get(self): """Test a "normal" retrieval of an image in chunks""" expected_image_size = 31 expected_returns = [ "I ", "am", " a", " t", "ea", "po", "t,", " s", "ho", "rt", " a", "nd", " s", "to", "ut", "\n", ] loc = get_location_from_uri( "vsphere://127.0.0.1/folder/openstack_glance/%s" "?dsName=ds1&dcPath=dc1" % FAKE_UUID ) with mock.patch("httplib.HTTPConnection") as HttpConn: HttpConn.return_value = FakeHTTPConnection() (image_file, image_size) = self.store.get(loc) self.assertEqual(image_size, expected_image_size) chunks = [c for c in image_file] self.assertEqual(chunks, expected_returns)
def test_cinder_get_size(self): fake_client = FakeObject(auth_token=None, management_url=None) fake_volumes = {"12345678-9012-3455-6789-012345678901": FakeObject(size=5)} class FakeCinderClient(FakeObject): def __init__(self, *args, **kwargs): super(FakeCinderClient, self).__init__(client=fake_client, volumes=fake_volumes) self.stubs.Set(cinderclient, "Client", FakeCinderClient) fake_sc = [ { u"endpoints": [{u"publicURL": u"foo_public_url"}], u"endpoints_links": [], u"name": u"cinder", u"type": u"volume", } ] fake_context = FakeObject(service_catalog=fake_sc, user="******", auth_tok="fake_token", tenant="fake_tenant") uri = "cinder://%s" % fake_volumes.keys()[0] loc = get_location_from_uri(uri) store = cinder.Store(context=fake_context) image_size = store.get_size(loc) self.assertEqual(image_size, fake_volumes.values()[0].size * units.Gi) self.assertEqual(fake_client.auth_token, "fake_token") self.assertEqual(fake_client.management_url, "foo_public_url")
def test_add_with_multiple_dirs(self): """Test adding multiple filesystem directories.""" store_map = [self.useFixture(fixtures.TempDir()).path, self.useFixture(fixtures.TempDir()).path] CONF.clear_override("filesystem_store_datadir") CONF.set_override("filesystem_store_datadirs", [store_map[0] + ":100", store_map[1] + ":200"]) self.store.configure_add() """Test that we can add an image via the filesystem backend""" ChunkedFile.CHUNKSIZE = 1024 expected_image_id = str(uuid.uuid4()) expected_file_size = 5 * units.Ki # 5K expected_file_contents = "*" * expected_file_size expected_checksum = hashlib.md5(expected_file_contents).hexdigest() expected_location = "file://%s/%s" % (store_map[1], expected_image_id) image_file = six.StringIO(expected_file_contents) location, size, checksum, _ = self.store.add(expected_image_id, image_file, expected_file_size) self.assertEqual(expected_location, location) self.assertEqual(expected_file_size, size) self.assertEqual(expected_checksum, checksum) loc = get_location_from_uri(expected_location) (new_image_file, new_image_size) = self.store.get(loc) new_image_contents = "" new_image_file_size = 0 for chunk in new_image_file: new_image_file_size += len(chunk) new_image_contents += chunk self.assertEqual(expected_file_contents, new_image_contents) self.assertEqual(expected_file_size, new_image_file_size)
def test_get(self): """Test a "normal" retrieval of an image in chunks""" # First add an image... image_id = utils.generate_uuid() file_contents = "chunk00000remainder" location = "file://%s/%s" % (self.test_dir, image_id) image_file = StringIO.StringIO(file_contents) location, size, checksum = self.store.add(image_id, image_file, len(file_contents)) # Now read it back... uri = "file:///%s/%s" % (self.test_dir, image_id) loc = get_location_from_uri(uri) (image_file, image_size) = self.store.get(loc) expected_data = "chunk00000remainder" expected_num_chunks = 2 data = "" num_chunks = 0 for chunk in image_file: num_chunks += 1 data += chunk self.assertEqual(expected_data, data) self.assertEqual(expected_num_chunks, num_chunks)
def test_add(self): """Test that we can add an image via the swift backend""" expected_swift_size = FIVE_KB expected_swift_contents = "*" * expected_swift_size expected_checksum = hashlib.md5(expected_swift_contents).hexdigest() expected_image_id = uuidutils.generate_uuid() loc = 'swift+https://%s:key@localhost:8080/glance/%s' expected_location = loc % (self.swift_store_user, expected_image_id) image_swift = StringIO.StringIO(expected_swift_contents) global SWIFT_PUT_OBJECT_CALLS SWIFT_PUT_OBJECT_CALLS = 0 location, size, checksum = self.store.add(expected_image_id, image_swift, expected_swift_size) self.assertEquals(expected_location, location) self.assertEquals(expected_swift_size, size) self.assertEquals(expected_checksum, checksum) # Expecting a single object to be created on Swift i.e. no chunking. self.assertEquals(SWIFT_PUT_OBJECT_CALLS, 1) loc = get_location_from_uri(expected_location) (new_image_swift, new_image_size) = self.store.get(loc) new_image_contents = new_image_swift.getvalue() new_image_swift_size = len(new_image_swift) self.assertEquals(expected_swift_contents, new_image_contents) self.assertEquals(expected_swift_size, new_image_swift_size)
def get_size_from_backend(context, uri): """Retrieves image size from backend specified by uri""" if utils.is_glance_location(uri): uri += ('?auth_token=' + context.auth_tok) loc = location.get_location_from_uri(uri) store = get_store_from_uri(context, uri, loc) return store.get_size(loc)
def test_add(self): """Test that we can add an image via the filesystem backend""" Store.WRITE_CHUNKSIZE = 1024 expected_image_id = str(uuid.uuid4()) expected_file_size = 5 * units.Ki # 5K expected_file_contents = "*" * expected_file_size expected_checksum = hashlib.md5(expected_file_contents).hexdigest() expected_location = "file://%s/%s" % (self.test_dir, expected_image_id) image_file = six.StringIO(expected_file_contents) location, size, checksum, _ = self.store.add(expected_image_id, image_file, expected_file_size) self.assertEqual(expected_location, location) self.assertEqual(expected_file_size, size) self.assertEqual(expected_checksum, checksum) uri = "file:///%s/%s" % (self.test_dir, expected_image_id) loc = get_location_from_uri(uri) (new_image_file, new_image_size) = self.store.get(loc) new_image_contents = "" new_image_file_size = 0 for chunk in new_image_file: new_image_file_size += len(chunk) new_image_contents += chunk self.assertEqual(expected_file_contents, new_image_contents) self.assertEqual(expected_file_size, new_image_file_size)
def test_delete_non_existing(self): """ Test that trying to delete a file that doesn't exist raises an error """ loc = get_location_from_uri("file:///tmp/glance-tests/non-existing") self.assertRaises(exception.NotFound, self.store.delete, loc)
def get_from_backend(uri, **kwargs): """Yields chunks of data from backend specified by uri""" store = get_store_from_uri(uri) loc = location.get_location_from_uri(uri) return store.get(loc)
def test_add(self): """Test that we can add an image via the filesystem backend""" ChunkedFile.CHUNKSIZE = 1024 expected_image_id = 42 expected_file_size = 1024 * 5 # 5K expected_file_contents = "*" * expected_file_size expected_checksum = hashlib.md5(expected_file_contents).hexdigest() expected_location = "file://%s/%s" % (stubs.FAKE_FILESYSTEM_ROOTDIR, expected_image_id) image_file = StringIO.StringIO(expected_file_contents) location, size, checksum = FilesystemBackend.add(42, image_file, FILESYSTEM_OPTIONS) self.assertEquals(expected_location, location) self.assertEquals(expected_file_size, size) self.assertEquals(expected_checksum, checksum) loc = get_location_from_uri("file:///tmp/glance-tests/42") new_image_file = FilesystemBackend.get(loc) new_image_contents = "" new_image_file_size = 0 for chunk in new_image_file: new_image_file_size += len(chunk) new_image_contents += chunk self.assertEquals(expected_file_contents, new_image_contents) self.assertEquals(expected_file_size, new_image_file_size)
def test_add(self): """Test that we can add an image via the s3 backend""" expected_image_id = str(uuid.uuid4()) expected_s3_size = FIVE_KB expected_s3_contents = "*" * expected_s3_size expected_checksum = hashlib.md5(expected_s3_contents).hexdigest() expected_location = format_s3_location( S3_CONF['s3_store_access_key'], S3_CONF['s3_store_secret_key'], S3_CONF['s3_store_host'], S3_CONF['s3_store_bucket'], expected_image_id) image_s3 = six.StringIO(expected_s3_contents) location, size, checksum, _ = self.store.add(expected_image_id, image_s3, expected_s3_size) self.assertEqual(expected_location, location) self.assertEqual(expected_s3_size, size) self.assertEqual(expected_checksum, checksum) loc = get_location_from_uri(expected_location) (new_image_s3, new_image_size) = self.store.get(loc) new_image_contents = six.StringIO() for chunk in new_image_s3: new_image_contents.write(chunk) new_image_s3_size = new_image_contents.len self.assertEqual(expected_s3_contents, new_image_contents.getvalue()) self.assertEqual(expected_s3_size, new_image_s3_size)
def test_get_location_from_uri_back_to_uri(self): """ Test that for various URIs, the correct Location object can be contructed and then the original URI returned via the get_store_uri() method. """ good_store_uris = [ 'https://*****:*****@example.com:80/images/some-id', 'http://images.oracle.com/123456', 'swift://account%3Auser:[email protected]/container/obj-id', 'swift://storeurl.com/container/obj-id', 'swift+https://account%3Auser:[email protected]/container/obj-id', 's3://accesskey:[email protected]/bucket/key-id', 's3://accesskey:secretwith/[email protected]/bucket/key-id', 's3+http://accesskey:[email protected]/bucket/key-id', 's3+https://accesskey:[email protected]/bucket/key-id', 'file:///var/lib/glance/images/1', 'rbd://imagename', 'rbd://fsid/pool/image/snap', 'rbd://%2F/%2F/%2F/%2F', ] for uri in good_store_uris: loc = location.get_location_from_uri(uri) # The get_store_uri() method *should* return an identical URI # to the URI that is passed to get_location_from_uri() self.assertEqual(loc.get_store_uri(), uri)
def get_size_from_backend(context, uri): """Retrieves image size from backend specified by uri""" loc = location.get_location_from_uri(uri) store = get_store_from_uri(context, uri, loc) return store.get_size(loc)
def test_cinder_get_size(self): fake_client = FakeObject(auth_token=None, management_url=None) fake_volumes = {'12345678-9012-3455-6789-012345678901': FakeObject(size=5)} class FakeCinderClient(FakeObject): def __init__(self, *args, **kwargs): super(FakeCinderClient, self).__init__(client=fake_client, volumes=fake_volumes) self.stubs.Set(cinderclient, 'Client', FakeCinderClient) fake_sc = [{u'endpoints': [{u'publicURL': u'foo_public_url'}], u'endpoints_links': [], u'name': u'cinder', u'type': u'volume'}] fake_context = FakeObject(service_catalog=fake_sc, user='******', auth_tok='fake_token', tenant='fake_tenant') uri = 'cinder://%s' % fake_volumes.keys()[0] loc = get_location_from_uri(uri) store = cinder.Store(context=fake_context) image_size = store.get_size(loc) self.assertEqual(image_size, fake_volumes.values()[0].size * units.Gi) self.assertEqual(fake_client.auth_token, 'fake_token') self.assertEqual(fake_client.management_url, 'foo_public_url')
def test_add_no_container_and_create(self): """ Tests that adding an image with a non-existing container creates the container automatically if flag is set """ options = SWIFT_OPTIONS.copy() options['swift_store_create_container_on_put'] = 'True' options['swift_store_container'] = 'noexist' expected_image_id = 42 expected_swift_size = FIVE_KB expected_swift_contents = "*" * expected_swift_size expected_checksum = hashlib.md5(expected_swift_contents).hexdigest() expected_location = format_swift_location( options['swift_store_user'], options['swift_store_key'], options['swift_store_auth_address'], options['swift_store_container'], expected_image_id) image_swift = StringIO.StringIO(expected_swift_contents) location, size, checksum = SwiftBackend.add(42, image_swift, options) self.assertEquals(expected_location, location) self.assertEquals(expected_swift_size, size) self.assertEquals(expected_checksum, checksum) loc = get_location_from_uri(expected_location) new_image_swift = SwiftBackend.get(loc) new_image_contents = new_image_swift.getvalue() new_image_swift_size = new_image_swift.len self.assertEquals(expected_swift_contents, new_image_contents) self.assertEquals(expected_swift_size, new_image_swift_size)
def test_add(self): """Test that we can add an image via the swift backend""" expected_image_id = 42 expected_swift_size = FIVE_KB expected_swift_contents = "*" * expected_swift_size expected_checksum = hashlib.md5(expected_swift_contents).hexdigest() expected_location = format_swift_location( SWIFT_OPTIONS['swift_store_user'], SWIFT_OPTIONS['swift_store_key'], SWIFT_OPTIONS['swift_store_auth_address'], SWIFT_OPTIONS['swift_store_container'], expected_image_id) image_swift = StringIO.StringIO(expected_swift_contents) location, size, checksum = SwiftBackend.add(42, image_swift, SWIFT_OPTIONS) self.assertEquals(expected_location, location) self.assertEquals(expected_swift_size, size) self.assertEquals(expected_checksum, checksum) loc = get_location_from_uri(expected_location) new_image_swift = SwiftBackend.get(loc) new_image_contents = new_image_swift.getvalue() new_image_swift_size = new_image_swift.len self.assertEquals(expected_swift_contents, new_image_contents) self.assertEquals(expected_swift_size, new_image_swift_size)
def test_http_delete_raise_error(self): uri = "https://netloc/path/to/file.tar.gz" loc = get_location_from_uri(uri) self.assertRaises(NotImplementedError, self.store.delete, loc) create_stores({}) self.assertRaises(exception.StoreDeleteNotSupported, delete_from_backend, uri)
def test_add_large_object_zero_size(self): """ Tests that adding an image to Swift which has both an unknown size and exceeds Swift's maximum limit of 5GB is correctly uploaded. We avoid the overhead of creating a 5GB object for this test by temporarily setting MAX_SWIFT_OBJECT_SIZE to 1KB, and then adding an object of 5KB. Bug lp:891738 """ # Set up a 'large' image of 5KB expected_swift_size = FIVE_KB expected_swift_contents = "*" * expected_swift_size expected_checksum = hashlib.md5(expected_swift_contents).hexdigest() expected_image_id = uuidutils.generate_uuid() loc = 'swift+https://%s:key@localhost:8080/glance/%s' expected_location = loc % (self.swift_store_user, expected_image_id) image_swift = StringIO.StringIO(expected_swift_contents) global SWIFT_PUT_OBJECT_CALLS SWIFT_PUT_OBJECT_CALLS = 0 # Temporarily set Swift MAX_SWIFT_OBJECT_SIZE to 1KB and add our image, # explicitly setting the image_length to 0 self.config(swift_store_container='glance') self.store = Store() orig_max_size = self.store.large_object_size orig_temp_size = self.store.large_object_chunk_size global MAX_SWIFT_OBJECT_SIZE orig_max_swift_object_size = MAX_SWIFT_OBJECT_SIZE try: MAX_SWIFT_OBJECT_SIZE = 1024 self.store.large_object_size = 1024 self.store.large_object_chunk_size = 1024 location, size, checksum = self.store.add(expected_image_id, image_swift, 0) finally: self.store.large_object_chunk_size = orig_temp_size self.store.large_object_size = orig_max_size MAX_SWIFT_OBJECT_SIZE = orig_max_swift_object_size self.assertEquals(expected_location, location) self.assertEquals(expected_swift_size, size) self.assertEquals(expected_checksum, checksum) # Expecting 7 calls to put_object -- 5 chunks, a zero chunk which is # then deleted, and the manifest. Note the difference with above # where the image_size is specified in advance (there's no zero chunk # in that case). self.assertEquals(SWIFT_PUT_OBJECT_CALLS, 7) loc = get_location_from_uri(expected_location) (new_image_swift, new_image_size) = self.store.get(loc) new_image_contents = new_image_swift.getvalue() new_image_swift_size = len(new_image_swift) self.assertEquals(expected_swift_contents, new_image_contents) self.assertEquals(expected_swift_size, new_image_swift_size)
def test_add_large_object(self): """ Tests that adding a very large image. We simulate the large object by setting store.large_object_size to a small number and then verify that there have been a number of calls to put_object()... """ expected_swift_size = FIVE_KB expected_swift_contents = "*" * expected_swift_size expected_checksum = hashlib.md5(expected_swift_contents).hexdigest() expected_image_id = uuidutils.generate_uuid() loc = 'swift+https://%s:key@localhost:8080/glance/%s' expected_location = loc % (self.swift_store_user, expected_image_id) image_swift = StringIO.StringIO(expected_swift_contents) global SWIFT_PUT_OBJECT_CALLS SWIFT_PUT_OBJECT_CALLS = 0 self.config(swift_store_container='glance') self.store = Store() orig_max_size = self.store.large_object_size orig_temp_size = self.store.large_object_chunk_size try: self.store.large_object_size = 1024 self.store.large_object_chunk_size = 1024 location, size, checksum, _ = self.store.add( expected_image_id, image_swift, expected_swift_size) finally: self.store.large_object_chunk_size = orig_temp_size self.store.large_object_size = orig_max_size self.assertEquals(expected_location, location) self.assertEquals(expected_swift_size, size) self.assertEquals(expected_checksum, checksum) # Expecting 6 objects to be created on Swift -- 5 chunks and 1 # manifest. self.assertEquals(SWIFT_PUT_OBJECT_CALLS, 6) loc = get_location_from_uri(expected_location) (new_image_swift, new_image_size) = self.store.get(loc) new_image_contents = new_image_swift.getvalue() new_image_swift_size = len(new_image_swift) self.assertEquals(expected_swift_contents, new_image_contents) self.assertEquals(expected_swift_size, new_image_swift_size)
def test_get_with_http_auth(self): """ Test a retrieval from Swift with an HTTP authurl. This is specified either via a Location header with swift+http:// or using http:// in the swift_store_auth_address config value """ loc = get_location_from_uri("swift+http://%s:key@auth_address/" "glance/%s" % (self.swift_store_user, FAKE_UUID)) (image_swift, image_size) = self.store.get(loc) self.assertEqual(image_size, 5120) expected_data = "*" * FIVE_KB data = "" for chunk in image_swift: data += chunk self.assertEqual(expected_data, data)
def test_add_size_variations(self): """ Test that adding images of various sizes which exercise both S3 single uploads and the multipart upload apis. We've configured the big upload threshold to 5MB and the part size to 6MB. """ variations = [ (FIVE_KB, 0), # simple put (5KB < 5MB) (5242880, 1), # 1 part (5MB <= 5MB < 6MB) (6291456, 1), # 1 part exact (5MB <= 6MB <= 6MB) (7340032, 2) ] # 2 parts (6MB < 7MB <= 12MB) for (vsize, vcnt) in variations: expected_image_id = str(uuid.uuid4()) expected_s3_size = vsize expected_s3_contents = "12345678" * (expected_s3_size / 8) expected_chksum = hashlib.md5(expected_s3_contents).hexdigest() expected_location = format_s3_location( S3_CONF['s3_store_access_key'], S3_CONF['s3_store_secret_key'], S3_CONF['s3_store_host'], S3_CONF['s3_store_bucket'], expected_image_id) image_s3 = six.StringIO(expected_s3_contents) # add image location, size, chksum, _ = self.store.add(expected_image_id, image_s3, expected_s3_size) self.assertEqual(expected_location, location) self.assertEqual(expected_s3_size, size) self.assertEqual(expected_chksum, chksum) self.assertEqual(vcnt, mpu_parts_uploaded) # get image loc = get_location_from_uri(expected_location) (new_image_s3, new_image_s3_size) = self.store.get(loc) new_image_contents = six.StringIO() for chunk in new_image_s3: new_image_contents.write(chunk) new_image_size = new_image_contents.len self.assertEqual(expected_s3_size, new_image_s3_size) self.assertEqual(expected_s3_size, new_image_size) self.assertEqual(expected_s3_contents, new_image_contents.getvalue())
def test_add_host_variations(self): """ Test that having http(s):// in the s3serviceurl in config options works as expected. """ variations = [ 'http://localhost:80', 'http://localhost', 'http://localhost/v1', 'http://localhost/v1/', 'https://localhost', 'https://localhost:8080', 'https://localhost/v1', 'https://localhost/v1/', 'localhost', 'localhost:8080/v1' ] i = 42 for variation in variations: expected_image_id = i expected_s3_size = FIVE_KB expected_s3_contents = "*" * expected_s3_size expected_checksum = \ hashlib.md5(expected_s3_contents).hexdigest() new_options = S3_OPTIONS.copy() new_options['s3_store_host'] = variation expected_location = format_s3_location( new_options['s3_store_access_key'], new_options['s3_store_secret_key'], new_options['s3_store_host'], new_options['s3_store_bucket'], expected_image_id) image_s3 = StringIO.StringIO(expected_s3_contents) self.store = Store(new_options) location, size, checksum = self.store.add(i, image_s3, expected_s3_size) self.assertEquals(expected_location, location) self.assertEquals(expected_s3_size, size) self.assertEquals(expected_checksum, checksum) loc = get_location_from_uri(expected_location) (new_image_s3, new_image_size) = self.store.get(loc) new_image_contents = new_image_s3.getvalue() new_image_s3_size = new_image_s3.len self.assertEquals(expected_s3_contents, new_image_contents) self.assertEquals(expected_s3_size, new_image_s3_size) i = i + 1
def test_delete(self): """ Test we can delete an existing image in the filesystem store """ # First add an image image_id = str(uuid.uuid4()) file_size = 5 * units.Ki # 5K file_contents = "*" * file_size image_file = six.StringIO(file_contents) location, size, checksum, _ = self.store.add(image_id, image_file, file_size) # Now check that we can delete it uri = "file:///%s/%s" % (self.test_dir, image_id) loc = get_location_from_uri(uri) self.store.delete(loc) self.assertRaises(exception.NotFound, self.store.get, loc)
def test_delete(self): """ Test we can delete an existing image in the filesystem store """ # First add an image image_id = uuidutils.generate_uuid() file_size = 1024 * 5 # 5K file_contents = "*" * file_size image_file = StringIO.StringIO(file_contents) location, size, checksum = self.store.add(image_id, image_file, file_size) # Now check that we can delete it uri = "file:///%s/%s" % (self.test_dir, image_id) loc = get_location_from_uri(uri) self.store.delete(loc) self.assertRaises(exception.NotFound, self.store.get, loc)
def set_acls(context, location_uri, public=False, read_tenants=None, write_tenants=None): if read_tenants is None: read_tenants = [] if write_tenants is None: write_tenants = [] loc = location.get_location_from_uri(location_uri) scheme = get_store_from_location(location_uri) store = get_store_from_scheme(context, scheme, loc) try: store.set_acls(loc, public=public, read_tenants=read_tenants, write_tenants=write_tenants) except NotImplementedError: LOG.debug("Skipping store.set_acls... not implemented.")
def test_get_with_retry(self): """ Test a retrieval where Swift does not get the full image in a single request. """ uri = "swift://%s:key@auth_address/glance/%s" % (self.swift_store_user, FAKE_UUID) loc = get_location_from_uri(uri) (image_swift, image_size) = self.store.get(loc) resp_full = ''.join([chunk for chunk in image_swift.wrapped]) resp_half = resp_full[:len(resp_full) / 2] image_swift.wrapped = swift_retry_iter(resp_half, image_size, self.store, loc.store_location) self.assertEqual(image_size, 5120) expected_data = "*" * FIVE_KB data = "" for chunk in image_swift: data += chunk self.assertEqual(expected_data, data)
def test_add_host_variations(self): """ Test that having http(s):// in the s3serviceurl in config options works as expected. """ variations = [ 'http://localhost:80', 'http://localhost', 'http://localhost/v1', 'http://localhost/v1/', 'https://localhost', 'https://localhost:8080', 'https://localhost/v1', 'https://localhost/v1/', 'localhost', 'localhost:8080/v1' ] for variation in variations: expected_image_id = uuidutils.generate_uuid() expected_s3_size = FIVE_KB expected_s3_contents = "*" * expected_s3_size expected_checksum = hashlib.md5(expected_s3_contents).hexdigest() new_conf = S3_CONF.copy() new_conf['s3_store_host'] = variation expected_location = format_s3_location( new_conf['s3_store_access_key'], new_conf['s3_store_secret_key'], new_conf['s3_store_host'], new_conf['s3_store_bucket'], expected_image_id) image_s3 = StringIO.StringIO(expected_s3_contents) self.config(**new_conf) self.store = Store() location, size, checksum, _ = self.store.add( expected_image_id, image_s3, expected_s3_size) self.assertEqual(expected_location, location) self.assertEqual(expected_s3_size, size) self.assertEqual(expected_checksum, checksum) loc = get_location_from_uri(expected_location) (new_image_s3, new_image_size) = self.store.get(loc) new_image_contents = new_image_s3.getvalue() new_image_s3_size = len(new_image_s3) self.assertEqual(expected_s3_contents, new_image_contents) self.assertEqual(expected_s3_size, new_image_s3_size)
def test_add_no_container_and_create(self): """ Tests that adding an image with a non-existing container creates the container automatically if flag is set """ swift_store_utils.is_multiple_swift_store_accounts_enabled = \ mock.Mock(return_value=True) expected_swift_size = FIVE_KB expected_swift_contents = "*" * expected_swift_size expected_checksum = hashlib.md5(expected_swift_contents).hexdigest() expected_image_id = str(uuid.uuid4()) loc = 'swift+config://ref1/noexist/%s' expected_location = loc % (expected_image_id) image_swift = six.StringIO(expected_swift_contents) global SWIFT_PUT_OBJECT_CALLS SWIFT_PUT_OBJECT_CALLS = 0 conf = copy.deepcopy(SWIFT_CONF) conf['swift_store_user'] = '******' conf['swift_store_create_container_on_put'] = True conf['swift_store_container'] = 'noexist' self.config(**conf) reload(swift) self.store = Store() location, size, checksum, _ = self.store.add(expected_image_id, image_swift, expected_swift_size) self.assertEqual(expected_location, location) self.assertEqual(expected_swift_size, size) self.assertEqual(expected_checksum, checksum) self.assertEqual(SWIFT_PUT_OBJECT_CALLS, 1) loc = get_location_from_uri(expected_location) (new_image_swift, new_image_size) = self.store.get(loc) new_image_contents = ''.join([chunk for chunk in new_image_swift]) new_image_swift_size = len(new_image_swift) self.assertEqual(expected_swift_contents, new_image_contents) self.assertEqual(expected_swift_size, new_image_swift_size)
def test_get_location_from_uri_back_to_uri(self): """ Test that for various URIs, the correct Location object can be contructed and then the original URI returned via the get_store_uri() method. """ good_store_uris = [ 'https://*****:*****@example.com:80/images/some-id', 'http://images.oracle.com/123456', 'swift://account%3Auser:[email protected]/container/obj-id', 'swift+https://account%3Auser:[email protected]/container/obj-id', 's3://accesskey:[email protected]/bucket/key-id', 's3://accesskey:secretwith/[email protected]/bucket/key-id', 's3+http://accesskey:[email protected]/bucket/key-id', 's3+https://accesskey:[email protected]/bucket/key-id', 'file:///var/lib/glance/images/1'] for uri in good_store_uris: loc = location.get_location_from_uri(uri) # The get_store_uri() method *should* return an identical URI # to the URI that is passed to get_location_from_uri() self.assertEqual(loc.get_store_uri(), uri)
def test_http_get_redirect(self): # Add two layers of redirects to the response stack, which will # return the default 200 OK with the expected data after resolving # both redirects. redirect_headers_1 = {"location": "http://example.com/teapot.img"} redirect_resp_1 = utils.FakeHTTPResponse(status=302, headers=redirect_headers_1) redirect_headers_2 = {"location": "http://example.com/teapot_real.img"} redirect_resp_2 = utils.FakeHTTPResponse(status=301, headers=redirect_headers_2) FAKE_RESPONSE_STACK.append(redirect_resp_1) FAKE_RESPONSE_STACK.append(redirect_resp_2) uri = "http://netloc/path/to/file.tar.gz" expected_returns = ['I ', 'am', ' a', ' t', 'ea', 'po', 't,', ' s', 'ho', 'rt', ' a', 'nd', ' s', 'to', 'ut', '\n'] loc = get_location_from_uri(uri) (image_file, image_size) = self.store.get(loc) self.assertEqual(image_size, 31) chunks = [c for c in image_file] self.assertEqual(chunks, expected_returns)
def test_add_with_multiple_dirs(self): """Test adding multiple filesystem directories.""" store_map = [ self.useFixture(fixtures.TempDir()).path, self.useFixture(fixtures.TempDir()).path ] CONF.clear_override('filesystem_store_datadir') CONF.set_override('filesystem_store_datadirs', [store_map[0] + ":100", store_map[1] + ":200"]) self.store.configure_add() """Test that we can add an image via the filesystem backend""" ChunkedFile.CHUNKSIZE = 1024 expected_image_id = str(uuid.uuid4()) expected_file_size = 5 * units.Ki # 5K expected_file_contents = "*" * expected_file_size expected_checksum = hashlib.md5(expected_file_contents).hexdigest() expected_location = "file://%s/%s" % (store_map[1], expected_image_id) image_file = six.StringIO(expected_file_contents) location, size, checksum, _ = self.store.add(expected_image_id, image_file, expected_file_size) self.assertEqual(expected_location, location) self.assertEqual(expected_file_size, size) self.assertEqual(expected_checksum, checksum) loc = get_location_from_uri(expected_location) (new_image_file, new_image_size) = self.store.get(loc) new_image_contents = "" new_image_file_size = 0 for chunk in new_image_file: new_image_file_size += len(chunk) new_image_contents += chunk self.assertEqual(expected_file_contents, new_image_contents) self.assertEqual(expected_file_size, new_image_file_size)
def test_add_no_container_and_create(self): """ Tests that adding an image with a non-existing container creates the container automatically if flag is set """ expected_swift_size = FIVE_KB expected_swift_contents = "*" * expected_swift_size expected_checksum = hashlib.md5(expected_swift_contents).hexdigest() expected_image_id = str(uuid.uuid4()) loc = 'swift+https://%s:key@localhost:8080/noexist/%s' expected_location = loc % (self.swift_store_user, expected_image_id) image_swift = six.StringIO(expected_swift_contents) global SWIFT_PUT_OBJECT_CALLS SWIFT_PUT_OBJECT_CALLS = 0 self.config(swift_store_create_container_on_put=True, swift_store_container='noexist') self.store = Store() location, size, checksum, _ = self.store.add(expected_image_id, image_swift, expected_swift_size) self.assertEqual(expected_location, location) self.assertEqual(expected_swift_size, size) self.assertEqual(expected_checksum, checksum) self.assertEqual(SWIFT_PUT_OBJECT_CALLS, 1) loc = get_location_from_uri(expected_location) (new_image_swift, new_image_size) = self.store.get(loc) new_image_contents = ''.join([chunk for chunk in new_image_swift]) new_image_swift_size = len(new_image_swift) self.assertEqual(expected_swift_contents, new_image_contents) self.assertEqual(expected_swift_size, new_image_swift_size)
def validate_location(context, uri): loc = location.get_location_from_uri(uri) store = get_store_from_uri(context, uri, loc) store.validate_location(uri)
def test_v2_with_no_tenant(self): uri = "swift://*****:*****@auth_address/glance/%s" % (FAKE_UUID) loc = get_location_from_uri(uri) self.assertRaises(exception.BadStoreUri, self.store.get, loc)
def test_large_objects(self): """ We test the large object manifest code path in the Swift driver. In the case where an image file is bigger than the config variable swift_store_large_object_size, then we chunk the image into Swift, and add a manifest put_object at the end. We test that the delete of the large object cleans up all the chunks in Swift, in addition to the manifest file (LP Bug# 833285) """ self.cleanup() self.swift_store_large_object_size = 2 # In MB self.swift_store_large_object_chunk_size = 1 # In MB self.start_servers(**self.__dict__.copy()) api_port = self.api_port registry_port = self.registry_port # GET /images # Verify no public images path = "http://%s:%d/v1/images" % ("0.0.0.0", self.api_port) http = httplib2.Http() response, content = http.request(path, 'GET') self.assertEqual(response.status, 200) self.assertEqual(content, '{"images": []}') # POST /images with public image named Image1 # attribute and no custom properties. Verify a 200 OK is returned image_data = "*" * FIVE_MB headers = { 'Content-Type': 'application/octet-stream', 'X-Image-Meta-Name': 'Image1', 'X-Image-Meta-Is-Public': 'True' } path = "http://%s:%d/v1/images" % ("0.0.0.0", self.api_port) http = httplib2.Http() response, content = http.request(path, 'POST', headers=headers, body=image_data) self.assertEqual(response.status, 201, content) data = json.loads(content) self.assertEqual(data['image']['checksum'], hashlib.md5(image_data).hexdigest()) self.assertEqual(data['image']['size'], FIVE_MB) self.assertEqual(data['image']['name'], "Image1") self.assertEqual(data['image']['is_public'], True) image_id = data['image']['id'] # HEAD image # Verify image found now path = "http://%s:%d/v1/images/%s" % ("0.0.0.0", self.api_port, image_id) http = httplib2.Http() response, content = http.request(path, 'HEAD') self.assertEqual(response.status, 200) self.assertEqual(response['x-image-meta-name'], "Image1") # GET image # Verify all information on image we just added is correct path = "http://%s:%d/v1/images/%s" % ("0.0.0.0", self.api_port, image_id) http = httplib2.Http() response, content = http.request(path, 'GET') self.assertEqual(response.status, 200) expected_image_headers = { 'x-image-meta-id': image_id, 'x-image-meta-name': 'Image1', 'x-image-meta-is_public': 'True', 'x-image-meta-status': 'active', 'x-image-meta-disk_format': '', 'x-image-meta-container_format': '', 'x-image-meta-size': str(FIVE_MB) } expected_std_headers = { 'content-length': str(FIVE_MB), 'content-type': 'application/octet-stream' } for expected_key, expected_value in expected_image_headers.items(): self.assertEqual( response[expected_key], expected_value, "For key '%s' expected header value '%s'. Got '%s'" % (expected_key, expected_value, response[expected_key])) for expected_key, expected_value in expected_std_headers.items(): self.assertEqual( response[expected_key], expected_value, "For key '%s' expected header value '%s'. Got '%s'" % (expected_key, expected_value, response[expected_key])) self.assertEqual(content, "*" * FIVE_MB) self.assertEqual( hashlib.md5(content).hexdigest(), hashlib.md5("*" * FIVE_MB).hexdigest()) # We test that the delete of the large object cleans up all the # chunks in Swift, in addition to the manifest file (LP Bug# 833285) # Grab the actual Swift location and query the object manifest for # the chunks/segments. We will check that the segments don't exist # after we delete the object through Glance... path = "http://%s:%d/images/%s" % ("0.0.0.0", self.registry_port, image_id) http = httplib2.Http() response, content = http.request(path, 'GET') self.assertEqual(response.status, 200) data = json.loads(content) image_loc = data['image']['location'] if hasattr(self, 'metadata_encryption_key'): key = self.metadata_encryption_key else: key = self.api_server.metadata_encryption_key image_loc = crypt.urlsafe_decrypt(key, image_loc) image_loc = get_location_from_uri(image_loc) swift_loc = image_loc.store_location from swift.common import client as swift_client swift_conn = swift_client.Connection(authurl=swift_loc.swift_auth_url, user=swift_loc.user, key=swift_loc.key) # Verify the object manifest exists headers = swift_conn.head_object(swift_loc.container, swift_loc.obj) manifest = headers.get('x-object-manifest') self.assertTrue(manifest is not None, "Manifest could not be found!") # Grab the segment identifiers obj_container, obj_prefix = manifest.split('/', 1) segments = [ segment['name'] for segment in swift_conn.get_container(obj_container, prefix=obj_prefix)[1] ] # Verify the segments exist for segment in segments: headers = swift_conn.head_object(obj_container, segment) self.assertTrue(headers.get('content-length') is not None, headers) # DELETE image # Verify image and all chunks are gone... path = "http://%s:%d/v1/images/%s" % ("0.0.0.0", self.api_port, image_id) http = httplib2.Http() response, content = http.request(path, 'DELETE') self.assertEqual(response.status, 200) # Verify the segments no longer exist for segment in segments: self.assertRaises(swift_client.ClientException, swift_conn.head_object, obj_container, segment) self.stop_servers()
def test_http_delete_raise_error(self): uri = "https://netloc/path/to/file.tar.gz" loc = get_location_from_uri(uri) self.assertRaises(NotImplementedError, self.store.delete, loc) self.assertRaises(exception.StoreDeleteNotSupported, delete_from_backend, uri)
def test_add_auth_url_variations(self): """ Test that we can add an image via the swift backend with a variety of different auth_address values """ variations = { 'http://*****:*****@localhost:80' '/glance/%s', 'http://localhost': 'swift+http://%s:key@localhost/glance/%s', 'http://localhost/v1': 'swift+http://%s:key@localhost' '/v1/glance/%s', 'http://localhost/v1/': 'swift+http://%s:key@localhost' '/v1/glance/%s', 'https://localhost': 'swift+https://%s:key@localhost/glance/%s', 'https://*****:*****@localhost:8080' '/glance/%s', 'https://localhost/v1': 'swift+https://%s:key@localhost' '/v1/glance/%s', 'https://localhost/v1/': 'swift+https://%s:key@localhost' '/v1/glance/%s', 'localhost': 'swift+https://%s:key@localhost/glance/%s', 'localhost:8080/v1': 'swift+https://%s:key@localhost:8080' '/v1/glance/%s', } for variation, expected_location in variations.items(): image_id = uuidutils.generate_uuid() expected_location = expected_location % (self.swift_store_user, image_id) expected_swift_size = FIVE_KB expected_swift_contents = "*" * expected_swift_size expected_checksum = \ hashlib.md5(expected_swift_contents).hexdigest() image_swift = StringIO.StringIO(expected_swift_contents) global SWIFT_PUT_OBJECT_CALLS SWIFT_PUT_OBJECT_CALLS = 0 self.config(swift_store_auth_address=variation) self.store = Store() location, size, checksum, _ = self.store.add( image_id, image_swift, expected_swift_size) self.assertEqual(expected_location, location) self.assertEqual(expected_swift_size, size) self.assertEqual(expected_checksum, checksum) self.assertEqual(SWIFT_PUT_OBJECT_CALLS, 1) loc = get_location_from_uri(expected_location) (new_image_swift, new_image_size) = self.store.get(loc) new_image_contents = new_image_swift.getvalue() new_image_swift_size = len(new_image_swift) self.assertEqual(expected_swift_contents, new_image_contents) self.assertEqual(expected_swift_size, new_image_swift_size)
def test_v2_multi_tenant_location(self): conf = self.getConfig() conf['swift_store_multi_tenant'] = True uri = "swift://auth_address/glance/%s" % (FAKE_UUID) loc = get_location_from_uri(uri) self.assertEqual('swift', loc.store_name)