Search in sources :

Example 21 with StopWatch

use of org.apache.geode.internal.util.StopWatch in project geode by apache.

the class PidFile method readPid.

/**
   * Reads in the pid from the specified file, retrying until the specified timeout.
   * 
   * @param timeout the maximum time to spend trying to read the pidFile
   * @param unit the unit of timeout
   * 
   * @return the process id (pid) contained within the pidFile
   * 
   * @throws IllegalArgumentException if the pid in the pidFile is not a positive integer
   * @throws IOException if unable to read from the specified file
   * @throws InterruptedException if interrupted
   * @throws TimeoutException if operation times out
   */
public int readPid(final long timeout, final TimeUnit unit) throws IOException, InterruptedException, TimeoutException {
    IllegalArgumentException iae = null;
    IOException ioe = null;
    int pid = 0;
    final long timeoutMillis = unit.toMillis(timeout);
    final StopWatch stopWatch = new StopWatch(true);
    while (pid <= 0) {
        try {
            pid = readPid();
        } catch (IllegalArgumentException e) {
            iae = e;
        } catch (IOException e) {
            ioe = e;
        }
        if (stopWatch.elapsedTimeMillis() > timeoutMillis) {
            if (iae != null) {
                throw new TimeoutException(iae.getMessage());
            }
            if (ioe != null) {
                throw new TimeoutException(ioe.getMessage());
            }
        } else {
            try {
                Thread.sleep(SLEEP_INTERVAL_MILLIS);
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
                if (iae != null) {
                    throw new InterruptedException(iae.getMessage());
                }
                if (ioe != null) {
                    throw new InterruptedException(ioe.getMessage());
                }
                throw e;
            }
        }
    }
    return pid;
}
Also used : IOException(java.io.IOException) StopWatch(org.apache.geode.internal.util.StopWatch) TimeoutException(java.util.concurrent.TimeoutException)

Example 22 with StopWatch

use of org.apache.geode.internal.util.StopWatch in project geode by apache.

the class BucketAdvisor method waitForPrimaryMember.

/**
   * Wait briefly for a primary member to be identified.
   * 
   * @param timeout time in milliseconds to wait for a primary
   * @return the primary bucket host
   */
protected InternalDistributedMember waitForPrimaryMember(long timeout) {
    synchronized (this) {
        // let's park this thread and wait for a primary!
        StopWatch timer = new StopWatch(true);
        long warnTime = getDistributionManager().getConfig().getAckWaitThreshold() * 1000L;
        boolean loggedWarning = false;
        try {
            for (; ; ) {
                // bail out if the system starts closing
                this.getAdvisee().getCancelCriterion().checkCancelInProgress(null);
                final InternalCache cache = getBucket().getCache();
                if (cache != null && cache.isCacheAtShutdownAll()) {
                    throw new CacheClosedException("Cache is shutting down");
                }
                if (getBucketRedundancy() == -1) {
                    // there are no real buckets in other vms... no reason to wait
                    return null;
                }
                getProxyBucketRegion().getPartitionedRegion().checkReadiness();
                if (isClosed()) {
                    break;
                }
                long elapsed = timer.elapsedTimeMillis();
                long timeLeft = timeout - elapsed;
                if (timeLeft <= 0) {
                    break;
                }
                if (getBucketRedundancy() == -1 || isClosed()) {
                    // early out... all bucket regions are gone or we closed
                    break;
                }
                InternalDistributedMember primary = basicGetPrimaryMember();
                if (primary != null) {
                    return primary;
                }
                if (logger.isDebugEnabled()) {
                    logger.debug("Waiting for bucket {}. Time left :{} ms", this, timeLeft);
                }
                // Log a warning if we have waited for the ack wait threshold time.
                if (!loggedWarning) {
                    long timeUntilWarning = warnTime - elapsed;
                    if (timeUntilWarning <= 0) {
                        logger.warn(LocalizedMessage.create(LocalizedStrings.BucketAdvisor_WAITING_FOR_PRIMARY, new Object[] { warnTime / 1000L, this, this.adviseInitialized() }));
                        // log a warning;
                        loggedWarning = true;
                    } else {
                        timeLeft = timeLeft > timeUntilWarning ? timeUntilWarning : timeLeft;
                    }
                }
                // spurious wakeup ok
                this.wait(timeLeft);
            }
        } catch (InterruptedException e) {
            // abort and return null
            Thread.currentThread().interrupt();
        } finally {
            if (loggedWarning) {
                logger.info(LocalizedMessage.create(LocalizedStrings.BucketAdvisor_WAITING_FOR_PRIMARY_DONE));
            }
        }
        return null;
    }
}
Also used : InternalDistributedMember(org.apache.geode.distributed.internal.membership.InternalDistributedMember) CacheClosedException(org.apache.geode.cache.CacheClosedException) StopWatch(org.apache.geode.internal.util.StopWatch)

