com.github.pires.hazelcast.HazelcastDiscoveryController.java Source code

Java tutorial

Introduction

Here is the source code for com.github.pires.hazelcast.HazelcastDiscoveryController.java

Source

/**
 * Licensed 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 com.github.pires.hazelcast;

import com.hazelcast.config.Config;
import com.hazelcast.config.GroupConfig;
import com.hazelcast.config.JoinConfig;
import com.hazelcast.config.MulticastConfig;
import com.hazelcast.config.NetworkConfig;
import com.hazelcast.config.SSLConfig;
import com.hazelcast.config.TcpIpConfig;
import com.hazelcast.core.Hazelcast;
import io.fabric8.kubernetes.api.KubernetesClient;
import io.fabric8.kubernetes.api.KubernetesFactory;
import io.fabric8.kubernetes.api.model.Pod;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.CopyOnWriteArrayList;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Controller;

/**
 * Read from Kubernetes API all labeled Hazelcast pods, get their IP and connect to them.
 */
@Controller
public class HazelcastDiscoveryController implements CommandLineRunner {

    private static final Logger log = LoggerFactory.getLogger(HazelcastDiscoveryController.class);

    private static final String HAZELCAST_LABEL_NAME = "name";
    private static final String HAZELCAST_LABEL_VALUE = "hazelcast";

    private static String getEnvOrDefault(String var, String def) {
        final String val = System.getenv(var);
        return (val == null || val.isEmpty()) ? def : val;
    }

    @Override
    public void run(String... args) {
        final String kubeApiHost = getEnvOrDefault("KUBERNETES_RO_SERVICE_HOST", "localhost");
        final String kubeApiPort = getEnvOrDefault("KUBERNETES_RO_SERVICE_PORT", "8080");
        final String kubeUrl = "http://" + kubeApiHost + ":" + kubeApiPort;
        log.info("Asking k8s registry at {}..", kubeUrl);
        final KubernetesClient kube = new KubernetesClient(new KubernetesFactory(kubeUrl));
        final List<Pod> hazelcastPods = new CopyOnWriteArrayList<>();
        kube.getPods().getItems().parallelStream()
                .filter(pod -> pod.getLabels().get(HAZELCAST_LABEL_NAME).equals(HAZELCAST_LABEL_VALUE))
                .forEach(hazelcastPods::add);
        log.info("Found {} pods running Hazelcast.", hazelcastPods.size());
        if (!hazelcastPods.isEmpty()) {
            runHazelcast(hazelcastPods);
        }
    }

    private void runHazelcast(final List<Pod> hazelcastPods) {
        // configure Hazelcast instance
        final Config cfg = new Config();
        cfg.setInstanceName(UUID.randomUUID().toString());
        // group configuration
        final String HC_GROUP_NAME = getEnvOrDefault("HC_GROUP_NAME", "someGroup");
        final String HC_GROUP_PASSWORD = getEnvOrDefault("HC_GROUP_PASSWORD", "someSecret");
        final int HC_PORT = Integer.parseInt(getEnvOrDefault("HC_PORT", "5701"));
        cfg.setGroupConfig(new GroupConfig(HC_GROUP_NAME, HC_GROUP_PASSWORD));
        // network configuration initialization
        final NetworkConfig netCfg = new NetworkConfig();
        netCfg.setPortAutoIncrement(false);
        netCfg.setPort(HC_PORT);
        // multicast
        final MulticastConfig mcCfg = new MulticastConfig();
        mcCfg.setEnabled(false);
        // tcp
        final TcpIpConfig tcpCfg = new TcpIpConfig();
        hazelcastPods.parallelStream().forEach(pod -> {
            tcpCfg.addMember(pod.getCurrentState().getPodIP());
        });
        tcpCfg.setEnabled(true);
        // network join configuration
        final JoinConfig joinCfg = new JoinConfig();
        joinCfg.setMulticastConfig(mcCfg);
        joinCfg.setTcpIpConfig(tcpCfg);
        netCfg.setJoin(joinCfg);
        // ssl
        netCfg.setSSLConfig(new SSLConfig().setEnabled(false));
        // set it all
        cfg.setNetworkConfig(netCfg);
        // run
        Hazelcast.newHazelcastInstance(cfg);
    }

}