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

org.apache.nifi.distributed.cache.client.DistributedMapCacheClientService Maven / Gradle / Ivy

There is a newer version: 2.0.0
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.nifi.distributed.cache.client;

import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit;

import org.apache.commons.io.IOUtils;
import org.apache.nifi.annotation.documentation.CapabilityDescription;
import org.apache.nifi.annotation.documentation.SeeAlso;
import org.apache.nifi.annotation.documentation.Tags;
import org.apache.nifi.annotation.lifecycle.OnEnabled;
import org.apache.nifi.annotation.lifecycle.OnStopped;
import org.apache.nifi.components.PropertyDescriptor;
import org.apache.nifi.controller.AbstractControllerService;
import org.apache.nifi.controller.ConfigurationContext;
import org.apache.nifi.distributed.cache.protocol.ProtocolHandshake;
import org.apache.nifi.distributed.cache.protocol.exception.HandshakeException;
import org.apache.nifi.processor.util.StandardValidators;
import org.apache.nifi.remote.StandardVersionNegotiator;
import org.apache.nifi.remote.VersionNegotiator;
import org.apache.nifi.ssl.SSLContextService;
import org.apache.nifi.ssl.SSLContextService.ClientAuth;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

@Tags({"distributed", "cache", "state", "map", "cluster"})
@SeeAlso(classNames = {"org.apache.nifi.distributed.cache.server.map.DistributedMapCacheServer", "org.apache.nifi.ssl.StandardSSLContextService"})
@CapabilityDescription("Provides the ability to communicate with a DistributedMapCacheServer. This can be used in order to share a Map "
    + "between nodes in a NiFi cluster")
public class DistributedMapCacheClientService extends AbstractControllerService implements AtomicDistributedMapCacheClient {

    private static final Logger logger = LoggerFactory.getLogger(DistributedMapCacheClientService.class);

    public static final PropertyDescriptor HOSTNAME = new PropertyDescriptor.Builder()
        .name("Server Hostname")
        .description("The name of the server that is running the DistributedMapCacheServer service")
        .required(true)
        .addValidator(StandardValidators.NON_EMPTY_VALIDATOR)
        .build();
    public static final PropertyDescriptor PORT = new PropertyDescriptor.Builder()
        .name("Server Port")
        .description("The port on the remote server that is to be used when communicating with the DistributedMapCacheServer service")
        .required(true)
        .addValidator(StandardValidators.PORT_VALIDATOR)
        .defaultValue("4557")
        .build();
    public static final PropertyDescriptor SSL_CONTEXT_SERVICE = new PropertyDescriptor.Builder()
        .name("SSL Context Service")
        .description("If specified, indicates the SSL Context Service that is used to communicate with the "
                + "remote server. If not specified, communications will not be encrypted")
        .required(false)
        .identifiesControllerService(SSLContextService.class)
        .build();
    public static final PropertyDescriptor COMMUNICATIONS_TIMEOUT = new PropertyDescriptor.Builder()
        .name("Communications Timeout")
        .description("Specifies how long to wait when communicating with the remote server before determining that "
                + "there is a communications failure if data cannot be sent or received")
        .required(true)
        .addValidator(StandardValidators.TIME_PERIOD_VALIDATOR)
        .defaultValue("30 secs")
        .build();

    private final BlockingQueue queue = new LinkedBlockingQueue<>();
    private volatile ConfigurationContext configContext;
    private volatile boolean closed = false;

    @Override
    protected List getSupportedPropertyDescriptors() {
        final List descriptors = new ArrayList<>();
        descriptors.add(HOSTNAME);
        descriptors.add(PORT);
        descriptors.add(SSL_CONTEXT_SERVICE);
        descriptors.add(COMMUNICATIONS_TIMEOUT);
        return descriptors;
    }

    @OnEnabled
    public void cacheConfig(final ConfigurationContext context) {
        this.configContext = context;
    }

    @OnStopped
    public void onStopped() throws IOException {
        close();
    }

    @Override
    public  boolean putIfAbsent(final K key, final V value, final Serializer keySerializer, final Serializer valueSerializer) throws IOException {
        return withCommsSession(new CommsAction() {
            @Override
            public Boolean execute(final CommsSession session) throws IOException {
                final DataOutputStream dos = new DataOutputStream(session.getOutputStream());
                dos.writeUTF("putIfAbsent");

                serialize(key, keySerializer, dos);
                serialize(value, valueSerializer, dos);

                dos.flush();

                final DataInputStream dis = new DataInputStream(session.getInputStream());
                return dis.readBoolean();
            }
        });
    }