Example 23 with StopWatch

use of org.apache.geode.internal.util.StopWatch in project geode by apache.

the class BucketAdvisor method waitForRedundancy.

/**
   * Wait the desired redundancy to be met.
   * 
   * @param minRedundancy the amount of desired redundancy.
   * @return true if desired redundancy is detected
   */
public boolean waitForRedundancy(int minRedundancy) {
    synchronized (this) {
        // let's park this thread and wait for redundancy!
        StopWatch timer = new StopWatch(true);
        try {
            for (; ; ) {
                if (getBucketRedundancy() >= minRedundancy) {
                    return true;
                }
                getProxyBucketRegion().getPartitionedRegion().checkReadiness();
                if (isClosed()) {
                    return false;
                }
                long timeLeft = BUCKET_REDUNDANCY_WAIT - timer.elapsedTimeMillis();
                if (timeLeft <= 0) {
                    return false;
                }
                if (logger.isDebugEnabled()) {
                    logger.debug("Waiting for bucket {}", this);
                }
                // spurious wakeup ok
                this.wait(timeLeft);
            }
        } catch (InterruptedException e) {
            // abort and return null
            Thread.currentThread().interrupt();
        }
        return false;
    }
}
Also used : StopWatch(org.apache.geode.internal.util.StopWatch)

Example 24 with StopWatch

use of org.apache.geode.internal.util.StopWatch in project geode by apache.

the class TXJUnitTest method waitForUpdates.

private static void waitForUpdates(final Index idx, final int expectedUpdates) {
    // DistributedTestCase.WaitCriterion wc = new DistributedTestCase.WaitCriterion() {
    // String excuse;
    // public boolean done() {
    // return idx.getStatistics().getNumUpdates() == expectedUpdates;
    // }
    //
    // public String description() {
    // return "expectedUpdates " + expectedUpdates + " but got this "
    // + idx.getStatistics().getNumUpdates();
    // }
    // };
    // DistributedTestCase.waitForCriterion(wc, 15 * 1000, 20, true);
    boolean done = false;
    try {
        for (StopWatch time = new StopWatch(true); !done && time.elapsedTimeMillis() < 15 * 1000; done = (idx.getStatistics().getNumUpdates() == expectedUpdates)) {
            Thread.sleep(20);
        }
    } catch (InterruptedException e) {
        Thread.currentThread().interrupt();
    }
    assertTrue("expectedUpdates " + expectedUpdates + " but got this " + idx.getStatistics().getNumUpdates(), done);
}
Also used : StopWatch(org.apache.geode.internal.util.StopWatch)

Example 25 with StopWatch

use of org.apache.geode.internal.util.StopWatch in project geode by apache.

the class PidFileJUnitTest method readsIntBeforeTimeout.

