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

io.takari.orchestra.plugins.nexus.perf.AgentPoolHolder Maven / Gradle / Ivy

package io.takari.orchestra.plugins.nexus.perf;

import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import com.google.common.cache.RemovalListener;
import com.google.common.util.concurrent.AbstractScheduledService;
import com.sonatype.nexus.perftest.controller.AgentPool;
import com.sonatype.nexus.perftest.controller.JMXServiceURLs;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.inject.Inject;
import javax.inject.Named;
import javax.inject.Singleton;
import java.util.concurrent.TimeUnit;

@Named
@Singleton
public class AgentPoolHolder extends AbstractScheduledService {

    private static final Logger log = LoggerFactory.getLogger(AgentPoolHolder.class);
    private static final long CLEANUP_INTERVAL = 15000;

    private final Cache agents;

    public AgentPoolHolder() {
        this.agents = CacheBuilder.newBuilder()
                .expireAfterAccess(1, TimeUnit.HOURS)
                .removalListener((RemovalListener) notification -> {
                    try {
                        notification.getValue().release();
                    } catch (Exception e) {
                        log.warn("removalListener -> error while releasing a manager for '{}'", notification.getKey());
                    }
                })
                .build();
    }

    @Inject
    public void start() {
        this.startAsync();
    }

    @Override
    protected void runOneIteration() throws Exception {
        agents.cleanUp();
        log.debug("cleanup -> done, {} pool(s) left", agents.size());
    }

    @Override
    protected Scheduler scheduler() {
        return AbstractScheduledService.Scheduler.newFixedDelaySchedule(CLEANUP_INTERVAL, CLEANUP_INTERVAL, TimeUnit.MILLISECONDS);
    }

    /**
     * Creates a new JMX agent pool for specified URLs.
     *
     * @param id   Unique ID that will be associated with the created pool.
     * @param urls
     */
    public void connect(String id, String[] urls) {
        AgentPoolManager m = null;

        synchronized (agents) {
            m = agents.getIfPresent(id);
            if (m != null) {
                throw new IllegalStateException("The agent pool for '" + id + "' is already created");
            }

            m = new AgentPoolManager(new AgentPool(JMXServiceURLs.of(urls)));
            agents.put(id, m);
        }
    }

    public AgentPoolManager get(String id) {
        synchronized (agents) {
            return agents.getIfPresent(id);
        }
    }
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy