Search in sources :

Example 1 with IgnitionListener

use of org.apache.ignite.IgnitionListener in project ignite by apache.

the class GridFactorySelfTest method checkConcurrentStartStop.

/**
 * @param igniteInstanceName Ignite instance name ({@code null} for default grid).
 * @throws Exception If failed.
 */
private void checkConcurrentStartStop(@Nullable final String igniteInstanceName) throws Exception {
    final AtomicInteger startedCnt = new AtomicInteger();
    final AtomicInteger stoppedCnt = new AtomicInteger();
    IgnitionListener lsnr = new IgnitionListener() {

        @SuppressWarnings("StringEquality")
        @Override
        public void onStateChange(@Nullable String name, IgniteState state) {
            assert name == igniteInstanceName;
            info("On state change fired: " + state);
            if (state == STARTED)
                startedCnt.incrementAndGet();
            else {
                assert state == STOPPED : "Unexpected state: " + state;
                stoppedCnt.incrementAndGet();
            }
        }
    };
    G.addListener(lsnr);
    try {
        final int iterCnt = 3;
        multithreaded(new Callable<Object>() {

            @Nullable
            @Override
            public Object call() throws Exception {
                for (int i = 0; i < iterCnt; i++) {
                    try {
                        IgniteConfiguration cfg = getConfiguration(igniteInstanceName);
                        G.start(cfg);
                    } catch (Exception e) {
                        String msg = e.getMessage();
                        if (msg != null && (msg.contains("Default Ignite instance has already been started.") || msg.contains("Ignite instance with this name has already been started:")))
                            info("Caught expected exception: " + msg);
                        else
                            // Unexpected exception.
                            throw e;
                    } finally {
                        stopGrid(igniteInstanceName);
                    }
                }
                info("Thread finished.");
                return null;
            }
        }, 5, "tester");
        assert G.allGrids().isEmpty();
        assert startedCnt.get() == iterCnt;
        assert stoppedCnt.get() == iterCnt;
    } finally {
        G.removeListener(lsnr);
        G.stopAll(true);
    }
}
Also used : IgniteConfiguration(org.apache.ignite.configuration.IgniteConfiguration) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) IgnitionListener(org.apache.ignite.IgnitionListener) IgniteState(org.apache.ignite.IgniteState) Nullable(org.jetbrains.annotations.Nullable) IgniteCheckedException(org.apache.ignite.IgniteCheckedException) IgniteException(org.apache.ignite.IgniteException) IgniteSpiException(org.apache.ignite.spi.IgniteSpiException) BeansException(org.springframework.beans.BeansException)

Example 2 with IgnitionListener

use of org.apache.ignite.IgnitionListener in project ignite by apache.

the class GridFactorySelfTest method testStartMultipleGridsFromSpring.

/**
 * @throws Exception If failed.
 */
@SuppressWarnings({ "SynchronizationOnLocalVariableOrMethodParameter" })
public void testStartMultipleGridsFromSpring() throws Exception {
    File cfgFile = GridTestUtils.resolveIgnitePath(GridTestProperties.getProperty("loader.self.multipletest.config"));
    assert cfgFile != null;
    String path = cfgFile.getAbsolutePath();
    info("Loading Grid from configuration file: " + path);
    final GridTuple<IgniteState> gridState1 = F.t(null);
    final GridTuple<IgniteState> gridState2 = F.t(null);
    final Object mux = new Object();
    IgnitionListener factoryLsnr = new IgnitionListener() {

        @Override
        public void onStateChange(String name, IgniteState state) {
            synchronized (mux) {
                if ("grid-factory-test-1".equals(name))
                    gridState1.set(state);
                else if ("grid-factory-test-2".equals(name))
                    gridState2.set(state);
            }
        }
    };
    G.addListener(factoryLsnr);
    G.start(path);
    assert G.ignite("grid-factory-test-1") != null;
    assert G.ignite("grid-factory-test-2") != null;
    synchronized (mux) {
        assert gridState1.get() == STARTED : "Invalid grid state [expected=" + STARTED + ", returned=" + gridState1 + ']';
        assert gridState2.get() == STARTED : "Invalid grid state [expected=" + STARTED + ", returned=" + gridState2 + ']';
    }
    G.stop("grid-factory-test-1", true);
    G.stop("grid-factory-test-2", true);
    synchronized (mux) {
        assert gridState1.get() == STOPPED : "Invalid grid state [expected=" + STOPPED + ", returned=" + gridState1 + ']';
        assert gridState2.get() == STOPPED : "Invalid grid state [expected=" + STOPPED + ", returned=" + gridState2 + ']';
    }
}
Also used : IgnitionListener(org.apache.ignite.IgnitionListener) File(java.io.File) IgniteState(org.apache.ignite.IgniteState)

Example 3 with IgnitionListener

use of org.apache.ignite.IgnitionListener in project ignite by apache.

the class GridFactoryVmShutdownTest method main.

/**
 * @param args Args (optional).
 * @throws Exception If failed.
 */
public static void main(String[] args) throws Exception {
    final ConcurrentMap<String, IgniteState> states = new ConcurrentHashMap<>();
    G.addListener(new IgnitionListener() {

        @Override
        public void onStateChange(@Nullable String name, IgniteState state) {
            if (state == STARTED) {
                IgniteState state0 = states.put(maskNull(name), STARTED);
                assert state0 == null;
            } else {
                assert state == STOPPED;
                boolean replaced = states.replace(maskNull(name), STARTED, STOPPED);
                assert replaced;
            }
        }
    });
    // Test with shutdown hook enabled and disabled.
    // System.setProperty(GridSystemProperties.IGNITE_NO_SHUTDOWN_HOOK, "true");
    // Grid will start and add shutdown hook.
    G.start();
    Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() {

        @Override
        public void run() {
            IgniteConfiguration cfg = new IgniteConfiguration();
            cfg.setIgniteInstanceName("test1");
            try {
                G.start(cfg);
            } finally {
                X.println("States: " + states);
            }
        }
    }));
    System.exit(0);
}
Also used : IgniteConfiguration(org.apache.ignite.configuration.IgniteConfiguration) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) IgnitionListener(org.apache.ignite.IgnitionListener) IgniteState(org.apache.ignite.IgniteState)

Example 4 with IgnitionListener

use of org.apache.ignite.IgnitionListener in project ignite by apache.

the class GridRandomCommandLineLoader method main.

/**
 * Main entry point.
 *
 * @param args Command line arguments.
 */
@SuppressWarnings({ "BusyWait" })
public static void main(String[] args) {
    System.setProperty(IgniteSystemProperties.IGNITE_UPDATE_NOTIFIER, "false");
    logo();
    Options options = createOptions();
    // Create the command line parser.
    CommandLineParser parser = new PosixParser();
    String cfgPath = null;
    long minTtl = DFLT_MIN_TIMEOUT;
    long maxTtl = DFLT_MAX_TIMEOUT;
    long duration = DFLT_RUN_TIMEOUT;
    String logCfgPath = null;
    try {
        CommandLine cmd = parser.parse(options, args);
        if (cmd.hasOption(OPTION_HELP))
            exit(null, options, 0);
        if (!cmd.hasOption(OPTION_LOG_CFG))
            exit("-log should be set", options, -1);
        else
            logCfgPath = cmd.getOptionValue(OPTION_LOG_CFG);
        if (cmd.hasOption(OPTION_CFG))
            cfgPath = cmd.getOptionValue(OPTION_CFG);
        try {
            if (cmd.hasOption(OPTION_DURATION))
                duration = Long.parseLong(cmd.getOptionValue(OPTION_DURATION));
        } catch (NumberFormatException ignored) {
            exit("Invalid argument for option: " + OPTION_DURATION, options, -1);
        }
        try {
            if (cmd.hasOption(OPTION_MIN_TTL))
                minTtl = Long.parseLong(cmd.getOptionValue(OPTION_MIN_TTL));
        } catch (NumberFormatException ignored) {
            exit("Invalid argument for option: " + OPTION_MIN_TTL, options, -1);
        }
        try {
            if (cmd.hasOption(OPTION_MAX_TTL))
                maxTtl = Long.parseLong(cmd.getOptionValue(OPTION_MAX_TTL));
        } catch (NumberFormatException ignored) {
            exit("Invalid argument for option: " + OPTION_MAX_TTL, options, -1);
        }
        if (minTtl >= maxTtl)
            exit("Invalid arguments for options: " + OPTION_MAX_TTL + ", " + OPTION_MIN_TTL, options, -1);
    } catch (ParseException e) {
        exit(e.getMessage(), options, -1);
    }
    System.out.println("Configuration path: " + cfgPath);
    System.out.println("Log4j configuration path: " + logCfgPath);
    System.out.println("Duration: " + duration);
    System.out.println("Minimum TTL: " + minTtl);
    System.out.println("Maximum TTL: " + maxTtl);
    G.addListener(new IgnitionListener() {

        @Override
        public void onStateChange(String name, IgniteState state) {
            if (state == STOPPED && latch != null)
                latch.countDown();
        }
    });
    Random rand = new Random();
    long now = System.currentTimeMillis();
    long end = duration + System.currentTimeMillis();
    try {
        while (now < end) {
            G.start(getConfiguration(cfgPath, logCfgPath));
            long delay = rand.nextInt((int) (maxTtl - minTtl)) + minTtl;
            delay = (now + delay > end) ? (end - now) : delay;
            now = System.currentTimeMillis();
            echo("Time left (ms): " + (end - now));
            echo("Going to sleep for (ms): " + delay);
            Thread.sleep(delay);
            G.stopAll(false);
            now = System.currentTimeMillis();
        }
    } catch (IgniteCheckedException e) {
        echo(e);
        exit("Failed to start grid: " + e.getMessage(), null, -1);
    } catch (InterruptedException e) {
        echo("Loader was interrupted (exiting): " + e.getMessage());
    }
    latch = new CountDownLatch(G.allGrids().size());
    try {
        while (latch.getCount() > 0) latch.await();
    } catch (InterruptedException e) {
        echo("Loader was interrupted (exiting): " + e.getMessage());
    }
    System.exit(0);
}
Also used : Options(org.apache.commons.cli.Options) PosixParser(org.apache.commons.cli.PosixParser) IgnitionListener(org.apache.ignite.IgnitionListener) CountDownLatch(java.util.concurrent.CountDownLatch) CommandLine(org.apache.commons.cli.CommandLine) IgniteCheckedException(org.apache.ignite.IgniteCheckedException) Random(java.util.Random) CommandLineParser(org.apache.commons.cli.CommandLineParser) ParseException(org.apache.commons.cli.ParseException) IgniteState(org.apache.ignite.IgniteState)

Example 5 with IgnitionListener

use of org.apache.ignite.IgnitionListener in project ignite by apache.

the class TcpClientDiscoverySpiSelfTest method testClientSegmentation.

/**
 * @throws Exception If failed.
 */
public void testClientSegmentation() throws Exception {
    clientsPerSrv = 1;
    reconnectDisabled = true;
    startServerNodes(3);
    startClientNodes(3);
    checkNodes(3, 3);
    srvFailedLatch = new CountDownLatch(2 + 2);
    clientFailedLatch = new CountDownLatch(2 + 2);
    attachListeners(2, 2);
    final CountDownLatch client2StoppedLatch = new CountDownLatch(1);
    IgnitionListener lsnr = new IgnitionListener() {

        @Override
        public void onStateChange(@Nullable String name, IgniteState state) {
            if (state == IgniteState.STOPPED_ON_SEGMENTATION)
                client2StoppedLatch.countDown();
        }
    };
    G.addListener(lsnr);
    final TcpDiscoverySpi disco = (TcpDiscoverySpi) G.ignite("client-2").configuration().getDiscoverySpi();
    try {
        log.info("Fail server: " + 2);
        failServer(2);
        awaitClient(srvFailedLatch);
        awaitClient(clientFailedLatch);
        await(client2StoppedLatch);
        checkNodes(2, 2);
    } finally {
        G.removeListener(lsnr);
    }
    assert disco.getRemoteNodes().isEmpty();
}
Also used : CountDownLatch(java.util.concurrent.CountDownLatch) IgnitionListener(org.apache.ignite.IgnitionListener) IgniteState(org.apache.ignite.IgniteState) Nullable(org.jetbrains.annotations.Nullable)

Aggregations

IgniteState (org.apache.ignite.IgniteState)7 IgnitionListener (org.apache.ignite.IgnitionListener)7 CountDownLatch (java.util.concurrent.CountDownLatch)3 IgniteCheckedException (org.apache.ignite.IgniteCheckedException)2 IgniteConfiguration (org.apache.ignite.configuration.IgniteConfiguration)2 Nullable (org.jetbrains.annotations.Nullable)2 File (java.io.File)1 IOException (java.io.IOException)1 Random (java.util.Random)1 ConcurrentHashMap (java.util.concurrent.ConcurrentHashMap)1 AtomicInteger (java.util.concurrent.atomic.AtomicInteger)1 CommandLine (org.apache.commons.cli.CommandLine)1 CommandLineParser (org.apache.commons.cli.CommandLineParser)1 Options (org.apache.commons.cli.Options)1 ParseException (org.apache.commons.cli.ParseException)1 PosixParser (org.apache.commons.cli.PosixParser)1 IgniteException (org.apache.ignite.IgniteException)1 IgniteSpiException (org.apache.ignite.spi.IgniteSpiException)1 BeansException (org.springframework.beans.BeansException)1