@Test
public void readsIntBeforeTimeout() throws Exception {
    final int AWAIT_LATCH_TIMEOUT_MILLIS = 10 * 1000;
    final int OPEN_LATCH_DELAY_MILLIS = 2 * 1000;
    final int FUTURE_GET_TIMEOUT_MILLIS = 2 * 1000;
    final int READ_PID_TIMEOUT_MILLIS = 2 * OPEN_LATCH_DELAY_MILLIS;
    final File file = testFolder.newFile("my.pid");
    final FileWriter writer = new FileWriter(file);
    final CountDownLatch writePidLatch = new CountDownLatch(1);
    final String value = "42";
    // start Future to write the pid later but before timeout
    Future<Boolean> futureWritePid = this.futures.submit(new Callable<Boolean>() {

        @Override
        public Boolean call() throws Exception {
            writePidLatch.await(AWAIT_LATCH_TIMEOUT_MILLIS, TimeUnit.MILLISECONDS);
            writeToFile(file, value);
            return true;
        }
    });
    // start Future to sleep and release the delay
    Future<Boolean> futureOpenLatch = this.futures.submit(new Callable<Boolean>() {

        @Override
        public Boolean call() throws Exception {
            Thread.sleep(OPEN_LATCH_DELAY_MILLIS);
            writePidLatch.countDown();
            return true;
        }
    });
    StopWatch stopWatch = new StopWatch(true);
    final int readValue = new PidFile(file).readPid(READ_PID_TIMEOUT_MILLIS, TimeUnit.MILLISECONDS);
    assertEquals(Integer.parseInt(value), readValue);
    long duration = stopWatch.elapsedTimeMillis();
    assertTrue(duration > OPEN_LATCH_DELAY_MILLIS);
    assertTrue(duration < READ_PID_TIMEOUT_MILLIS);
    assertEquals(0, writePidLatch.getCount());
    assertTrue(futureOpenLatch.get(FUTURE_GET_TIMEOUT_MILLIS, TimeUnit.MILLISECONDS));
    assertTrue(futureWritePid.get(FUTURE_GET_TIMEOUT_MILLIS, TimeUnit.MILLISECONDS));
}
Also used : FileWriter(java.io.FileWriter) CountDownLatch(java.util.concurrent.CountDownLatch) TimeoutException(java.util.concurrent.TimeoutException) ExpectedException(org.junit.rules.ExpectedException) IOException(java.io.IOException) FileNotFoundException(java.io.FileNotFoundException) StopWatch(org.apache.geode.internal.util.StopWatch) File(java.io.File) Test(org.junit.Test) IntegrationTest(org.apache.geode.test.junit.categories.IntegrationTest)

Aggregations

StopWatch (org.apache.geode.internal.util.StopWatch)37 Test (org.junit.Test)13 IntegrationTest (org.apache.geode.test.junit.categories.IntegrationTest)9 ClientServerTest (org.apache.geode.test.junit.categories.ClientServerTest)4 FlakyTest (org.apache.geode.test.junit.categories.FlakyTest)4 File (java.io.File)3 IOException (java.io.IOException)3 Properties (java.util.Properties)2 TimeoutException (java.util.concurrent.TimeoutException)2 AtomicInteger (java.util.concurrent.atomic.AtomicInteger)2 Statistics (org.apache.geode.Statistics)2 Region (org.apache.geode.cache.Region)2 FailureTracker (org.apache.geode.cache.client.internal.ServerBlackList.FailureTracker)2 ConfigurationProperties (org.apache.geode.distributed.ConfigurationProperties)2 ServerLocation (org.apache.geode.distributed.internal.ServerLocation)2 InternalDistributedMember (org.apache.geode.distributed.internal.membership.InternalDistributedMember)2 MemberMXBean (org.apache.geode.management.MemberMXBean)2 CliMetaData (org.apache.geode.management.cli.CliMetaData)2 MXBeanProvider.getMemberMXBean (org.apache.geode.management.internal.cli.shell.MXBeanProvider.getMemberMXBean)2 SerializableRunnable (org.apache.geode.test.dunit.SerializableRunnable)2