    @Override
    public  void put(final K key, final V value, final Serializer keySerializer, final Serializer valueSerializer) throws IOException {
        withCommsSession(new CommsAction() {
            @Override
            public Object execute(final CommsSession session) throws IOException {
                final DataOutputStream dos = new DataOutputStream(session.getOutputStream());
                dos.writeUTF("put");

                serialize(key, keySerializer, dos);
                serialize(value, valueSerializer, dos);

                dos.flush();
                final DataInputStream dis = new DataInputStream(session.getInputStream());
                final boolean success = dis.readBoolean();
                if ( !success ) {
                    throw new IOException("Expected to receive confirmation of 'put' request but received unexpected response");
                }

                return null;
            }
        });
    }

    @Override
    public  boolean containsKey(final K key, final Serializer keySerializer) throws IOException {
        return withCommsSession(new CommsAction() {
            @Override
            public Boolean execute(final CommsSession session) throws IOException {
                final DataOutputStream dos = new DataOutputStream(session.getOutputStream());
                dos.writeUTF("containsKey");

                serialize(key, keySerializer, dos);
                dos.flush();

                final DataInputStream dis = new DataInputStream(session.getInputStream());
                return dis.readBoolean();
            }
        });
    }

    @Override
    public  V getAndPutIfAbsent(final K key, final V value, final Serializer keySerializer, final Serializer valueSerializer, final Deserializer valueDeserializer) throws IOException {
        return withCommsSession(new CommsAction() {
            @Override
            public V execute(final CommsSession session) throws IOException {
                final DataOutputStream dos = new DataOutputStream(session.getOutputStream());
                dos.writeUTF("getAndPutIfAbsent");

                serialize(key, keySerializer, dos);
                serialize(value, valueSerializer, dos);
                dos.flush();

                // read response
                final DataInputStream dis = new DataInputStream(session.getInputStream());
                final byte[] responseBuffer = readLengthDelimitedResponse(dis);
                return valueDeserializer.deserialize(responseBuffer);
            }
        });
    }

    @Override
    public  V get(final K key, final Serializer keySerializer, final Deserializer valueDeserializer) throws IOException {
        return withCommsSession(new CommsAction() {
            @Override
            public V execute(final CommsSession session) throws IOException {
                final DataOutputStream dos = new DataOutputStream(session.getOutputStream());
                dos.writeUTF("get");

                serialize(key, keySerializer, dos);
                dos.flush();

                // read response
                final DataInputStream dis = new DataInputStream(session.getInputStream());
                final byte[] responseBuffer = readLengthDelimitedResponse(dis);
                return valueDeserializer.deserialize(responseBuffer);
            }
        });
    }

    @Override
    public  Map subMap(Set keys, Serializer keySerializer, Deserializer valueDeserializer) throws IOException {
        return withCommsSession(session -> {
            Map response = new HashMap<>(keys.size());
            try {
                validateProtocolVersion(session, 3);

                final DataOutputStream dos = new DataOutputStream(session.getOutputStream());
                dos.writeUTF("subMap");
                serialize(keys, keySerializer, dos);
                dos.flush();

                // read response
                final DataInputStream dis = new DataInputStream(session.getInputStream());

                for (K key : keys) {
                    final byte[] responseBuffer = readLengthDelimitedResponse(dis);
                    response.put(key, valueDeserializer.deserialize(responseBuffer));
                }
            } catch (UnsupportedOperationException uoe) {
                // If the server doesn't support subMap, just emulate it with multiple calls to get()
                for (K key : keys) {
                    response.put(key, get(key, keySerializer, valueDeserializer));
                }
            }

            return response;
        });
    }

    @Override
    public  boolean remove(final K key, final Serializer serializer) throws IOException {
        return withCommsSession(new CommsAction() {
            @Override
            public Boolean execute(final CommsSession session) throws IOException {
                final DataOutputStream dos = new DataOutputStream(session.getOutputStream());
                dos.writeUTF("remove");

                serialize(key, serializer, dos);
                dos.flush();

                // read response
                final DataInputStream dis = new DataInputStream(session.getInputStream());
                return dis.readBoolean();
            }
        });
    }

    @Override
    public  V removeAndGet(K key, Serializer keySerializer, Deserializer valueDeserializer) throws IOException {
        return withCommsSession(new CommsAction() {
            @Override
            public V execute(final CommsSession session) throws IOException {
                validateProtocolVersion(session, 3);

                final DataOutputStream dos = new DataOutputStream(session.getOutputStream());
                dos.writeUTF("removeAndGet");

                serialize(key, keySerializer, dos);
                dos.flush();

                // read response
                final DataInputStream dis = new DataInputStream(session.getInputStream());
                final byte[] responseBuffer = readLengthDelimitedResponse(dis);
                return valueDeserializer.deserialize(responseBuffer);
            }
        });
    }

