You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@flink.apache.org by gy...@apache.org on 2016/03/16 15:12:22 UTC
[2/2] flink git commit: [FLINK-3620] [streaming] Remove DbStateBackend
[FLINK-3620] [streaming] Remove DbStateBackend
Closes #1800
Project: http://git-wip-us.apache.org/repos/asf/flink/repo
Commit: http://git-wip-us.apache.org/repos/asf/flink/commit/33f43114
Tree: http://git-wip-us.apache.org/repos/asf/flink/tree/33f43114
Diff: http://git-wip-us.apache.org/repos/asf/flink/diff/33f43114
Branch: refs/heads/master
Commit: 33f43114d5961fbcfc792d7a4fd74d3bdee738c5
Parents: 40d5205
Author: Gyula Fora <gy...@apache.org>
Authored: Wed Mar 16 10:42:48 2016 +0100
Committer: Gyula Fora <gy...@apache.org>
Committed: Wed Mar 16 15:08:59 2016 +0100
----------------------------------------------------------------------
flink-contrib/flink-streaming-contrib/pom.xml | 24 -
.../contrib/streaming/state/DbAdapter.java | 186 -----
.../streaming/state/DbBackendConfig.java | 330 ---------
.../contrib/streaming/state/DbStateBackend.java | 325 ---------
.../contrib/streaming/state/DbStateHandle.java | 105 ---
.../streaming/state/LazyDbValueState.java | 692 ------------------
.../contrib/streaming/state/MySqlAdapter.java | 245 -------
.../contrib/streaming/state/SQLRetrier.java | 176 -----
.../streaming/state/ShardedConnection.java | 153 ----
.../state/DBStateCheckpointingTest.java | 258 -------
.../streaming/state/DbStateBackendTest.java | 723 -------------------
.../contrib/streaming/state/DerbyAdapter.java | 165 -----
12 files changed, 3382 deletions(-)
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/flink/blob/33f43114/flink-contrib/flink-streaming-contrib/pom.xml
----------------------------------------------------------------------
diff --git a/flink-contrib/flink-streaming-contrib/pom.xml b/flink-contrib/flink-streaming-contrib/pom.xml
index c85635f..ac090ef 100644
--- a/flink-contrib/flink-streaming-contrib/pom.xml
+++ b/flink-contrib/flink-streaming-contrib/pom.xml
@@ -58,30 +58,6 @@ under the License.
<version>${project.version}</version>
<scope>test</scope>
</dependency>
- <dependency>
- <groupId>org.apache.flink</groupId>
- <artifactId>flink-tests_2.10</artifactId>
- <version>${project.version}</version>
- <type>test-jar</type>
- <scope>test</scope>
- </dependency>
- <dependency>
- <groupId>com.google.guava</groupId>
- <artifactId>guava</artifactId>
- <version>${guava.version}</version>
- </dependency>
- <dependency>
- <groupId>org.apache.derby</groupId>
- <artifactId>derbyclient</artifactId>
- <version>10.12.1.1</version>
- <scope>test</scope>
- </dependency>
- <dependency>
- <groupId>org.apache.derby</groupId>
- <artifactId>derbynet</artifactId>
- <version>10.12.1.1</version>
- <scope>test</scope>
- </dependency>
</dependencies>
<build>
http://git-wip-us.apache.org/repos/asf/flink/blob/33f43114/flink-contrib/flink-streaming-contrib/src/main/java/org/apache/flink/contrib/streaming/state/DbAdapter.java
----------------------------------------------------------------------
diff --git a/flink-contrib/flink-streaming-contrib/src/main/java/org/apache/flink/contrib/streaming/state/DbAdapter.java b/flink-contrib/flink-streaming-contrib/src/main/java/org/apache/flink/contrib/streaming/state/DbAdapter.java
deleted file mode 100644
index 9ab9c23..0000000
--- a/flink-contrib/flink-streaming-contrib/src/main/java/org/apache/flink/contrib/streaming/state/DbAdapter.java
+++ /dev/null
@@ -1,186 +0,0 @@
-/*
- * 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.contrib.streaming.state;
-
-import java.io.IOException;
-import java.io.Serializable;
-import java.sql.Connection;
-import java.sql.PreparedStatement;
-import java.sql.SQLException;
-import java.util.List;
-
-import org.apache.flink.api.java.tuple.Tuple2;
-
-/**
- * Adapter interface for executing different checkpointing related operations on
- * the underlying database.
- */
-public interface DbAdapter extends Serializable {
-
- /**
- * Initialize tables for storing non-partitioned checkpoints for the given
- * job id and database connection.
- */
- void createCheckpointsTable(String jobId, Connection con) throws SQLException;
-
- /**
- * Checkpoints will be inserted in the database using prepared statements.
- * This methods should prepare and return the statement that will be used
- * later to insert using the given connection.
- *
- */
- PreparedStatement prepareCheckpointInsert(String jobId, Connection con) throws SQLException;
-
- /**
- * Set the {@link PreparedStatement} parameters for the statement returned
- * by {@link #prepareCheckpointInsert(String, Connection)}.
- *
- * @param jobId
- * Id of the current job.
- * @param insertStatement
- * Statement returned by
- * {@link #prepareCheckpointInsert(String, Connection)}.
- * @param checkpointId
- * Global checkpoint id.
- * @param timestamp
- * Global checkpoint timestamp.
- * @param handleId
- * Unique id assigned to this state checkpoint (should be primary
- * key).
- * @param checkpoint
- * The serialized checkpoint.
- * @throws SQLException
- */
- void setCheckpointInsertParams(String jobId, PreparedStatement insertStatement, long checkpointId,
- long timestamp, long handleId, byte[] checkpoint) throws SQLException;
-
- /**
- * Retrieve the serialized checkpoint data from the database.
- *
- * @param jobId
- * Id of the current job.
- * @param con
- * Database connection
- * @param checkpointId
- * Global checkpoint id.
- * @param checkpointTs
- * Global checkpoint timestamp.
- * @param handleId
- * Unique id assigned to this state checkpoint (should be primary
- * key).
- * @return The byte[] corresponding to the checkpoint or null if missing.
- * @throws SQLException
- */
- byte[] getCheckpoint(String jobId, Connection con, long checkpointId, long checkpointTs, long handleId)
- throws SQLException;
-
- /**
- * Remove the given checkpoint from the database.
- *
- * @param jobId
- * Id of the current job.
- * @param con
- * Database connection
- * @param checkpointId
- * Global checkpoint id.
- * @param checkpointTs
- * Global checkpoint timestamp.
- * @param handleId
- * Unique id assigned to this state checkpoint (should be primary
- * key).
- * @return The byte[] corresponding to the checkpoint or null if missing.
- * @throws SQLException
- */
- void deleteCheckpoint(String jobId, Connection con, long checkpointId, long checkpointTs, long handleId)
- throws SQLException;
-
- /**
- * Remove all states for the given {@link org.apache.flink.api.common.JobID},
- * by for instance dropping the entire table.
- *
- * @throws SQLException
- */
- void disposeAllStateForJob(String jobId, Connection con) throws SQLException;
-
- /**
- * Initialize the necessary tables for the given stateId. The state id
- * consist of the JobId+OperatorId+StateName.
- *
- */
- void createKVStateTable(String stateId, Connection con) throws SQLException;
-
- /**
- * Prepare the the statement that will be used to insert key-value pairs in
- * the database.
- *
- */
- String prepareKVCheckpointInsert(String stateId) throws SQLException;
-
- /**
- * Prepare the statement that will be used to lookup keys from the database.
- * Keys and values are assumed to be byte arrays.
- *
- */
- String prepareKeyLookup(String stateId) throws SQLException;
-
- /**
- * Retrieve the latest value from the database for a given key and
- * timestamp.
- *
- * @param stateId
- * Unique identifier of the kvstate (usually the table name).
- * @param lookupStatement
- * The statement returned by
- * {@link #prepareKeyLookup(String, Connection)}.
- * @param key
- * The key to lookup.
- * @return The latest valid value for the key.
- * @throws SQLException
- */
- byte[] lookupKey(String stateId, PreparedStatement lookupStatement, byte[] key, long lookupId)
- throws SQLException;
-
- /**
- * Clean up states between the checkpoint and recovery timestamp.
- *
- */
- void cleanupFailedCheckpoints(String stateId, Connection con, long checkpointTimestamp,
- long recoveryTimestamp) throws SQLException;
-
- /**
- * Insert a list of Key-Value pairs into the database. The suggested
- * approach is to use idempotent inserts(updates) as 1 batch operation.
- *
- */
- void insertBatch(String stateId, DbBackendConfig conf, Connection con, PreparedStatement insertStatement,
- long checkpointTimestamp, List<Tuple2<byte[], byte[]>> toInsert) throws IOException;
-
- /**
- * Compact the states between two checkpoint timestamp by only keeping the
- * most recent.
- */
- void compactKvStates(String kvStateId, Connection con, long lowerTs, long upperTs) throws SQLException;
-
- /**
- * Execute a simple operation to refresh the current database connection in
- * case no data is written for a longer time period. Usually something like
- * "select 1"
- */
- void keepAlive(Connection con) throws SQLException;
-
-}
http://git-wip-us.apache.org/repos/asf/flink/blob/33f43114/flink-contrib/flink-streaming-contrib/src/main/java/org/apache/flink/contrib/streaming/state/DbBackendConfig.java
----------------------------------------------------------------------
diff --git a/flink-contrib/flink-streaming-contrib/src/main/java/org/apache/flink/contrib/streaming/state/DbBackendConfig.java b/flink-contrib/flink-streaming-contrib/src/main/java/org/apache/flink/contrib/streaming/state/DbBackendConfig.java
deleted file mode 100644
index 883b65a..0000000
--- a/flink-contrib/flink-streaming-contrib/src/main/java/org/apache/flink/contrib/streaming/state/DbBackendConfig.java
+++ /dev/null
@@ -1,330 +0,0 @@
-/*
- * 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.contrib.streaming.state;
-
-import java.io.Serializable;
-import java.sql.SQLException;
-import java.util.List;
-
-import org.apache.flink.contrib.streaming.state.ShardedConnection.Partitioner;
-
-import com.google.common.collect.Lists;
-
-/**
- *
- * Configuration object for {@link DbStateBackend}, containing information to
- * shard and connect to the databases that will store the state checkpoints.
- *
- */
-public class DbBackendConfig implements Serializable {
-
- private static final long serialVersionUID = 1L;
-
- // Database connection properties
- private final String userName;
- private final String userPassword;
- private final List<String> shardUrls;
-
- // JDBC Driver + DbAdapter information
- private DbAdapter dbAdapter = new MySqlAdapter();
- private String JDBCDriver = null;
-
- private int maxNumberOfSqlRetries = 5;
- private int sleepBetweenSqlRetries = 100;
-
- // KvState properties
- private int kvStateCacheSize = 10000;
- private int maxKvInsertBatchSize = 1000;
- private float maxKvEvictFraction = 0.1f;
- private int kvStateCompactionFreq = -1;
-
- private Partitioner shardPartitioner;
-
- /**
- * Creates a new sharded database state backend configuration with the given
- * parameters and default {@link MySqlAdapter}.
- *
- * @param dbUserName
- * The username used to connect to the database at the given url.
- * @param dbUserPassword
- * The password used to connect to the database at the given url
- * and username.
- * @param dbShardUrls
- * The list of JDBC urls of the databases that will be used as
- * shards for the state backend. Sharding of the state will
- * happen based on the subtask index of the given task.
- */
- public DbBackendConfig(String dbUserName, String dbUserPassword, List<String> dbShardUrls) {
- this.userName = dbUserName;
- this.userPassword = dbUserPassword;
- this.shardUrls = dbShardUrls;
- }
-
- /**
- * Creates a new database state backend configuration with the given
- * parameters and default {@link MySqlAdapter}.
- *
- * @param dbUserName
- * The username used to connect to the database at the given url.
- * @param dbUserPassword
- * The password used to connect to the database at the given url
- * and username.
- * @param dbUrl
- * The JDBC url of the database for example
- * "jdbc:mysql://localhost:3306/flinkdb".
- */
- public DbBackendConfig(String dbUserName, String dbUserPassword, String dbUrl) {
- this(dbUserName, dbUserPassword, Lists.newArrayList(dbUrl));
- }
-
- /**
- * The username used to connect to the database at the given urls.
- */
- public String getUserName() {
- return userName;
- }
-
- /**
- * The password used to connect to the database at the given url and
- * username.
- */
- public String getUserPassword() {
- return userPassword;
- }
-
- /**
- * Number of database shards defined.
- */
- public int getNumberOfShards() {
- return shardUrls.size();
- }
-
- /**
- * Database shard urls as provided in the constructor.
- *
- */
- public List<String> getShardUrls() {
- return shardUrls;
- }
-
- /**
- * The url of the first shard.
- *
- */
- public String getUrl() {
- return getShardUrl(0);
- }
-
- /**
- * The url of a specific shard.
- *
- */
- public String getShardUrl(int shardIndex) {
- validateShardIndex(shardIndex);
- return shardUrls.get(shardIndex);
- }
-
- private void validateShardIndex(int i) {
- if (i < 0) {
- throw new IllegalArgumentException("Index must be positive.");
- } else if (getNumberOfShards() <= i) {
- throw new IllegalArgumentException("Index must be less then the total number of shards.");
- }
- }
-
- /**
- * Get the {@link DbAdapter} that will be used to operate on the database
- * during checkpointing.
- *
- */
- public DbAdapter getDbAdapter() {
- return dbAdapter;
- }
-
- /**
- * Set the {@link DbAdapter} that will be used to operate on the database
- * during checkpointing.
- *
- */
- public void setDbAdapter(DbAdapter adapter) {
- this.dbAdapter = adapter;
- }
-
- /**
- * The class name that should be used to load the JDBC driver using
- * Class.forName(JDBCDriverClass).
- */
- public String getJDBCDriver() {
- return JDBCDriver;
- }
-
- /**
- * Set the class name that should be used to load the JDBC driver using
- * Class.forName(JDBCDriverClass).
- */
- public void setJDBCDriver(String jDBCDriverClassName) {
- JDBCDriver = jDBCDriverClassName;
- }
-
- /**
- * The maximum number of key-value pairs stored in one task instance's cache
- * before evicting to the underlying database.
- *
- */
- public int getKvCacheSize() {
- return kvStateCacheSize;
- }
-
- /**
- * Set the maximum number of key-value pairs stored in one task instance's
- * cache before evicting to the underlying database. When the cache is full
- * the N least recently used keys will be evicted to the database, where N =
- * maxKvEvictFraction*KvCacheSize.
- *
- */
- public void setKvCacheSize(int size) {
- kvStateCacheSize = size;
- }
-
- /**
- * The maximum number of key-value pairs inserted in the database as one
- * batch operation.
- */
- public int getMaxKvInsertBatchSize() {
- return maxKvInsertBatchSize;
- }
-
- /**
- * Set the maximum number of key-value pairs inserted in the database as one
- * batch operation.
- */
- public void setMaxKvInsertBatchSize(int size) {
- maxKvInsertBatchSize = size;
- }
-
- /**
- * Sets the maximum fraction of key-value states evicted from the cache if
- * the cache is full.
- */
- public void setMaxKvCacheEvictFraction(float fraction) {
- if (fraction > 1 || fraction <= 0) {
- throw new RuntimeException("Must be a number between 0 and 1");
- } else {
- maxKvEvictFraction = fraction;
- }
- }
-
- /**
- * The maximum fraction of key-value states evicted from the cache if the
- * cache is full.
- */
- public float getMaxKvCacheEvictFraction() {
- return maxKvEvictFraction;
- }
-
- /**
- * The number of elements that will be evicted when the cache is full.
- *
- */
- public int getNumElementsToEvict() {
- return (int) Math.ceil(getKvCacheSize() * getMaxKvCacheEvictFraction());
- }
-
- /**
- * Sets how often will automatic compaction be performed on the database to
- * remove old overwritten state changes. The frequency is set in terms of
- * number of successful checkpoints between two compactions and should take
- * the state size and checkpoint frequency into account.
- * <p>
- * By default automatic compaction is turned off.
- */
- public void setKvStateCompactionFrequency(int compactEvery) {
- this.kvStateCompactionFreq = compactEvery;
- }
-
- /**
- * Sets how often will automatic compaction be performed on the database to
- * remove old overwritten state changes. The frequency is set in terms of
- * number of successful checkpoints between two compactions and should take
- * the state size and checkpoint frequency into account.
- * <p>
- * By default automatic compaction is turned off.
- */
- public int getKvStateCompactionFrequency() {
- return kvStateCompactionFreq;
- }
-
- /**
- * The number of times each SQL command will be retried on failure.
- */
- public int getMaxNumberOfSqlRetries() {
- return maxNumberOfSqlRetries;
- }
-
- /**
- * Sets the number of times each SQL command will be retried on failure.
- */
- public void setMaxNumberOfSqlRetries(int maxNumberOfSqlRetries) {
- this.maxNumberOfSqlRetries = maxNumberOfSqlRetries;
- }
-
- /**
- * The number of milliseconds slept between two SQL retries. The actual
- * sleep time will be chosen randomly between 1 and the given time.
- *
- */
- public int getSleepBetweenSqlRetries() {
- return sleepBetweenSqlRetries;
- }
-
- /**
- * Sets the number of milliseconds slept between two SQL retries. The actual
- * sleep time will be chosen randomly between 1 and the given time.
- *
- */
- public void setSleepBetweenSqlRetries(int sleepBetweenSqlRetries) {
- this.sleepBetweenSqlRetries = sleepBetweenSqlRetries;
- }
-
- /**
- * Sets the partitioner used to assign keys to different database shards
- */
- public void setPartitioner(Partitioner partitioner) {
- this.shardPartitioner = partitioner;
- }
-
- /**
- * Creates a new {@link ShardedConnection} using the set parameters.
- *
- * @throws SQLException
- */
- public ShardedConnection createShardedConnection() throws SQLException {
- if (JDBCDriver != null) {
- try {
- Class.forName(JDBCDriver);
- } catch (ClassNotFoundException e) {
- throw new RuntimeException("Could not load JDBC driver class", e);
- }
- }
- if (shardPartitioner == null) {
- return new ShardedConnection(shardUrls, userName, userPassword);
- } else {
- return new ShardedConnection(shardUrls, userName, userPassword, shardPartitioner);
- }
- }
-}
http://git-wip-us.apache.org/repos/asf/flink/blob/33f43114/flink-contrib/flink-streaming-contrib/src/main/java/org/apache/flink/contrib/streaming/state/DbStateBackend.java
----------------------------------------------------------------------
diff --git a/flink-contrib/flink-streaming-contrib/src/main/java/org/apache/flink/contrib/streaming/state/DbStateBackend.java b/flink-contrib/flink-streaming-contrib/src/main/java/org/apache/flink/contrib/streaming/state/DbStateBackend.java
deleted file mode 100644
index 964c687..0000000
--- a/flink-contrib/flink-streaming-contrib/src/main/java/org/apache/flink/contrib/streaming/state/DbStateBackend.java
+++ /dev/null
@@ -1,325 +0,0 @@
-/*
- * 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.contrib.streaming.state;
-
-import org.apache.flink.api.common.state.FoldingState;
-import org.apache.flink.api.common.state.FoldingStateDescriptor;
-import org.apache.flink.api.common.state.ListState;
-import org.apache.flink.api.common.state.ListStateDescriptor;
-import org.apache.flink.api.common.state.ReducingState;
-import org.apache.flink.api.common.state.ReducingStateDescriptor;
-import org.apache.flink.api.common.state.ValueState;
-import org.apache.flink.api.common.state.ValueStateDescriptor;
-import org.apache.flink.api.common.typeutils.TypeSerializer;
-import org.apache.flink.runtime.execution.Environment;
-import org.apache.flink.runtime.state.AbstractStateBackend;
-import org.apache.flink.runtime.state.ArrayListSerializer;
-import org.apache.flink.runtime.state.GenericFoldingState;
-import org.apache.flink.runtime.state.GenericListState;
-import org.apache.flink.runtime.state.GenericReducingState;
-import org.apache.flink.runtime.state.StateHandle;
-import org.apache.flink.util.InstantiationUtil;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import java.io.Serializable;
-import java.sql.Connection;
-import java.sql.PreparedStatement;
-import java.sql.SQLException;
-import java.util.ArrayList;
-import java.util.Random;
-import java.util.concurrent.Callable;
-
-import static org.apache.flink.contrib.streaming.state.SQLRetrier.retry;
-
-/**
- * {@link AbstractStateBackend} for storing checkpoints in JDBC supporting databases.
- * Key-Value state is stored out-of-core and is lazily fetched using the
- * {@link LazyDbValueState} implementation. A different backend can also be
- * provided in the constructor to store the non-partitioned states. A common use
- * case would be to store the key-value states in the database and store larger
- * non-partitioned states on a distributed file system.
- * <p>
- * This backend implementation also allows the sharding of the checkpointed
- * states among multiple database instances, which can be enabled by passing
- * multiple database urls to the {@link DbBackendConfig} instance.
- * <p>
- * By default there are multiple tables created in the given databases: 1 table
- * for non-partitioned checkpoints and 1 table for each key-value state in the
- * streaming program.
- * <p>
- * To control table creation, insert/lookup operations and to provide
- * compatibility for different SQL implementations, a custom
- * {@link MySqlAdapter} can be supplied in the {@link DbBackendConfig}.
- *
- */
-public class DbStateBackend extends AbstractStateBackend {
-
- private static final long serialVersionUID = 1L;
- private static final Logger LOG = LoggerFactory.getLogger(DbStateBackend.class);
-
- private Random rnd;
-
- // ------------------------------------------------------
-
- private transient Environment env;
-
- private transient String jobId;
-
- // ------------------------------------------------------
-
- private final DbBackendConfig dbConfig;
- private final DbAdapter dbAdapter;
-
- private ShardedConnection connections;
-
- private final int numSqlRetries;
- private final int sqlRetrySleep;
-
- private transient PreparedStatement insertStatement;
-
- private String operatorIdentifier;
-
- // ------------------------------------------------------
-
- // We allow to use a different backend for storing non-partitioned states
- private AbstractStateBackend nonPartitionedStateBackend = null;
-
- // ------------------------------------------------------
-
- /**
- * Create a new {@link DbStateBackend} using the provided
- * {@link DbBackendConfig} configuration.
- *
- */
- public DbStateBackend(DbBackendConfig backendConfig) {
- this.dbConfig = backendConfig;
- dbAdapter = backendConfig.getDbAdapter();
- numSqlRetries = backendConfig.getMaxNumberOfSqlRetries();
- sqlRetrySleep = backendConfig.getSleepBetweenSqlRetries();
- }
-
- /**
- * Create a new {@link DbStateBackend} using the provided
- * {@link DbBackendConfig} configuration and a different backend for storing
- * non-partitioned state snapshots.
- *
- */
- public DbStateBackend(DbBackendConfig backendConfig, AbstractStateBackend backend) {
- this(backendConfig);
- this.nonPartitionedStateBackend = backend;
- }
-
- /**
- * Get the database connections maintained by the backend.
- */
- public ShardedConnection getConnections() {
- return connections;
- }
-
- /**
- * Check whether the backend has been initialized.
- *
- */
- public boolean isInitialized() {
- return connections != null;
- }
-
- public Environment getEnvironment() {
- return env;
- }
-
- /**
- * Get the backend configuration object.
- */
- public DbBackendConfig getConfiguration() {
- return dbConfig;
- }
-
- @Override
- public <S extends Serializable> StateHandle<S> checkpointStateSerializable(final S state, final long checkpointID,
- final long timestamp) throws Exception {
-
- // If we set a different backend for non-partitioned checkpoints we use
- // that otherwise write to the database.
- if (nonPartitionedStateBackend == null) {
- return retry(new Callable<DbStateHandle<S>>() {
- public DbStateHandle<S> call() throws Exception {
- // We create a unique long id for each handle, but we also
- // store the checkpoint id and timestamp for bookkeeping
- long handleId = rnd.nextLong();
-
- byte[] serializedState = InstantiationUtil.serializeObject(state);
- dbAdapter.setCheckpointInsertParams(jobId, insertStatement,
- checkpointID, timestamp, handleId,
- serializedState);
-
- insertStatement.executeUpdate();
-
- return new DbStateHandle<>(jobId, checkpointID, timestamp, handleId,
- dbConfig, serializedState.length);
- }
- }, numSqlRetries, sqlRetrySleep);
- } else {
- return nonPartitionedStateBackend.checkpointStateSerializable(state, checkpointID, timestamp);
- }
- }
-
- @Override
- public CheckpointStateOutputStream createCheckpointStateOutputStream(long checkpointID, long timestamp)
- throws Exception {
- if (nonPartitionedStateBackend == null) {
- // We don't implement this functionality for the DbStateBackend as
- // we cannot directly write a stream to the database anyways.
- throw new UnsupportedOperationException("Use ceckpointStateSerializable instead.");
- } else {
- return nonPartitionedStateBackend.createCheckpointStateOutputStream(checkpointID, timestamp);
- }
- }
-
- @Override
- protected <N, T> ValueState<T> createValueState(TypeSerializer<N> namespaceSerializer,
- ValueStateDescriptor<T> stateDesc) throws Exception {
-
- if (!stateDesc.isSerializerInitialized()) {
- throw new IllegalArgumentException("state descriptor serializer not initialized");
- }
-
- String stateName = operatorIdentifier + "_"+ stateDesc.getName();
-
- return new LazyDbValueState<>(
- stateName,
- env.getTaskInfo().getIndexOfThisSubtask() == 0,
- getConnections(),
- getConfiguration(),
- keySerializer,
- namespaceSerializer,
- stateDesc);
- }
-
- @Override
- protected <N, T> ListState<T> createListState(TypeSerializer<N> namespaceSerializer,
- ListStateDescriptor<T> stateDesc) throws Exception {
-
- if (!stateDesc.isSerializerInitialized()) {
- throw new IllegalArgumentException("state descriptor serializer not initialized");
- }
-
- ValueStateDescriptor<ArrayList<T>> valueStateDescriptor = new ValueStateDescriptor<>(stateDesc.getName(),
- new ArrayListSerializer<>(stateDesc.getSerializer()), null);
-
- ValueState<ArrayList<T>> valueState = createValueState(namespaceSerializer, valueStateDescriptor);
- return new GenericListState<>(valueState);
- }
-
- @Override
- @SuppressWarnings("unchecked")
- protected <N, T> ReducingState<T> createReducingState(TypeSerializer<N> namespaceSerializer,
- ReducingStateDescriptor<T> stateDesc) throws Exception {
-
- if (!stateDesc.isSerializerInitialized()) {
- throw new IllegalArgumentException("state descriptor serializer not initialized");
- }
-
- ValueStateDescriptor<T> valueStateDescriptor = new ValueStateDescriptor<>(
- stateDesc.getName(), stateDesc.getSerializer(), null);
-
- ValueState<T> valueState = createValueState(namespaceSerializer, valueStateDescriptor);
- return new GenericReducingState<>(valueState, stateDesc.getReduceFunction());
- }
-
- @Override
- protected <N, T, ACC> FoldingState<T, ACC> createFoldingState(TypeSerializer<N> namespaceSerializer,
- FoldingStateDescriptor<T, ACC> stateDesc) throws Exception {
-
- if (!stateDesc.isSerializerInitialized()) {
- throw new IllegalArgumentException("state descriptor serializer not initialized");
- }
-
- ValueStateDescriptor<ACC> valueStateDescriptor = new ValueStateDescriptor<>(
- stateDesc.getName(), stateDesc.getSerializer(), stateDesc.getDefaultValue());
-
- ValueState<ACC> valueState = createValueState(namespaceSerializer, valueStateDescriptor);
- return new GenericFoldingState<>(valueState, stateDesc.getFoldFunction());
- }
-
- @Override
- public void initializeForJob(final Environment env,
- String operatorIdentifier,
- TypeSerializer<?> keySerializer) throws Exception {
- super.initializeForJob(env, operatorIdentifier, keySerializer);
-
- this.operatorIdentifier = operatorIdentifier;
-
- this.rnd = new Random();
- this.env = env;
- this.jobId = env.getJobID().toString().substring(0, 16);
-
- connections = dbConfig.createShardedConnection();
-
- // We want the most light-weight transaction isolation level as we don't
- // have conflicting reads/writes. We just want to be able to roll back
- // batch inserts for k-v snapshots. This requirement might be removed in
- // the future.
- connections.setTransactionIsolation(Connection.TRANSACTION_READ_UNCOMMITTED);
-
- // If we have a different backend for non-partitioned states we
- // initialize that, otherwise create tables for storing the checkpoints.
- //
- // Currently all non-partitioned states are written to the first
- // database shard
- if (nonPartitionedStateBackend == null) {
- insertStatement = retry(new Callable<PreparedStatement>() {
- public PreparedStatement call() throws SQLException {
- dbAdapter.createCheckpointsTable(jobId, getConnections().getFirst());
- return dbAdapter.prepareCheckpointInsert(jobId,
- getConnections().getFirst());
- }
- }, numSqlRetries, sqlRetrySleep);
- } else {
- nonPartitionedStateBackend.initializeForJob(env, operatorIdentifier, keySerializer);
- }
-
- if (LOG.isDebugEnabled()) {
- LOG.debug("Database state backend successfully initialized");
- }
- }
-
- @Override
- public void close() throws Exception {
- // We first close the statement/non-partitioned backend, then we close
- // the database connection
- try (ShardedConnection c = connections) {
- if (nonPartitionedStateBackend == null) {
- insertStatement.close();
- } else {
- nonPartitionedStateBackend.close();
- }
- }
- }
-
- @Override
- public void disposeAllStateForCurrentJob() throws Exception {
- if (nonPartitionedStateBackend == null) {
- dbAdapter.disposeAllStateForJob(jobId, connections.getFirst());
- } else {
- nonPartitionedStateBackend.disposeAllStateForCurrentJob();
- }
- }
-
-}
http://git-wip-us.apache.org/repos/asf/flink/blob/33f43114/flink-contrib/flink-streaming-contrib/src/main/java/org/apache/flink/contrib/streaming/state/DbStateHandle.java
----------------------------------------------------------------------
diff --git a/flink-contrib/flink-streaming-contrib/src/main/java/org/apache/flink/contrib/streaming/state/DbStateHandle.java b/flink-contrib/flink-streaming-contrib/src/main/java/org/apache/flink/contrib/streaming/state/DbStateHandle.java
deleted file mode 100644
index cc42b3f..0000000
--- a/flink-contrib/flink-streaming-contrib/src/main/java/org/apache/flink/contrib/streaming/state/DbStateHandle.java
+++ /dev/null
@@ -1,105 +0,0 @@
-/*
- * 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.contrib.streaming.state;
-
-import org.apache.flink.runtime.state.StateHandle;
-import org.apache.flink.util.InstantiationUtil;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import java.io.IOException;
-import java.io.Serializable;
-import java.util.concurrent.Callable;
-
-import static org.apache.flink.contrib.streaming.state.SQLRetrier.retry;
-
-/**
- * State handle implementation for storing checkpoints as byte arrays in
- * databases using the {@link MySqlAdapter} defined in the {@link DbBackendConfig}.
- *
- */
-public class DbStateHandle<S> implements Serializable, StateHandle<S> {
-
- private static final long serialVersionUID = 1L;
- private static final Logger LOG = LoggerFactory.getLogger(DbStateHandle.class);
-
- private final String jobId;
- private final DbBackendConfig dbConfig;
-
- private final long checkpointId;
- private final long checkpointTs;
-
- private final long handleId;
-
- private final long stateSize;
-
- public DbStateHandle(
- String jobId,
- long checkpointId,
- long checkpointTs,
- long handleId,
- DbBackendConfig dbConfig,
- long stateSize) {
-
- this.checkpointId = checkpointId;
- this.handleId = handleId;
- this.jobId = jobId;
- this.dbConfig = dbConfig;
- this.checkpointTs = checkpointTs;
- this.stateSize = stateSize;
- }
-
- protected byte[] getBytes() throws IOException {
- return retry(new Callable<byte[]>() {
- public byte[] call() throws Exception {
- try (ShardedConnection con = dbConfig.createShardedConnection()) {
- return dbConfig.getDbAdapter().getCheckpoint(jobId, con.getFirst(), checkpointId, checkpointTs, handleId);
- }
- }
- }, dbConfig.getMaxNumberOfSqlRetries(), dbConfig.getSleepBetweenSqlRetries());
- }
-
- @Override
- public void discardState() {
- try {
- retry(new Callable<Boolean>() {
- public Boolean call() throws Exception {
- try (ShardedConnection con = dbConfig.createShardedConnection()) {
- dbConfig.getDbAdapter().deleteCheckpoint(jobId, con.getFirst(), checkpointId, checkpointTs, handleId);
- }
- return true;
- }
- }, dbConfig.getMaxNumberOfSqlRetries(), dbConfig.getSleepBetweenSqlRetries());
- } catch (IOException e) {
- // We don't want to fail the job here, but log the error.
- if (LOG.isDebugEnabled()) {
- LOG.debug("Could not discard state.");
- }
- }
- }
-
- @Override
- public S getState(ClassLoader userCodeClassLoader) throws IOException, ClassNotFoundException {
- return InstantiationUtil.deserializeObject(getBytes(), userCodeClassLoader);
- }
-
- @Override
- public long getStateSize() {
- return stateSize;
- }
-}
http://git-wip-us.apache.org/repos/asf/flink/blob/33f43114/flink-contrib/flink-streaming-contrib/src/main/java/org/apache/flink/contrib/streaming/state/LazyDbValueState.java
----------------------------------------------------------------------
diff --git a/flink-contrib/flink-streaming-contrib/src/main/java/org/apache/flink/contrib/streaming/state/LazyDbValueState.java b/flink-contrib/flink-streaming-contrib/src/main/java/org/apache/flink/contrib/streaming/state/LazyDbValueState.java
deleted file mode 100644
index 753850a..0000000
--- a/flink-contrib/flink-streaming-contrib/src/main/java/org/apache/flink/contrib/streaming/state/LazyDbValueState.java
+++ /dev/null
@@ -1,692 +0,0 @@
-/*
- * 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.contrib.streaming.state;
-
-import static org.apache.flink.contrib.streaming.state.SQLRetrier.retry;
-
-import java.io.ByteArrayOutputStream;
-import java.io.IOException;
-import java.sql.Connection;
-import java.sql.SQLException;
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.Iterator;
-import java.util.LinkedHashMap;
-import java.util.List;
-import java.util.Map;
-import java.util.Map.Entry;
-import java.util.concurrent.Callable;
-import java.util.concurrent.ExecutorService;
-import java.util.concurrent.Executors;
-
-import org.apache.flink.api.common.state.ValueState;
-import org.apache.flink.api.common.state.ValueStateDescriptor;
-import org.apache.flink.api.common.typeutils.TypeSerializer;
-import org.apache.flink.api.java.tuple.Tuple2;
-import org.apache.flink.contrib.streaming.state.ShardedConnection.ShardedStatement;
-import org.apache.flink.core.memory.DataOutputViewStreamWrapper;
-import org.apache.flink.runtime.state.KvState;
-import org.apache.flink.runtime.state.KvStateSnapshot;
-import org.apache.flink.runtime.state.CheckpointListener;
-import org.apache.flink.util.InstantiationUtil;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import com.google.common.base.Optional;
-
-/**
- *
- * Lazily fetched {@link KvState} using a SQL backend. Key-value pairs are
- * cached on heap and are lazily retrieved on access.
- *
- */
-public class LazyDbValueState<K, N, V>
- implements KvState<K, N, ValueState<V>, ValueStateDescriptor<V>, DbStateBackend>, ValueState<V>, CheckpointListener {
-
- private static final Logger LOG = LoggerFactory.getLogger(LazyDbValueState.class);
-
- // ------------------------------------------------------
-
- // Unique id for this state (appID_operatorID_stateName)
- private final String kvStateId;
- private final boolean compact;
-
- private K currentKey;
- private N currentNamespace;
- private final V defaultValue;
-
- private final TypeSerializer<K> keySerializer;
- private final TypeSerializer<N> namespaceSerializer;
- private final TypeSerializer<V> valueSerializer;
- private final ValueStateDescriptor<V> stateDesc;
-
- // ------------------------------------------------------
-
- // Max number of retries for failed database operations
- private final int numSqlRetries;
- // Sleep time between two retries
- private final int sqlRetrySleep;
- // Max number of key-value pairs inserted in one batch to the database
- private final int maxInsertBatchSize;
- // We will do database compaction every so many checkpoints
- private final int compactEvery;
- // Executor for automatic compactions
- private ExecutorService executor = null;
-
- // Database properties
- private final DbBackendConfig conf;
- private final ShardedConnection connections;
- private final DbAdapter dbAdapter;
-
- // Convenience object for handling inserts to the database
- private final BatchInserter batchInsert;
-
- // Statements for key-lookups and inserts as prepared by the dbAdapter
- private ShardedStatement selectStatements;
- private ShardedStatement insertStatements;
-
- // ------------------------------------------------------
-
- // LRU cache for the key-value states backed by the database
- private final StateCache cache;
-
- private long nextTs;
- private Map<Long, Long> completedCheckpoints = new HashMap<>();
-
- private volatile long lastCompactedTs;
-
- // ------------------------------------------------------
-
- /**
- * Constructor to initialize the {@link LazyDbValueState} the first time the
- * job starts.
- */
- public LazyDbValueState(String kvStateId,
- boolean compact,
- ShardedConnection cons,
- DbBackendConfig conf,
- TypeSerializer<K> keySerializer,
- TypeSerializer<N> namespaceSerializer,
- ValueStateDescriptor<V> stateDesc) throws IOException {
- this(kvStateId, compact, cons, conf, keySerializer, namespaceSerializer, stateDesc, 1, 0);
- }
-
- /**
- * Initialize the {@link LazyDbValueState} from a snapshot.
- */
- public LazyDbValueState(String kvStateId,
- boolean compact,
- ShardedConnection cons,
- final DbBackendConfig conf,
- TypeSerializer<K> keySerializer,
- TypeSerializer<N> namespaceSerializer,
- ValueStateDescriptor<V> stateDesc,
- long nextTs,
- long lastCompactedTs) throws IOException {
-
- this.kvStateId = kvStateId;
- this.compact = compact;
- if (compact) {
- // Compactions will run in a seperate thread
- executor = Executors.newSingleThreadExecutor();
- }
-
- this.keySerializer = keySerializer;
- this.namespaceSerializer = namespaceSerializer;
- this.valueSerializer = stateDesc.getSerializer();
- this.defaultValue = stateDesc.getDefaultValue();
- this.stateDesc = stateDesc;
-
- this.maxInsertBatchSize = conf.getMaxKvInsertBatchSize();
- this.conf = conf;
- this.connections = cons;
- this.dbAdapter = conf.getDbAdapter();
- this.compactEvery = conf.getKvStateCompactionFrequency();
- this.numSqlRetries = conf.getMaxNumberOfSqlRetries();
- this.sqlRetrySleep = conf.getSleepBetweenSqlRetries();
-
- this.nextTs = nextTs;
- this.lastCompactedTs = lastCompactedTs;
-
- this.cache = new StateCache(conf.getKvCacheSize(), conf.getNumElementsToEvict());
-
- initDB(this.connections);
-
- batchInsert = new BatchInserter(connections.getNumShards());
-
- if (LOG.isDebugEnabled()) {
- LOG.debug("Lazy database kv-state ({}) successfully initialized", kvStateId);
- }
- }
-
- @Override
- public void setCurrentKey(K key) {
- this.currentKey = key;
- }
-
- @Override
- public void setCurrentNamespace(N namespace) {
- this.currentNamespace = namespace;
- }
-
- @Override
- public void update(V value) throws IOException {
- try {
- cache.put(Tuple2.of(currentKey, currentNamespace), Optional.fromNullable(value));
- } catch (RuntimeException e) {
- // We need to catch the RuntimeExceptions thrown in the StateCache
- // methods here
- throw new IOException(e);
- }
- }
-
- @Override
- public V value() throws IOException {
- try {
- // We get the value from the cache (which will automatically load it
- // from the database if necessary). If null, we return a copy of the
- // default value
- V val = cache.get(Tuple2.of(currentKey, currentNamespace)).orNull();
- return val != null ? val : copyDefault();
- } catch (RuntimeException e) {
- // We need to catch the RuntimeExceptions thrown in the StateCache
- // methods here
- throw new IOException(e);
- }
- }
-
- @Override
- public void clear() {
- cache.put(Tuple2.of(currentKey, currentNamespace), Optional.<V>fromNullable(null));
- }
-
- @Override
- public DbKvStateSnapshot<K, N, V> snapshot(long checkpointId, long timestamp) throws IOException {
-
- // Validate timing assumptions
- if (timestamp <= nextTs) {
- throw new RuntimeException("Checkpoint timestamp is smaller than previous ts + 1, "
- + "this should not happen.");
- }
-
- // If there are any modified states we perform the inserts
- if (!cache.modified.isEmpty()) {
- // We insert the modified elements to the database with the current
- // timestamp then clear the modified states
- for (Entry<Tuple2<K, N>, Optional<V>> state : cache.modified.entrySet()) {
- batchInsert.add(state, timestamp);
- }
- batchInsert.flush(timestamp);
- cache.modified.clear();
- } else if (compact) {
- // Otherwise we call the keep alive method to avoid dropped
- // connections (only call this on the compactor instance)
- for (final Connection c : connections.connections()) {
- SQLRetrier.retry(new Callable<Void>() {
- @Override
- public Void call() throws Exception {
- dbAdapter.keepAlive(c);
- return null;
- }
- }, numSqlRetries, sqlRetrySleep);
- }
- }
-
- nextTs = timestamp + 1;
- completedCheckpoints.put(checkpointId, timestamp);
- return new DbKvStateSnapshot<K, N, V>(kvStateId, timestamp, lastCompactedTs, namespaceSerializer, stateDesc);
- }
-
- /**
- * Returns the number of elements currently stored in the task's cache. Note
- * that the number of elements in the database is not counted here.
- */
- public int size() {
- return cache.size();
- }
-
- /**
- * Return a copy the default value or null if the default was null.
- *
- */
- private V copyDefault() {
- return defaultValue != null ? valueSerializer.copy(defaultValue) : null;
- }
-
- /**
- * Create a table for the kvstate checkpoints (based on the kvStateId) and
- * prepare the statements used during checkpointing.
- */
- private void initDB(final ShardedConnection cons) throws IOException {
-
- retry(new Callable<Void>() {
- public Void call() throws Exception {
-
- for (Connection con : cons.connections()) {
- dbAdapter.createKVStateTable(kvStateId, con);
- }
-
- insertStatements = cons.prepareStatement(dbAdapter.prepareKVCheckpointInsert(kvStateId));
- selectStatements = cons.prepareStatement(dbAdapter.prepareKeyLookup(kvStateId));
-
- return null;
- }
-
- }, numSqlRetries, sqlRetrySleep);
- }
-
- @Override
- public void notifyCheckpointComplete(long checkpointId) {
- final Long ts = completedCheckpoints.remove(checkpointId);
- if (ts == null) {
- LOG.warn("Complete notification for missing checkpoint: " + checkpointId);
- } else {
- // If compaction is turned on we compact on the compactor subtask
- // asynchronously in the background
- if (compactEvery > 0 && compact && checkpointId % compactEvery == 0) {
- executor.execute(new Compactor(ts));
- }
- }
- }
-
- @Override
- public void dispose() {
- // We are only closing the statements here, the connection is borrowed
- // from the state backend and will be closed there.
- try {
- selectStatements.close();
- } catch (SQLException e) {
- // There is not much to do about this
- }
- try {
- insertStatements.close();
- } catch (SQLException e) {
- // There is not much to do about this
- }
-
- if (executor != null) {
- executor.shutdown();
- }
- }
-
- /**
- * Return the Map of cached states.
- *
- */
- public Map<Tuple2<K, N>, Optional<V>> getStateCache() {
- return cache;
- }
-
- /**
- * Return the Map of modified states that hasn't been written to the
- * database yet.
- *
- */
- public Map<Tuple2<K, N>, Optional<V>> getModified() {
- return cache.modified;
- }
-
- /**
- * Used for testing purposes
- */
- public boolean isCompactor() {
- return compact;
- }
-
- /**
- * Used for testing purposes
- */
- public ExecutorService getExecutor() {
- return executor;
- }
-
- /**
- * Snapshot that stores a specific checkpoint timestamp and state id, and
- * also rolls back the database to that point upon restore. The rollback is
- * done by removing all state checkpoints that have timestamps between the
- * checkpoint and recovery timestamp.
- *
- */
- private static class DbKvStateSnapshot<K, N, V> implements KvStateSnapshot<K, N, ValueState<V>, ValueStateDescriptor<V>, DbStateBackend> {
-
- private static final long serialVersionUID = 1L;
-
- private final String kvStateId;
- private final long checkpointTimestamp;
- private final long lastCompactedTimestamp;
-
- /** Namespace Serializer */
- private final TypeSerializer<N> namespaceSerializer;
-
- /** StateDescriptor, for sanity checks */
- private final ValueStateDescriptor<V> stateDesc;
-
- public DbKvStateSnapshot(String kvStateId,
- long checkpointTimestamp,
- long lastCompactedTs,
- TypeSerializer<N> namespaceSerializer,
- ValueStateDescriptor<V> stateDesc) {
- this.checkpointTimestamp = checkpointTimestamp;
- this.kvStateId = kvStateId;
- this.lastCompactedTimestamp = lastCompactedTs;
- this.namespaceSerializer = namespaceSerializer;
- this.stateDesc = stateDesc;
- }
-
- @Override
- public KvState<K, N, ValueState<V>, ValueStateDescriptor<V>, DbStateBackend> restoreState(
- final DbStateBackend stateBackend,
- TypeSerializer<K> keySerializer,
- ClassLoader classLoader,
- final long recoveryTimestamp) throws Exception {
-
- // Validate timing assumptions
- if (recoveryTimestamp <= checkpointTimestamp) {
- throw new RuntimeException(
- "Recovery timestamp is smaller or equal to checkpoint timestamp. "
- + "This might happen if the job was started with a new JobManager "
- + "and the clocks got really out of sync.");
- }
-
- // First we clean up the states written by partially failed
- // snapshots
- retry(new Callable<Void>() {
- public Void call() throws Exception {
-
- // We need to perform cleanup on all shards to be safe here
- for (Connection c : stateBackend.getConnections().connections()) {
- stateBackend.getConfiguration().getDbAdapter().cleanupFailedCheckpoints(kvStateId,
- c, checkpointTimestamp, recoveryTimestamp);
- }
-
- return null;
- }
- }, stateBackend.getConfiguration().getMaxNumberOfSqlRetries(),
- stateBackend.getConfiguration().getSleepBetweenSqlRetries());
-
- boolean cleanup = stateBackend.getEnvironment().getTaskInfo().getIndexOfThisSubtask() == 0;
-
- // Restore the KvState
- LazyDbValueState<K, N, V> restored = new LazyDbValueState<>(kvStateId,
- cleanup,
- stateBackend.getConnections(),
- stateBackend.getConfiguration(),
- keySerializer,
- namespaceSerializer,
- stateDesc,
- recoveryTimestamp,
- lastCompactedTimestamp);
-
- if (LOG.isDebugEnabled()) {
- LOG.debug("KV state({},{}) restored.", kvStateId, recoveryTimestamp);
- }
-
- return restored;
- }
-
- @Override
- public void discardState() throws Exception {
- // Don't discard, it will be compacted by the LazyDbKvState
- }
-
- @Override
- public long getStateSize() throws Exception {
- // Because the state is serialzied in a lazy fashion we don't know
- // the size of the state yet.
- return 0;
- }
-
- }
-
- /**
- * LRU cache implementation for storing the key-value states. When the cache
- * is full elements are not evicted one by one but are evicted in a batch
- * defined by the evictionSize parameter.
- * <p>
- * Keys not found in the cached will be retrieved from the underlying
- * database
- */
- private final class StateCache extends LinkedHashMap<Tuple2<K, N>, Optional<V>> {
- private static final long serialVersionUID = 1L;
-
- private final int cacheSize;
- private final int evictionSize;
-
- // We keep track the state modified since the last checkpoint
- private final Map<Tuple2<K, N>, Optional<V>> modified = new HashMap<>();
-
- public StateCache(int cacheSize, int evictionSize) {
- super(cacheSize, 0.75f, true);
- this.cacheSize = cacheSize;
- this.evictionSize = evictionSize;
- }
-
- @Override
- public Optional<V> put(Tuple2<K, N> key, Optional<V> value) {
- // Put kv pair in the cache and evict elements if the cache is full
- Optional<V> old = super.put(key, value);
- modified.put(key, value);
- evictIfFull();
- return old;
- }
-
- @SuppressWarnings("unchecked")
- @Override
- public Optional<V> get(Object key) {
- // First we check whether the value is cached
- Optional<V> value = super.get(key);
- if (value == null) {
- // If it doesn't try to load it from the database
- value = Optional.fromNullable(getFromDatabaseOrNull((Tuple2<K, N>) key));
- put((Tuple2<K, N>) key, value);
- }
- return value;
- }
-
- @Override
- protected boolean removeEldestEntry(Entry<Tuple2<K, N>, Optional<V>> eldest) {
- // We need to remove elements manually if the cache becomes full, so
- // we always return false here.
- return false;
- }
-
- /**
- * Fetch the current value from the database if exists or return null.
- *
- * @param key
- * @return The value corresponding to the key and the last checkpointid
- * from the database if exists or null.
- */
- private V getFromDatabaseOrNull(final Tuple2<K, N> key) {
- try {
- return retry(new Callable<V>() {
- public V call() throws Exception {
- ByteArrayOutputStream baos = new ByteArrayOutputStream();
- DataOutputViewStreamWrapper out = new DataOutputViewStreamWrapper(baos);
- keySerializer.serialize(key.f0, out);
- namespaceSerializer.serialize(key.f1, out);
- out.close();
-
- // We lookup using the adapter and serialize/deserialize
- // with the TypeSerializers
- byte[] serializedVal = dbAdapter.lookupKey(kvStateId,
- selectStatements.getForKey(key.f0), baos.toByteArray(), nextTs);
-
- return serializedVal != null
- ? InstantiationUtil.deserializeFromByteArray(valueSerializer, serializedVal) : null;
- }
- }, numSqlRetries, sqlRetrySleep);
- } catch (IOException e) {
- // We need to re-throw this exception to conform to the map
- // interface, we will catch this when we call the the put/get
- throw new RuntimeException(e);
- }
- }
-
- /**
- * If the cache is full we remove the evictionSize least recently
- * accessed elements and write them to the database if they were
- * modified since the last checkpoint.
- */
- private void evictIfFull() {
- if (size() > cacheSize) {
- if (LOG.isDebugEnabled()) {
- LOG.debug("State cache is full for {}, evicting {} elements.", kvStateId, evictionSize);
- }
- try {
- int numEvicted = 0;
-
- Iterator<Entry<Tuple2<K, N>, Optional<V>>> entryIterator = entrySet().iterator();
- while (numEvicted++ < evictionSize && entryIterator.hasNext()) {
-
- Entry<Tuple2<K, N>, Optional<V>> next = entryIterator.next();
-
- // We only need to write to the database if modified
- if (modified.remove(next.getKey()) != null) {
- batchInsert.add(next, nextTs);
- }
-
- entryIterator.remove();
- }
-
- batchInsert.flush(nextTs);
-
- } catch (IOException e) {
- // We need to re-throw this exception to conform to the map
- // interface, we will catch this when we call the the
- // put/get
- throw new RuntimeException(e);
- }
- }
- }
-
- @Override
- public void putAll(Map<? extends Tuple2<K, N>, ? extends Optional<V>> m) {
- throw new UnsupportedOperationException();
- }
-
- @Override
- public void clear() {
- throw new UnsupportedOperationException();
- }
- }
-
- /**
- * Object for handling inserts to the database by batching them together
- * partitioned on the sharding key. The batches are written to the database
- * when they are full or when the inserter is flushed.
- *
- */
- private class BatchInserter {
-
- // Map from shard index to the kv pairs to be inserted
- // Map<Integer, List<Tuple2<byte[], byte[]>>> inserts = new HashMap<>();
-
- List<Tuple2<byte[], byte[]>>[] inserts;
-
- @SuppressWarnings("unchecked")
- public BatchInserter(int numShards) {
- inserts = new List[numShards];
- for (int i = 0; i < numShards; i++) {
- inserts[i] = new ArrayList<>();
- }
- }
-
- public void add(Entry<Tuple2<K, N>, Optional<V>> next, long timestamp) throws IOException {
-
- K key = next.getKey().f0;
- N namespace = next.getKey().f1;
- V value = next.getValue().orNull();
-
- // Get the current partition if present or initialize empty list
- int shardIndex = connections.getShardIndex(key);
-
- List<Tuple2<byte[], byte[]>> insertPartition = inserts[shardIndex];
-
- // Add the k-v pair to the partition
- ByteArrayOutputStream baos = new ByteArrayOutputStream();
- DataOutputViewStreamWrapper out = new DataOutputViewStreamWrapper(baos);
- keySerializer.serialize(key, out);
- namespaceSerializer.serialize(namespace, out);
- out.close();
-
- byte[] kn = baos.toByteArray();
- byte[] v = value != null ? InstantiationUtil.serializeToByteArray(valueSerializer, value) : null;
- insertPartition.add(Tuple2.of(kn, v));
-
- // If partition is full write to the database and clear
- if (insertPartition.size() == maxInsertBatchSize) {
- dbAdapter.insertBatch(kvStateId, conf,
- connections.getForIndex(shardIndex),
- insertStatements.getForIndex(shardIndex),
- timestamp, insertPartition);
-
- insertPartition.clear();
- }
- }
-
- public void flush(long timestamp) throws IOException {
- // We flush all non-empty partitions
- for (int i = 0; i < inserts.length; i++) {
- List<Tuple2<byte[], byte[]>> insertPartition = inserts[i];
- if (!insertPartition.isEmpty()) {
- dbAdapter.insertBatch(kvStateId, conf, connections.getForIndex(i),
- insertStatements.getForIndex(i), timestamp, insertPartition);
- insertPartition.clear();
- }
- }
-
- }
- }
-
- private class Compactor implements Runnable {
-
- private long upperBound;
-
- public Compactor(long upperBound) {
- this.upperBound = upperBound;
- }
-
- @Override
- public void run() {
- // We create new database connections to make sure we don't
- // interfere with the checkpointing (connections are not thread
- // safe)
- try (ShardedConnection sc = conf.createShardedConnection()) {
- for (final Connection c : sc.connections()) {
- SQLRetrier.retry(new Callable<Void>() {
- @Override
- public Void call() throws Exception {
- dbAdapter.compactKvStates(kvStateId, c, lastCompactedTs, upperBound);
- return null;
- }
- }, numSqlRetries, sqlRetrySleep);
- }
- if (LOG.isInfoEnabled()) {
- LOG.info("State succesfully compacted for {} between {} and {}.", kvStateId,
- lastCompactedTs,
- upperBound);
- }
- lastCompactedTs = upperBound;
- } catch (SQLException | IOException e) {
- LOG.warn("State compaction failed due: {}", e);
- }
- }
-
- }
-}
http://git-wip-us.apache.org/repos/asf/flink/blob/33f43114/flink-contrib/flink-streaming-contrib/src/main/java/org/apache/flink/contrib/streaming/state/MySqlAdapter.java
----------------------------------------------------------------------
diff --git a/flink-contrib/flink-streaming-contrib/src/main/java/org/apache/flink/contrib/streaming/state/MySqlAdapter.java b/flink-contrib/flink-streaming-contrib/src/main/java/org/apache/flink/contrib/streaming/state/MySqlAdapter.java
deleted file mode 100644
index 7c71b51..0000000
--- a/flink-contrib/flink-streaming-contrib/src/main/java/org/apache/flink/contrib/streaming/state/MySqlAdapter.java
+++ /dev/null
@@ -1,245 +0,0 @@
-/*
- * 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.contrib.streaming.state;
-
-import java.io.IOException;
-import java.sql.Connection;
-import java.sql.PreparedStatement;
-import java.sql.ResultSet;
-import java.sql.SQLException;
-import java.sql.Statement;
-import java.sql.Types;
-import java.util.List;
-import java.util.concurrent.Callable;
-
-import org.apache.flink.api.java.tuple.Tuple2;
-
-/**
- *
- * Adapter for bridging inconsistencies between the different SQL
- * implementations. The default implementation has been tested to work well with
- * MySQL
- *
- */
-public class MySqlAdapter implements DbAdapter {
-
- private static final long serialVersionUID = 1L;
-
- // -----------------------------------------------------------------------------
- // Non-partitioned state checkpointing
- // -----------------------------------------------------------------------------
-
- @Override
- public void createCheckpointsTable(String jobId, Connection con) throws SQLException {
- try (Statement smt = con.createStatement()) {
- smt.executeUpdate(
- "CREATE TABLE IF NOT EXISTS checkpoints_" + jobId
- + " ("
- + "checkpointId bigint, "
- + "timestamp bigint, "
- + "handleId bigint,"
- + "checkpoint blob,"
- + "PRIMARY KEY (handleId)"
- + ")");
- }
-
- }
-
- @Override
- public PreparedStatement prepareCheckpointInsert(String jobId, Connection con) throws SQLException {
- return con.prepareStatement(
- "INSERT INTO checkpoints_" + jobId
- + " (checkpointId, timestamp, handleId, checkpoint) VALUES (?,?,?,?)");
- }
-
- @Override
- public void setCheckpointInsertParams(String jobId, PreparedStatement insertStatement, long checkpointId,
- long timestamp, long handleId, byte[] checkpoint) throws SQLException {
- insertStatement.setLong(1, checkpointId);
- insertStatement.setLong(2, timestamp);
- insertStatement.setLong(3, handleId);
- insertStatement.setBytes(4, checkpoint);
- }
-
- @Override
- public byte[] getCheckpoint(String jobId, Connection con, long checkpointId, long checkpointTs, long handleId)
- throws SQLException {
- try (Statement smt = con.createStatement()) {
- ResultSet rs = smt.executeQuery(
- "SELECT checkpoint FROM checkpoints_" + jobId
- + " WHERE handleId = " + handleId);
- if (rs.next()) {
- return rs.getBytes(1);
- } else {
- throw new SQLException("Checkpoint cannot be found in the database.");
- }
- }
- }
-
- @Override
- public void deleteCheckpoint(String jobId, Connection con, long checkpointId, long checkpointTs, long handleId)
- throws SQLException {
- try (Statement smt = con.createStatement()) {
- smt.executeUpdate(
- "DELETE FROM checkpoints_" + jobId
- + " WHERE handleId = " + handleId);
- }
- }
-
- @Override
- public void disposeAllStateForJob(String jobId, Connection con) throws SQLException {
- try (Statement smt = con.createStatement()) {
- smt.executeUpdate(
- "DROP TABLE checkpoints_" + jobId);
- }
- }
-
- // -----------------------------------------------------------------------------
- // Partitioned state checkpointing
- // -----------------------------------------------------------------------------
-
- @Override
- public void createKVStateTable(String stateId, Connection con) throws SQLException {
- validateStateId(stateId);
- try (Statement smt = con.createStatement()) {
- smt.executeUpdate(
- "CREATE TABLE IF NOT EXISTS " + stateId
- + " ("
- + "timestamp bigint, "
- + "k varbinary(256), "
- + "v blob, "
- + "PRIMARY KEY (k, timestamp) "
- + ")");
- }
- }
-
- @Override
- public String prepareKVCheckpointInsert(String stateId) throws SQLException {
- validateStateId(stateId);
- return "INSERT INTO " + stateId + " (timestamp, k, v) VALUES (?,?,?) "
- + "ON DUPLICATE KEY UPDATE v=? ";
- }
-
- @Override
- public String prepareKeyLookup(String stateId) throws SQLException {
- validateStateId(stateId);
- return "SELECT v"
- + " FROM " + stateId
- + " WHERE k = ?"
- + " AND timestamp <= ?"
- + " ORDER BY timestamp DESC LIMIT 1";
- }
-
- @Override
- public byte[] lookupKey(String stateId, PreparedStatement lookupStatement, byte[] key, long lookupTs)
- throws SQLException {
- lookupStatement.setBytes(1, key);
- lookupStatement.setLong(2, lookupTs);
-
- ResultSet res = lookupStatement.executeQuery();
-
- if (res.next()) {
- return res.getBytes(1);
- } else {
- return null;
- }
- }
-
- @Override
- public void cleanupFailedCheckpoints(String stateId, Connection con, long checkpointTs,
- long recoveryTs) throws SQLException {
- validateStateId(stateId);
- try (Statement smt = con.createStatement()) {
- smt.executeUpdate("DELETE FROM " + stateId
- + " WHERE timestamp > " + checkpointTs
- + " AND timestamp < " + recoveryTs);
- }
- }
-
- @Override
- public void compactKvStates(String stateId, Connection con, long lowerId, long upperId)
- throws SQLException {
- validateStateId(stateId);
-
- try (Statement smt = con.createStatement()) {
- smt.executeUpdate("DELETE state.* FROM " + stateId + " AS state"
- + " JOIN"
- + " ("
- + " SELECT MAX(timestamp) AS maxts, k FROM " + stateId
- + " WHERE timestamp BETWEEN " + lowerId + " AND " + upperId
- + " GROUP BY k"
- + " ) m"
- + " ON state.k = m.k"
- + " AND state.timestamp >= " + lowerId);
- }
- }
-
- /**
- * Tries to avoid SQL injection with weird state names.
- *
- */
- protected static void validateStateId(String name) {
- if (!name.matches("[a-zA-Z0-9_]+")) {
- throw new RuntimeException("State name contains invalid characters: " + name);
- }
- }
-
- @Override
- public void insertBatch(final String stateId, final DbBackendConfig conf,
- final Connection con, final PreparedStatement insertStatement, final long checkpointTs,
- final List<Tuple2<byte[], byte[]>> toInsert) throws IOException {
-
- SQLRetrier.retry(new Callable<Void>() {
- public Void call() throws Exception {
- for (Tuple2<byte[], byte[]> kv : toInsert) {
- setKvInsertParams(stateId, insertStatement, checkpointTs, kv.f0, kv.f1);
- insertStatement.addBatch();
- }
- insertStatement.executeBatch();
- insertStatement.clearBatch();
- return null;
- }
- }, new Callable<Void>() {
- public Void call() throws Exception {
- insertStatement.clearBatch();
- return null;
- }
- }, conf.getMaxNumberOfSqlRetries(), conf.getSleepBetweenSqlRetries());
- }
-
- private void setKvInsertParams(String stateId, PreparedStatement insertStatement, long checkpointTs,
- byte[] key, byte[] value) throws SQLException {
- insertStatement.setLong(1, checkpointTs);
- insertStatement.setBytes(2, key);
- if (value != null) {
- insertStatement.setBytes(3, value);
- insertStatement.setBytes(4, value);
- } else {
- insertStatement.setNull(3, Types.BLOB);
- insertStatement.setNull(4, Types.BLOB);
- }
- }
-
- @Override
- public void keepAlive(Connection con) throws SQLException {
- try(Statement smt = con.createStatement()) {
- smt.executeQuery("SELECT 1");
- }
- }
-
-}
http://git-wip-us.apache.org/repos/asf/flink/blob/33f43114/flink-contrib/flink-streaming-contrib/src/main/java/org/apache/flink/contrib/streaming/state/SQLRetrier.java
----------------------------------------------------------------------
diff --git a/flink-contrib/flink-streaming-contrib/src/main/java/org/apache/flink/contrib/streaming/state/SQLRetrier.java b/flink-contrib/flink-streaming-contrib/src/main/java/org/apache/flink/contrib/streaming/state/SQLRetrier.java
deleted file mode 100644
index 4ae3fd2..0000000
--- a/flink-contrib/flink-streaming-contrib/src/main/java/org/apache/flink/contrib/streaming/state/SQLRetrier.java
+++ /dev/null
@@ -1,176 +0,0 @@
-/*
- * 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.contrib.streaming.state;
-
-import java.io.IOException;
-import java.io.Serializable;
-import java.sql.SQLException;
-import java.util.Random;
-import java.util.concurrent.Callable;
-
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-/**
- * Simple utility to retry failed SQL commands for a predefined number of times
- * before declaring failure. The retrier waits (randomly) between 2 retries.
- *
- */
-public final class SQLRetrier implements Serializable {
- private static final long serialVersionUID = 1L;
-
- private static final Logger LOG = LoggerFactory.getLogger(SQLRetrier.class);
- private static final Random rnd = new Random();
-
- private static final int SLEEP_TIME = 10;
-
- private SQLRetrier() {
-
- }
-
- /**
- * Tries to run the given {@link Callable} the predefined number of times
- * before throwing an {@link IOException}. This method will only retries
- * calls ending in {@link SQLException}. Other exceptions will cause a
- * {@link RuntimeException}.
- *
- * @param callable
- * The callable to be retried.
- * @param numRetries
- * Max number of retries before throwing an {@link IOException}.
- * @throws IOException
- * The wrapped {@link SQLException}.
- */
- public static <X> X retry(Callable<X> callable, int numRetries) throws IOException {
- return retry(callable, numRetries, SLEEP_TIME);
- }
-
- /**
- * Tries to run the given {@link Callable} the predefined number of times
- * before throwing an {@link IOException}. This method will only retries
- * calls ending in {@link SQLException}. Other exceptions will cause a
- * {@link RuntimeException}.
- *
- * @param callable
- * The callable to be retried.
- * @param numRetries
- * Max number of retries before throwing an {@link IOException}.
- * @param sleep
- * The retrier will wait a random number of msecs between 1 and
- * sleep.
- * @return The result of the {@link Callable#call()}.
- * @throws IOException
- * The wrapped {@link SQLException}.
- */
- public static <X> X retry(Callable<X> callable, int numRetries, int sleep) throws IOException {
- int numtries = 0;
- while (true) {
- try {
- return callable.call();
- } catch (SQLException e) {
- handleSQLException(e, ++numtries, numRetries, sleep);
- } catch (Exception e) {
- throw new RuntimeException(e);
- }
- }
- }
-
- /**
- * Tries to run the given {@link Callable} the predefined number of times
- * before throwing an {@link IOException}. This method will only retries
- * calls ending in {@link SQLException}. Other exceptions will cause a
- * {@link RuntimeException}.
- *
- * Additionally the user can supply a second callable which will be executed
- * every time the first callable throws a {@link SQLException}.
- *
- * @param callable
- * The callable to be retried.
- * @param onException
- * The callable to be executed when an {@link SQLException} was
- * encountered. Exceptions thrown during this call are ignored.
- * @param numRetries
- * Max number of retries before throwing an {@link IOException}.
- * @param sleep
- * The retrier will wait a random number of msecs between 1 and
- * sleep.
- * @return The result of the {@link Callable#call()}.
- * @throws IOException
- * The wrapped {@link SQLException}.
- */
- public static <X, Y> X retry(Callable<X> callable, Callable<Y> onException, int numRetries, int sleep)
- throws IOException {
- int numtries = 0;
- while (true) {
- try {
- return callable.call();
- } catch (SQLException se) {
- try {
- onException.call();
- } catch (Exception e) {
- // Exceptions thrown in this call will be ignored
- }
- handleSQLException(se, ++numtries, numRetries, sleep);
- } catch (Exception ex) {
- throw new RuntimeException(ex);
- }
- }
- }
-
- /**
- * Tries to run the given {@link Callable} the predefined number of times
- * before throwing an {@link IOException}. This method will only retries
- * calls ending in {@link SQLException}. Other exceptions will cause a
- * {@link RuntimeException}.
- *
- * Additionally the user can supply a second callable which will be executed
- * every time the first callable throws a {@link SQLException}.
- *
- * @param callable
- * The callable to be retried.
- * @param onException
- * The callable to be executed when an {@link SQLException} was
- * encountered. Exceptions thrown during this call are ignored.
- * @param numRetries
- * Max number of retries before throwing an {@link IOException}.
- * @return The result of the {@link Callable#call()}.
- * @throws IOException
- * The wrapped {@link SQLException}.
- */
- public static <X, Y> X retry(Callable<X> callable, Callable<Y> onException, int numRetries)
- throws IOException {
- return retry(callable, onException, numRetries, SLEEP_TIME);
- }
-
- private static void handleSQLException(SQLException e, int numTries, int maxRetries, int sleep) throws IOException {
- if (numTries < maxRetries) {
- if (LOG.isDebugEnabled()) {
- LOG.debug("Error while executing SQL statement: {}\nRetrying...",
- e.getMessage());
- }
- try {
- Thread.sleep(numTries * rnd.nextInt(sleep));
- } catch (InterruptedException ie) {
- throw new RuntimeException("Thread has been interrupted.");
- }
- } else {
- throw new IOException(
- "Could not execute SQL statement after " + maxRetries + " retries.", e);
- }
- }
-}
http://git-wip-us.apache.org/repos/asf/flink/blob/33f43114/flink-contrib/flink-streaming-contrib/src/main/java/org/apache/flink/contrib/streaming/state/ShardedConnection.java
----------------------------------------------------------------------
diff --git a/flink-contrib/flink-streaming-contrib/src/main/java/org/apache/flink/contrib/streaming/state/ShardedConnection.java b/flink-contrib/flink-streaming-contrib/src/main/java/org/apache/flink/contrib/streaming/state/ShardedConnection.java
deleted file mode 100644
index 44995de..0000000
--- a/flink-contrib/flink-streaming-contrib/src/main/java/org/apache/flink/contrib/streaming/state/ShardedConnection.java
+++ /dev/null
@@ -1,153 +0,0 @@
-/*
- * 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.contrib.streaming.state;
-
-import java.io.Serializable;
-import java.sql.Connection;
-import java.sql.DriverManager;
-import java.sql.PreparedStatement;
-import java.sql.SQLException;
-import java.util.List;
-
-/**
- * Helper class to maintain a sharded database connection and get
- * {@link Connection}s and {@link PreparedStatement}s for keys.
- *
- */
-public class ShardedConnection implements AutoCloseable, Serializable {
-
- private static final long serialVersionUID = 1L;
- private final Connection[] connections;
- private final int numShards;
-
- private final Partitioner partitioner;
-
- public ShardedConnection(List<String> shardUrls, String user, String password, Partitioner partitioner)
- throws SQLException {
- numShards = shardUrls.size();
- connections = new Connection[numShards];
- for (int i = 0; i < numShards; i++) {
- connections[i] = DriverManager.getConnection(shardUrls.get(i), user, password);
- }
- this.partitioner = partitioner;
- }
-
- public ShardedConnection(List<String> shardUrls, String user, String password) throws SQLException {
- this(shardUrls, user, password, new ModHashPartitioner());
- }
-
- public ShardedStatement prepareStatement(String sql) throws SQLException {
- return new ShardedStatement(sql);
- }
-
- public Connection[] connections() {
- return connections;
- }
-
- public Connection getForKey(Object key) {
- return connections[getShardIndex(key)];
- }
-
- public Connection getForIndex(int index) {
- if (index < numShards) {
- return connections[index];
- } else {
- throw new RuntimeException("Index out of range");
- }
- }
-
- public Connection getFirst() {
- return connections[0];
- }
-
- public int getNumShards() {
- return numShards;
- }
-
- @Override
- public void close() throws SQLException {
- if (connections != null) {
- for (Connection c : connections) {
- c.close();
- }
- }
- }
-
- public int getShardIndex(Object key) {
- return partitioner.getShardIndex(key, numShards);
- }
-
- public void setTransactionIsolation(int level) throws SQLException {
- for (Connection con : connections) {
- con.setTransactionIsolation(level);
- }
- }
-
- public class ShardedStatement implements AutoCloseable, Serializable {
-
- private static final long serialVersionUID = 1L;
- private final PreparedStatement[] statements = new PreparedStatement[numShards];
-
- public ShardedStatement(final String sql) throws SQLException {
- for (int i = 0; i < numShards; i++) {
- statements[i] = connections[i].prepareStatement(sql);
- }
- }
-
- public PreparedStatement getForKey(Object key) {
- return statements[getShardIndex(key)];
- }
-
- public PreparedStatement getForIndex(int index) {
- if (index < numShards) {
- return statements[index];
- } else {
- throw new RuntimeException("Index out of range");
- }
- }
-
- public PreparedStatement getFirst() {
- return statements[0];
- }
-
- @Override
- public void close() throws SQLException {
- if (statements != null) {
- for (PreparedStatement t : statements) {
- t.close();
- }
- }
- }
-
- }
-
- public interface Partitioner extends Serializable {
- int getShardIndex(Object key, int numShards);
- }
-
- public static class ModHashPartitioner implements Partitioner {
-
- private static final long serialVersionUID = 1L;
-
- @Override
- public int getShardIndex(Object key, int numShards) {
- return Math.abs(key.hashCode() % numShards);
- }
-
- }
-}