You are viewing a plain text version of this content. The canonical link for it is here.
Posted to issues@flink.apache.org by StephanEwen <gi...@git.apache.org> on 2017/03/13 10:43:54 UTC

[GitHub] flink pull request #3522: [FLINK-5823] [checkpoints] State Backends also han...

GitHub user StephanEwen opened a pull request:

    https://github.com/apache/flink/pull/3522

    [FLINK-5823] [checkpoints] State Backends also handle Checkpoint Metadata and introduce Global Cleanup Hooks

    ## Core Changes
    
    ### Store Metadata in State Backend
    
    The state backend is now responsible for storing the checkpoint metadata. There is no implicit assumption that the checkpoint metadata is stored in a file systems any more.
    
      - All checkpoint directory / savepoint directory specific config settings are now part of the state backends. The Checkpoint Coordinator simply calls the relevant methods on the state backends to store metadata.
      
      - Similar as the `CheckpointStreamFactory` for storing checkpoint state, there is now a `CheckpointMetadataStreamFactory` for the metadata.
    
      - State backends are not required to be able to persist metadata - only ifor HA setups and when externalized checkpoints are requested. 
    
      - All checkpoints with persisted metadata are addressable via a "pointer", which is state-backend specific. For File-system based statebackends (all statebackends in Flink currently), this pointer is the file path.
      
    ### Global cleanup hooks
    
    State backends can implement an extended interface to create global cleanup hooks. For example for a file system, a global cleanup hook simply recursively deletes the checkpoint directory, which is for most file systems much faster than issuing a delete call per file.
    
    The `MemoryStateBackend` and `FsStateBackend` use fast cleanup hooks, the `RocksDBStateBackend` should get then in a followup (see below).
    
    ### Application-defined State Backends pick up additional values from the configuration
    
    We need to keep supporting the scenario of setting a state backends in the user program, but configuring parameters like checkpoint directory in the cluster config. To support that, state backends may implement an additional interface which lets them pick up configuration values from the cluster configuration.
    
    
    ## Altered user-facing Behavior
    
      - Externalized checkpoints store all files (state and metadata) strictly in the same directory now. (Savepoints were contained in a single directory already before)
      
      - Both savepoint commands and configuration parameters now require qualified URIs as well (i.e., `file:///path/do/savepoint`, whereas before the configs and command line also excepted `/path/do/savepoint`. 
      Because not having qualified URIs is error-prone anyways (auto fallback to local file system) I am actually in favor of doing this change.
    
    ## Tests
    
    This adds a lot of tests, which can due to the changed design be done completely on the state backends,
    without instantiating a CheckpointCoordinator.
    
      - Checkpoint / Savepoint delete with global hook works as expected
      - Interaction of old cleanup logic and optional global cleanup hook
      - State backends are properly loaded from configuration
      - Application-configured State backends properly pick up additional configuration values
    
    ## Followups
    
      - Implement the global hooks for the RocksDB state backend. Because the RocksDB state backend internally delegates to a "storage backend", this need to few extra tricks and was not done in this already large pull request.
      
      - The HA checkpoint store needs not store checkpoint metadata itself any more, it can simply store the pointer.
    
      - This abstraction allows state backends to over periodic cleanup hooks that can search for lost state (files that are not referenced any more), which can happen when TaskManager / JobManager processes fail during finalizing a checkpoint or when handing over state between JobManager / TaskManager.

You can merge this pull request into a Git repository by running:

    $ git pull https://github.com/StephanEwen/incubator-flink filestatebackend

Alternatively you can review and apply these changes as the patch at:

    https://github.com/apache/flink/pull/3522.patch

To close this pull request, make a commit to your master/trunk branch
with (at least) the following in the commit message:

    This closes #3522
    
----
commit 2bd817286f89693af4bb98504091afc1f45749ad
Author: Stephan Ewen <se...@apache.org>
Date:   2017-03-01T22:00:55Z

    [FLINK-5823] [checkpoints] State Backends also handle Checkpoint Metadata

----


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

[GitHub] flink pull request #3522: [FLINK-5823] [checkpoints] State Backends also han...

Posted by tillrohrmann <gi...@git.apache.org>.
Github user tillrohrmann commented on a diff in the pull request:

    https://github.com/apache/flink/pull/3522#discussion_r108728575
  
    --- Diff: flink-runtime/src/main/java/org/apache/flink/runtime/state/filesystem/FsStateBackendFactory.java ---
    @@ -18,44 +18,47 @@
     
     package org.apache.flink.runtime.state.filesystem;
     
    +import org.apache.flink.annotation.PublicEvolving;
    +import org.apache.flink.configuration.ConfigOption;
    +import org.apache.flink.configuration.ConfigOptions;
     import org.apache.flink.configuration.Configuration;
     import org.apache.flink.configuration.IllegalConfigurationException;
     import org.apache.flink.core.fs.Path;
     import org.apache.flink.runtime.state.StateBackendFactory;
     
    -import java.io.IOException;
    +import java.net.URI;
     
     /**
    - * A factory that creates an {@link org.apache.flink.runtime.state.filesystem.FsStateBackend}
    - * from a configuration.
    + * A factory that creates an {@link FsStateBackend} from a configuration.
      */
    +@PublicEvolving
     public class FsStateBackendFactory implements StateBackendFactory<FsStateBackend> {
    -	
    -	/** The key under which the config stores the directory where checkpoints should be stored */
    -	public static final String CHECKPOINT_DIRECTORY_URI_CONF_KEY = "state.backend.fs.checkpointdir";
     
    -	/** The key under which the config stores the threshold for state to be store in memory,
    -	 * rather than in files */
    -	public static final String MEMORY_THRESHOLD_CONF_KEY = "state.backend.fs.memory-threshold";
    +	/** Config key for the maximum state size that is stored with the metadata */
    +	public static final ConfigOption<Integer> MEMORY_THRESHOLD_CONF = ConfigOptions
    --- End diff --
    
    I'm wondering whether we want to group all relevant state options into a dedicated `StateOptions` class or keep them in the respective class where they are used. I fear that it will be quite hard for the user to find all available options.


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

[GitHub] flink pull request #3522: [FLINK-5823] [checkpoints] State Backends also han...

Posted by tillrohrmann <gi...@git.apache.org>.
Github user tillrohrmann commented on a diff in the pull request:

    https://github.com/apache/flink/pull/3522#discussion_r108729089
  
    --- Diff: flink-runtime/src/main/java/org/apache/flink/runtime/state/memory/MemoryStateBackend.java ---
    @@ -18,33 +18,89 @@
     
     package org.apache.flink.runtime.state.memory;
     
    +import org.apache.flink.annotation.PublicEvolving;
     import org.apache.flink.api.common.JobID;
     import org.apache.flink.api.common.typeutils.TypeSerializer;
    +import org.apache.flink.configuration.Configuration;
    +import org.apache.flink.core.fs.FileStatus;
    +import org.apache.flink.core.fs.Path;
    +import org.apache.flink.runtime.checkpoint.CompletedCheckpoint;
     import org.apache.flink.runtime.execution.Environment;
     import org.apache.flink.runtime.query.TaskKvStateRegistry;
     import org.apache.flink.runtime.state.AbstractKeyedStateBackend;
    -import org.apache.flink.runtime.state.AbstractStateBackend;
     import org.apache.flink.runtime.state.CheckpointStreamFactory;
    +import org.apache.flink.runtime.state.ConfigurableStateBackend;
     import org.apache.flink.runtime.state.KeyGroupRange;
    +import org.apache.flink.runtime.state.filesystem.AbstractFileStateBackend;
     import org.apache.flink.runtime.state.heap.HeapKeyedStateBackend;
    +import org.apache.flink.util.FlinkException;
    +
    +import javax.annotation.Nullable;
     
     import java.io.IOException;
     
    +import static org.apache.flink.util.Preconditions.checkArgument;
    +
     /**
    - * A {@link AbstractStateBackend} that stores all its data and checkpoints in memory and has no
    - * capabilities to spill to disk. Checkpoints are serialized and the serialized data is
    - * transferred
    + * This state backend holds the working state in the memory (JVM heap) of the TaskManagers.
    + * The state backend checkpoints state directly the JobManager's memory (hence the backend's name),
    --- End diff --
    
    preposition seems to be missing here


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

[GitHub] flink pull request #3522: [FLINK-5823] [checkpoints] State Backends also han...

Posted by tillrohrmann <gi...@git.apache.org>.
Github user tillrohrmann commented on a diff in the pull request:

    https://github.com/apache/flink/pull/3522#discussion_r108715154
  
    --- Diff: flink-runtime/src/main/java/org/apache/flink/runtime/state/filesystem/AbstractFileStateBackend.java ---
    @@ -0,0 +1,556 @@
    +/*
    + * Licensed to the Apache Software Foundation (ASF) under one
    + * or more contributor license agreements.  See the NOTICE file
    + * distributed with this work for additional information
    + * regarding copyright ownership.  The ASF licenses this file
    + * to you under the Apache License, Version 2.0 (the
    + * "License"); you may not use this file except in compliance
    + * with the License.  You may obtain a copy of the License at
    + *
    + *     http://www.apache.org/licenses/LICENSE-2.0
    + *
    + * Unless required by applicable law or agreed to in writing, software
    + * distributed under the License is distributed on an "AS IS" BASIS,
    + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    + * See the License for the specific language governing permissions and
    + * limitations under the License.
    + */
    +
    +package org.apache.flink.runtime.state.filesystem;
    +
    +import org.apache.flink.annotation.PublicEvolving;
    +import org.apache.flink.api.common.JobID;
    +import org.apache.flink.configuration.ConfigConstants;
    +import org.apache.flink.configuration.ConfigOption;
    +import org.apache.flink.configuration.ConfigOptions;
    +import org.apache.flink.configuration.Configuration;
    +import org.apache.flink.configuration.IllegalConfigurationException;
    +import org.apache.flink.core.fs.FileStatus;
    +import org.apache.flink.core.fs.FileSystem;
    +import org.apache.flink.core.fs.Path;
    +import org.apache.flink.runtime.state.AbstractStateBackend;
    +import org.apache.flink.runtime.state.CheckpointMetadataStreamFactory;
    +import org.apache.flink.runtime.state.StateBackendGlobalHooks;
    +import org.apache.flink.runtime.state.StreamStateHandle;
    +import org.apache.flink.util.FileUtils;
    +import org.apache.flink.util.FlinkException;
    +import org.apache.flink.util.FlinkRuntimeException;
    +
    +import org.slf4j.Logger;
    +import org.slf4j.LoggerFactory;
    +
    +import javax.annotation.Nullable;
    +import java.io.FileNotFoundException;
    +import java.io.IOException;
    +import java.net.URI;
    +import java.net.URISyntaxException;
    +
    +import static org.apache.flink.util.Preconditions.checkArgument;
    +import static org.apache.flink.util.Preconditions.checkNotNull;
    +
    +/**
    + * A base class for all state backends that store their metadata (and data) in files.
    + * Examples that inherit from this are the {@link FsStateBackend}, the
    + * {@link org.apache.flink.runtime.state.memory.MemoryStateBackend MemoryStateBackend}, or the
    + * {@code RocksDBStateBackend}.
    + * 
    + * <p>This class takes the base checkpoint- and savepoint directory paths, but also accepts null
    + * for both of then, in which case creating externalized checkpoint is not possible, and it is not
    + * possible to create a savepoint with a default path. Null is accepted to enable implementations
    + * that only optionally support default savepoints and externalized checkpoints.
    + * 
    + * <h1>Checkpoint Layout</h1>
    + * 
    + * The state backend is configured with a base directory and persists the checkpoint data of specific
    + * checkpoints in specific subdirectories. For example, if the base directory was set to 
    + * {@code hdfs://namenode:port/flink-checkpoints/}, the state backend will create a subdirectory with
    + * the job's ID that will contain the actual checkpoints:
    + * ({@code hdfs://namenode:port/flink-checkpoints/1b080b6e710aabbef8993ab18c6de98b})
    + *
    + * <p>Each checkpoint individually will store all its files in a subdirectory that includes the
    + * checkpoint number, such as {@code hdfs://namenode:port/flink-checkpoints/1b080b6e710aabbef8993ab18c6de98b/chk-17/}.
    + * 
    + * <h1>Savepoint Layout</h1>
    + * 
    + * A savepoint that is set to be stored in path {@code hdfs://namenode:port/flink-savepoints/}, will create
    + * a subdirectory {@code savepoint-jobId(0, 6)-randomDigits} in which it stores all savepoint data.
    + * The random digits are added as "entropy" to avoid directory collisions.
    + */
    +@PublicEvolving
    +public abstract class AbstractFileStateBackend extends AbstractStateBackend implements StateBackendGlobalHooks {
    +
    +	private static final long serialVersionUID = 1L;
    +
    +	private static final Logger LOG = LoggerFactory.getLogger(AbstractFileStateBackend.class);
    +
    +	// ------------------------------------------------------------------------
    +	//  Configuration
    +	// ------------------------------------------------------------------------
    +
    +	/**
    +	 * The configuration parameter for the checkpoint path/directory.
    +	 */
    +	public static final ConfigOption<String> CHECKPOINT_PATH = ConfigOptions
    +			.key(ConfigConstants.CHECKPOINTS_DIRECTORY_KEY)
    +			.noDefaultValue()
    +			.withDeprecatedKeys("state.backend.fs.checkpointdir");
    +
    +	/**
    +	 * The configuration parameter for the savepoint path/directory.
    +	 */
    +	public static final ConfigOption<String> SAVEPOINT_PATH = ConfigOptions
    +			.key(ConfigConstants.SAVEPOINT_DIRECTORY_KEY)
    +			.noDefaultValue()
    +			.withDeprecatedKeys("state.backend.fs.savepointdir");
    +
    +	// ------------------------------------------------------------------------
    +	//  Constants
    +	// ------------------------------------------------------------------------
    +
    +	/** The name of the metadata files in checkpoints / savepoints. */
    +	public static final String METADATA_FILE_NAME = "_metadata";
    +
    +	/** The prefix of the checkpoint directory names */
    +	public static final String CHECKPOINT_DIR_PREFIX = "chk-";
    +
    +	// ------------------------------------------------------------------------
    +	//  State Backend Properties
    +	// ------------------------------------------------------------------------
    +
    +	/** The path where checkpoints will be stored, or null, if none has been configured */
    +	@Nullable
    +	private final Path baseCheckpointPath;
    +
    +	/** The path where savepoints will be stored, or null, if none has been configured */
    +	@Nullable
    +	private final Path baseSavepointPath;
    +
    +	/**
    +	 * Creates a backend with the given optional checkpoint- and savepoint base directories.
    +	 * 
    +	 * @param baseCheckpointPath The base directory for checkpoints, or null, if none is configured.
    +	 * @param baseSavepointPath The default directory for savepoints, or null, if none is set.
    +	 */
    +	protected AbstractFileStateBackend(
    +			@Nullable Path baseCheckpointPath,
    +			@Nullable Path baseSavepointPath) {
    +
    +		this(baseCheckpointPath == null ? null : baseCheckpointPath.toUri(),
    +				baseSavepointPath == null ? null : baseSavepointPath.toUri());
    +	}
    +
    +	/**
    +	 * Creates a backend with the given optional checkpoint- and savepoint base directories.
    +	 * 
    +	 * @param baseCheckpointPath The base directory for checkpoints, or null, if none is configured.
    +	 * @param baseSavepointPath The default directory for savepoints, or null, if none is set.
    +	 */
    +	protected AbstractFileStateBackend(
    +			@Nullable URI baseCheckpointPath,
    +			@Nullable URI baseSavepointPath) {
    +
    +		this.baseCheckpointPath = baseCheckpointPath == null ? null : validateAndNormalizeUri(baseCheckpointPath);
    +		this.baseSavepointPath = baseSavepointPath == null ? null : validateAndNormalizeUri(baseSavepointPath);
    +	}
    +
    +	/**
    +	 * Creates a new backend using the given checkpoint-/savepoint directories, or the values defined in
    +	 * the given configuration. If a checkpoint-/savepoint parameter is not null, that value takes precedence
    +	 * over the value in the configuration. If the configuration does not specify a value, it is possible
    +	 * that the checkpoint-/savepoint directories in the backend will be null.
    +	 * 
    +	 * <p>This constructor can be used to create a backend that is based partially on a given backend
    +	 * and partially on a configuration.
    +	 * 
    +	 * @param baseCheckpointPath The checkpoint base directory to use (or null).
    +	 * @param baseSavepointPath The default savepoint directory to use (or null).
    +	 * @param configuration The configuration to read values from 
    +	 */
    +	protected AbstractFileStateBackend(
    +			@Nullable Path baseCheckpointPath,
    +			@Nullable Path baseSavepointPath,
    +			Configuration configuration) {
    +
    +		this(parameterOrConfigured(baseCheckpointPath, configuration, CHECKPOINT_PATH),
    +				parameterOrConfigured(baseSavepointPath, configuration, SAVEPOINT_PATH));
    +	}
    +
    +	// ------------------------------------------------------------------------
    +
    +	/**
    +	 * Gets the checkpoint base directory. Jobs will create job-specific subdirectories
    +	 * for checkpoints within this directory. May be null, if not configured.
    +	 * 
    +	 * @return The checkpoint base directory
    +	 */
    +	@Nullable
    +	public Path getCheckpointPath() {
    +		return baseCheckpointPath;
    +	}
    +
    +	/**
    +	 * Gets the directory where savepoints are stored by default (when no custom path is given
    +	 * to the savepoint trigger command).
    +	 *
    +	 * @return The default directory for savepoints, or null, if no default directory has been configured.
    +	 */
    +	@Nullable
    +	public Path getSavepointPath() {
    +		return baseSavepointPath;
    +	}
    +
    +	// ------------------------------------------------------------------------
    +	//  Metadata Persistence
    +	// ------------------------------------------------------------------------
    +
    +	/**
    +	 * Checks whether this backend supports externalized checkpoints, which is the case when
    +	 * a checkpoint base directory is configured.
    +	 */
    +	@Override
    +	public boolean supportsExternalizedMetadata() {
    +		return baseCheckpointPath != null;
    +	}
    +
    +	@Nullable
    +	@Override
    +	public String getMetadataPersistenceLocation() {
    +		return baseCheckpointPath == null ? null : baseCheckpointPath.toString();
    +	}
    +
    +	@Override
    +	public StreamStateHandle resolveCheckpointLocation(String checkpointPath) throws IOException {
    +		checkNotNull(checkpointPath, "checkpointPath");
    +		checkArgument(!checkpointPath.isEmpty(), "empty checkpoint path");
    +
    +		// we resolve without strictly validating the metadata file, to resume from cases
    +		// where a differently named metadata file was written (as in prior Flink version)
    +		final FileStatus metadataFileStatus = resolveCheckpointPointer(checkpointPath, false);
    +		return new FileStateHandle(metadataFileStatus.getPath(), metadataFileStatus.getLen());
    +	}
    +
    +	@Override
    +	public CheckpointMetadataStreamFactory createCheckpointMetadataStreamFactory(
    +			JobID jobID,
    +			long checkpointId) throws IOException {
    +
    +		checkNotNull(jobID, "jobID");
    +
    +		final Path checkpointBaseDir = getCheckpointDirectoryForJob(jobID);
    +		final Path checkpointDir = createSpecificCheckpointPath(checkpointBaseDir, checkpointId);
    +		final Path metadataFilePath = new Path(checkpointDir, METADATA_FILE_NAME);
    +
    +		return new FsCheckpointMetadataStreamFactory(checkpointDir.getFileSystem(), checkpointDir, metadataFilePath);
    +	}
    +
    +	@Override
    +	public CheckpointMetadataStreamFactory createSavepointMetadataStreamFactory(
    +			JobID jobID,
    +			@Nullable String targetLocation) throws IOException {
    +
    +		// the directory inside which we create the savepoint
    +		final Path basePath;
    +
    +		if (targetLocation != null) {
    +			try {
    +				basePath = new Path(targetLocation);
    +			}
    +			catch (IllegalArgumentException e) {
    +				throw new IOException("Cannot initialize savepoint to '" + targetLocation + 
    +						"' because it is not a valid file path.");
    +			}
    +		}
    +		else if (baseSavepointPath != null) {
    +			basePath = baseSavepointPath;
    +		}
    +		else {
    +			throw new UnsupportedOperationException(
    +					"Cannot perform a savepoint without a target location when no default savepoint directory " +
    +							"has been configured via '" + SAVEPOINT_PATH.key() + "'.");
    +		}
    +
    +		final FileSystem fs = basePath.getFileSystem();
    +		final Path savepointDir = initializeSavepointDirectory(fs, basePath, jobID);
    +		final Path metadataFilePath = new Path(savepointDir, METADATA_FILE_NAME);
    +
    +		return new FsCheckpointMetadataStreamFactory(fs, savepointDir, metadataFilePath);
    +	}
    +
    +	// ------------------------------------------------------------------------
    +	//  Global Hooks
    +	// ------------------------------------------------------------------------
    +
    +	@Override
    +	public void disposeSavepoint(String pointer) throws IOException {
    +		checkNotNull(pointer, "pointer");
    +
    +		// to be save, we make sure we call this to verify that the metadata file exists
    +		// in the pointed directory, or that this points to the metadata file directly
    +		final FileStatus metadataFileStatus = resolveCheckpointPointer(pointer, true);
    +
    +		final Path savepointDir = metadataFileStatus.getPath().getParent();
    +		final FileSystem fs = savepointDir.getFileSystem();
    +		fs.delete(savepointDir, true);
    +	}
    +
    +	// ------------------------------------------------------------------------
    +	//  Paths
    +	// ------------------------------------------------------------------------
    +
    +	/**
    +	 * Builds directory into which a specific job checkpoints, meaning the directory inside which
    +	 * it creates the checkpoint-specific subdirectories.
    +	 *
    +	 * <p>This method only succeeds if a base checkpoint directory has been set; otherwise
    +	 * the method fails with an exception.
    +	 *
    +	 * @param jobId The ID of the job
    +	 * @return The job's checkpoint directory, re
    +	 *
    +	 * @throws UnsupportedOperationException Thrown, if no base checkpoint directory has been set.
    +	 */
    +	protected Path getCheckpointDirectoryForJob(JobID jobId) {
    +		if (baseCheckpointPath != null) {
    +			return new Path(baseCheckpointPath, jobId.toString());
    +		}
    +		else {
    +			throw new UnsupportedOperationException(
    +					"Cannot write checkpoint data when no checkpoint directory has been configured via '" +
    +							CHECKPOINT_PATH.key() + "'.");
    +		}
    +	}
    +
    +	/**
    +	 * Creates the directory path for a specific checkpoint of a job.
    +	 *
    +	 * @param jobCheckpointDir The directory into which the job checkpoints
    +	 * @param checkpointId The ID (logical timestamp) of the checkpoint
    +	 *
    +	 * @return The checkpoint directory path.
    +	 */
    +	protected static Path createSpecificCheckpointPath(Path jobCheckpointDir, long checkpointId) {
    +		return new Path(jobCheckpointDir, CHECKPOINT_DIR_PREFIX + checkpointId);
    +	}
    +
    +	/**
    +	 * 
    +	 * <p>Important - if the pointer points directly to a file, this does not valicate t
    +	 * 
    +	 * @param checkpointPointer The pointer to resolve
    +	 * @return The file status of the checkpoint/savepoint's metadata file.
    +	 * 
    +	 * @throws IOException Thrown, if the pointer cannot be resolved, the file system not accessed, or
    +	 *                     the pointer points to a location that does not seem to be a checkpoint/savepoint.
    +	 */
    +	protected static FileStatus resolveCheckpointPointer(
    +			String checkpointPointer,
    +			boolean validateMetadataFileName) throws IOException {
    +
    +		// check if the pointer is in fact a valid file path
    +		final Path path;
    +		try {
    +			path = new Path(checkpointPointer);
    +		}
    +		catch (Exception e) {
    +			throw new IOException("Checkpoint/savepoint path '" + checkpointPointer + "' is not a valid file URI");
    +		}
    +
    +		// check if the file system can be accessed
    +		final FileSystem fs;
    +		try {
    +			fs = path.getFileSystem();
    +		}
    +		catch (IOException e) {
    +			throw new IOException("Cannot access file system for checkpoint/savepoint path '" + 
    +					checkpointPointer + "'.");
    +		}
    +
    +		final FileStatus status;
    +		try {
    +			status = fs.getFileStatus(path);
    +		}
    +		catch (FileNotFoundException e) {
    +			throw new IOException("Cannot find the file/directory '" + checkpointPointer +
    +					"' on file system '" + fs.getUri().getScheme() + "'.", e);
    +		}
    +
    +		// if we are here, the file / directory exists
    +
    +		// If this is a directory, we need to find the meta data file
    +		if (status.isDir()) {
    +			final Path metadataFilePath = new Path(path, METADATA_FILE_NAME);
    +			try {
    +				return fs.getFileStatus(metadataFilePath);
    +			}
    +			catch (FileNotFoundException e) {
    +				throw new FileNotFoundException("Cannot find meta data file '" + METADATA_FILE_NAME +
    +						"' in directory '" + path + "'. Please try to load the checkpoint/savepoint " +
    +						"directly from the metadata file instead of the directory.");
    +			}
    +		}
    +		else if (validateMetadataFileName && !METADATA_FILE_NAME.equals(status.getPath().getName())) {
    +			throw new IOException("The given path does not point to a checkpoint/savepoint directory or " +
    +					"metadata file (" + METADATA_FILE_NAME + ')');
    +		}
    +		else {
    +			// this points to a file and we either do no name validation, or
    +			// the name is actually correct, so we can return the path
    +			return status;
    +		}
    +	}
    +
    +	/**
    +	 * Constructs the savepoint directory path and creates the directory. This method retries several
    +	 * times when directory collisions occur and the target path cannot be created.
    +	 */
    +	private static Path initializeSavepointDirectory(FileSystem fs, Path basePath, JobID jobId) throws IOException {
    +		final String prefix;
    +		if (jobId == null) {
    +			prefix = "savepoint-";
    +		} else {
    +			prefix = "savepoint-" + jobId.toString().substring(0, 6) + '-';
    --- End diff --
    
    Why do we only take a substring of the job id for the prefix?


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

[GitHub] flink pull request #3522: [FLINK-5823] [checkpoints] State Backends also han...

Posted by tillrohrmann <gi...@git.apache.org>.
Github user tillrohrmann commented on a diff in the pull request:

    https://github.com/apache/flink/pull/3522#discussion_r108463247
  
    --- Diff: flink-runtime/src/main/java/org/apache/flink/runtime/checkpoint/CompletedCheckpoint.java ---
    @@ -213,6 +218,23 @@ public boolean discard(JobStatus jobStatus) throws Exception {
     
     	void discard() throws Exception {
     		try {
    +			// check if we have a shortcut hook to dispose the state
    +			final StateDisposeHook disposeHook = this.disposeHook;
    +			if (disposeHook != null) {
    +				// fast path!
    +				try {
    +					disposeHook.disposeCheckpointState();
    +					return;
    +				}
    +				catch (Exception e) {
    +					// we catch all exceptions here to make sure we go through the generic path as a
    +					// fallback in case where cleanup fails
    +					LOG.warn("Fast cleanup hook f");
    --- End diff --
    
    `e` is being swallowed and the log message seems to be truncated.


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

[GitHub] flink pull request #3522: [FLINK-5823] [checkpoints] State Backends also han...

Posted by StephanEwen <gi...@git.apache.org>.
Github user StephanEwen commented on a diff in the pull request:

    https://github.com/apache/flink/pull/3522#discussion_r115140655
  
    --- Diff: flink-runtime/src/main/java/org/apache/flink/runtime/state/CheckpointMetadataStreamFactory.java ---
    @@ -0,0 +1,101 @@
    +/*
    + * Licensed to the Apache Software Foundation (ASF) under one
    + * or more contributor license agreements.  See the NOTICE file
    + * distributed with this work for additional information
    + * regarding copyright ownership.  The ASF licenses this file
    + * to you under the Apache License, Version 2.0 (the
    + * "License"); you may not use this file except in compliance
    + * with the License.  You may obtain a copy of the License at
    + *
    + *     http://www.apache.org/licenses/LICENSE-2.0
    + *
    + * Unless required by applicable law or agreed to in writing, software
    + * distributed under the License is distributed on an "AS IS" BASIS,
    + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    + * See the License for the specific language governing permissions and
    + * limitations under the License.
    + */
    +
    +package org.apache.flink.runtime.state;
    +
    +import org.apache.flink.core.fs.FSDataOutputStream;
    +
    +import java.io.IOException;
    +
    +import static org.apache.flink.util.Preconditions.checkNotNull;
    +
    +/**
    + * The {@link CheckpointMetadataStreamFactory} creates streams to write checkpoint <i>metadata</i>,
    + * similar as the {@link CheckpointStreamFactory} creates streams to write checkpoint <i>data</i>.
    + */
    +public interface CheckpointMetadataStreamFactory {
    +
    +	/**
    +	 * Creates a stream to write the metadata for the particular checkpoint that this factory
    +	 * belongs to.
    +	 * 
    +	 * @return The metadata output stream for this factory's checkpoint.
    +	 * @throws IOException Thrown, if the stream could not be opened.
    +	 */
    +	CheckpointMetadataOutputStream createCheckpointStateOutputStream() throws IOException;
    +
    +	/**
    +	 * Gets the location (as a string pointer) where the metadata factory 
    +	 * The interpretation of the pointer is up to the implementation of the state backend.
    +	 * 
    +	 * <p>In case of high-availability setups, the target location pointer is stored
    +	 * in the "ground-truth" store for checkpoint recovery.
    +	 * 
    +	 * @return The checkpoint location pointer.
    +	 */
    +	String getTargetLocation();
    +
    +	// ------------------------------------------------------------------------
    +
    +	/**
    +	 * A dedicated output stream for persisting checkpoint metadata. Upon completion, this returns
    +	 * the state handle to the persisted metadata, plus the external pointer that can be used
    +	 * to restore from that checkpoint.
    +	 */
    +	abstract class CheckpointMetadataOutputStream extends FSDataOutputStream {
    +
    +		/**
    +		 * Closes the metadata stream and gets the external pointer to the checkpoint and a
    +		 * handle that can create an input stream producing the data written to this stream.
    +		 *
    +		 * @return The pointer and state handle with access to the written metadata.
    +		 * @throws IOException Thrown, if the stream cannot be closed.
    +		 */
    +		public abstract StreamHandleAndPointer closeAndGetPointerHandle() throws IOException;
    +	}
    +
    +	// ------------------------------------------------------------------------
    +
    +	/**
    +	 * A combination of a {@code StreamStateHandle} and an external pointer (in the form of a String).
    +	 */
    +	final class StreamHandleAndPointer {
    --- End diff --
    
    The idea of the pointer is to have a state-backend independent string that indicates a checkpoint location. I picked a string, because the location is ultimately passed as a string, either from the user command `flink run -s <savepoint path>` or from ZooKeeper' "last completed checkpoint" entry.
    
    Introducing the `StreamHandleAndPointer` here spares the code from having to reason about state backend specific file handles. We can change that at some point, but for the breadth of changes already in this PR, this helped reduce the scope a bit.


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

[GitHub] flink pull request #3522: [FLINK-5823] [checkpoints] State Backends also han...

Posted by tillrohrmann <gi...@git.apache.org>.
Github user tillrohrmann commented on a diff in the pull request:

    https://github.com/apache/flink/pull/3522#discussion_r108474546
  
    --- Diff: flink-runtime/src/main/java/org/apache/flink/runtime/state/StateBackendGlobalHooks.java ---
    @@ -0,0 +1,74 @@
    +/*
    + * Licensed to the Apache Software Foundation (ASF) under one
    + * or more contributor license agreements.  See the NOTICE file
    + * distributed with this work for additional information
    + * regarding copyright ownership.  The ASF licenses this file
    + * to you under the Apache License, Version 2.0 (the
    + * "License"); you may not use this file except in compliance
    + * with the License.  You may obtain a copy of the License at
    + *
    + *     http://www.apache.org/licenses/LICENSE-2.0
    + *
    + * Unless required by applicable law or agreed to in writing, software
    + * distributed under the License is distributed on an "AS IS" BASIS,
    + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    + * See the License for the specific language governing permissions and
    + * limitations under the License.
    + */
    +
    +package org.apache.flink.runtime.state;
    +
    +import org.apache.flink.annotation.PublicEvolving;
    +import org.apache.flink.runtime.checkpoint.CompletedCheckpoint;
    +import org.apache.flink.util.FlinkException;
    +
    +import javax.annotation.Nullable;
    +import java.io.IOException;
    +
    +/**
    + * An interface that {@link StateBackend State Backends} can optionally implement to offer
    --- End diff --
    
    I didn't know this syntax of `{@link}`. Again learned something new :-)


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

[GitHub] flink issue #3522: [FLINK-5823] [checkpoints] State Backends also handle Che...

Posted by StephanEwen <gi...@git.apache.org>.
Github user StephanEwen commented on the issue:

    https://github.com/apache/flink/pull/3522
  
    CI tests pass (except one profile which does not complete within the limit of 50 minutes)


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

[GitHub] flink pull request #3522: [FLINK-5823] [checkpoints] State Backends also han...

Posted by tillrohrmann <gi...@git.apache.org>.
Github user tillrohrmann commented on a diff in the pull request:

    https://github.com/apache/flink/pull/3522#discussion_r108469205
  
    --- Diff: flink-runtime/src/main/java/org/apache/flink/runtime/checkpoint/savepoint/SavepointV1.java ---
    @@ -61,10 +61,24 @@ public long getCheckpointId() {
     
     	@Override
     	public void dispose() throws Exception {
    +		Exception firstException = null;
    +
     		for (TaskState taskState : taskStates) {
    -			taskState.discardState();
    +			try {
    +				taskState.discardState();
    +			}
    +			catch (Exception e) {
    +				if (firstException == null) {
    +					firstException = e;
    --- End diff --
    
    We could add all following exceptions as suppressed exceptions.


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

[GitHub] flink pull request #3522: [FLINK-5823] [checkpoints] State Backends also han...

Posted by tillrohrmann <gi...@git.apache.org>.
Github user tillrohrmann commented on a diff in the pull request:

    https://github.com/apache/flink/pull/3522#discussion_r108716656
  
    --- Diff: flink-runtime/src/main/java/org/apache/flink/runtime/state/filesystem/AbstractFileStateBackend.java ---
    @@ -0,0 +1,556 @@
    +/*
    + * Licensed to the Apache Software Foundation (ASF) under one
    + * or more contributor license agreements.  See the NOTICE file
    + * distributed with this work for additional information
    + * regarding copyright ownership.  The ASF licenses this file
    + * to you under the Apache License, Version 2.0 (the
    + * "License"); you may not use this file except in compliance
    + * with the License.  You may obtain a copy of the License at
    + *
    + *     http://www.apache.org/licenses/LICENSE-2.0
    + *
    + * Unless required by applicable law or agreed to in writing, software
    + * distributed under the License is distributed on an "AS IS" BASIS,
    + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    + * See the License for the specific language governing permissions and
    + * limitations under the License.
    + */
    +
    +package org.apache.flink.runtime.state.filesystem;
    +
    +import org.apache.flink.annotation.PublicEvolving;
    +import org.apache.flink.api.common.JobID;
    +import org.apache.flink.configuration.ConfigConstants;
    +import org.apache.flink.configuration.ConfigOption;
    +import org.apache.flink.configuration.ConfigOptions;
    +import org.apache.flink.configuration.Configuration;
    +import org.apache.flink.configuration.IllegalConfigurationException;
    +import org.apache.flink.core.fs.FileStatus;
    +import org.apache.flink.core.fs.FileSystem;
    +import org.apache.flink.core.fs.Path;
    +import org.apache.flink.runtime.state.AbstractStateBackend;
    +import org.apache.flink.runtime.state.CheckpointMetadataStreamFactory;
    +import org.apache.flink.runtime.state.StateBackendGlobalHooks;
    +import org.apache.flink.runtime.state.StreamStateHandle;
    +import org.apache.flink.util.FileUtils;
    +import org.apache.flink.util.FlinkException;
    +import org.apache.flink.util.FlinkRuntimeException;
    +
    +import org.slf4j.Logger;
    +import org.slf4j.LoggerFactory;
    +
    +import javax.annotation.Nullable;
    +import java.io.FileNotFoundException;
    +import java.io.IOException;
    +import java.net.URI;
    +import java.net.URISyntaxException;
    +
    +import static org.apache.flink.util.Preconditions.checkArgument;
    +import static org.apache.flink.util.Preconditions.checkNotNull;
    +
    +/**
    + * A base class for all state backends that store their metadata (and data) in files.
    + * Examples that inherit from this are the {@link FsStateBackend}, the
    + * {@link org.apache.flink.runtime.state.memory.MemoryStateBackend MemoryStateBackend}, or the
    + * {@code RocksDBStateBackend}.
    + * 
    + * <p>This class takes the base checkpoint- and savepoint directory paths, but also accepts null
    + * for both of then, in which case creating externalized checkpoint is not possible, and it is not
    + * possible to create a savepoint with a default path. Null is accepted to enable implementations
    + * that only optionally support default savepoints and externalized checkpoints.
    + * 
    + * <h1>Checkpoint Layout</h1>
    + * 
    + * The state backend is configured with a base directory and persists the checkpoint data of specific
    + * checkpoints in specific subdirectories. For example, if the base directory was set to 
    + * {@code hdfs://namenode:port/flink-checkpoints/}, the state backend will create a subdirectory with
    + * the job's ID that will contain the actual checkpoints:
    + * ({@code hdfs://namenode:port/flink-checkpoints/1b080b6e710aabbef8993ab18c6de98b})
    + *
    + * <p>Each checkpoint individually will store all its files in a subdirectory that includes the
    + * checkpoint number, such as {@code hdfs://namenode:port/flink-checkpoints/1b080b6e710aabbef8993ab18c6de98b/chk-17/}.
    + * 
    + * <h1>Savepoint Layout</h1>
    + * 
    + * A savepoint that is set to be stored in path {@code hdfs://namenode:port/flink-savepoints/}, will create
    + * a subdirectory {@code savepoint-jobId(0, 6)-randomDigits} in which it stores all savepoint data.
    + * The random digits are added as "entropy" to avoid directory collisions.
    + */
    +@PublicEvolving
    +public abstract class AbstractFileStateBackend extends AbstractStateBackend implements StateBackendGlobalHooks {
    +
    +	private static final long serialVersionUID = 1L;
    +
    +	private static final Logger LOG = LoggerFactory.getLogger(AbstractFileStateBackend.class);
    +
    +	// ------------------------------------------------------------------------
    +	//  Configuration
    +	// ------------------------------------------------------------------------
    +
    +	/**
    +	 * The configuration parameter for the checkpoint path/directory.
    +	 */
    +	public static final ConfigOption<String> CHECKPOINT_PATH = ConfigOptions
    +			.key(ConfigConstants.CHECKPOINTS_DIRECTORY_KEY)
    +			.noDefaultValue()
    +			.withDeprecatedKeys("state.backend.fs.checkpointdir");
    +
    +	/**
    +	 * The configuration parameter for the savepoint path/directory.
    +	 */
    +	public static final ConfigOption<String> SAVEPOINT_PATH = ConfigOptions
    +			.key(ConfigConstants.SAVEPOINT_DIRECTORY_KEY)
    +			.noDefaultValue()
    +			.withDeprecatedKeys("state.backend.fs.savepointdir");
    +
    +	// ------------------------------------------------------------------------
    +	//  Constants
    +	// ------------------------------------------------------------------------
    +
    +	/** The name of the metadata files in checkpoints / savepoints. */
    +	public static final String METADATA_FILE_NAME = "_metadata";
    +
    +	/** The prefix of the checkpoint directory names */
    +	public static final String CHECKPOINT_DIR_PREFIX = "chk-";
    +
    +	// ------------------------------------------------------------------------
    +	//  State Backend Properties
    +	// ------------------------------------------------------------------------
    +
    +	/** The path where checkpoints will be stored, or null, if none has been configured */
    +	@Nullable
    +	private final Path baseCheckpointPath;
    +
    +	/** The path where savepoints will be stored, or null, if none has been configured */
    +	@Nullable
    +	private final Path baseSavepointPath;
    +
    +	/**
    +	 * Creates a backend with the given optional checkpoint- and savepoint base directories.
    +	 * 
    +	 * @param baseCheckpointPath The base directory for checkpoints, or null, if none is configured.
    +	 * @param baseSavepointPath The default directory for savepoints, or null, if none is set.
    +	 */
    +	protected AbstractFileStateBackend(
    +			@Nullable Path baseCheckpointPath,
    +			@Nullable Path baseSavepointPath) {
    +
    +		this(baseCheckpointPath == null ? null : baseCheckpointPath.toUri(),
    +				baseSavepointPath == null ? null : baseSavepointPath.toUri());
    +	}
    +
    +	/**
    +	 * Creates a backend with the given optional checkpoint- and savepoint base directories.
    +	 * 
    +	 * @param baseCheckpointPath The base directory for checkpoints, or null, if none is configured.
    +	 * @param baseSavepointPath The default directory for savepoints, or null, if none is set.
    +	 */
    +	protected AbstractFileStateBackend(
    +			@Nullable URI baseCheckpointPath,
    +			@Nullable URI baseSavepointPath) {
    +
    +		this.baseCheckpointPath = baseCheckpointPath == null ? null : validateAndNormalizeUri(baseCheckpointPath);
    +		this.baseSavepointPath = baseSavepointPath == null ? null : validateAndNormalizeUri(baseSavepointPath);
    +	}
    +
    +	/**
    +	 * Creates a new backend using the given checkpoint-/savepoint directories, or the values defined in
    +	 * the given configuration. If a checkpoint-/savepoint parameter is not null, that value takes precedence
    +	 * over the value in the configuration. If the configuration does not specify a value, it is possible
    +	 * that the checkpoint-/savepoint directories in the backend will be null.
    +	 * 
    +	 * <p>This constructor can be used to create a backend that is based partially on a given backend
    +	 * and partially on a configuration.
    +	 * 
    +	 * @param baseCheckpointPath The checkpoint base directory to use (or null).
    +	 * @param baseSavepointPath The default savepoint directory to use (or null).
    +	 * @param configuration The configuration to read values from 
    +	 */
    +	protected AbstractFileStateBackend(
    +			@Nullable Path baseCheckpointPath,
    +			@Nullable Path baseSavepointPath,
    +			Configuration configuration) {
    +
    +		this(parameterOrConfigured(baseCheckpointPath, configuration, CHECKPOINT_PATH),
    +				parameterOrConfigured(baseSavepointPath, configuration, SAVEPOINT_PATH));
    +	}
    +
    +	// ------------------------------------------------------------------------
    +
    +	/**
    +	 * Gets the checkpoint base directory. Jobs will create job-specific subdirectories
    +	 * for checkpoints within this directory. May be null, if not configured.
    +	 * 
    +	 * @return The checkpoint base directory
    +	 */
    +	@Nullable
    +	public Path getCheckpointPath() {
    +		return baseCheckpointPath;
    +	}
    +
    +	/**
    +	 * Gets the directory where savepoints are stored by default (when no custom path is given
    +	 * to the savepoint trigger command).
    +	 *
    +	 * @return The default directory for savepoints, or null, if no default directory has been configured.
    +	 */
    +	@Nullable
    +	public Path getSavepointPath() {
    +		return baseSavepointPath;
    +	}
    +
    +	// ------------------------------------------------------------------------
    +	//  Metadata Persistence
    +	// ------------------------------------------------------------------------
    +
    +	/**
    +	 * Checks whether this backend supports externalized checkpoints, which is the case when
    +	 * a checkpoint base directory is configured.
    +	 */
    +	@Override
    +	public boolean supportsExternalizedMetadata() {
    +		return baseCheckpointPath != null;
    +	}
    +
    +	@Nullable
    +	@Override
    +	public String getMetadataPersistenceLocation() {
    +		return baseCheckpointPath == null ? null : baseCheckpointPath.toString();
    +	}
    +
    +	@Override
    +	public StreamStateHandle resolveCheckpointLocation(String checkpointPath) throws IOException {
    +		checkNotNull(checkpointPath, "checkpointPath");
    +		checkArgument(!checkpointPath.isEmpty(), "empty checkpoint path");
    +
    +		// we resolve without strictly validating the metadata file, to resume from cases
    +		// where a differently named metadata file was written (as in prior Flink version)
    +		final FileStatus metadataFileStatus = resolveCheckpointPointer(checkpointPath, false);
    +		return new FileStateHandle(metadataFileStatus.getPath(), metadataFileStatus.getLen());
    +	}
    +
    +	@Override
    +	public CheckpointMetadataStreamFactory createCheckpointMetadataStreamFactory(
    +			JobID jobID,
    +			long checkpointId) throws IOException {
    +
    +		checkNotNull(jobID, "jobID");
    +
    +		final Path checkpointBaseDir = getCheckpointDirectoryForJob(jobID);
    +		final Path checkpointDir = createSpecificCheckpointPath(checkpointBaseDir, checkpointId);
    +		final Path metadataFilePath = new Path(checkpointDir, METADATA_FILE_NAME);
    +
    +		return new FsCheckpointMetadataStreamFactory(checkpointDir.getFileSystem(), checkpointDir, metadataFilePath);
    +	}
    +
    +	@Override
    +	public CheckpointMetadataStreamFactory createSavepointMetadataStreamFactory(
    +			JobID jobID,
    +			@Nullable String targetLocation) throws IOException {
    +
    +		// the directory inside which we create the savepoint
    +		final Path basePath;
    +
    +		if (targetLocation != null) {
    +			try {
    +				basePath = new Path(targetLocation);
    +			}
    +			catch (IllegalArgumentException e) {
    +				throw new IOException("Cannot initialize savepoint to '" + targetLocation + 
    +						"' because it is not a valid file path.");
    +			}
    +		}
    +		else if (baseSavepointPath != null) {
    +			basePath = baseSavepointPath;
    +		}
    +		else {
    +			throw new UnsupportedOperationException(
    +					"Cannot perform a savepoint without a target location when no default savepoint directory " +
    +							"has been configured via '" + SAVEPOINT_PATH.key() + "'.");
    +		}
    +
    +		final FileSystem fs = basePath.getFileSystem();
    +		final Path savepointDir = initializeSavepointDirectory(fs, basePath, jobID);
    +		final Path metadataFilePath = new Path(savepointDir, METADATA_FILE_NAME);
    +
    +		return new FsCheckpointMetadataStreamFactory(fs, savepointDir, metadataFilePath);
    +	}
    +
    +	// ------------------------------------------------------------------------
    +	//  Global Hooks
    +	// ------------------------------------------------------------------------
    +
    +	@Override
    +	public void disposeSavepoint(String pointer) throws IOException {
    +		checkNotNull(pointer, "pointer");
    +
    +		// to be save, we make sure we call this to verify that the metadata file exists
    +		// in the pointed directory, or that this points to the metadata file directly
    +		final FileStatus metadataFileStatus = resolveCheckpointPointer(pointer, true);
    +
    +		final Path savepointDir = metadataFileStatus.getPath().getParent();
    +		final FileSystem fs = savepointDir.getFileSystem();
    +		fs.delete(savepointDir, true);
    +	}
    +
    +	// ------------------------------------------------------------------------
    +	//  Paths
    +	// ------------------------------------------------------------------------
    +
    +	/**
    +	 * Builds directory into which a specific job checkpoints, meaning the directory inside which
    +	 * it creates the checkpoint-specific subdirectories.
    +	 *
    +	 * <p>This method only succeeds if a base checkpoint directory has been set; otherwise
    +	 * the method fails with an exception.
    +	 *
    +	 * @param jobId The ID of the job
    +	 * @return The job's checkpoint directory, re
    +	 *
    +	 * @throws UnsupportedOperationException Thrown, if no base checkpoint directory has been set.
    +	 */
    +	protected Path getCheckpointDirectoryForJob(JobID jobId) {
    +		if (baseCheckpointPath != null) {
    +			return new Path(baseCheckpointPath, jobId.toString());
    +		}
    +		else {
    +			throw new UnsupportedOperationException(
    +					"Cannot write checkpoint data when no checkpoint directory has been configured via '" +
    +							CHECKPOINT_PATH.key() + "'.");
    +		}
    +	}
    +
    +	/**
    +	 * Creates the directory path for a specific checkpoint of a job.
    +	 *
    +	 * @param jobCheckpointDir The directory into which the job checkpoints
    +	 * @param checkpointId The ID (logical timestamp) of the checkpoint
    +	 *
    +	 * @return The checkpoint directory path.
    +	 */
    +	protected static Path createSpecificCheckpointPath(Path jobCheckpointDir, long checkpointId) {
    +		return new Path(jobCheckpointDir, CHECKPOINT_DIR_PREFIX + checkpointId);
    +	}
    +
    +	/**
    +	 * 
    +	 * <p>Important - if the pointer points directly to a file, this does not valicate t
    +	 * 
    +	 * @param checkpointPointer The pointer to resolve
    +	 * @return The file status of the checkpoint/savepoint's metadata file.
    +	 * 
    +	 * @throws IOException Thrown, if the pointer cannot be resolved, the file system not accessed, or
    +	 *                     the pointer points to a location that does not seem to be a checkpoint/savepoint.
    +	 */
    +	protected static FileStatus resolveCheckpointPointer(
    +			String checkpointPointer,
    +			boolean validateMetadataFileName) throws IOException {
    +
    +		// check if the pointer is in fact a valid file path
    +		final Path path;
    +		try {
    +			path = new Path(checkpointPointer);
    +		}
    +		catch (Exception e) {
    +			throw new IOException("Checkpoint/savepoint path '" + checkpointPointer + "' is not a valid file URI");
    +		}
    +
    +		// check if the file system can be accessed
    +		final FileSystem fs;
    +		try {
    +			fs = path.getFileSystem();
    +		}
    +		catch (IOException e) {
    +			throw new IOException("Cannot access file system for checkpoint/savepoint path '" + 
    +					checkpointPointer + "'.");
    +		}
    +
    +		final FileStatus status;
    +		try {
    +			status = fs.getFileStatus(path);
    +		}
    +		catch (FileNotFoundException e) {
    +			throw new IOException("Cannot find the file/directory '" + checkpointPointer +
    +					"' on file system '" + fs.getUri().getScheme() + "'.", e);
    +		}
    +
    +		// if we are here, the file / directory exists
    +
    +		// If this is a directory, we need to find the meta data file
    +		if (status.isDir()) {
    +			final Path metadataFilePath = new Path(path, METADATA_FILE_NAME);
    +			try {
    +				return fs.getFileStatus(metadataFilePath);
    +			}
    +			catch (FileNotFoundException e) {
    +				throw new FileNotFoundException("Cannot find meta data file '" + METADATA_FILE_NAME +
    +						"' in directory '" + path + "'. Please try to load the checkpoint/savepoint " +
    +						"directly from the metadata file instead of the directory.");
    +			}
    +		}
    +		else if (validateMetadataFileName && !METADATA_FILE_NAME.equals(status.getPath().getName())) {
    +			throw new IOException("The given path does not point to a checkpoint/savepoint directory or " +
    +					"metadata file (" + METADATA_FILE_NAME + ')');
    +		}
    +		else {
    +			// this points to a file and we either do no name validation, or
    +			// the name is actually correct, so we can return the path
    +			return status;
    +		}
    +	}
    +
    +	/**
    +	 * Constructs the savepoint directory path and creates the directory. This method retries several
    +	 * times when directory collisions occur and the target path cannot be created.
    +	 */
    +	private static Path initializeSavepointDirectory(FileSystem fs, Path basePath, JobID jobId) throws IOException {
    +		final String prefix;
    +		if (jobId == null) {
    +			prefix = "savepoint-";
    +		} else {
    +			prefix = "savepoint-" + jobId.toString().substring(0, 6) + '-';
    +		}
    +
    +		Exception latestException = null;
    +
    +		// Initialize the actual savepoint directory. This MUST create a new directory!
    +		for (int attempt = 0; attempt < 10; attempt++) {
    +			Path path = new Path(basePath, FileUtils.getRandomFilename(prefix));
    +
    +			try {
    +				if (fs.mkdirs(path)) {
    +					return path;
    +				}
    +			} catch (Exception e) {
    +				latestException = e;
    +			}
    +		}
    +
    +		throw new IOException("Failed to create savepoint directory at " + basePath, latestException);
    +	}
    +
    +	// ------------------------------------------------------------------------
    +	//  Utilities
    +	// ------------------------------------------------------------------------
    +
    +	// 
    +	/**
    +	 * Checks and normalizes the checkpoint data URI. This method first checks the validity of the
    +	 * URI (scheme, path, availability of a matching file system) and then normalizes the URI
    +	 * to a path.
    +	 *
    +	 * <p>If the URI does not include an authority, but the file system configured for the URI has an
    +	 * authority, then the normalized path will include this authority.
    +	 *
    +	 * @param checkpointDataUri The URI to check and normalize.
    +	 * @return A normalized URI as a Path.
    +	 *
    +	 * @throws IllegalArgumentException Thrown, if the URI misses scheme or path.
    +	 */
    +	public static Path validateAndNormalizeUri(URI checkpointDataUri) {
    +		final String scheme = checkpointDataUri.getScheme();
    +		final String path = checkpointDataUri.getPath();
    +
    +		// some validity checks
    +		if (scheme == null) {
    +			throw new IllegalArgumentException("The scheme (hdfs://, file://, etc) is null. " +
    +					"Please specify the file system scheme explicitly in the URI.");
    +		}
    +		if (path == null) {
    +			throw new IllegalArgumentException("The path to store the checkpoint data in is null. " +
    +					"Please specify a directory path for the checkpoint data.");
    +		}
    +		if (path.length() == 0 || path.equals("/")) {
    +			throw new IllegalArgumentException("Cannot use the root directory for checkpoints.");
    +		}
    +
    +		if (!FileSystem.isFlinkSupportedScheme(checkpointDataUri.getScheme())) {
    +			// skip verification checks for non-flink supported filesystem
    +			// this is because the required filesystem classes may not be available to the flink client
    +			return new Path(checkpointDataUri);
    +		}
    +		else {
    +			// we do a bit of work to make sure that the URI for the filesystem refers to exactly the same
    +			// (distributed) filesystem on all hosts and includes full host/port information, even if the
    +			// original URI did not include that. We count on the filesystem loading from the configuration
    +			// to fill in the missing data.
    +
    +			// try to grab the file system for this path/URI. this should always succeed, since we
    +			// are only in this branch if this is a flink-supported file system
    +			FileSystem filesystem;
    +			try {
    +				filesystem = FileSystem.get(checkpointDataUri);
    +			} catch (IOException e) {
    +				// should never happen
    +				throw new FlinkRuntimeException("cannot access file system for URI " + checkpointDataUri);
    +			}
    +
    +			if (filesystem == null) {
    +				String reason = "Could not find a file system for the given scheme in" +
    +						"the available configurations.";
    +				LOG.warn("Could not verify checkpoint path. This might be caused by a genuine " +
    +						"problem or by the fact that the file system is not accessible from the " +
    +						"client. Reason:{}", reason);
    --- End diff --
    
    We could fuse `reason` and the logging statement into a single string.


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

[GitHub] flink pull request #3522: [FLINK-5823] [checkpoints] State Backends also han...

Posted by tillrohrmann <gi...@git.apache.org>.
Github user tillrohrmann commented on a diff in the pull request:

    https://github.com/apache/flink/pull/3522#discussion_r108716333
  
    --- Diff: flink-runtime/src/main/java/org/apache/flink/runtime/state/filesystem/AbstractFileStateBackend.java ---
    @@ -0,0 +1,556 @@
    +/*
    + * Licensed to the Apache Software Foundation (ASF) under one
    + * or more contributor license agreements.  See the NOTICE file
    + * distributed with this work for additional information
    + * regarding copyright ownership.  The ASF licenses this file
    + * to you under the Apache License, Version 2.0 (the
    + * "License"); you may not use this file except in compliance
    + * with the License.  You may obtain a copy of the License at
    + *
    + *     http://www.apache.org/licenses/LICENSE-2.0
    + *
    + * Unless required by applicable law or agreed to in writing, software
    + * distributed under the License is distributed on an "AS IS" BASIS,
    + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    + * See the License for the specific language governing permissions and
    + * limitations under the License.
    + */
    +
    +package org.apache.flink.runtime.state.filesystem;
    +
    +import org.apache.flink.annotation.PublicEvolving;
    +import org.apache.flink.api.common.JobID;
    +import org.apache.flink.configuration.ConfigConstants;
    +import org.apache.flink.configuration.ConfigOption;
    +import org.apache.flink.configuration.ConfigOptions;
    +import org.apache.flink.configuration.Configuration;
    +import org.apache.flink.configuration.IllegalConfigurationException;
    +import org.apache.flink.core.fs.FileStatus;
    +import org.apache.flink.core.fs.FileSystem;
    +import org.apache.flink.core.fs.Path;
    +import org.apache.flink.runtime.state.AbstractStateBackend;
    +import org.apache.flink.runtime.state.CheckpointMetadataStreamFactory;
    +import org.apache.flink.runtime.state.StateBackendGlobalHooks;
    +import org.apache.flink.runtime.state.StreamStateHandle;
    +import org.apache.flink.util.FileUtils;
    +import org.apache.flink.util.FlinkException;
    +import org.apache.flink.util.FlinkRuntimeException;
    +
    +import org.slf4j.Logger;
    +import org.slf4j.LoggerFactory;
    +
    +import javax.annotation.Nullable;
    +import java.io.FileNotFoundException;
    +import java.io.IOException;
    +import java.net.URI;
    +import java.net.URISyntaxException;
    +
    +import static org.apache.flink.util.Preconditions.checkArgument;
    +import static org.apache.flink.util.Preconditions.checkNotNull;
    +
    +/**
    + * A base class for all state backends that store their metadata (and data) in files.
    + * Examples that inherit from this are the {@link FsStateBackend}, the
    + * {@link org.apache.flink.runtime.state.memory.MemoryStateBackend MemoryStateBackend}, or the
    + * {@code RocksDBStateBackend}.
    + * 
    + * <p>This class takes the base checkpoint- and savepoint directory paths, but also accepts null
    + * for both of then, in which case creating externalized checkpoint is not possible, and it is not
    + * possible to create a savepoint with a default path. Null is accepted to enable implementations
    + * that only optionally support default savepoints and externalized checkpoints.
    + * 
    + * <h1>Checkpoint Layout</h1>
    + * 
    + * The state backend is configured with a base directory and persists the checkpoint data of specific
    + * checkpoints in specific subdirectories. For example, if the base directory was set to 
    + * {@code hdfs://namenode:port/flink-checkpoints/}, the state backend will create a subdirectory with
    + * the job's ID that will contain the actual checkpoints:
    + * ({@code hdfs://namenode:port/flink-checkpoints/1b080b6e710aabbef8993ab18c6de98b})
    + *
    + * <p>Each checkpoint individually will store all its files in a subdirectory that includes the
    + * checkpoint number, such as {@code hdfs://namenode:port/flink-checkpoints/1b080b6e710aabbef8993ab18c6de98b/chk-17/}.
    + * 
    + * <h1>Savepoint Layout</h1>
    + * 
    + * A savepoint that is set to be stored in path {@code hdfs://namenode:port/flink-savepoints/}, will create
    + * a subdirectory {@code savepoint-jobId(0, 6)-randomDigits} in which it stores all savepoint data.
    + * The random digits are added as "entropy" to avoid directory collisions.
    + */
    +@PublicEvolving
    +public abstract class AbstractFileStateBackend extends AbstractStateBackend implements StateBackendGlobalHooks {
    +
    +	private static final long serialVersionUID = 1L;
    +
    +	private static final Logger LOG = LoggerFactory.getLogger(AbstractFileStateBackend.class);
    +
    +	// ------------------------------------------------------------------------
    +	//  Configuration
    +	// ------------------------------------------------------------------------
    +
    +	/**
    +	 * The configuration parameter for the checkpoint path/directory.
    +	 */
    +	public static final ConfigOption<String> CHECKPOINT_PATH = ConfigOptions
    +			.key(ConfigConstants.CHECKPOINTS_DIRECTORY_KEY)
    +			.noDefaultValue()
    +			.withDeprecatedKeys("state.backend.fs.checkpointdir");
    +
    +	/**
    +	 * The configuration parameter for the savepoint path/directory.
    +	 */
    +	public static final ConfigOption<String> SAVEPOINT_PATH = ConfigOptions
    +			.key(ConfigConstants.SAVEPOINT_DIRECTORY_KEY)
    +			.noDefaultValue()
    +			.withDeprecatedKeys("state.backend.fs.savepointdir");
    +
    +	// ------------------------------------------------------------------------
    +	//  Constants
    +	// ------------------------------------------------------------------------
    +
    +	/** The name of the metadata files in checkpoints / savepoints. */
    +	public static final String METADATA_FILE_NAME = "_metadata";
    +
    +	/** The prefix of the checkpoint directory names */
    +	public static final String CHECKPOINT_DIR_PREFIX = "chk-";
    +
    +	// ------------------------------------------------------------------------
    +	//  State Backend Properties
    +	// ------------------------------------------------------------------------
    +
    +	/** The path where checkpoints will be stored, or null, if none has been configured */
    +	@Nullable
    +	private final Path baseCheckpointPath;
    +
    +	/** The path where savepoints will be stored, or null, if none has been configured */
    +	@Nullable
    +	private final Path baseSavepointPath;
    +
    +	/**
    +	 * Creates a backend with the given optional checkpoint- and savepoint base directories.
    +	 * 
    +	 * @param baseCheckpointPath The base directory for checkpoints, or null, if none is configured.
    +	 * @param baseSavepointPath The default directory for savepoints, or null, if none is set.
    +	 */
    +	protected AbstractFileStateBackend(
    +			@Nullable Path baseCheckpointPath,
    +			@Nullable Path baseSavepointPath) {
    +
    +		this(baseCheckpointPath == null ? null : baseCheckpointPath.toUri(),
    +				baseSavepointPath == null ? null : baseSavepointPath.toUri());
    +	}
    +
    +	/**
    +	 * Creates a backend with the given optional checkpoint- and savepoint base directories.
    +	 * 
    +	 * @param baseCheckpointPath The base directory for checkpoints, or null, if none is configured.
    +	 * @param baseSavepointPath The default directory for savepoints, or null, if none is set.
    +	 */
    +	protected AbstractFileStateBackend(
    +			@Nullable URI baseCheckpointPath,
    +			@Nullable URI baseSavepointPath) {
    +
    +		this.baseCheckpointPath = baseCheckpointPath == null ? null : validateAndNormalizeUri(baseCheckpointPath);
    +		this.baseSavepointPath = baseSavepointPath == null ? null : validateAndNormalizeUri(baseSavepointPath);
    +	}
    +
    +	/**
    +	 * Creates a new backend using the given checkpoint-/savepoint directories, or the values defined in
    +	 * the given configuration. If a checkpoint-/savepoint parameter is not null, that value takes precedence
    +	 * over the value in the configuration. If the configuration does not specify a value, it is possible
    +	 * that the checkpoint-/savepoint directories in the backend will be null.
    +	 * 
    +	 * <p>This constructor can be used to create a backend that is based partially on a given backend
    +	 * and partially on a configuration.
    +	 * 
    +	 * @param baseCheckpointPath The checkpoint base directory to use (or null).
    +	 * @param baseSavepointPath The default savepoint directory to use (or null).
    +	 * @param configuration The configuration to read values from 
    +	 */
    +	protected AbstractFileStateBackend(
    +			@Nullable Path baseCheckpointPath,
    +			@Nullable Path baseSavepointPath,
    +			Configuration configuration) {
    +
    +		this(parameterOrConfigured(baseCheckpointPath, configuration, CHECKPOINT_PATH),
    +				parameterOrConfigured(baseSavepointPath, configuration, SAVEPOINT_PATH));
    +	}
    +
    +	// ------------------------------------------------------------------------
    +
    +	/**
    +	 * Gets the checkpoint base directory. Jobs will create job-specific subdirectories
    +	 * for checkpoints within this directory. May be null, if not configured.
    +	 * 
    +	 * @return The checkpoint base directory
    +	 */
    +	@Nullable
    +	public Path getCheckpointPath() {
    +		return baseCheckpointPath;
    +	}
    +
    +	/**
    +	 * Gets the directory where savepoints are stored by default (when no custom path is given
    +	 * to the savepoint trigger command).
    +	 *
    +	 * @return The default directory for savepoints, or null, if no default directory has been configured.
    +	 */
    +	@Nullable
    +	public Path getSavepointPath() {
    +		return baseSavepointPath;
    +	}
    +
    +	// ------------------------------------------------------------------------
    +	//  Metadata Persistence
    +	// ------------------------------------------------------------------------
    +
    +	/**
    +	 * Checks whether this backend supports externalized checkpoints, which is the case when
    +	 * a checkpoint base directory is configured.
    +	 */
    +	@Override
    +	public boolean supportsExternalizedMetadata() {
    +		return baseCheckpointPath != null;
    +	}
    +
    +	@Nullable
    +	@Override
    +	public String getMetadataPersistenceLocation() {
    +		return baseCheckpointPath == null ? null : baseCheckpointPath.toString();
    +	}
    +
    +	@Override
    +	public StreamStateHandle resolveCheckpointLocation(String checkpointPath) throws IOException {
    +		checkNotNull(checkpointPath, "checkpointPath");
    +		checkArgument(!checkpointPath.isEmpty(), "empty checkpoint path");
    +
    +		// we resolve without strictly validating the metadata file, to resume from cases
    +		// where a differently named metadata file was written (as in prior Flink version)
    +		final FileStatus metadataFileStatus = resolveCheckpointPointer(checkpointPath, false);
    +		return new FileStateHandle(metadataFileStatus.getPath(), metadataFileStatus.getLen());
    +	}
    +
    +	@Override
    +	public CheckpointMetadataStreamFactory createCheckpointMetadataStreamFactory(
    +			JobID jobID,
    +			long checkpointId) throws IOException {
    +
    +		checkNotNull(jobID, "jobID");
    +
    +		final Path checkpointBaseDir = getCheckpointDirectoryForJob(jobID);
    +		final Path checkpointDir = createSpecificCheckpointPath(checkpointBaseDir, checkpointId);
    +		final Path metadataFilePath = new Path(checkpointDir, METADATA_FILE_NAME);
    +
    +		return new FsCheckpointMetadataStreamFactory(checkpointDir.getFileSystem(), checkpointDir, metadataFilePath);
    +	}
    +
    +	@Override
    +	public CheckpointMetadataStreamFactory createSavepointMetadataStreamFactory(
    +			JobID jobID,
    +			@Nullable String targetLocation) throws IOException {
    +
    +		// the directory inside which we create the savepoint
    +		final Path basePath;
    +
    +		if (targetLocation != null) {
    +			try {
    +				basePath = new Path(targetLocation);
    +			}
    +			catch (IllegalArgumentException e) {
    +				throw new IOException("Cannot initialize savepoint to '" + targetLocation + 
    +						"' because it is not a valid file path.");
    +			}
    +		}
    +		else if (baseSavepointPath != null) {
    +			basePath = baseSavepointPath;
    +		}
    +		else {
    +			throw new UnsupportedOperationException(
    +					"Cannot perform a savepoint without a target location when no default savepoint directory " +
    +							"has been configured via '" + SAVEPOINT_PATH.key() + "'.");
    +		}
    +
    +		final FileSystem fs = basePath.getFileSystem();
    +		final Path savepointDir = initializeSavepointDirectory(fs, basePath, jobID);
    +		final Path metadataFilePath = new Path(savepointDir, METADATA_FILE_NAME);
    +
    +		return new FsCheckpointMetadataStreamFactory(fs, savepointDir, metadataFilePath);
    +	}
    +
    +	// ------------------------------------------------------------------------
    +	//  Global Hooks
    +	// ------------------------------------------------------------------------
    +
    +	@Override
    +	public void disposeSavepoint(String pointer) throws IOException {
    +		checkNotNull(pointer, "pointer");
    +
    +		// to be save, we make sure we call this to verify that the metadata file exists
    +		// in the pointed directory, or that this points to the metadata file directly
    +		final FileStatus metadataFileStatus = resolveCheckpointPointer(pointer, true);
    +
    +		final Path savepointDir = metadataFileStatus.getPath().getParent();
    +		final FileSystem fs = savepointDir.getFileSystem();
    +		fs.delete(savepointDir, true);
    +	}
    +
    +	// ------------------------------------------------------------------------
    +	//  Paths
    +	// ------------------------------------------------------------------------
    +
    +	/**
    +	 * Builds directory into which a specific job checkpoints, meaning the directory inside which
    +	 * it creates the checkpoint-specific subdirectories.
    +	 *
    +	 * <p>This method only succeeds if a base checkpoint directory has been set; otherwise
    +	 * the method fails with an exception.
    +	 *
    +	 * @param jobId The ID of the job
    +	 * @return The job's checkpoint directory, re
    +	 *
    +	 * @throws UnsupportedOperationException Thrown, if no base checkpoint directory has been set.
    +	 */
    +	protected Path getCheckpointDirectoryForJob(JobID jobId) {
    +		if (baseCheckpointPath != null) {
    +			return new Path(baseCheckpointPath, jobId.toString());
    +		}
    +		else {
    +			throw new UnsupportedOperationException(
    +					"Cannot write checkpoint data when no checkpoint directory has been configured via '" +
    +							CHECKPOINT_PATH.key() + "'.");
    +		}
    +	}
    +
    +	/**
    +	 * Creates the directory path for a specific checkpoint of a job.
    +	 *
    +	 * @param jobCheckpointDir The directory into which the job checkpoints
    +	 * @param checkpointId The ID (logical timestamp) of the checkpoint
    +	 *
    +	 * @return The checkpoint directory path.
    +	 */
    +	protected static Path createSpecificCheckpointPath(Path jobCheckpointDir, long checkpointId) {
    +		return new Path(jobCheckpointDir, CHECKPOINT_DIR_PREFIX + checkpointId);
    +	}
    +
    +	/**
    +	 * 
    +	 * <p>Important - if the pointer points directly to a file, this does not valicate t
    +	 * 
    +	 * @param checkpointPointer The pointer to resolve
    +	 * @return The file status of the checkpoint/savepoint's metadata file.
    +	 * 
    +	 * @throws IOException Thrown, if the pointer cannot be resolved, the file system not accessed, or
    +	 *                     the pointer points to a location that does not seem to be a checkpoint/savepoint.
    +	 */
    +	protected static FileStatus resolveCheckpointPointer(
    +			String checkpointPointer,
    +			boolean validateMetadataFileName) throws IOException {
    +
    +		// check if the pointer is in fact a valid file path
    +		final Path path;
    +		try {
    +			path = new Path(checkpointPointer);
    +		}
    +		catch (Exception e) {
    +			throw new IOException("Checkpoint/savepoint path '" + checkpointPointer + "' is not a valid file URI");
    +		}
    +
    +		// check if the file system can be accessed
    +		final FileSystem fs;
    +		try {
    +			fs = path.getFileSystem();
    +		}
    +		catch (IOException e) {
    +			throw new IOException("Cannot access file system for checkpoint/savepoint path '" + 
    +					checkpointPointer + "'.");
    +		}
    +
    +		final FileStatus status;
    +		try {
    +			status = fs.getFileStatus(path);
    +		}
    +		catch (FileNotFoundException e) {
    +			throw new IOException("Cannot find the file/directory '" + checkpointPointer +
    +					"' on file system '" + fs.getUri().getScheme() + "'.", e);
    +		}
    +
    +		// if we are here, the file / directory exists
    +
    +		// If this is a directory, we need to find the meta data file
    +		if (status.isDir()) {
    +			final Path metadataFilePath = new Path(path, METADATA_FILE_NAME);
    +			try {
    +				return fs.getFileStatus(metadataFilePath);
    +			}
    +			catch (FileNotFoundException e) {
    +				throw new FileNotFoundException("Cannot find meta data file '" + METADATA_FILE_NAME +
    +						"' in directory '" + path + "'. Please try to load the checkpoint/savepoint " +
    +						"directly from the metadata file instead of the directory.");
    +			}
    +		}
    +		else if (validateMetadataFileName && !METADATA_FILE_NAME.equals(status.getPath().getName())) {
    +			throw new IOException("The given path does not point to a checkpoint/savepoint directory or " +
    +					"metadata file (" + METADATA_FILE_NAME + ')');
    +		}
    +		else {
    +			// this points to a file and we either do no name validation, or
    +			// the name is actually correct, so we can return the path
    +			return status;
    +		}
    +	}
    +
    +	/**
    +	 * Constructs the savepoint directory path and creates the directory. This method retries several
    +	 * times when directory collisions occur and the target path cannot be created.
    +	 */
    +	private static Path initializeSavepointDirectory(FileSystem fs, Path basePath, JobID jobId) throws IOException {
    +		final String prefix;
    +		if (jobId == null) {
    +			prefix = "savepoint-";
    +		} else {
    +			prefix = "savepoint-" + jobId.toString().substring(0, 6) + '-';
    +		}
    +
    +		Exception latestException = null;
    +
    +		// Initialize the actual savepoint directory. This MUST create a new directory!
    +		for (int attempt = 0; attempt < 10; attempt++) {
    +			Path path = new Path(basePath, FileUtils.getRandomFilename(prefix));
    +
    +			try {
    +				if (fs.mkdirs(path)) {
    +					return path;
    +				}
    +			} catch (Exception e) {
    +				latestException = e;
    +			}
    +		}
    +
    +		throw new IOException("Failed to create savepoint directory at " + basePath, latestException);
    +	}
    +
    +	// ------------------------------------------------------------------------
    +	//  Utilities
    +	// ------------------------------------------------------------------------
    +
    +	// 
    +	/**
    +	 * Checks and normalizes the checkpoint data URI. This method first checks the validity of the
    +	 * URI (scheme, path, availability of a matching file system) and then normalizes the URI
    +	 * to a path.
    +	 *
    +	 * <p>If the URI does not include an authority, but the file system configured for the URI has an
    +	 * authority, then the normalized path will include this authority.
    +	 *
    +	 * @param checkpointDataUri The URI to check and normalize.
    +	 * @return A normalized URI as a Path.
    +	 *
    +	 * @throws IllegalArgumentException Thrown, if the URI misses scheme or path.
    +	 */
    +	public static Path validateAndNormalizeUri(URI checkpointDataUri) {
    +		final String scheme = checkpointDataUri.getScheme();
    +		final String path = checkpointDataUri.getPath();
    +
    +		// some validity checks
    +		if (scheme == null) {
    +			throw new IllegalArgumentException("The scheme (hdfs://, file://, etc) is null. " +
    +					"Please specify the file system scheme explicitly in the URI.");
    +		}
    +		if (path == null) {
    +			throw new IllegalArgumentException("The path to store the checkpoint data in is null. " +
    +					"Please specify a directory path for the checkpoint data.");
    +		}
    +		if (path.length() == 0 || path.equals("/")) {
    +			throw new IllegalArgumentException("Cannot use the root directory for checkpoints.");
    +		}
    +
    +		if (!FileSystem.isFlinkSupportedScheme(checkpointDataUri.getScheme())) {
    +			// skip verification checks for non-flink supported filesystem
    +			// this is because the required filesystem classes may not be available to the flink client
    +			return new Path(checkpointDataUri);
    +		}
    +		else {
    +			// we do a bit of work to make sure that the URI for the filesystem refers to exactly the same
    +			// (distributed) filesystem on all hosts and includes full host/port information, even if the
    +			// original URI did not include that. We count on the filesystem loading from the configuration
    +			// to fill in the missing data.
    +
    +			// try to grab the file system for this path/URI. this should always succeed, since we
    +			// are only in this branch if this is a flink-supported file system
    +			FileSystem filesystem;
    +			try {
    +				filesystem = FileSystem.get(checkpointDataUri);
    +			} catch (IOException e) {
    +				// should never happen
    +				throw new FlinkRuntimeException("cannot access file system for URI " + checkpointDataUri);
    --- End diff --
    
    Maybe adding `e` as cause?


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

[GitHub] flink pull request #3522: [FLINK-5823] [checkpoints] State Backends also han...

Posted by tillrohrmann <gi...@git.apache.org>.
Github user tillrohrmann commented on a diff in the pull request:

    https://github.com/apache/flink/pull/3522#discussion_r108714224
  
    --- Diff: flink-runtime/src/main/java/org/apache/flink/runtime/state/filesystem/AbstractFileStateBackend.java ---
    @@ -0,0 +1,556 @@
    +/*
    + * Licensed to the Apache Software Foundation (ASF) under one
    + * or more contributor license agreements.  See the NOTICE file
    + * distributed with this work for additional information
    + * regarding copyright ownership.  The ASF licenses this file
    + * to you under the Apache License, Version 2.0 (the
    + * "License"); you may not use this file except in compliance
    + * with the License.  You may obtain a copy of the License at
    + *
    + *     http://www.apache.org/licenses/LICENSE-2.0
    + *
    + * Unless required by applicable law or agreed to in writing, software
    + * distributed under the License is distributed on an "AS IS" BASIS,
    + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    + * See the License for the specific language governing permissions and
    + * limitations under the License.
    + */
    +
    +package org.apache.flink.runtime.state.filesystem;
    +
    +import org.apache.flink.annotation.PublicEvolving;
    +import org.apache.flink.api.common.JobID;
    +import org.apache.flink.configuration.ConfigConstants;
    +import org.apache.flink.configuration.ConfigOption;
    +import org.apache.flink.configuration.ConfigOptions;
    +import org.apache.flink.configuration.Configuration;
    +import org.apache.flink.configuration.IllegalConfigurationException;
    +import org.apache.flink.core.fs.FileStatus;
    +import org.apache.flink.core.fs.FileSystem;
    +import org.apache.flink.core.fs.Path;
    +import org.apache.flink.runtime.state.AbstractStateBackend;
    +import org.apache.flink.runtime.state.CheckpointMetadataStreamFactory;
    +import org.apache.flink.runtime.state.StateBackendGlobalHooks;
    +import org.apache.flink.runtime.state.StreamStateHandle;
    +import org.apache.flink.util.FileUtils;
    +import org.apache.flink.util.FlinkException;
    +import org.apache.flink.util.FlinkRuntimeException;
    +
    +import org.slf4j.Logger;
    +import org.slf4j.LoggerFactory;
    +
    +import javax.annotation.Nullable;
    +import java.io.FileNotFoundException;
    +import java.io.IOException;
    +import java.net.URI;
    +import java.net.URISyntaxException;
    +
    +import static org.apache.flink.util.Preconditions.checkArgument;
    +import static org.apache.flink.util.Preconditions.checkNotNull;
    +
    +/**
    + * A base class for all state backends that store their metadata (and data) in files.
    + * Examples that inherit from this are the {@link FsStateBackend}, the
    + * {@link org.apache.flink.runtime.state.memory.MemoryStateBackend MemoryStateBackend}, or the
    + * {@code RocksDBStateBackend}.
    + * 
    + * <p>This class takes the base checkpoint- and savepoint directory paths, but also accepts null
    + * for both of then, in which case creating externalized checkpoint is not possible, and it is not
    + * possible to create a savepoint with a default path. Null is accepted to enable implementations
    + * that only optionally support default savepoints and externalized checkpoints.
    + * 
    + * <h1>Checkpoint Layout</h1>
    + * 
    + * The state backend is configured with a base directory and persists the checkpoint data of specific
    + * checkpoints in specific subdirectories. For example, if the base directory was set to 
    + * {@code hdfs://namenode:port/flink-checkpoints/}, the state backend will create a subdirectory with
    + * the job's ID that will contain the actual checkpoints:
    + * ({@code hdfs://namenode:port/flink-checkpoints/1b080b6e710aabbef8993ab18c6de98b})
    + *
    + * <p>Each checkpoint individually will store all its files in a subdirectory that includes the
    + * checkpoint number, such as {@code hdfs://namenode:port/flink-checkpoints/1b080b6e710aabbef8993ab18c6de98b/chk-17/}.
    + * 
    + * <h1>Savepoint Layout</h1>
    + * 
    + * A savepoint that is set to be stored in path {@code hdfs://namenode:port/flink-savepoints/}, will create
    + * a subdirectory {@code savepoint-jobId(0, 6)-randomDigits} in which it stores all savepoint data.
    + * The random digits are added as "entropy" to avoid directory collisions.
    + */
    +@PublicEvolving
    +public abstract class AbstractFileStateBackend extends AbstractStateBackend implements StateBackendGlobalHooks {
    +
    +	private static final long serialVersionUID = 1L;
    +
    +	private static final Logger LOG = LoggerFactory.getLogger(AbstractFileStateBackend.class);
    +
    +	// ------------------------------------------------------------------------
    +	//  Configuration
    +	// ------------------------------------------------------------------------
    +
    +	/**
    +	 * The configuration parameter for the checkpoint path/directory.
    +	 */
    +	public static final ConfigOption<String> CHECKPOINT_PATH = ConfigOptions
    +			.key(ConfigConstants.CHECKPOINTS_DIRECTORY_KEY)
    +			.noDefaultValue()
    +			.withDeprecatedKeys("state.backend.fs.checkpointdir");
    +
    +	/**
    +	 * The configuration parameter for the savepoint path/directory.
    +	 */
    +	public static final ConfigOption<String> SAVEPOINT_PATH = ConfigOptions
    +			.key(ConfigConstants.SAVEPOINT_DIRECTORY_KEY)
    +			.noDefaultValue()
    +			.withDeprecatedKeys("state.backend.fs.savepointdir");
    +
    +	// ------------------------------------------------------------------------
    +	//  Constants
    +	// ------------------------------------------------------------------------
    +
    +	/** The name of the metadata files in checkpoints / savepoints. */
    +	public static final String METADATA_FILE_NAME = "_metadata";
    +
    +	/** The prefix of the checkpoint directory names */
    +	public static final String CHECKPOINT_DIR_PREFIX = "chk-";
    +
    +	// ------------------------------------------------------------------------
    +	//  State Backend Properties
    +	// ------------------------------------------------------------------------
    +
    +	/** The path where checkpoints will be stored, or null, if none has been configured */
    +	@Nullable
    +	private final Path baseCheckpointPath;
    +
    +	/** The path where savepoints will be stored, or null, if none has been configured */
    +	@Nullable
    +	private final Path baseSavepointPath;
    +
    +	/**
    +	 * Creates a backend with the given optional checkpoint- and savepoint base directories.
    +	 * 
    +	 * @param baseCheckpointPath The base directory for checkpoints, or null, if none is configured.
    +	 * @param baseSavepointPath The default directory for savepoints, or null, if none is set.
    +	 */
    +	protected AbstractFileStateBackend(
    +			@Nullable Path baseCheckpointPath,
    +			@Nullable Path baseSavepointPath) {
    +
    +		this(baseCheckpointPath == null ? null : baseCheckpointPath.toUri(),
    +				baseSavepointPath == null ? null : baseSavepointPath.toUri());
    +	}
    +
    +	/**
    +	 * Creates a backend with the given optional checkpoint- and savepoint base directories.
    +	 * 
    +	 * @param baseCheckpointPath The base directory for checkpoints, or null, if none is configured.
    +	 * @param baseSavepointPath The default directory for savepoints, or null, if none is set.
    +	 */
    +	protected AbstractFileStateBackend(
    +			@Nullable URI baseCheckpointPath,
    +			@Nullable URI baseSavepointPath) {
    +
    +		this.baseCheckpointPath = baseCheckpointPath == null ? null : validateAndNormalizeUri(baseCheckpointPath);
    +		this.baseSavepointPath = baseSavepointPath == null ? null : validateAndNormalizeUri(baseSavepointPath);
    +	}
    +
    +	/**
    +	 * Creates a new backend using the given checkpoint-/savepoint directories, or the values defined in
    +	 * the given configuration. If a checkpoint-/savepoint parameter is not null, that value takes precedence
    +	 * over the value in the configuration. If the configuration does not specify a value, it is possible
    +	 * that the checkpoint-/savepoint directories in the backend will be null.
    +	 * 
    +	 * <p>This constructor can be used to create a backend that is based partially on a given backend
    +	 * and partially on a configuration.
    +	 * 
    +	 * @param baseCheckpointPath The checkpoint base directory to use (or null).
    +	 * @param baseSavepointPath The default savepoint directory to use (or null).
    +	 * @param configuration The configuration to read values from 
    +	 */
    +	protected AbstractFileStateBackend(
    +			@Nullable Path baseCheckpointPath,
    +			@Nullable Path baseSavepointPath,
    +			Configuration configuration) {
    +
    +		this(parameterOrConfigured(baseCheckpointPath, configuration, CHECKPOINT_PATH),
    +				parameterOrConfigured(baseSavepointPath, configuration, SAVEPOINT_PATH));
    +	}
    +
    +	// ------------------------------------------------------------------------
    +
    +	/**
    +	 * Gets the checkpoint base directory. Jobs will create job-specific subdirectories
    +	 * for checkpoints within this directory. May be null, if not configured.
    +	 * 
    +	 * @return The checkpoint base directory
    +	 */
    +	@Nullable
    +	public Path getCheckpointPath() {
    +		return baseCheckpointPath;
    +	}
    +
    +	/**
    +	 * Gets the directory where savepoints are stored by default (when no custom path is given
    +	 * to the savepoint trigger command).
    +	 *
    +	 * @return The default directory for savepoints, or null, if no default directory has been configured.
    +	 */
    +	@Nullable
    +	public Path getSavepointPath() {
    +		return baseSavepointPath;
    +	}
    +
    +	// ------------------------------------------------------------------------
    +	//  Metadata Persistence
    +	// ------------------------------------------------------------------------
    +
    +	/**
    +	 * Checks whether this backend supports externalized checkpoints, which is the case when
    +	 * a checkpoint base directory is configured.
    +	 */
    +	@Override
    +	public boolean supportsExternalizedMetadata() {
    +		return baseCheckpointPath != null;
    +	}
    +
    +	@Nullable
    +	@Override
    +	public String getMetadataPersistenceLocation() {
    +		return baseCheckpointPath == null ? null : baseCheckpointPath.toString();
    +	}
    +
    +	@Override
    +	public StreamStateHandle resolveCheckpointLocation(String checkpointPath) throws IOException {
    +		checkNotNull(checkpointPath, "checkpointPath");
    +		checkArgument(!checkpointPath.isEmpty(), "empty checkpoint path");
    +
    +		// we resolve without strictly validating the metadata file, to resume from cases
    +		// where a differently named metadata file was written (as in prior Flink version)
    +		final FileStatus metadataFileStatus = resolveCheckpointPointer(checkpointPath, false);
    +		return new FileStateHandle(metadataFileStatus.getPath(), metadataFileStatus.getLen());
    +	}
    +
    +	@Override
    +	public CheckpointMetadataStreamFactory createCheckpointMetadataStreamFactory(
    +			JobID jobID,
    +			long checkpointId) throws IOException {
    +
    +		checkNotNull(jobID, "jobID");
    +
    +		final Path checkpointBaseDir = getCheckpointDirectoryForJob(jobID);
    +		final Path checkpointDir = createSpecificCheckpointPath(checkpointBaseDir, checkpointId);
    +		final Path metadataFilePath = new Path(checkpointDir, METADATA_FILE_NAME);
    +
    +		return new FsCheckpointMetadataStreamFactory(checkpointDir.getFileSystem(), checkpointDir, metadataFilePath);
    +	}
    +
    +	@Override
    +	public CheckpointMetadataStreamFactory createSavepointMetadataStreamFactory(
    +			JobID jobID,
    +			@Nullable String targetLocation) throws IOException {
    +
    +		// the directory inside which we create the savepoint
    +		final Path basePath;
    +
    +		if (targetLocation != null) {
    +			try {
    +				basePath = new Path(targetLocation);
    +			}
    +			catch (IllegalArgumentException e) {
    +				throw new IOException("Cannot initialize savepoint to '" + targetLocation + 
    +						"' because it is not a valid file path.");
    +			}
    +		}
    +		else if (baseSavepointPath != null) {
    +			basePath = baseSavepointPath;
    +		}
    +		else {
    +			throw new UnsupportedOperationException(
    +					"Cannot perform a savepoint without a target location when no default savepoint directory " +
    +							"has been configured via '" + SAVEPOINT_PATH.key() + "'.");
    +		}
    +
    +		final FileSystem fs = basePath.getFileSystem();
    +		final Path savepointDir = initializeSavepointDirectory(fs, basePath, jobID);
    +		final Path metadataFilePath = new Path(savepointDir, METADATA_FILE_NAME);
    +
    +		return new FsCheckpointMetadataStreamFactory(fs, savepointDir, metadataFilePath);
    +	}
    +
    +	// ------------------------------------------------------------------------
    +	//  Global Hooks
    +	// ------------------------------------------------------------------------
    +
    +	@Override
    +	public void disposeSavepoint(String pointer) throws IOException {
    +		checkNotNull(pointer, "pointer");
    +
    +		// to be save, we make sure we call this to verify that the metadata file exists
    +		// in the pointed directory, or that this points to the metadata file directly
    +		final FileStatus metadataFileStatus = resolveCheckpointPointer(pointer, true);
    +
    +		final Path savepointDir = metadataFileStatus.getPath().getParent();
    +		final FileSystem fs = savepointDir.getFileSystem();
    +		fs.delete(savepointDir, true);
    +	}
    +
    +	// ------------------------------------------------------------------------
    +	//  Paths
    +	// ------------------------------------------------------------------------
    +
    +	/**
    +	 * Builds directory into which a specific job checkpoints, meaning the directory inside which
    +	 * it creates the checkpoint-specific subdirectories.
    +	 *
    +	 * <p>This method only succeeds if a base checkpoint directory has been set; otherwise
    +	 * the method fails with an exception.
    +	 *
    +	 * @param jobId The ID of the job
    +	 * @return The job's checkpoint directory, re
    +	 *
    +	 * @throws UnsupportedOperationException Thrown, if no base checkpoint directory has been set.
    +	 */
    +	protected Path getCheckpointDirectoryForJob(JobID jobId) {
    +		if (baseCheckpointPath != null) {
    +			return new Path(baseCheckpointPath, jobId.toString());
    +		}
    +		else {
    +			throw new UnsupportedOperationException(
    +					"Cannot write checkpoint data when no checkpoint directory has been configured via '" +
    +							CHECKPOINT_PATH.key() + "'.");
    +		}
    +	}
    +
    +	/**
    +	 * Creates the directory path for a specific checkpoint of a job.
    +	 *
    +	 * @param jobCheckpointDir The directory into which the job checkpoints
    +	 * @param checkpointId The ID (logical timestamp) of the checkpoint
    +	 *
    +	 * @return The checkpoint directory path.
    +	 */
    +	protected static Path createSpecificCheckpointPath(Path jobCheckpointDir, long checkpointId) {
    +		return new Path(jobCheckpointDir, CHECKPOINT_DIR_PREFIX + checkpointId);
    +	}
    +
    +	/**
    +	 * 
    +	 * <p>Important - if the pointer points directly to a file, this does not valicate t
    +	 * 
    +	 * @param checkpointPointer The pointer to resolve
    +	 * @return The file status of the checkpoint/savepoint's metadata file.
    +	 * 
    +	 * @throws IOException Thrown, if the pointer cannot be resolved, the file system not accessed, or
    +	 *                     the pointer points to a location that does not seem to be a checkpoint/savepoint.
    +	 */
    +	protected static FileStatus resolveCheckpointPointer(
    +			String checkpointPointer,
    +			boolean validateMetadataFileName) throws IOException {
    +
    +		// check if the pointer is in fact a valid file path
    +		final Path path;
    +		try {
    +			path = new Path(checkpointPointer);
    +		}
    +		catch (Exception e) {
    +			throw new IOException("Checkpoint/savepoint path '" + checkpointPointer + "' is not a valid file URI");
    +		}
    +
    +		// check if the file system can be accessed
    +		final FileSystem fs;
    +		try {
    +			fs = path.getFileSystem();
    +		}
    +		catch (IOException e) {
    +			throw new IOException("Cannot access file system for checkpoint/savepoint path '" + 
    +					checkpointPointer + "'.");
    --- End diff --
    
    Maybe we could add `e` as the cause.


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

[GitHub] flink issue #3522: [FLINK-5823] [checkpoints] State Backends also handle Che...

Posted by StefanRRichter <gi...@git.apache.org>.
Github user StefanRRichter commented on the issue:

    https://github.com/apache/flink/pull/3522
  
    I agree that we can change the Strings to some proper types later. Besides what I mentioned before, I just thought that even if a string is the underlying data type for the moment, having it wrapped in a named `Pointer` class to make code more readable and "typesafe".


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

[GitHub] flink pull request #3522: [FLINK-5823] [checkpoints] State Backends also han...

Posted by StefanRRichter <gi...@git.apache.org>.
Github user StefanRRichter commented on a diff in the pull request:

    https://github.com/apache/flink/pull/3522#discussion_r113682062
  
    --- Diff: flink-runtime/src/main/java/org/apache/flink/runtime/state/filesystem/FsCheckpointMetadataOutputStream.java ---
    @@ -0,0 +1,152 @@
    +/*
    + * Licensed to the Apache Software Foundation (ASF) under one
    + * or more contributor license agreements.  See the NOTICE file
    + * distributed with this work for additional information
    + * regarding copyright ownership.  The ASF licenses this file
    + * to you under the Apache License, Version 2.0 (the
    + * "License"); you may not use this file except in compliance
    + * with the License.  You may obtain a copy of the License at
    + *
    + *     http://www.apache.org/licenses/LICENSE-2.0
    + *
    + * Unless required by applicable law or agreed to in writing, software
    + * distributed under the License is distributed on an "AS IS" BASIS,
    + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    + * See the License for the specific language governing permissions and
    + * limitations under the License.
    + */
    +
    +package org.apache.flink.runtime.state.filesystem;
    +
    +import org.apache.flink.core.fs.FSDataOutputStream;
    +import org.apache.flink.core.fs.FileSystem;
    +import org.apache.flink.core.fs.FileSystem.WriteMode;
    +import org.apache.flink.core.fs.Path;
    +import org.apache.flink.runtime.state.CheckpointMetadataStreamFactory.CheckpointMetadataOutputStream;
    +import org.apache.flink.runtime.state.CheckpointMetadataStreamFactory.StreamHandleAndPointer;
    +import org.apache.flink.runtime.state.StreamStateHandle;
    +
    +import org.slf4j.Logger;
    +import org.slf4j.LoggerFactory;
    +
    +import java.io.IOException;
    +
    +import static org.apache.flink.util.Preconditions.checkNotNull;
    +
    +/**
    + * A {@link CheckpointMetadataOutputStream} that writes into a file and
    + * returns a {@link StreamStateHandle} upon closing.
    --- End diff --
    
    I think the comment here is outdated and should link to `StreamHandleAndPointer`.


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

[GitHub] flink pull request #3522: [FLINK-5823] [checkpoints] State Backends also han...

Posted by tillrohrmann <gi...@git.apache.org>.
Github user tillrohrmann commented on a diff in the pull request:

    https://github.com/apache/flink/pull/3522#discussion_r108469956
  
    --- Diff: flink-runtime/src/main/java/org/apache/flink/runtime/state/CheckpointMetadataStreamFactory.java ---
    @@ -0,0 +1,101 @@
    +/*
    + * Licensed to the Apache Software Foundation (ASF) under one
    + * or more contributor license agreements.  See the NOTICE file
    + * distributed with this work for additional information
    + * regarding copyright ownership.  The ASF licenses this file
    + * to you under the Apache License, Version 2.0 (the
    + * "License"); you may not use this file except in compliance
    + * with the License.  You may obtain a copy of the License at
    + *
    + *     http://www.apache.org/licenses/LICENSE-2.0
    + *
    + * Unless required by applicable law or agreed to in writing, software
    + * distributed under the License is distributed on an "AS IS" BASIS,
    + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    + * See the License for the specific language governing permissions and
    + * limitations under the License.
    + */
    +
    +package org.apache.flink.runtime.state;
    +
    +import org.apache.flink.core.fs.FSDataOutputStream;
    +
    +import java.io.IOException;
    +
    +import static org.apache.flink.util.Preconditions.checkNotNull;
    +
    +/**
    + * The {@link CheckpointMetadataStreamFactory} creates streams to write checkpoint <i>metadata</i>,
    + * similar as the {@link CheckpointStreamFactory} creates streams to write checkpoint <i>data</i>.
    + */
    +public interface CheckpointMetadataStreamFactory {
    +
    +	/**
    +	 * Creates a stream to write the metadata for the particular checkpoint that this factory
    +	 * belongs to.
    +	 * 
    +	 * @return The metadata output stream for this factory's checkpoint.
    +	 * @throws IOException Thrown, if the stream could not be opened.
    +	 */
    +	CheckpointMetadataOutputStream createCheckpointStateOutputStream() throws IOException;
    +
    +	/**
    +	 * Gets the location (as a string pointer) where the metadata factory 
    --- End diff --
    
    Sentence does not seem to be complete


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

[GitHub] flink pull request #3522: [FLINK-5823] [checkpoints] State Backends also han...

Posted by StefanRRichter <gi...@git.apache.org>.
Github user StefanRRichter commented on a diff in the pull request:

    https://github.com/apache/flink/pull/3522#discussion_r113657592
  
    --- Diff: flink-contrib/flink-statebackend-rocksdb/src/main/java/org/apache/flink/contrib/streaming/state/RocksDBStateBackend.java ---
    @@ -222,11 +227,40 @@ public CheckpointStreamFactory createStreamFactory(JobID jobId,
     
     	@Override
     	public CheckpointStreamFactory createSavepointStreamFactory(
    -			JobID jobId,
     			String operatorIdentifier,
     			String targetLocation) throws IOException {
     
    -		return checkpointStreamBackend.createSavepointStreamFactory(jobId, operatorIdentifier, targetLocation);
    +		return checkpointStreamBackend.createSavepointStreamFactory(operatorIdentifier, targetLocation);
    +	}
    +
    +	@Override
    +	public boolean supportsExternalizedMetadata() {
    +		return checkpointStreamBackend.supportsExternalizedMetadata();
    +	}
    +
    +	@Nullable
    +	@Override
    +	public String getMetadataPersistenceLocation() {
    +		return checkpointStreamBackend.getMetadataPersistenceLocation();
    +	}
    +
    +	@Override
    +	public CheckpointMetadataStreamFactory createCheckpointMetadataStreamFactory(
    +			JobID jobID,
    +			long checkpointId) throws IOException {
    +		return checkpointStreamBackend.createCheckpointMetadataStreamFactory(jobID, checkpointId);
    +	}
    +
    +	@Override
    +	public CheckpointMetadataStreamFactory createSavepointMetadataStreamFactory(
    +			JobID jobID,
    +			@Nullable String targetLocation) throws IOException {
    +		return checkpointStreamBackend.createSavepointMetadataStreamFactory(jobID, targetLocation);
    +	}
    +
    +	@Override
    +	public StreamStateHandle resolveCheckpointLocation(String pointer) throws IOException {
    --- End diff --
    
    I would suggest to introduce an actual class for the concept of pointers to improve type safety and readability. Through subclasses, it can also be easier to reason about what kinds of pointer a backend accepts or rejects, compared to think about how a string was parsed and failed.


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

[GitHub] flink pull request #3522: [FLINK-5823] [checkpoints] State Backends also han...

Posted by StefanRRichter <gi...@git.apache.org>.
Github user StefanRRichter commented on a diff in the pull request:

    https://github.com/apache/flink/pull/3522#discussion_r113662147
  
    --- Diff: flink-runtime/src/main/java/org/apache/flink/runtime/checkpoint/CompletedCheckpoint.java ---
    @@ -213,6 +218,23 @@ public boolean discard(JobStatus jobStatus) throws Exception {
     
     	void discard() throws Exception {
     		try {
    +			// check if we have a shortcut hook to dispose the state
    +			final StateDisposeHook disposeHook = this.disposeHook;
    +			if (disposeHook != null) {
    +				// fast path!
    --- End diff --
    
    On a second look, do you think it could even make sense to have the previous behaviour also encapsulated as a cleanup hook and get rid of the if completely?


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

[GitHub] flink pull request #3522: [FLINK-5823] [checkpoints] State Backends also han...

Posted by StefanRRichter <gi...@git.apache.org>.
Github user StefanRRichter commented on a diff in the pull request:

    https://github.com/apache/flink/pull/3522#discussion_r113657881
  
    --- Diff: flink-contrib/flink-statebackend-rocksdb/src/main/java/org/apache/flink/contrib/streaming/state/RocksDBStateBackend.java ---
    @@ -222,11 +227,40 @@ public CheckpointStreamFactory createStreamFactory(JobID jobId,
     
     	@Override
     	public CheckpointStreamFactory createSavepointStreamFactory(
    -			JobID jobId,
     			String operatorIdentifier,
     			String targetLocation) throws IOException {
     
    -		return checkpointStreamBackend.createSavepointStreamFactory(jobId, operatorIdentifier, targetLocation);
    +		return checkpointStreamBackend.createSavepointStreamFactory(operatorIdentifier, targetLocation);
    +	}
    +
    +	@Override
    +	public boolean supportsExternalizedMetadata() {
    +		return checkpointStreamBackend.supportsExternalizedMetadata();
    +	}
    +
    +	@Nullable
    +	@Override
    +	public String getMetadataPersistenceLocation() {
    --- End diff --
    
    The  meta data location might be a concept that justifies introducing a class. In particular, it seems that there might be different location concepts in the future, so simply encoding all this in a string is questionable.


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

[GitHub] flink pull request #3522: [FLINK-5823] [checkpoints] State Backends also han...

Posted by tillrohrmann <gi...@git.apache.org>.
Github user tillrohrmann commented on a diff in the pull request:

    https://github.com/apache/flink/pull/3522#discussion_r108718168
  
    --- Diff: flink-runtime/src/main/java/org/apache/flink/runtime/state/filesystem/FsCheckpointStateOutputStream.java ---
    @@ -0,0 +1,285 @@
    +/*
    + * Licensed to the Apache Software Foundation (ASF) under one
    + * or more contributor license agreements.  See the NOTICE file
    + * distributed with this work for additional information
    + * regarding copyright ownership.  The ASF licenses this file
    + * to you under the Apache License, Version 2.0 (the
    + * "License"); you may not use this file except in compliance
    + * with the License.  You may obtain a copy of the License at
    + *
    + *     http://www.apache.org/licenses/LICENSE-2.0
    + *
    + * Unless required by applicable law or agreed to in writing, software
    + * distributed under the License is distributed on an "AS IS" BASIS,
    + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    + * See the License for the specific language governing permissions and
    + * limitations under the License.
    + */
    +
    +package org.apache.flink.runtime.state.filesystem;
    +
    +import org.apache.flink.core.fs.FSDataOutputStream;
    +import org.apache.flink.core.fs.FileSystem;
    +import org.apache.flink.core.fs.FileSystem.WriteMode;
    +import org.apache.flink.core.fs.Path;
    +import org.apache.flink.runtime.state.CheckpointStreamFactory;
    +import org.apache.flink.runtime.state.StreamStateHandle;
    +import org.apache.flink.runtime.state.memory.ByteStreamStateHandle;
    +import org.apache.flink.util.FileUtils;
    +
    +import org.slf4j.Logger;
    +import org.slf4j.LoggerFactory;
    +
    +import java.io.IOException;
    +import java.util.Arrays;
    +import java.util.UUID;
    +
    +/**
    + * A {@link CheckpointStreamFactory.CheckpointStateOutputStream} that writes into a file and
    + * returns a {@link StreamStateHandle} for the written data upon closing.
    + * 
    + * <p>This stream prevents the creation of very small files with sizes below a configurable
    + * threshold. If the written data is below that threshold, the returned handle is a
    + * {@link ByteStreamStateHandle} that directly contains the data. If the written data size is above
    + * the threshold, the data is written to a file and the returned handle is a {@link FileStateHandle}.
    + *
    + * <p>Note: Flushing the stream always creates the file. 
    + */
    +public final class FsCheckpointStateOutputStream extends CheckpointStreamFactory.CheckpointStateOutputStream {
    +
    +	private static final Logger LOG = LoggerFactory.getLogger(FsCheckpointStateOutputStream.class);
    +
    +	// ------------------------------------------------------------------------
    +
    +	private final byte[] writeBuffer;
    +
    +	private int pos;
    +
    +	private FSDataOutputStream outStream;
    +
    +	private final int localStateThreshold;
    +
    +	private final Path basePath;
    +
    +	private final FileSystem fs;
    +
    +	private Path statePath;
    +
    +	private volatile boolean closed;
    +
    +	public FsCheckpointStateOutputStream(
    +				Path basePath, FileSystem fs,
    +				int bufferSize, int localStateThreshold)
    +	{
    +		if (bufferSize < localStateThreshold) {
    +			throw new IllegalArgumentException();
    +		}
    +
    +		this.basePath = basePath;
    +		this.fs = fs;
    --- End diff --
    
    `checkNotNull` checks could be inserted here.


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

[GitHub] flink pull request #3522: [FLINK-5823] [checkpoints] State Backends also han...

Posted by tillrohrmann <gi...@git.apache.org>.
Github user tillrohrmann commented on a diff in the pull request:

    https://github.com/apache/flink/pull/3522#discussion_r108477718
  
    --- Diff: flink-runtime/src/main/java/org/apache/flink/runtime/state/filesystem/AbstractFileStateBackend.java ---
    @@ -0,0 +1,556 @@
    +/*
    + * Licensed to the Apache Software Foundation (ASF) under one
    + * or more contributor license agreements.  See the NOTICE file
    + * distributed with this work for additional information
    + * regarding copyright ownership.  The ASF licenses this file
    + * to you under the Apache License, Version 2.0 (the
    + * "License"); you may not use this file except in compliance
    + * with the License.  You may obtain a copy of the License at
    + *
    + *     http://www.apache.org/licenses/LICENSE-2.0
    + *
    + * Unless required by applicable law or agreed to in writing, software
    + * distributed under the License is distributed on an "AS IS" BASIS,
    + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    + * See the License for the specific language governing permissions and
    + * limitations under the License.
    + */
    +
    +package org.apache.flink.runtime.state.filesystem;
    +
    +import org.apache.flink.annotation.PublicEvolving;
    +import org.apache.flink.api.common.JobID;
    +import org.apache.flink.configuration.ConfigConstants;
    +import org.apache.flink.configuration.ConfigOption;
    +import org.apache.flink.configuration.ConfigOptions;
    +import org.apache.flink.configuration.Configuration;
    +import org.apache.flink.configuration.IllegalConfigurationException;
    +import org.apache.flink.core.fs.FileStatus;
    +import org.apache.flink.core.fs.FileSystem;
    +import org.apache.flink.core.fs.Path;
    +import org.apache.flink.runtime.state.AbstractStateBackend;
    +import org.apache.flink.runtime.state.CheckpointMetadataStreamFactory;
    +import org.apache.flink.runtime.state.StateBackendGlobalHooks;
    +import org.apache.flink.runtime.state.StreamStateHandle;
    +import org.apache.flink.util.FileUtils;
    +import org.apache.flink.util.FlinkException;
    +import org.apache.flink.util.FlinkRuntimeException;
    +
    +import org.slf4j.Logger;
    +import org.slf4j.LoggerFactory;
    +
    +import javax.annotation.Nullable;
    +import java.io.FileNotFoundException;
    +import java.io.IOException;
    +import java.net.URI;
    +import java.net.URISyntaxException;
    +
    +import static org.apache.flink.util.Preconditions.checkArgument;
    +import static org.apache.flink.util.Preconditions.checkNotNull;
    +
    +/**
    + * A base class for all state backends that store their metadata (and data) in files.
    + * Examples that inherit from this are the {@link FsStateBackend}, the
    + * {@link org.apache.flink.runtime.state.memory.MemoryStateBackend MemoryStateBackend}, or the
    + * {@code RocksDBStateBackend}.
    + * 
    + * <p>This class takes the base checkpoint- and savepoint directory paths, but also accepts null
    + * for both of then, in which case creating externalized checkpoint is not possible, and it is not
    + * possible to create a savepoint with a default path. Null is accepted to enable implementations
    + * that only optionally support default savepoints and externalized checkpoints.
    + * 
    + * <h1>Checkpoint Layout</h1>
    + * 
    + * The state backend is configured with a base directory and persists the checkpoint data of specific
    + * checkpoints in specific subdirectories. For example, if the base directory was set to 
    + * {@code hdfs://namenode:port/flink-checkpoints/}, the state backend will create a subdirectory with
    + * the job's ID that will contain the actual checkpoints:
    + * ({@code hdfs://namenode:port/flink-checkpoints/1b080b6e710aabbef8993ab18c6de98b})
    + *
    + * <p>Each checkpoint individually will store all its files in a subdirectory that includes the
    + * checkpoint number, such as {@code hdfs://namenode:port/flink-checkpoints/1b080b6e710aabbef8993ab18c6de98b/chk-17/}.
    + * 
    + * <h1>Savepoint Layout</h1>
    + * 
    + * A savepoint that is set to be stored in path {@code hdfs://namenode:port/flink-savepoints/}, will create
    + * a subdirectory {@code savepoint-jobId(0, 6)-randomDigits} in which it stores all savepoint data.
    + * The random digits are added as "entropy" to avoid directory collisions.
    + */
    +@PublicEvolving
    +public abstract class AbstractFileStateBackend extends AbstractStateBackend implements StateBackendGlobalHooks {
    +
    +	private static final long serialVersionUID = 1L;
    +
    +	private static final Logger LOG = LoggerFactory.getLogger(AbstractFileStateBackend.class);
    +
    +	// ------------------------------------------------------------------------
    +	//  Configuration
    +	// ------------------------------------------------------------------------
    +
    +	/**
    +	 * The configuration parameter for the checkpoint path/directory.
    +	 */
    +	public static final ConfigOption<String> CHECKPOINT_PATH = ConfigOptions
    +			.key(ConfigConstants.CHECKPOINTS_DIRECTORY_KEY)
    +			.noDefaultValue()
    +			.withDeprecatedKeys("state.backend.fs.checkpointdir");
    +
    +	/**
    +	 * The configuration parameter for the savepoint path/directory.
    +	 */
    +	public static final ConfigOption<String> SAVEPOINT_PATH = ConfigOptions
    +			.key(ConfigConstants.SAVEPOINT_DIRECTORY_KEY)
    +			.noDefaultValue()
    +			.withDeprecatedKeys("state.backend.fs.savepointdir");
    --- End diff --
    
    Shall we move these `ConfigOptions` to a dedicated `StateOptions` class which is put under `org.apache.flink.configuration`? I think most of the options live there, currently.


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

[GitHub] flink pull request #3522: [FLINK-5823] [checkpoints] State Backends also han...

Posted by StephanEwen <gi...@git.apache.org>.
Github user StephanEwen closed the pull request at:

    https://github.com/apache/flink/pull/3522


---

[GitHub] flink pull request #3522: [FLINK-5823] [checkpoints] State Backends also han...

Posted by StefanRRichter <gi...@git.apache.org>.
Github user StefanRRichter commented on a diff in the pull request:

    https://github.com/apache/flink/pull/3522#discussion_r113686064
  
    --- Diff: flink-runtime/src/main/java/org/apache/flink/runtime/state/CheckpointMetadataStreamFactory.java ---
    @@ -0,0 +1,101 @@
    +/*
    + * Licensed to the Apache Software Foundation (ASF) under one
    + * or more contributor license agreements.  See the NOTICE file
    + * distributed with this work for additional information
    + * regarding copyright ownership.  The ASF licenses this file
    + * to you under the Apache License, Version 2.0 (the
    + * "License"); you may not use this file except in compliance
    + * with the License.  You may obtain a copy of the License at
    + *
    + *     http://www.apache.org/licenses/LICENSE-2.0
    + *
    + * Unless required by applicable law or agreed to in writing, software
    + * distributed under the License is distributed on an "AS IS" BASIS,
    + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    + * See the License for the specific language governing permissions and
    + * limitations under the License.
    + */
    +
    +package org.apache.flink.runtime.state;
    +
    +import org.apache.flink.core.fs.FSDataOutputStream;
    +
    +import java.io.IOException;
    +
    +import static org.apache.flink.util.Preconditions.checkNotNull;
    +
    +/**
    + * The {@link CheckpointMetadataStreamFactory} creates streams to write checkpoint <i>metadata</i>,
    + * similar as the {@link CheckpointStreamFactory} creates streams to write checkpoint <i>data</i>.
    + */
    +public interface CheckpointMetadataStreamFactory {
    +
    +	/**
    +	 * Creates a stream to write the metadata for the particular checkpoint that this factory
    +	 * belongs to.
    +	 * 
    +	 * @return The metadata output stream for this factory's checkpoint.
    +	 * @throws IOException Thrown, if the stream could not be opened.
    +	 */
    +	CheckpointMetadataOutputStream createCheckpointStateOutputStream() throws IOException;
    +
    +	/**
    +	 * Gets the location (as a string pointer) where the metadata factory 
    +	 * The interpretation of the pointer is up to the implementation of the state backend.
    +	 * 
    +	 * <p>In case of high-availability setups, the target location pointer is stored
    +	 * in the "ground-truth" store for checkpoint recovery.
    +	 * 
    +	 * @return The checkpoint location pointer.
    +	 */
    +	String getTargetLocation();
    +
    +	// ------------------------------------------------------------------------
    +
    +	/**
    +	 * A dedicated output stream for persisting checkpoint metadata. Upon completion, this returns
    +	 * the state handle to the persisted metadata, plus the external pointer that can be used
    +	 * to restore from that checkpoint.
    +	 */
    +	abstract class CheckpointMetadataOutputStream extends FSDataOutputStream {
    +
    +		/**
    +		 * Closes the metadata stream and gets the external pointer to the checkpoint and a
    +		 * handle that can create an input stream producing the data written to this stream.
    +		 *
    +		 * @return The pointer and state handle with access to the written metadata.
    +		 * @throws IOException Thrown, if the stream cannot be closed.
    +		 */
    +		public abstract StreamHandleAndPointer closeAndGetPointerHandle() throws IOException;
    +	}
    +
    +	// ------------------------------------------------------------------------
    +
    +	/**
    +	 * A combination of a {@code StreamStateHandle} and an external pointer (in the form of a String).
    +	 */
    +	final class StreamHandleAndPointer {
    --- End diff --
    
    Not entirely sure why we need this "AndPointer" part. The pointer in the end is a string and the interpretation of the string is generic and up to the backend that is confronted with it. So right now, the string is always a path, which is already contained in the plain `StreamStateHandle` that happens to be a `FileStateHandle` for the current backends. So similar to expecting a certain string format, the backend could as well expect certain subclasses of `StreamStateHandle`, like `FileStateHandle` and resolve the "pointer" from there. Or maybe I am missing something fundamental here?


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

[GitHub] flink issue #3522: [FLINK-5823] [checkpoints] State Backends also handle Che...

Posted by StephanEwen <gi...@git.apache.org>.
Github user StephanEwen commented on the issue:

    https://github.com/apache/flink/pull/3522
  
    Here is a summary of why I picked a String initially for the metadata persistence location:
    
    > The idea of the pointer is to have a state-backend independent string that indicates a checkpoint location. I picked a string, because the location is ultimately passed as a string, either from the user command flink run -s <savepoint path> or from ZooKeeper' "last completed checkpoint" entry.
    > 
    > Introducing the StreamHandleAndPointer here spares the code from having to reason about state backend specific file handles. We can change that at some point, but for the breadth of changes already in this PR, this helped reduce the scope a bit.


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

[GitHub] flink pull request #3522: [FLINK-5823] [checkpoints] State Backends also han...

Posted by tillrohrmann <gi...@git.apache.org>.
Github user tillrohrmann commented on a diff in the pull request:

    https://github.com/apache/flink/pull/3522#discussion_r108471375
  
    --- Diff: flink-runtime/src/main/java/org/apache/flink/runtime/state/StateBackend.java ---
    @@ -84,41 +84,117 @@
     public interface StateBackend extends java.io.Serializable {
     
     	// ------------------------------------------------------------------------
    -	//  Persistent Bytes Storage
    +	//  Persistent Bytes Storage for Checkpoint Data 
     	// ------------------------------------------------------------------------
     
     	/**
    -	 * Creates a {@link CheckpointStreamFactory} that can be used to create streams
    -	 * that should end up in a checkpoint.
    +	 * Creates a CheckpointStreamFactory that can produces streams to persist data as part of a checkpoint.
    --- End diff --
    
    typo: produce


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

[GitHub] flink pull request #3522: [FLINK-5823] [checkpoints] State Backends also han...

Posted by StefanRRichter <gi...@git.apache.org>.
Github user StefanRRichter commented on a diff in the pull request:

    https://github.com/apache/flink/pull/3522#discussion_r113661393
  
    --- Diff: flink-runtime/src/main/java/org/apache/flink/runtime/checkpoint/CompletedCheckpoint.java ---
    @@ -213,6 +218,23 @@ public boolean discard(JobStatus jobStatus) throws Exception {
     
     	void discard() throws Exception {
     		try {
    +			// check if we have a shortcut hook to dispose the state
    +			final StateDisposeHook disposeHook = this.disposeHook;
    +			if (disposeHook != null) {
    +				// fast path!
    --- End diff --
    
    This method is now a bit more lengthy than it could be; i would suggest to factor out the two paths (fast and standard) in 2 private methods.


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

[GitHub] flink pull request #3522: [FLINK-5823] [checkpoints] State Backends also han...

Posted by StephanEwen <gi...@git.apache.org>.
Github user StephanEwen commented on a diff in the pull request:

    https://github.com/apache/flink/pull/3522#discussion_r115140665
  
    --- Diff: flink-runtime/src/main/java/org/apache/flink/runtime/checkpoint/CompletedCheckpoint.java ---
    @@ -213,6 +218,23 @@ public boolean discard(JobStatus jobStatus) throws Exception {
     
     	void discard() throws Exception {
     		try {
    +			// check if we have a shortcut hook to dispose the state
    +			final StateDisposeHook disposeHook = this.disposeHook;
    +			if (disposeHook != null) {
    +				// fast path!
    --- End diff --
    
    Agree, that should be the case in the long run.


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

[GitHub] flink pull request #3522: [FLINK-5823] [checkpoints] State Backends also han...

Posted by tillrohrmann <gi...@git.apache.org>.
Github user tillrohrmann commented on a diff in the pull request:

    https://github.com/apache/flink/pull/3522#discussion_r108451291
  
    --- Diff: flink-runtime/src/main/java/org/apache/flink/runtime/checkpoint/CheckpointCoordinator.java ---
    @@ -758,17 +769,36 @@ else if (checkpoint != null) {
     	 * @throws CheckpointException if the completion failed
     	 */
     	private void completePendingCheckpoint(PendingCheckpoint pendingCheckpoint) throws CheckpointException {
    +		assert Thread.holdsLock(lock);
    +
     		final long checkpointId = pendingCheckpoint.getCheckpointId();
    -		CompletedCheckpoint completedCheckpoint = null;
     
    +		final boolean externalize =
    +				completedCheckpointStore.requiresExternalizedCheckpoints() ||
    +				pendingCheckpoint.getProps().externalizeCheckpoint() ||
    +				pendingCheckpoint.getProps().isSavepoint();
    +
    +		CompletedCheckpoint completedCheckpoint = null;
     		try {
     			// externalize the checkpoint if required
    -			if (pendingCheckpoint.getProps().externalizeCheckpoint()) {
    +			if (externalize) {
     				completedCheckpoint = pendingCheckpoint.finalizeCheckpointExternalized();
     			} else {
     				completedCheckpoint = pendingCheckpoint.finalizeCheckpointNonExternalized();
     			}
     
    +			try {
    +				if (globalStateHooks != null) {
    +					completedCheckpoint.registerDisposeHook(
    +							globalStateHooks.createCheckpointDisposeHook(completedCheckpoint));
    +				}
    +			}
    +			catch (Exception e) {
    +				// catch all exception, to not let errors in cleanup hooks fail the checkpoint
    +				LOG.warn("Failed to create the cleanup hook for checkpoint " + checkpointId + 
    +						". Generic cleanup path will be executed...");
    --- End diff --
    
    `e` might be interesting to log since it could contain information what went wrong.


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

[GitHub] flink pull request #3522: [FLINK-5823] [checkpoints] State Backends also han...

Posted by tillrohrmann <gi...@git.apache.org>.
Github user tillrohrmann commented on a diff in the pull request:

    https://github.com/apache/flink/pull/3522#discussion_r108451623
  
    --- Diff: flink-runtime/src/main/java/org/apache/flink/runtime/checkpoint/CheckpointCoordinator.java ---
    @@ -1084,10 +1114,10 @@ private void discardState(
     				public void run() {
     					try {
     						stateObject.discardState();
    -					} catch (Throwable throwable) {
    -					LOG.warn("Could not properly discard state object of checkpoint {} " +
    -						"belonging to task {} of job {}.", checkpointId, executionAttemptID, jobId,
    -						throwable);
    +					}
    +					catch (Throwable t) {
    --- End diff --
    
    Code reformatting


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

[GitHub] flink pull request #3522: [FLINK-5823] [checkpoints] State Backends also han...

Posted by StefanRRichter <gi...@git.apache.org>.
Github user StefanRRichter commented on a diff in the pull request:

    https://github.com/apache/flink/pull/3522#discussion_r113682942
  
    --- Diff: flink-runtime/src/main/java/org/apache/flink/runtime/state/filesystem/FsCheckpointMetadataOutputStream.java ---
    @@ -0,0 +1,152 @@
    +/*
    + * Licensed to the Apache Software Foundation (ASF) under one
    + * or more contributor license agreements.  See the NOTICE file
    + * distributed with this work for additional information
    + * regarding copyright ownership.  The ASF licenses this file
    + * to you under the Apache License, Version 2.0 (the
    + * "License"); you may not use this file except in compliance
    + * with the License.  You may obtain a copy of the License at
    + *
    + *     http://www.apache.org/licenses/LICENSE-2.0
    + *
    + * Unless required by applicable law or agreed to in writing, software
    + * distributed under the License is distributed on an "AS IS" BASIS,
    + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    + * See the License for the specific language governing permissions and
    + * limitations under the License.
    + */
    +
    +package org.apache.flink.runtime.state.filesystem;
    +
    +import org.apache.flink.core.fs.FSDataOutputStream;
    +import org.apache.flink.core.fs.FileSystem;
    +import org.apache.flink.core.fs.FileSystem.WriteMode;
    +import org.apache.flink.core.fs.Path;
    +import org.apache.flink.runtime.state.CheckpointMetadataStreamFactory.CheckpointMetadataOutputStream;
    +import org.apache.flink.runtime.state.CheckpointMetadataStreamFactory.StreamHandleAndPointer;
    +import org.apache.flink.runtime.state.StreamStateHandle;
    +
    +import org.slf4j.Logger;
    +import org.slf4j.LoggerFactory;
    +
    +import java.io.IOException;
    +
    +import static org.apache.flink.util.Preconditions.checkNotNull;
    +
    +/**
    + * A {@link CheckpointMetadataOutputStream} that writes into a file and
    + * returns a {@link StreamStateHandle} upon closing.
    + */
    +public final class FsCheckpointMetadataOutputStream extends CheckpointMetadataOutputStream {
    +
    +	private static final Logger LOG = LoggerFactory.getLogger(FsCheckpointMetadataOutputStream.class);
    +
    +	// ------------------------------------------------------------------------
    +
    +	private final FSDataOutputStream out;
    +
    +	private final Path path;
    +
    +	private final FileSystem fileSystem;
    +
    +	private volatile boolean closed;
    +
    +
    +	public FsCheckpointMetadataOutputStream(FileSystem fileSystem, Path path) throws IOException {
    +		this.fileSystem = checkNotNull(fileSystem);
    +		this.path = checkNotNull(path);
    +
    +		this.out = fileSystem.create(path, WriteMode.NO_OVERWRITE);
    +	}
    +
    +	// ------------------------------------------------------------------------
    +	//  I/O
    +	// ------------------------------------------------------------------------
    +
    +	@Override
    +	public final void write(int b) throws IOException {
    +		out.write(b);
    +	}
    +
    +	@Override
    +	public final void write(byte[] b, int off, int len) throws IOException {
    +		out.write(b, off, len);
    +	}
    +
    +	@Override
    +	public long getPos() throws IOException {
    +		return out.getPos();
    +	}
    +
    +	@Override
    +	public void flush() throws IOException {
    +		out.flush();
    +	}
    +
    +	@Override
    +	public void sync() throws IOException {
    +		out.sync();
    +	}
    +
    +	// ------------------------------------------------------------------------
    +	//  Closing
    +	// ------------------------------------------------------------------------
    +
    +	public boolean isClosed() {
    +		return closed;
    +	}
    +
    +	@Override
    +	public void close() {
    +		if (!closed) {
    +			closed = true;
    +
    +			try {
    +				out.close();
    +				fileSystem.delete(path, false);
    --- End diff --
    
    I wonder if this delete is intended to be inside the `try` or should be moved to a `finally` clause


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

[GitHub] flink issue #3522: [FLINK-5823] [checkpoints] State Backends also handle Che...

Posted by StephanEwen <gi...@git.apache.org>.
Github user StephanEwen commented on the issue:

    https://github.com/apache/flink/pull/3522
  
    I would like to merge this for 1.3 with a slightly reduced scope.
    
    I would include the refactoring to make the State Backends also responsible for storing the Metadata.
    
    I would NOT merge the started work about cleanup hooks. The reason for that is that after some digging through this, I found we actually have to treat different file systems quite differently. For example for HDFS and posix-style file systems, we want to dispose the checkpoint-exclusive state via a `rm -r`.
    However, for S3 we explicitly do not want to do that, but issue DELETE commands for each state object independently, because Flink has a more consistent view on what objects exist for a checkpoint than S3 has. Also, because a `rm -r` on the S3 file system means "list objects with path prefix; foreach object: delete" which is even worse.


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

[GitHub] flink pull request #3522: [FLINK-5823] [checkpoints] State Backends also han...

Posted by tillrohrmann <gi...@git.apache.org>.
Github user tillrohrmann commented on a diff in the pull request:

    https://github.com/apache/flink/pull/3522#discussion_r108471140
  
    --- Diff: flink-runtime/src/main/java/org/apache/flink/runtime/state/CheckpointStreamFactory.java ---
    @@ -15,37 +15,34 @@
      * See the License for the specific language governing permissions and
      * limitations under the License.
      */
    +
     package org.apache.flink.runtime.state;
     
     import org.apache.flink.core.fs.FSDataOutputStream;
     
     import java.io.IOException;
     import java.io.OutputStream;
     
    +/**
    + * The CheckpointStreamFactory creates streams to persist raw checkpointed data (not metadata) as part
    + * of a checkpoint.
    + */
     public interface CheckpointStreamFactory {
     
     	/**
    -	 * Creates an new {@link CheckpointStateOutputStream}. When the stream
    -	 * is closed, it returns a state handle that can retrieve the state back.
    +	 * Creates an new {@code CheckpointStateOutputStream}. When the stream is closed, it returns a
    --- End diff --
    
    Why not leaving the link to the `CheckpointStateOutputStream` here?


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

[GitHub] flink pull request #3522: [FLINK-5823] [checkpoints] State Backends also han...

Posted by StefanRRichter <gi...@git.apache.org>.
Github user StefanRRichter commented on a diff in the pull request:

    https://github.com/apache/flink/pull/3522#discussion_r113682224
  
    --- Diff: flink-runtime/src/main/java/org/apache/flink/runtime/state/filesystem/FsCheckpointMetadataOutputStream.java ---
    @@ -0,0 +1,152 @@
    +/*
    + * Licensed to the Apache Software Foundation (ASF) under one
    + * or more contributor license agreements.  See the NOTICE file
    + * distributed with this work for additional information
    + * regarding copyright ownership.  The ASF licenses this file
    + * to you under the Apache License, Version 2.0 (the
    + * "License"); you may not use this file except in compliance
    + * with the License.  You may obtain a copy of the License at
    + *
    + *     http://www.apache.org/licenses/LICENSE-2.0
    + *
    + * Unless required by applicable law or agreed to in writing, software
    + * distributed under the License is distributed on an "AS IS" BASIS,
    + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    + * See the License for the specific language governing permissions and
    + * limitations under the License.
    + */
    +
    +package org.apache.flink.runtime.state.filesystem;
    +
    +import org.apache.flink.core.fs.FSDataOutputStream;
    +import org.apache.flink.core.fs.FileSystem;
    +import org.apache.flink.core.fs.FileSystem.WriteMode;
    +import org.apache.flink.core.fs.Path;
    +import org.apache.flink.runtime.state.CheckpointMetadataStreamFactory.CheckpointMetadataOutputStream;
    +import org.apache.flink.runtime.state.CheckpointMetadataStreamFactory.StreamHandleAndPointer;
    +import org.apache.flink.runtime.state.StreamStateHandle;
    +
    +import org.slf4j.Logger;
    +import org.slf4j.LoggerFactory;
    +
    +import java.io.IOException;
    +
    +import static org.apache.flink.util.Preconditions.checkNotNull;
    +
    +/**
    + * A {@link CheckpointMetadataOutputStream} that writes into a file and
    + * returns a {@link StreamStateHandle} upon closing.
    + */
    +public final class FsCheckpointMetadataOutputStream extends CheckpointMetadataOutputStream {
    +
    +	private static final Logger LOG = LoggerFactory.getLogger(FsCheckpointMetadataOutputStream.class);
    +
    +	// ------------------------------------------------------------------------
    +
    +	private final FSDataOutputStream out;
    +
    +	private final Path path;
    +
    +	private final FileSystem fileSystem;
    +
    +	private volatile boolean closed;
    +
    +
    +	public FsCheckpointMetadataOutputStream(FileSystem fileSystem, Path path) throws IOException {
    +		this.fileSystem = checkNotNull(fileSystem);
    +		this.path = checkNotNull(path);
    +
    +		this.out = fileSystem.create(path, WriteMode.NO_OVERWRITE);
    +	}
    +
    +	// ------------------------------------------------------------------------
    +	//  I/O
    +	// ------------------------------------------------------------------------
    +
    +	@Override
    +	public final void write(int b) throws IOException {
    +		out.write(b);
    +	}
    +
    +	@Override
    +	public final void write(byte[] b, int off, int len) throws IOException {
    +		out.write(b, off, len);
    +	}
    +
    +	@Override
    +	public long getPos() throws IOException {
    +		return out.getPos();
    +	}
    +
    +	@Override
    +	public void flush() throws IOException {
    +		out.flush();
    +	}
    +
    +	@Override
    +	public void sync() throws IOException {
    +		out.sync();
    +	}
    +
    +	// ------------------------------------------------------------------------
    +	//  Closing
    +	// ------------------------------------------------------------------------
    +
    +	public boolean isClosed() {
    +		return closed;
    +	}
    +
    +	@Override
    +	public void close() {
    +		if (!closed) {
    --- End diff --
    
    Either the `volatile` on `closed` is not required or this does not give full thread safety and should be replaced by `AtomicBoolean`.


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---