def cache(self, fetch_func, filename, size=None, *args, **kwargs): """Creates image from template. Ensures that template and image not already exists. Ensures that base directory exists. Synchronizes on template fetching. :fetch_func: Function that creates the base image Should accept `target` argument. :filename: Name of the file in the image directory :size: Size of created image in bytes (optional) """ @utils.synchronized(filename, external=True, lock_path=self.lock_path) def fetch_func_sync(target, *args, **kwargs): fetch_func(target=target, *args, **kwargs) base_dir = os.path.join(CONF.instances_path, CONF.image_cache_subdirectory_name) if not os.path.exists(base_dir): fileutils.ensure_tree(base_dir) base = os.path.join(base_dir, filename) imagecache.refresh_timestamp(base) if not self.check_image_exists() or not os.path.exists(base): self.create_image(fetch_func_sync, base, size, *args, **kwargs) if (size and self.preallocate and self._can_fallocate() and os.access(self.path, os.W_OK)): utils.execute('fallocate', '-n', '-l', size, self.path)
def test_cache_image_exists(self): self.mox.StubOutWithMock(imagecache, 'refresh_timestamp') self.mox.StubOutWithMock(os.path, 'exists') if self.OLD_STYLE_INSTANCE_PATH: os.path.exists(self.OLD_STYLE_INSTANCE_PATH).AndReturn(False) os.path.exists(self.TEMPLATE_DIR).AndReturn(True) os.path.exists(self.PATH).AndReturn(True) os.path.exists(self.TEMPLATE_PATH).AndReturn(True) imagecache.refresh_timestamp(self.TEMPLATE_PATH) self.mox.ReplayAll() image = self.image_class(self.INSTANCE, self.NAME) image.cache(None, self.TEMPLATE) self.mox.VerifyAll()
def test_cache_template_exists(self): image = self.image_class(self.INSTANCE, self.NAME) self.mox.StubOutWithMock(os.path, 'exists') self.mox.StubOutWithMock(image, 'check_image_exists') self.mox.StubOutWithMock(imagecache, 'refresh_timestamp') os.path.exists(self.TEMPLATE_DIR).AndReturn(True) image.check_image_exists().AndReturn(False) imagecache.refresh_timestamp(self.TEMPLATE_PATH) fn = self.mox.CreateMockAnything() fn(target=self.TEMPLATE_PATH) self.mox.ReplayAll() self.mock_create_image(image) image.cache(fn, self.TEMPLATE) self.mox.VerifyAll()
def test_cache_base_dir_exists(self): self.mox.StubOutWithMock(imagecache, 'refresh_timestamp') self.mox.StubOutWithMock(os.path, 'exists') if self.OLD_STYLE_INSTANCE_PATH: os.path.exists(self.OLD_STYLE_INSTANCE_PATH).AndReturn(False) os.path.exists(self.TEMPLATE_DIR).AndReturn(True) os.path.exists(self.PATH).AndReturn(False) imagecache.refresh_timestamp(self.TEMPLATE_PATH) fn = self.mox.CreateMockAnything() fn(target=self.TEMPLATE_PATH) self.mox.StubOutWithMock(imagebackend.fileutils, 'ensure_tree') self.mox.ReplayAll() image = self.image_class(self.INSTANCE, self.NAME) self.mock_create_image(image) image.cache(fn, self.TEMPLATE) self.mox.VerifyAll()