    @Override
    public long removeByPattern(String regex) throws IOException {
        return withCommsSession(session -> {
            final DataOutputStream dos = new DataOutputStream(session.getOutputStream());
            dos.writeUTF("removeByPattern");
            dos.writeUTF(regex);
            dos.flush();

            // read response
            final DataInputStream dis = new DataInputStream(session.getInputStream());
            return dis.readLong();
        });
    }

    @Override
    public  Map removeByPatternAndGet(String regex, Deserializer keyDeserializer, Deserializer valueDeserializer) throws IOException {
        return withCommsSession(new CommsAction>() {
            @Override
            public Map execute(CommsSession session) throws IOException {
                validateProtocolVersion(session, 3);

                final DataOutputStream dos = new DataOutputStream(session.getOutputStream());
                dos.writeUTF("removeByPatternAndGet");
                dos.writeUTF(regex);
                dos.flush();

                // read response
                final DataInputStream dis = new DataInputStream(session.getInputStream());
                final int mapSize = dis.readInt();
                HashMap resultMap = new HashMap<>(mapSize);
                for (int i=0; i AtomicCacheEntry fetch(K key, Serializer keySerializer, Deserializer valueDeserializer) throws IOException {
        return withCommsSession(session -> {
            validateProtocolVersion(session, 2);

            final DataOutputStream dos = new DataOutputStream(session.getOutputStream());
            dos.writeUTF("fetch");

            serialize(key, keySerializer, dos);
            dos.flush();

            // read response
            final DataInputStream dis = new DataInputStream(session.getInputStream());
            final long revision = dis.readLong();
            final byte[] responseBuffer = readLengthDelimitedResponse(dis);

            if (revision < 0) {
                // This indicates that key was not found.
                return null;
            }

            return new AtomicCacheEntry(key, valueDeserializer.deserialize(responseBuffer), revision);
        });
    }

    private void validateProtocolVersion(final CommsSession session, final int requiredProtocolVersion) {
        if (session.getProtocolVersion() < requiredProtocolVersion) {
            throw new UnsupportedOperationException("Remote cache server doesn't support protocol version " + requiredProtocolVersion);
        }
    }

    @Override
    public  boolean replace(AtomicCacheEntry entry, Serializer keySerializer, Serializer valueSerializer) throws IOException {
        return withCommsSession(session -> {
            validateProtocolVersion(session, 2);

            final DataOutputStream dos = new DataOutputStream(session.getOutputStream());
            dos.writeUTF("replace");

            serialize(entry.getKey(), keySerializer, dos);
            dos.writeLong(entry.getRevision().orElse(0L));
            serialize(entry.getValue(), valueSerializer, dos);

            dos.flush();

            // read response
            final DataInputStream dis = new DataInputStream(session.getInputStream());
            return dis.readBoolean();
        });
    }

    @Override
    public  Set keySet(Deserializer keyDeserializer) throws IOException {
        return withCommsSession(session -> {
            validateProtocolVersion(session, 3);

            final DataOutputStream dos = new DataOutputStream(session.getOutputStream());
            dos.writeUTF("keySet");
            dos.flush();

            // read response
            final DataInputStream dis = new DataInputStream(session.getInputStream());
            final int setSize = dis.readInt();
            HashSet resultSet = new HashSet<>(setSize);
            for (int i=0; i void serialize(final T value, final Serializer serializer, final DataOutputStream dos) throws IOException {
        final ByteArrayOutputStream baos = new ByteArrayOutputStream();
        serializer.serialize(value, baos);
        dos.writeInt(baos.size());
        baos.writeTo(dos);
    }

    private  void serialize(final Set values, final Serializer serializer, final DataOutputStream dos) throws IOException {
        // Write the number of elements to follow, then each element and its size
        dos.writeInt(values.size());
        for(T value : values) {
            final ByteArrayOutputStream baos = new ByteArrayOutputStream();
            serializer.serialize(value, baos);
            dos.writeInt(baos.size());
            baos.writeTo(dos);
        }
    }

    private  T withCommsSession(final CommsAction action) throws IOException {
        if (closed) {
            throw new IllegalStateException("Client is closed");
        }
        boolean tryToRequeue = true;
        final CommsSession session = leaseCommsSession();
        try {
            return action.execute(session);
        } catch (final IOException ioe) {
            tryToRequeue = false;
            throw ioe;
        } finally {
            if (tryToRequeue == true && this.closed == false) {
                queue.offer(session);
            } else {
                IOUtils.closeQuietly(session);
            }
        }
    }

    private static interface CommsAction {

        T execute(CommsSession commsSession) throws IOException;
    }

}