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

org.zodic.kubernetes.leader.LeaderInitiator Maven / Gradle / Ivy

package org.zodic.kubernetes.leader;

import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import org.springframework.context.SmartLifecycle;

public class LeaderInitiator implements SmartLifecycle {

    private static final Logger LOGGER = LoggerFactory.getLogger(LeaderInitiator.class);

    private final LeaderInfo leaderInfo;

    private final LeadershipController leadershipController;

    private final LeaderRecordWatcher leaderRecordWatcher;

    private final PodReadinessWatcher hostPodWatcher;

    private ScheduledExecutorService scheduledExecutorService;

    private boolean isRunning;

    public LeaderInitiator(LeaderInfo leaderInfo, LeadershipController leadershipController,
        LeaderRecordWatcher leaderRecordWatcher, PodReadinessWatcher hostPodWatcher) {
        this.leaderInfo = leaderInfo;
        this.leadershipController = leadershipController;
        this.leaderRecordWatcher = leaderRecordWatcher;
        this.hostPodWatcher = hostPodWatcher;
    }

    @Override
    public boolean isAutoStartup() {
        return this.leaderInfo.isAutoStartup();
    }

    @Override
    public void start() {
        if (!isRunning()) {
            LOGGER.debug("Leader initiator starting");
            this.leaderRecordWatcher.start();
            this.hostPodWatcher.start();
            this.scheduledExecutorService = Executors.newSingleThreadScheduledExecutor();
            this.scheduledExecutorService.scheduleAtFixedRate(this.leadershipController::update,
                this.leaderInfo.getUpdatePeriod().toMillis(), this.leaderInfo.getUpdatePeriod().toMillis(),
                TimeUnit.MILLISECONDS);
            this.isRunning = true;
        }
    }

    @Override
    public void stop() {
        if (isRunning()) {
            LOGGER.debug("Leader initiator stopping");
            this.scheduledExecutorService.shutdown();
            this.scheduledExecutorService = null;
            this.hostPodWatcher.stop();
            this.leaderRecordWatcher.stop();
            this.leadershipController.revoke();
            this.isRunning = false;
        }
    }

    @Override
    public void stop(Runnable callback) {
        stop();
        callback.run();
    }

    @Override
    public boolean isRunning() {
        return this.isRunning;
    }

    @Override
    public int getPhase() {
        return 0;
    }

}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy