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:21 UTC
[1/2] flink git commit: [FLINK-3620] [streaming] Remove DbStateBackend
Repository: flink
Updated Branches:
refs/heads/master 40d5205bc -> 33f43114d
http://git-wip-us.apache.org/repos/asf/flink/blob/33f43114/flink-contrib/flink-streaming-contrib/src/test/java/org/apache/flink/contrib/streaming/state/DBStateCheckpointingTest.java
----------------------------------------------------------------------
diff --git a/flink-contrib/flink-streaming-contrib/src/test/java/org/apache/flink/contrib/streaming/state/DBStateCheckpointingTest.java b/flink-contrib/flink-streaming-contrib/src/test/java/org/apache/flink/contrib/streaming/state/DBStateCheckpointingTest.java
deleted file mode 100644
index cc2147f..0000000
--- a/flink-contrib/flink-streaming-contrib/src/test/java/org/apache/flink/contrib/streaming/state/DBStateCheckpointingTest.java
+++ /dev/null
@@ -1,258 +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.junit.Assert.assertEquals;
-
-import java.io.File;
-import java.io.IOException;
-import java.net.InetAddress;
-import java.net.UnknownHostException;
-import java.util.Map;
-import java.util.Map.Entry;
-import java.util.Random;
-import java.util.UUID;
-import java.util.concurrent.ConcurrentHashMap;
-
-import org.apache.commons.io.FileUtils;
-
-import org.apache.derby.drda.NetworkServerControl;
-
-import org.apache.flink.api.common.functions.RichMapFunction;
-import org.apache.flink.api.common.state.ValueState;
-import org.apache.flink.api.common.state.ValueStateDescriptor;
-import org.apache.flink.api.java.tuple.Tuple2;
-import org.apache.flink.configuration.ConfigConstants;
-import org.apache.flink.configuration.Configuration;
-import org.apache.flink.runtime.state.memory.MemoryStateBackend;
-import org.apache.flink.streaming.api.checkpoint.Checkpointed;
-import org.apache.flink.streaming.api.datastream.DataStream;
-import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
-import org.apache.flink.streaming.api.functions.sink.RichSinkFunction;
-import org.apache.flink.streaming.api.functions.source.RichParallelSourceFunction;
-import org.apache.flink.test.checkpointing.PartitionedStateCheckpointingITCase.IdentityKeySelector;
-import org.apache.flink.test.checkpointing.PartitionedStateCheckpointingITCase.NonSerializableLong;
-import org.apache.flink.test.checkpointing.StreamFaultToleranceTestBase;
-
-import org.junit.After;
-import org.junit.Before;
-
-@SuppressWarnings("serial")
-public class DBStateCheckpointingTest extends StreamFaultToleranceTestBase {
-
- final long NUM_STRINGS = 1_000_000L;
- final static int NUM_KEYS = 100;
- private static NetworkServerControl server;
- private static File tempDir;
-
- @Before
- public void startDerbyServer() throws UnknownHostException, Exception {
- server = new NetworkServerControl(InetAddress.getByName("localhost"), 1526, "flink", "flink");
- server.start(null);
- tempDir = new File(ConfigConstants.DEFAULT_TASK_MANAGER_TMP_PATH, UUID.randomUUID().toString());
- // We need to ensure that the Derby server starts properly before
- // beginning the tests
- DbStateBackendTest.ensureServerStarted(server);
- }
-
- @After
- public void stopDerbyServer() {
- try {
- server.shutdown();
- FileUtils.deleteDirectory(new File(tempDir.getAbsolutePath() + "/flinkDB1"));
- FileUtils.forceDelete(new File("derby.log"));
- } catch (Exception ignore) {
- }
- }
-
- @Override
- public void testProgram(StreamExecutionEnvironment env) {
- env.enableCheckpointing(500);
-
- DbBackendConfig conf = new DbBackendConfig("flink", "flink",
- "jdbc:derby://localhost:1526/" + tempDir.getAbsolutePath() + "/flinkDB1;create=true");
- conf.setDbAdapter(new DerbyAdapter());
- conf.setKvStateCompactionFrequency(2);
-
- // We store the non-partitioned states (source offset) in-memory
- DbStateBackend backend = new DbStateBackend(conf, new MemoryStateBackend());
-
- env.setStateBackend(backend);
-
- DataStream<Integer> stream1 = env.addSource(new IntGeneratingSourceFunction(NUM_STRINGS / 2));
- DataStream<Integer> stream2 = env.addSource(new IntGeneratingSourceFunction(NUM_STRINGS / 2));
-
- stream1.union(stream2).keyBy(new IdentityKeySelector<Integer>()).map(new OnceFailingPartitionedSum(NUM_STRINGS))
- .keyBy(0).addSink(new CounterSink());
- }
-
- @Override
- public void postSubmit() {
- // verify that we counted exactly right
- for (Entry<Integer, Long> sum : OnceFailingPartitionedSum.allSums.entrySet()) {
- assertEquals(new Long(sum.getKey() * NUM_STRINGS / NUM_KEYS), sum.getValue());
- }
- for (Long count : CounterSink.allCounts.values()) {
- assertEquals(new Long(NUM_STRINGS / NUM_KEYS), count);
- }
-
- assertEquals(NUM_KEYS, CounterSink.allCounts.size());
- assertEquals(NUM_KEYS, OnceFailingPartitionedSum.allSums.size());
- }
-
- // --------------------------------------------------------------------------------------------
- // Custom Functions
- // --------------------------------------------------------------------------------------------
-
- private static class IntGeneratingSourceFunction extends RichParallelSourceFunction<Integer>
- implements Checkpointed<Integer> {
-
- private final long numElements;
-
- private int index;
- private int step;
-
- private Random rnd = new Random();
-
- private volatile boolean isRunning = true;
-
- static final long[] counts = new long[PARALLELISM];
-
- @Override
- public void close() throws IOException {
- counts[getRuntimeContext().getIndexOfThisSubtask()] = index;
- }
-
- IntGeneratingSourceFunction(long numElements) {
- this.numElements = numElements;
- }
-
- @Override
- public void open(Configuration parameters) throws IOException {
- step = getRuntimeContext().getNumberOfParallelSubtasks();
- if (index == 0) {
- index = getRuntimeContext().getIndexOfThisSubtask();
- }
- }
-
- @Override
- public void run(SourceContext<Integer> ctx) throws Exception {
- final Object lockingObject = ctx.getCheckpointLock();
-
- while (isRunning && index < numElements) {
-
- synchronized (lockingObject) {
- index += step;
- ctx.collect(index % NUM_KEYS);
- }
-
- if (rnd.nextDouble() < 0.008) {
- Thread.sleep(1);
- }
- }
- }
-
- @Override
- public void cancel() {
- isRunning = false;
- }
-
- @Override
- public Integer snapshotState(long checkpointId, long checkpointTimestamp) {
- return index;
- }
-
- @Override
- public void restoreState(Integer state) {
- index = state;
- }
- }
-
- private static class OnceFailingPartitionedSum extends RichMapFunction<Integer, Tuple2<Integer, Long>> {
-
- private static Map<Integer, Long> allSums = new ConcurrentHashMap<>();
-
- private static volatile boolean hasFailed = false;
-
- private final long numElements;
-
- private long failurePos;
- private long count;
-
- private ValueState<Long> sum;
-
- OnceFailingPartitionedSum(long numElements) {
- this.numElements = numElements;
- }
-
- @Override
- public void open(Configuration parameters) throws IOException {
- long failurePosMin = (long) (0.6 * numElements / getRuntimeContext().getNumberOfParallelSubtasks());
- long failurePosMax = (long) (0.8 * numElements / getRuntimeContext().getNumberOfParallelSubtasks());
-
- failurePos = (new Random().nextLong() % (failurePosMax - failurePosMin)) + failurePosMin;
- count = 0;
- sum = getRuntimeContext().getState(
- new ValueStateDescriptor<>("my_state", Long.class, 0L));
- }
-
- @Override
- public Tuple2<Integer, Long> map(Integer value) throws Exception {
- count++;
- if (!hasFailed && count >= failurePos) {
- hasFailed = true;
- throw new Exception("Test Failure");
- }
-
- long currentSum = sum.value() + value;
- sum.update(currentSum);
- allSums.put(value, currentSum);
- return new Tuple2<Integer, Long>(value, currentSum);
- }
- }
-
- private static class CounterSink extends RichSinkFunction<Tuple2<Integer, Long>> {
-
- private static Map<Integer, Long> allCounts = new ConcurrentHashMap<>();
-
- private ValueState<NonSerializableLong> aCounts;
- private ValueState<Long> bCounts;
-
- @Override
- public void open(Configuration parameters) throws IOException {
- aCounts = getRuntimeContext().getState(
- new ValueStateDescriptor<>("a", NonSerializableLong.class, NonSerializableLong.of(0L)));
-
- bCounts = getRuntimeContext().getState(new ValueStateDescriptor<>("b", Long.class, 0L));
- }
-
- @Override
- public void invoke(Tuple2<Integer, Long> value) throws Exception {
- long ac = aCounts.value().value;
- long bc = bCounts.value();
- assertEquals(ac, bc);
-
- long currentCount = ac + 1;
- aCounts.update(NonSerializableLong.of(currentCount));
- bCounts.update(currentCount);
-
- allCounts.put(value.f0, currentCount);
- }
- }
-}
http://git-wip-us.apache.org/repos/asf/flink/blob/33f43114/flink-contrib/flink-streaming-contrib/src/test/java/org/apache/flink/contrib/streaming/state/DbStateBackendTest.java
----------------------------------------------------------------------
diff --git a/flink-contrib/flink-streaming-contrib/src/test/java/org/apache/flink/contrib/streaming/state/DbStateBackendTest.java b/flink-contrib/flink-streaming-contrib/src/test/java/org/apache/flink/contrib/streaming/state/DbStateBackendTest.java
deleted file mode 100644
index adef7db..0000000
--- a/flink-contrib/flink-streaming-contrib/src/test/java/org/apache/flink/contrib/streaming/state/DbStateBackendTest.java
+++ /dev/null
@@ -1,723 +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.File;
-import java.io.IOException;
-import java.net.InetAddress;
-import java.net.UnknownHostException;
-import java.sql.Connection;
-import java.sql.DriverManager;
-import java.sql.ResultSet;
-import java.sql.SQLException;
-import java.sql.Statement;
-import java.util.List;
-import java.util.Map;
-import java.util.UUID;
-import java.util.concurrent.TimeUnit;
-import java.util.concurrent.atomic.AtomicInteger;
-
-import com.google.common.base.Joiner;
-import org.apache.commons.io.FileUtils;
-import org.apache.derby.drda.NetworkServerControl;
-import org.apache.flink.api.common.functions.ReduceFunction;
-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.base.IntSerializer;
-import org.apache.flink.api.common.typeutils.base.StringSerializer;
-import org.apache.flink.api.common.typeutils.base.VoidSerializer;
-import org.apache.flink.api.java.tuple.Tuple2;
-import org.apache.flink.configuration.ConfigConstants;
-import org.apache.flink.core.testutils.CommonTestUtils;
-import org.apache.flink.runtime.execution.Environment;
-import org.apache.flink.runtime.operators.testutils.DummyEnvironment;
-import org.apache.flink.runtime.state.KvState;
-import org.apache.flink.runtime.state.KvStateSnapshot;
-import org.apache.flink.runtime.state.StateHandle;
-import org.apache.flink.runtime.state.filesystem.FsStateBackend;
-import com.google.common.collect.Lists;
-import org.junit.AfterClass;
-import org.junit.BeforeClass;
-import org.junit.Test;
-
-import com.google.common.base.Optional;
-
-import static org.junit.Assert.*;
-
-public class DbStateBackendTest {
-
- private static NetworkServerControl server;
- private static File tempDir;
- private static DbBackendConfig conf;
- private static String url1;
- private static String url2;
-
- @BeforeClass
- public static void startDerbyServer() throws UnknownHostException, Exception {
- server = new NetworkServerControl(InetAddress.getByName("localhost"), 1527, "flink", "flink");
-
- // Async call, we need to ensure that the server starts before leaving
- // the method
- server.start(null);
-
- tempDir = new File(ConfigConstants.DEFAULT_TASK_MANAGER_TMP_PATH, UUID.randomUUID().toString());
- conf = new DbBackendConfig("flink", "flink",
- "jdbc:derby://localhost:1527/" + tempDir.getAbsolutePath() + "/flinkDB1;create=true");
- conf.setDbAdapter(new DerbyAdapter());
- conf.setKvStateCompactionFrequency(1);
-
- url1 = "jdbc:derby://localhost:1527/" + tempDir.getAbsolutePath() + "/flinkDB1;create=true";
- url2 = "jdbc:derby://localhost:1527/" + tempDir.getAbsolutePath() + "/flinkDB2;create=true";
-
- // We need to ensure that the Derby server starts properly before
- // beginning the tests
- ensureServerStarted(server);
- }
-
- public static void ensureServerStarted(NetworkServerControl server) throws InterruptedException {
- // We try to ping the server 10 times with 1s sleep in between
- // If the ping succeeds without exception the server started
- int retry = 0;
- while (true) {
- if (retry < 10) {
- try {
- server.ping();
- break;
- } catch (Exception e) {
- retry++;
- Thread.sleep(1000);
- }
- } else {
- throw new RuntimeException("Could not start the Derby server in 10 seconds.");
- }
- }
- }
-
- @AfterClass
- public static void stopDerbyServer() throws Exception {
- try {
- server.shutdown();
- FileUtils.deleteDirectory(new File(tempDir.getAbsolutePath() + "/flinkDB1"));
- FileUtils.deleteDirectory(new File(tempDir.getAbsolutePath() + "/flinkDB2"));
- FileUtils.forceDelete(new File("derby.log"));
- } catch (Exception ignore) {
- }
- }
-
- @Test
- public void testSetupAndSerialization() throws Exception {
- DbStateBackend dbBackend = new DbStateBackend(conf);
-
- assertFalse(dbBackend.isInitialized());
-
- // serialize / copy the backend
- DbStateBackend backend = CommonTestUtils.createCopySerializable(dbBackend);
- assertFalse(backend.isInitialized());
-
- Environment env = new DummyEnvironment("test", 1, 0);
- backend.initializeForJob(env, "dummy-setup-ser", StringSerializer.INSTANCE);
- String jobId = env.getJobID().toString().substring(0, 16);
-
- assertNotNull(backend.getConnections());
- assertTrue(
- isTableCreated(backend.getConnections().getFirst(), "checkpoints_" + jobId));
-
- backend.disposeAllStateForCurrentJob();
- assertFalse(
- isTableCreated(backend.getConnections().getFirst(), "checkpoints_" + jobId));
- backend.close();
-
- assertTrue(backend.getConnections().getFirst().isClosed());
- }
-
- @Test
- public void testSerializableState() throws Exception {
- Environment env = new DummyEnvironment("test", 1, 0);
- DbStateBackend backend = new DbStateBackend(conf);
- String jobId = env.getJobID().toString().substring(0, 16);
-
- backend.initializeForJob(env, "dummy-ser-state", StringSerializer.INSTANCE);
-
- String state1 = "dummy state";
- String state2 = "row row row your boat";
- Integer state3 = 42;
-
- StateHandle<String> handle1 = backend.checkpointStateSerializable(state1, 439568923746L,
- System.currentTimeMillis());
- StateHandle<String> handle2 = backend.checkpointStateSerializable(state2, 439568923746L,
- System.currentTimeMillis());
- StateHandle<Integer> handle3 = backend.checkpointStateSerializable(state3, 439568923746L,
- System.currentTimeMillis());
-
- assertEquals(state1, handle1.getState(getClass().getClassLoader()));
- handle1.discardState();
-
- assertEquals(state2, handle2.getState(getClass().getClassLoader()));
- handle2.discardState();
-
- assertFalse(isTableEmpty(backend.getConnections().getFirst(), "checkpoints_" + jobId));
-
- assertEquals(state3, handle3.getState(getClass().getClassLoader()));
- handle3.discardState();
-
- assertTrue(isTableEmpty(backend.getConnections().getFirst(), "checkpoints_" + jobId));
-
- backend.close();
-
- }
-
- @Test
- public void testKeyValueState() throws Exception {
-
- // We will create the DbStateBackend backed with a FsStateBackend for
- // nonPartitioned states
- File tempDir = new File(ConfigConstants.DEFAULT_TASK_MANAGER_TMP_PATH, UUID.randomUUID().toString());
- try {
- FsStateBackend fileBackend = new FsStateBackend(localFileUri(tempDir));
-
- DbStateBackend backend = new DbStateBackend(conf, fileBackend);
-
- Environment env = new DummyEnvironment("test", 2, 0);
-
- backend.initializeForJob(env, "dummy_test_kv", IntSerializer.INSTANCE);
-
- ValueState<String> state = backend.createValueState(IntSerializer.INSTANCE,
- new ValueStateDescriptor<>("state1", StringSerializer.INSTANCE, null));
-
- LazyDbValueState<Integer, Integer, String> kv = (LazyDbValueState<Integer, Integer, String>) state;
-
- String tableName = "dummy_test_kv_state1";
- assertTrue(isTableCreated(backend.getConnections().getFirst(), tableName));
-
- assertEquals(0, kv.size());
-
- kv.setCurrentNamespace(1);
-
- // some modifications to the state
- kv.setCurrentKey(1);
- assertNull(kv.value());
- kv.update("1");
- assertEquals(1, kv.size());
- kv.setCurrentKey(2);
- assertNull(kv.value());
- kv.update("2");
- assertEquals(2, kv.size());
- kv.setCurrentKey(1);
- assertEquals("1", kv.value());
- assertEquals(2, kv.size());
-
- kv.snapshot(682375462378L, 100);
-
- // make some more modifications
- kv.setCurrentKey(1);
- kv.update("u1");
- kv.setCurrentKey(2);
- kv.update("u2");
- kv.setCurrentKey(3);
- kv.update("u3");
-
- // draw another snapshot
- KvStateSnapshot<Integer, Integer, ValueState<String>, ValueStateDescriptor<String>, DbStateBackend> snapshot2 = kv.snapshot(682375462379L,
- 200);
-
- // validate the original state
- assertEquals(3, kv.size());
- kv.setCurrentKey(1);
- assertEquals("u1", kv.value());
- kv.setCurrentKey(2);
- assertEquals("u2", kv.value());
- kv.setCurrentKey(3);
- assertEquals("u3", kv.value());
-
- // restore the first snapshot and validate it
- KvState<Integer, Integer, ValueState<String>, ValueStateDescriptor<String>, DbStateBackend> restored2 = snapshot2.restoreState(
- backend,
- IntSerializer.INSTANCE,
- getClass().getClassLoader(),
- 6823754623710L);
-
- restored2.setCurrentNamespace(1);
-
- @SuppressWarnings("unchecked")
- ValueState<String> restoredState2 = (ValueState<String>) restored2;
-
- restored2.setCurrentKey(1);
- assertEquals("u1", restoredState2.value());
- restored2.setCurrentKey(2);
- assertEquals("u2", restoredState2.value());
- restored2.setCurrentKey(3);
- assertEquals("u3", restoredState2.value());
-
- backend.close();
- } finally {
- deleteDirectorySilently(tempDir);
- }
- }
-
- @Test
- @SuppressWarnings("unchecked,rawtypes")
- public void testListState() {
- File tempDir = new File(ConfigConstants.DEFAULT_TASK_MANAGER_TMP_PATH, UUID.randomUUID().toString());
- try {
- FsStateBackend fileBackend = new FsStateBackend(localFileUri(tempDir));
-
- DbStateBackend backend = new DbStateBackend(conf, fileBackend);
-
- Environment env = new DummyEnvironment("test", 2, 0);
-
- backend.initializeForJob(env, "dummy_test_kv_list", IntSerializer.INSTANCE);
-
- ListStateDescriptor<String> kvId = new ListStateDescriptor<>("id", StringSerializer.INSTANCE);
- ListState<String> state = backend.getPartitionedState(null, VoidSerializer.INSTANCE, kvId);
-
- @SuppressWarnings("unchecked")
- KvState<Integer, Void, ListState<String>, ListStateDescriptor<String>, DbStateBackend> kv =
- (KvState<Integer, Void, ListState<String>, ListStateDescriptor<String>, DbStateBackend>) state;
-
- Joiner joiner = Joiner.on(",");
- // some modifications to the state
- kv.setCurrentKey(1);
- assertEquals("", joiner.join(state.get()));
- state.add("1");
- kv.setCurrentKey(2);
- assertEquals("", joiner.join(state.get()));
- state.add("2");
- kv.setCurrentKey(1);
- assertEquals("1", joiner.join(state.get()));
-
- // draw a snapshot
- KvStateSnapshot<Integer, Void, ListState<String>, ListStateDescriptor<String>, DbStateBackend> snapshot1 =
- kv.snapshot(682375462378L, 2);
-
- // make some more modifications
- kv.setCurrentKey(1);
- state.add("u1");
- kv.setCurrentKey(2);
- state.add("u2");
- kv.setCurrentKey(3);
- state.add("u3");
-
- // draw another snapshot
- KvStateSnapshot<Integer, Void, ListState<String>, ListStateDescriptor<String>, DbStateBackend> snapshot2 =
- kv.snapshot(682375462379L, 4);
-
- // validate the original state
- kv.setCurrentKey(1);
- assertEquals("1,u1", joiner.join(state.get()));
- kv.setCurrentKey(2);
- assertEquals("2,u2", joiner.join(state.get()));
- kv.setCurrentKey(3);
- assertEquals("u3", joiner.join(state.get()));
-
- kv.dispose();
-
- // restore the second snapshot and validate it
- KvState<Integer, Void, ListState<String>, ListStateDescriptor<String>, DbStateBackend> restored2 = snapshot2.restoreState(
- backend,
- IntSerializer.INSTANCE,
- this.getClass().getClassLoader(), 20);
-
- @SuppressWarnings("unchecked")
- ListState<String> restored2State = (ListState<String>) restored2;
-
- restored2.setCurrentKey(1);
- assertEquals("1,u1", joiner.join(restored2State.get()));
- restored2.setCurrentKey(2);
- assertEquals("2,u2", joiner.join(restored2State.get()));
- restored2.setCurrentKey(3);
- assertEquals("u3", joiner.join(restored2State.get()));
- }
- catch (Exception e) {
- e.printStackTrace();
- fail(e.getMessage());
- }
- }
-
- @Test
- @SuppressWarnings("unchecked,rawtypes")
- public void testReducingState() {
- File tempDir = new File(ConfigConstants.DEFAULT_TASK_MANAGER_TMP_PATH, UUID.randomUUID().toString());
- try {
- FsStateBackend fileBackend = new FsStateBackend(localFileUri(tempDir));
-
- DbStateBackend backend = new DbStateBackend(conf, fileBackend);
-
- Environment env = new DummyEnvironment("test", 2, 0);
-
- backend.initializeForJob(env, "dummy_test_kv_reduce", IntSerializer.INSTANCE);
-
- ReducingStateDescriptor<String> kvId = new ReducingStateDescriptor<>("id",
- new ReduceFunction<String>() {
- private static final long serialVersionUID = 1L;
-
- @Override
- public String reduce(String value1, String value2) throws Exception {
- return value1 + "," + value2;
- }
- },
- StringSerializer.INSTANCE);
- ReducingState<String> state = backend.getPartitionedState(null, VoidSerializer.INSTANCE, kvId);
-
- @SuppressWarnings("unchecked")
- KvState<Integer, Void, ReducingState<String>, ReducingStateDescriptor<String>, DbStateBackend> kv =
- (KvState<Integer, Void, ReducingState<String>, ReducingStateDescriptor<String>, DbStateBackend>) state;
-
- Joiner joiner = Joiner.on(",");
- // some modifications to the state
- kv.setCurrentKey(1);
- assertEquals(null, state.get());
- state.add("1");
- kv.setCurrentKey(2);
- assertEquals(null, state.get());
- state.add("2");
- kv.setCurrentKey(1);
- assertEquals("1", state.get());
-
- // draw a snapshot
- KvStateSnapshot<Integer, Void, ReducingState<String>, ReducingStateDescriptor<String>, DbStateBackend> snapshot1 =
- kv.snapshot(682375462378L, 2);
-
- // make some more modifications
- kv.setCurrentKey(1);
- state.add("u1");
- kv.setCurrentKey(2);
- state.add("u2");
- kv.setCurrentKey(3);
- state.add("u3");
-
- // draw another snapshot
- KvStateSnapshot<Integer, Void, ReducingState<String>, ReducingStateDescriptor<String>, DbStateBackend> snapshot2 =
- kv.snapshot(682375462379L, 4);
-
- // validate the original state
- kv.setCurrentKey(1);
- assertEquals("1,u1", state.get());
- kv.setCurrentKey(2);
- assertEquals("2,u2", state.get());
- kv.setCurrentKey(3);
- assertEquals("u3", state.get());
-
- kv.dispose();
-
- // restore the second snapshot and validate it
- KvState<Integer, Void, ReducingState<String>, ReducingStateDescriptor<String>, DbStateBackend> restored2 = snapshot2.restoreState(
- backend,
- IntSerializer.INSTANCE,
- this.getClass().getClassLoader(), 20);
-
- @SuppressWarnings("unchecked")
- ReducingState<String> restored2State = (ReducingState<String>) restored2;
-
- restored2.setCurrentKey(1);
- assertEquals("1,u1", restored2State.get());
- restored2.setCurrentKey(2);
- assertEquals("2,u2", restored2State.get());
- restored2.setCurrentKey(3);
- assertEquals("u3", restored2State.get());
- }
- catch (Exception e) {
- e.printStackTrace();
- fail(e.getMessage());
- }
- }
-
- @Test
- public void testCompaction() throws Exception {
- DbBackendConfig conf = new DbBackendConfig("flink", "flink", url1);
- MockAdapter adapter = new MockAdapter();
- conf.setKvStateCompactionFrequency(2);
- conf.setDbAdapter(adapter);
-
- DbStateBackend backend1 = new DbStateBackend(conf);
- DbStateBackend backend2 = new DbStateBackend(conf);
- DbStateBackend backend3 = new DbStateBackend(conf);
-
- backend1.initializeForJob(new DummyEnvironment("test", 3, 0), "dummy_1", StringSerializer.INSTANCE);
- backend2.initializeForJob(new DummyEnvironment("test", 3, 1), "dummy_2", StringSerializer.INSTANCE);
- backend3.initializeForJob(new DummyEnvironment("test", 3, 2), "dummy_3", StringSerializer.INSTANCE);
-
- ValueState<String> s1State = backend1.createValueState(StringSerializer.INSTANCE,
- new ValueStateDescriptor<>("a1", StringSerializer.INSTANCE, null));
-
- ValueState<String> s2State = backend2.createValueState(StringSerializer.INSTANCE,
- new ValueStateDescriptor<>("a2", StringSerializer.INSTANCE, null));
-
- ValueState<String> s3State = backend3.createValueState(StringSerializer.INSTANCE,
- new ValueStateDescriptor<>("a3", StringSerializer.INSTANCE, null));
-
- LazyDbValueState<?, ?, ?> s1 = (LazyDbValueState<?, ?, ?>) s1State;
- LazyDbValueState<?, ?, ?> s2 = (LazyDbValueState<?, ?, ?>) s2State;
- LazyDbValueState<?, ?, ?> s3 = (LazyDbValueState<?, ?, ?>) s3State;
-
- assertTrue(s1.isCompactor());
- assertFalse(s2.isCompactor());
- assertFalse(s3.isCompactor());
- assertNotNull(s1.getExecutor());
- assertNull(s2.getExecutor());
- assertNull(s3.getExecutor());
-
- s1.snapshot(1, 100);
- s1.notifyCheckpointComplete(1);
- s1.snapshot(2, 200);
- s1.snapshot(3, 300);
- s1.notifyCheckpointComplete(2);
- s1.notifyCheckpointComplete(3);
- s1.snapshot(4, 400);
- s1.snapshot(5, 500);
- s1.notifyCheckpointComplete(4);
- s1.notifyCheckpointComplete(5);
-
- s1.dispose();
- s2.dispose();
- s3.dispose();
-
- // Wait until the compaction completes
- s1.getExecutor().awaitTermination(5, TimeUnit.SECONDS);
- assertEquals(2, adapter.numCompcations.get());
- assertEquals(5, adapter.keptAlive);
-
- backend1.close();
- backend2.close();
- backend3.close();
- }
-
- @Test
- public void testCaching() throws Exception {
-
- List<String> urls = Lists.newArrayList(url1, url2);
- DbBackendConfig conf = new DbBackendConfig("flink", "flink",
- urls);
-
- conf.setDbAdapter(new DerbyAdapter());
- conf.setKvCacheSize(3);
- conf.setMaxKvInsertBatchSize(2);
-
- // We evict 2 elements when the cache is full
- conf.setMaxKvCacheEvictFraction(0.6f);
-
- DbStateBackend backend = new DbStateBackend(conf);
-
- Environment env = new DummyEnvironment("test", 2, 0);
-
- String tableName = "dummy_test_caching_state1";
- assertFalse(isTableCreated(DriverManager.getConnection(url1, "flink", "flink"), tableName));
- assertFalse(isTableCreated(DriverManager.getConnection(url2, "flink", "flink"), tableName));
-
- backend.initializeForJob(env, "dummy_test_caching", IntSerializer.INSTANCE);
-
- ValueState<String> state = backend.createValueState(IntSerializer.INSTANCE,
- new ValueStateDescriptor<>("state1", StringSerializer.INSTANCE, "a"));
-
- LazyDbValueState<Integer, Integer, String> kv = (LazyDbValueState<Integer, Integer, String>) state;
-
- assertTrue(isTableCreated(DriverManager.getConnection(url1, "flink", "flink"), tableName));
- assertTrue(isTableCreated(DriverManager.getConnection(url2, "flink", "flink"), tableName));
-
- Map<Tuple2<Integer, Integer>, Optional<String>> cache = kv.getStateCache();
- Map<Tuple2<Integer, Integer>, Optional<String>> modified = kv.getModified();
-
- assertEquals(0, kv.size());
-
- kv.setCurrentNamespace(1);
-
- // some modifications to the state
- kv.setCurrentKey(1);
- assertEquals("a", kv.value());
-
- kv.update(null);
- assertEquals(1, kv.size());
- kv.setCurrentKey(2);
- assertEquals("a", kv.value());
- kv.update("2");
- assertEquals(2, kv.size());
- assertEquals("2", kv.value());
-
- kv.setCurrentKey(1);
- assertEquals("a", kv.value());
-
- kv.setCurrentKey(3);
- kv.update("3");
- assertEquals("3", kv.value());
-
- assertTrue(modified.containsKey(Tuple2.of(1, 1)));
- assertTrue(modified.containsKey(Tuple2.of(2, 1)));
- assertTrue(modified.containsKey(Tuple2.of(3, 1)));
-
- // 1,2 should be evicted as the cache filled
- kv.setCurrentKey(4);
- kv.update("4");
- assertEquals("4", kv.value());
-
- assertFalse(modified.containsKey(Tuple2.of(1, 1)));
- assertFalse(modified.containsKey(Tuple2.of(2, 1)));
- assertTrue(modified.containsKey(Tuple2.of(3, 1)));
- assertTrue(modified.containsKey(Tuple2.of(4, 1)));
-
- assertEquals(Optional.of("3"), cache.get(Tuple2.of(3, 1)));
- assertEquals(Optional.of("4"), cache.get(Tuple2.of(4, 1)));
- assertFalse(cache.containsKey(Tuple2.of(1, 1)));
- assertFalse(cache.containsKey(Tuple2.of(2, 1)));
-
- // draw a snapshot
- kv.snapshot(682375462378L, 100);
-
- assertTrue(modified.isEmpty());
-
- // make some more modifications
- kv.setCurrentKey(2);
- assertEquals("2", kv.value());
- kv.update(null);
- assertEquals("a", kv.value());
-
- assertTrue(modified.containsKey(Tuple2.of(2, 1)));
- assertEquals(1, modified.size());
-
- assertEquals(Optional.of("3"), cache.get(Tuple2.of(3, 1)));
- assertEquals(Optional.of("4"), cache.get(Tuple2.of(4, 1)));
- assertEquals(Optional.absent(), cache.get(Tuple2.of(2, 1)));
- assertFalse(cache.containsKey(Tuple2.of(1, 1)));
-
- assertTrue(modified.containsKey(Tuple2.of(2, 1)));
- assertFalse(modified.containsKey(Tuple2.of(3, 1)));
- assertFalse(modified.containsKey(Tuple2.of(4, 1)));
- assertTrue(cache.containsKey(Tuple2.of(3, 1)));
- assertTrue(cache.containsKey(Tuple2.of(4, 1)));
-
- // clear cache from initial keys
-
- kv.setCurrentKey(5);
- kv.value();
- kv.setCurrentKey(6);
- kv.value();
- kv.setCurrentKey(7);
- kv.value();
-
- assertFalse(modified.containsKey(Tuple2.of(5, 1)));
- assertTrue(modified.containsKey(Tuple2.of(6, 1)));
- assertTrue(modified.containsKey(Tuple2.of(7, 1)));
-
- assertFalse(cache.containsKey(Tuple2.of(1, 1)));
- assertFalse(cache.containsKey(Tuple2.of(2, 1)));
- assertFalse(cache.containsKey(Tuple2.of(3, 1)));
- assertFalse(cache.containsKey(Tuple2.of(4, 1)));
-
- kv.setCurrentKey(2);
- assertEquals("a", kv.value());
-
- long checkpointTs = System.currentTimeMillis();
-
- // Draw a snapshot that we will restore later
- KvStateSnapshot<Integer, Integer, ValueState<String>, ValueStateDescriptor<String>, DbStateBackend> snapshot1 = kv.snapshot(682375462379L, checkpointTs);
-
- assertTrue(modified.isEmpty());
-
- // Do some updates then draw another snapshot (imitate a partial
- // failure), these updates should not be visible if we restore snapshot1
- kv.setCurrentKey(1);
- kv.update("123");
- kv.setCurrentKey(3);
- kv.update("456");
- kv.setCurrentKey(2);
- kv.notifyCheckpointComplete(682375462379L);
- kv.update("2");
- kv.setCurrentKey(4);
- kv.update("4");
- kv.update("5");
-
- kv.snapshot(6823754623710L, checkpointTs + 10);
-
- // restore the second snapshot and validate it (we set a new default
- // value here to make sure that the default wasn't written)
- KvState<Integer, Integer, ValueState<String>, ValueStateDescriptor<String>, DbStateBackend> restored = snapshot1.restoreState(
- backend,
- IntSerializer.INSTANCE,
- getClass().getClassLoader(),
- 6823754623711L);
-
- LazyDbValueState<Integer, Integer, String> lazyRestored = (LazyDbValueState<Integer, Integer, String>) restored;
-
- cache = lazyRestored.getStateCache();
- modified = lazyRestored.getModified();
-
- restored.setCurrentNamespace(1);
-
- @SuppressWarnings("unchecked")
- ValueState<String> restoredState = (ValueState<String>) restored;
-
- restored.setCurrentKey(1);
-
- assertEquals("a", restoredState.value());
- // make sure that we got the default and not some value from the db
- assertEquals(cache.get(Tuple2.of(1, 1)), Optional.<String>absent());
- restored.setCurrentKey(2);
- assertEquals("a", restoredState.value());
- // make sure that we got the default and not some value from the db
- assertEquals(cache.get(Tuple2.of(2, 1)), Optional.<String>absent());
- restored.setCurrentKey(3);
- assertEquals("3", restoredState.value());
- restored.setCurrentKey(4);
- assertEquals("4", restoredState.value());
-
- backend.close();
- }
-
- private static boolean isTableCreated(Connection con, String tableName) throws SQLException {
- return con.getMetaData().getTables(null, null, tableName.toUpperCase(), null).next();
- }
-
- private static boolean isTableEmpty(Connection con, String tableName) throws SQLException {
- try (Statement smt = con.createStatement()) {
- ResultSet res = smt.executeQuery("select * from " + tableName);
- return !res.next();
- }
- }
-
- private static String localFileUri(File path) {
- return path.toURI().toString();
- }
-
- private static void deleteDirectorySilently(File dir) {
- try {
- FileUtils.deleteDirectory(dir);
- } catch (IOException ignored) {
- }
- }
-
- private static class MockAdapter extends DerbyAdapter {
-
- private static final long serialVersionUID = 1L;
- public AtomicInteger numCompcations = new AtomicInteger(0);
- public int keptAlive = 0;
-
- @Override
- public void compactKvStates(String kvStateId, Connection con, long lowerTs, long upperTs) throws SQLException {
- numCompcations.incrementAndGet();
- }
-
- @Override
- public void keepAlive(Connection con) throws SQLException {
- keptAlive++;
- }
- }
-
-}
http://git-wip-us.apache.org/repos/asf/flink/blob/33f43114/flink-contrib/flink-streaming-contrib/src/test/java/org/apache/flink/contrib/streaming/state/DerbyAdapter.java
----------------------------------------------------------------------
diff --git a/flink-contrib/flink-streaming-contrib/src/test/java/org/apache/flink/contrib/streaming/state/DerbyAdapter.java b/flink-contrib/flink-streaming-contrib/src/test/java/org/apache/flink/contrib/streaming/state/DerbyAdapter.java
deleted file mode 100644
index 5331956..0000000
--- a/flink-contrib/flink-streaming-contrib/src/test/java/org/apache/flink/contrib/streaming/state/DerbyAdapter.java
+++ /dev/null
@@ -1,165 +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.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 the Derby JDBC driver which has slightly restricted CREATE TABLE
- * and SELECT semantics compared to the default assumptions.
- *
- */
-public class DerbyAdapter extends MySqlAdapter {
-
- private static final long serialVersionUID = 1L;
-
- /**
- * We need to override this method as Derby does not support the
- * "IF NOT EXISTS" clause at table creation
- */
- @Override
- public void createCheckpointsTable(String jobId, Connection con) throws SQLException {
-
- try (Statement smt = con.createStatement()) {
- smt.executeUpdate(
- "CREATE TABLE checkpoints_" + jobId
- + " ("
- + "checkpointId bigint, "
- + "timestamp bigint, "
- + "handleId bigint,"
- + "checkpoint blob,"
- + "PRIMARY KEY (handleId)"
- + ")");
- } catch (SQLException se) {
- if (se.getSQLState().equals("X0Y32")) {
- // table already created, ignore
- } else {
- throw se;
- }
- }
- }
-
- /**
- * We need to override this method as Derby does not support the
- * "IF NOT EXISTS" clause at table creation
- */
- @Override
- public void createKVStateTable(String stateId, Connection con) throws SQLException {
- validateStateId(stateId);
- try (Statement smt = con.createStatement()) {
- smt.executeUpdate(
- "CREATE TABLE " + stateId
- + " ("
- + "timestamp bigint, "
- + "k varchar(256) for bit data, "
- + "v blob, "
- + "PRIMARY KEY (k, timestamp)"
- + ")");
- } catch (SQLException se) {
- if (se.getSQLState().equals("X0Y32")) {
- // table already created, ignore
- } else {
- throw se;
- }
- }
- }
-
- /**
- * We need to override this method as Derby does not support "LIMIT n" for
- * select statements.
- */
- @Override
- public String prepareKeyLookup(String stateId) throws SQLException {
- validateStateId(stateId);
- return "SELECT v " + "FROM " + stateId
- + " WHERE k = ? "
- + " AND timestamp <= ?"
- + " ORDER BY timestamp DESC";
- }
-
- @Override
- public void compactKvStates(String stateId, Connection con, long lowerBound, long upperBound)
- throws SQLException {
- validateStateId(stateId);
-
- try (Statement smt = con.createStatement()) {
- smt.executeUpdate("DELETE FROM " + stateId + " t1"
- + " WHERE EXISTS"
- + " ("
- + " SELECT * FROM " + stateId + " t2"
- + " WHERE t2.k = t1.k"
- + " AND t2.timestamp > t1.timestamp"
- + " AND t2.timestamp <=" + upperBound
- + " AND t2.timestamp >= " + lowerBound
- + " )");
- }
- }
-
- @Override
- public String prepareKVCheckpointInsert(String stateId) throws SQLException {
- validateStateId(stateId);
- return "INSERT INTO " + stateId + " (timestamp, k, v) VALUES (?,?,?)";
- }
-
- @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 {
- con.setAutoCommit(false);
- for (Tuple2<byte[], byte[]> kv : toInsert) {
- setKVInsertParams(stateId, insertStatement, checkpointTs, kv.f0, kv.f1);
- insertStatement.addBatch();
- }
- insertStatement.executeBatch();
- con.commit();
- con.setAutoCommit(true);
- insertStatement.clearBatch();
- return null;
- }
- }, new Callable<Void>() {
- public Void call() throws Exception {
- con.rollback();
- insertStatement.clearBatch();
- return null;
- }
- }, conf.getMaxNumberOfSqlRetries(), conf.getSleepBetweenSqlRetries());
- }
-
- private void setKVInsertParams(String stateId, PreparedStatement insertStatement, long checkpointId,
- byte[] key, byte[] value) throws SQLException {
- insertStatement.setLong(1, checkpointId);
- insertStatement.setBytes(2, key);
- if (value != null) {
- insertStatement.setBytes(3, value);
- } else {
- insertStatement.setNull(3, Types.BLOB);
- }
- }
-}
[2/2] flink git commit: [FLINK-3620] [streaming] Remove DbStateBackend
Posted by gy...@apache.org.
[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);
- }
-
- }
-}