All Downloads are FREE. Search and download functionalities are using the official Maven repository.

org.apache.flink.runtime.state.gemini.keyed.GeminiKeyedListStateImpl Maven / Gradle / Ivy

There is a newer version: 1.5.1
Show newest version
/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.apache.flink.runtime.state.gemini.keyed;

import org.apache.flink.api.common.typeutils.TypeSerializer;
import org.apache.flink.core.memory.DataOutputViewStreamWrapper;
import org.apache.flink.queryablestate.client.state.serialization.KvStateSerializer;
import org.apache.flink.runtime.state.StateStorage;
import org.apache.flink.runtime.state.VoidNamespaceSerializer;
import org.apache.flink.runtime.state.gemini.engine.GRegion;
import org.apache.flink.runtime.state.gemini.engine.hashtable.GRegionKListImpl;
import org.apache.flink.runtime.state.gemini.engine.hashtable.GTableKeyedListImpl;
import org.apache.flink.runtime.state.gemini.engine.metrics.StateMetrics;
import org.apache.flink.runtime.state.keyed.KeyedListState;
import org.apache.flink.runtime.state.keyed.KeyedListStateDescriptor;
import org.apache.flink.util.Preconditions;

import java.io.ByteArrayOutputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

/**
 * An implementation of {@link KeyedListState} backed by a {@link StateStorage}.
 * The pairs are formatted as {K -> List{E}}, and the pairs are partitioned by K.
 *
 * @param  Type of the keys in the state.
 * @param  Type of the elements in the state.
 */
public final class GeminiKeyedListStateImpl implements KeyedListState {

	/**
	 * The descriptor of current state.
	 */
	private final KeyedListStateDescriptor descriptor;

	private final GTableKeyedListImpl table;

	private final StateMetrics metrics;

	//--------------------------------------------------------------------------

	/**
	 * Constructor with the state storage to store the values.
	 *
	 * @param descriptor The descriptor of this state.
	 */
	public GeminiKeyedListStateImpl(
		KeyedListStateDescriptor descriptor,
		GTableKeyedListImpl table,
		StateMetrics metrics) {
		this.descriptor = Preconditions.checkNotNull(descriptor);
		this.table = Preconditions.checkNotNull(table);
		this.metrics = metrics;
	}

	@Override
	public KeyedListStateDescriptor getDescriptor() {
		return descriptor;
	}

	//--------------------------------------------------------------------------

	@Override
	public boolean contains(K key) {
		List list = getOrDefault(key, null);

		return list != null;
	}

	@SuppressWarnings("unchecked")
	@Override
	public List get(K key) {
		return getOrDefault(key, null);
	}

	@Override
	public List getOrDefault(K key, List defaultValue) {
		if (key == null) {
			return defaultValue;
		}

		if (metrics.checkAndUpdateKListGetCounter()) {
			return getOrDefaultWithMetrics(key, defaultValue);
		} else {
			return doGetOrDefault(key, defaultValue);
		}
	}

	private List doGetOrDefault(K key, List defaultValue) {
		if (key == null) {
			return defaultValue;
		}

		List result = getRegion(key).get(key);
		return result == null ? defaultValue : result;
	}

	private List getOrDefaultWithMetrics(K key, List defaultValue) {
		long start = System.nanoTime();
		List result = doGetOrDefault(key, defaultValue);
		long end = System.nanoTime();
		metrics.updateKListGetHistogram(end - start);
		if (result != defaultValue && result != null) {
			metrics.updateKListGetListSizeHistogram(result.size());
		}

		return result;
	}

	@Override
	public Map> getAll(Collection keys) {
		if (keys == null || keys.isEmpty()) {
			return Collections.emptyMap();
		}

		if (metrics.checkAndUpdateKListMultiGetCounter()) {
			return getAllWithMetrics(keys);
		} else {
			return doGetAll(keys);
		}
	}

	private Map> doGetAll(Collection keys) {
		Map> results = new HashMap<>();

		for (K key : keys) {
			if (key == null) {
				continue;
			}

			List result = doGetOrDefault(key, null);
			if (result != null && !result.isEmpty()) {
				results.put(key, result);
			}
		}

		return results;
	}

	private Map> getAllWithMetrics(Collection keys) {
		long start = System.nanoTime();
		Map> result = doGetAll(keys);
		long end = System.nanoTime();
		metrics.updateKListMultiGetHistogram(end - start);
		for (List o : result.values()) {
			if (o != null) {
				metrics.updateKListGetListSizeHistogram(o.size());
				// only select one map to update
				break;
			}
		}

		return result;
	}

	@Override
	public void add(K key, E element) {
		Preconditions.checkNotNull(key);
		Preconditions.checkNotNull(element, "You can not add null value to list state.");

		if (metrics.checkAndUpdateKListPutCounter()) {
			addWithMetrics(key, element);
		} else {
			getRegion(key).add(key, element);
		}
	}

	private void addWithMetrics(K key, E element) {
		long start = System.nanoTime();
		getRegion(key).add(key, element);
		long end = System.nanoTime();
		metrics.updateKListPutHistogram(end - start);
	}

	@Override
	public void addAll(K key, Collection elements) {
		Preconditions.checkNotNull(key);
		Preconditions.checkNotNull(elements, "List of values to add cannot be null.");

		if (elements.isEmpty()) {
			return;
		}

		if (metrics.checkAndUpdateKListMultiPutCounter()) {
			addAllWithMetrics(key, elements);
		} else {
			doAddAll(key, elements);
		}
	}

	private void doAddAll(K key, Collection elements) {
		Preconditions.checkNotNull(key);
		Preconditions.checkNotNull(elements, "List of values to add cannot be null.");

		if (elements.isEmpty()) {
			return;
		}

		getRegion(key).addAll(key, elements);
	}

	private void addAllWithMetrics(K key, Collection elements) {
		long start = System.nanoTime();
		doAddAll(key, elements);
		long end = System.nanoTime();
		metrics.updateKListMultiPutHistogram(end - start);
	}

	@Override
	public void addAll(Map> map) {
		if (map == null || map.isEmpty()) {
			return;
		}

		if (metrics.checkAndUpdateKListMultiPutCounter()) {
			addAllWithMetrics(map);
		} else {
			for (Map.Entry> entry : map.entrySet()) {
				doAddAll(entry.getKey(), entry.getValue());
			}
		}
	}

	private void addAllWithMetrics(Map> map) {
		long start = System.nanoTime();
		for (Map.Entry> entry : map.entrySet()) {
			doAddAll(entry.getKey(), entry.getValue());
		}
		long end = System.nanoTime();
		metrics.updateKListMultiPutHistogram(end - start);
	}

	@Override
	public void put(K key, E element) {
		Preconditions.checkNotNull(key);
		Preconditions.checkNotNull(element, "You can not add null value to list state.");

		if (metrics.checkAndUpdateKListPutCounter()) {
			putWithMetrics(key, element);
		} else {
			getRegion(key).put(key, new ArrayList<>(Arrays.asList(element)));
		}
	}

	private void putWithMetrics(K key, E element) {
		long start = System.nanoTime();
		getRegion(key).put(key, new ArrayList<>(Arrays.asList(element)));
		long end = System.nanoTime();
		metrics.updateKListPutHistogram(end - start);
	}

	@Override
	public void putAll(K key, Collection elements) {
		Preconditions.checkNotNull(key);

		if (metrics.checkAndUpdateKListMultiPutCounter()) {
			putWithMetrics(key, elements);
		} else {
			doPutAll(key, elements);
		}
	}

	private void doPutAll(K key, Collection elements) {
		List list = new ArrayList<>();
		for (E element : elements) {
			Preconditions.checkNotNull(element, "You cannot add null to a ListState.");
			list.add(element);
		}
		getRegion(key).put(key, list);
	}

	private void putWithMetrics(K key, Collection elements) {
		long start = System.nanoTime();
		doPutAll(key, elements);
		long end = System.nanoTime();
		metrics.updateKListMultiPutHistogram(end - start);
	}

	@Override
	public void putAll(Map> map) {
		if (map == null || map.isEmpty()) {
			return;
		}

		if (metrics.checkAndUpdateKListMultiPutCounter()) {
			putWithMetrics(map);
		} else {
			for (Map.Entry> entry : map.entrySet()) {
				doPutAll(entry.getKey(), entry.getValue());
			}
		}
	}

	private void putWithMetrics(Map> map) {
		long start = System.nanoTime();
		for (Map.Entry> entry : map.entrySet()) {
			doPutAll(entry.getKey(), entry.getValue());
		}
		long end = System.nanoTime();
		metrics.updateKListMultiPutHistogram(end - start);
	}

	@Override
	public void remove(K key) {
		if (key == null) {
			return;
		}

		if (metrics.checkAndUpdateKListRemoveCounter()) {
			removeWithMetrics(key);
		} else {
			getRegion(key).remove(key);
		}
	}

	private void removeWithMetrics(K key) {
		long start = System.nanoTime();
		getRegion(key).remove(key);
		long end = System.nanoTime();
		metrics.updateKListRemoveHistogram(end - start);
	}

	@Override
	public boolean remove(K key, E elementToRemove) {
		if (key == null) {
			return false;
		}

		if (metrics.checkAndUpdateKListRemoveCounter()) {
			removeWithMetrics(key, elementToRemove);
		} else {
			// TODO remove should return a value
			getRegion(key).remove(key, elementToRemove);
		}

		return true;
	}

	private void removeWithMetrics(K key, E elementToRemove) {
		long start = System.nanoTime();
		getRegion(key).remove(key, elementToRemove);
		long end = System.nanoTime();
		metrics.updateKListRemoveHistogram(end - start);
	}

	@Override
	public void removeAll(Collection keys) {
		if (keys == null || keys.isEmpty()) {
			return;
		}

		if (metrics.checkAndUpdateKListMultiRemoveCounter()) {
			removeAllWithMetrics(keys);
		} else {
			for (K key : keys) {
				if (key != null) {
					getRegion(key).remove(key);
				}
			}
		}
	}

	private void removeAllWithMetrics(Collection keys) {
		long start = System.nanoTime();
		for (K key : keys) {
			if (key != null) {
				getRegion(key).remove(key);
			}
		}
		long end = System.nanoTime();
		metrics.updateKListMultiRemoveHistogram(end - start);
	}

	@Override
	public boolean removeAll(K key, Collection elementsToRemove) {
		if (key == null) {
			return false;
		}

		if (metrics.checkAndUpdateKListMultiRemoveCounter()) {
			removeAllWithMetrics(key, elementsToRemove);
		} else {
			// TODO removeAll should return a value
			doRemoveAll(key, elementsToRemove);
		}

		return true;
	}

	private boolean doRemoveAll(K key, Collection elementsToRemove) {
		if (key == null) {
			return false;
		}

		// TODO removeAll should return a value
		getRegion(key).removeAll(key, elementsToRemove);

		return true;
	}

	private void removeAllWithMetrics(K key, Collection elementsToRemove) {
		long start = System.nanoTime();
		getRegion(key).removeAll(key, elementsToRemove);
		long end = System.nanoTime();
		metrics.updateKListMultiRemoveHistogram(end - start);
	}

	@Override
	public boolean removeAll(Map> map) {
		if (map == null || map.isEmpty()) {
			return false;
		}

		if (metrics.checkAndUpdateKListMultiRemoveCounter()) {
			return removeAllWithMetrics(map);
		} else {
			return doRemoveAll(map);
		}
	}

	private boolean doRemoveAll(Map> map) {
		boolean success = false;
		for (Map.Entry> entry : map.entrySet()) {
			K key = entry.getKey();
			Collection elements = entry.getValue();
			success = doRemoveAll(key, elements) || success;
		}

		return success;
	}

	private boolean removeAllWithMetrics(Map> map) {
		long start = System.nanoTime();
		boolean success = doRemoveAll(map);
		long end = System.nanoTime();
		metrics.updateKListMultiRemoveHistogram(end - start);

		return success;
	}

	@Override
	public Map> getAll() {
		if (metrics.checkAndUpdateKListMultiGetCounter()) {
			return getAllWithMetrics();
		} else {
			return doGetAll();
		}
	}

	private Map> doGetAll() {
		Map> results = new HashMap<>();
		Iterator iterator = table.dataRegionIterator();
		while (iterator.hasNext()) {
			GRegionKListImpl region = (GRegionKListImpl) iterator.next();
			region.getAll(results);
		}
		return results;
	}

	private Map> getAllWithMetrics() {
		long start = System.nanoTime();
		Map> result = doGetAll();
		long end = System.nanoTime();
		metrics.updateKListMultiGetHistogram(end - start);
		for (List o : result.values()) {
			if (o != null) {
				metrics.updateKListGetListSizeHistogram(o.size());
				// only select one map to update
				break;
			}
		}

		return result;
	}

	@Override
	public void removeAll() {
		if (metrics.checkAndUpdateKListMultiRemoveCounter()) {
			removeAllWithMetrics();
		} else {
			doRemoveAll();
		}
	}

	private void doRemoveAll() {
		Iterator iterator = table.dataRegionIterator();
		while (iterator.hasNext()) {
			GRegionKListImpl> region = (GRegionKListImpl>) iterator.next();
			region.removeAll();
		}
	}

	private void removeAllWithMetrics() {
		long start = System.nanoTime();
		doRemoveAll();
		long end = System.nanoTime();
		metrics.updateKListMultiRemoveHistogram(end - start);
	}

	@Override
	public Iterable keys() {
		// TODO complexity
		return getAll().keySet();
	}

	@Override
	public E poll(K key) {
		return getRegion(key).poll(key);
	}

	@Override
	public E peek(K key) {
		return getRegion(key).peek(key);
	}

	@Override
	public byte[] getSerializedValue(
		final byte[] serializedKeyAndNamespace,
		final TypeSerializer safeKeySerializer,
		final TypeSerializer> safeValueSerializer) throws Exception {

		K key = KvStateSerializer.deserializeKeyAndNamespace(serializedKeyAndNamespace,
			safeKeySerializer,
			VoidNamespaceSerializer.INSTANCE).f0;

		List value = get(key);
		if (value == null) {
			return null;
		}

		final TypeSerializer dupSerializer = descriptor.getElementSerializer();

		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		DataOutputViewStreamWrapper view = new DataOutputViewStreamWrapper(baos);

		for (int i = 0; i < value.size(); i++) {
			dupSerializer.serialize(value.get(i), view);
			if (i < value.size() - 1) {
				view.writeByte(',');
			}
		}
		view.flush();

		return baos.toByteArray();
	}

	@Override
	public StateStorage> getStateStorage() {
		throw new UnsupportedOperationException();
	}

	@SuppressWarnings("unchecked")
	private GRegionKListImpl getRegion(K key) {
		return (GRegionKListImpl) table.getRegion(key);
	}
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy