Search in sources :

Example 21 with TimeUnit

use of java.util.concurrent.TimeUnit in project legacy-jclouds-examples by jclouds.

the class WindowsInstanceStarter method run.

public void run() {
    final String region = arguments.getRegion();
    // Build a template
    Template template = computeService.templateBuilder().locationId(region).imageNameMatches(arguments.getImageNamePattern()).hardwareId(arguments.getInstanceType()).build();
    logger.info("Selected AMI is: %s", template.getImage().toString());
    template.getOptions().inboundPorts(3389);
    // Create the node
    logger.info("Creating node and waiting for it to become available");
    Set<? extends NodeMetadata> nodes = null;
    try {
        nodes = computeService.createNodesInGroup("basic-ami", 1, template);
    } catch (RunNodesException e) {
        logger.error(e, "Unable to start nodes; aborting");
        return;
    }
    NodeMetadata node = Iterables.getOnlyElement(nodes);
    // Wait for the administrator password
    logger.info("Waiting for administrator password to become available");
    // This predicate will call EC2's API to get the Windows Administrator
    // password, and returns true if there is password data available.
    Predicate<String> passwordReady = new Predicate<String>() {

        @Override
        public boolean apply(@Nullable String s) {
            if (Strings.isNullOrEmpty(s))
                return false;
            PasswordData data = ec2Client.getWindowsServices().getPasswordDataInRegion(region, s);
            if (data == null)
                return false;
            return !Strings.isNullOrEmpty(data.getPasswordData());
        }
    };
    // Now wait, using RetryablePredicate
    final int maxWait = 600;
    final int period = 10;
    final TimeUnit timeUnit = TimeUnit.SECONDS;
    RetryablePredicate<String> passwordReadyRetryable = new RetryablePredicate<String>(passwordReady, maxWait, period, timeUnit);
    boolean isPasswordReady = passwordReadyRetryable.apply(node.getProviderId());
    if (!isPasswordReady) {
        logger.error("Password is not ready after %s %s - aborting and shutting down node", maxWait, timeUnit.toString());
        computeService.destroyNode(node.getId());
        return;
    }
    // Now we can get the password data, decrypt it, and get a LoginCredentials instance
    PasswordDataAndPrivateKey dataAndKey = new PasswordDataAndPrivateKey(ec2Client.getWindowsServices().getPasswordDataInRegion(region, node.getProviderId()), node.getCredentials().getPrivateKey());
    WindowsLoginCredentialsFromEncryptedData f = context.getUtils().getInjector().getInstance(WindowsLoginCredentialsFromEncryptedData.class);
    LoginCredentials credentials = f.apply(dataAndKey);
    // Send to the log the details you need to log in to the instance with RDP
    String publicIp = Iterables.getFirst(node.getPublicAddresses(), null);
    logger.info("IP address: %s", publicIp);
    logger.info("Login name: %s", credentials.getUser());
    logger.info("Password:   %s", credentials.getPassword());
    // Wait for Enter on the console
    logger.info("Hit Enter to shut down the node.");
    InputStreamReader converter = new InputStreamReader(System.in);
    BufferedReader in = new BufferedReader(converter);
    try {
        in.readLine();
    } catch (IOException e) {
        logger.error(e, "IOException while reading console input");
    }
    // Tidy up
    logger.info("Shutting down");
    computeService.destroyNode(node.getId());
}
Also used : RetryablePredicate(org.jclouds.predicates.RetryablePredicate) WindowsLoginCredentialsFromEncryptedData(org.jclouds.ec2.compute.functions.WindowsLoginCredentialsFromEncryptedData) InputStreamReader(java.io.InputStreamReader) IOException(java.io.IOException) Template(org.jclouds.compute.domain.Template) Predicate(com.google.common.base.Predicate) RetryablePredicate(org.jclouds.predicates.RetryablePredicate) NodeMetadata(org.jclouds.compute.domain.NodeMetadata) LoginCredentials(org.jclouds.domain.LoginCredentials) RunNodesException(org.jclouds.compute.RunNodesException) PasswordData(org.jclouds.ec2.domain.PasswordData) BufferedReader(java.io.BufferedReader) TimeUnit(java.util.concurrent.TimeUnit) PasswordDataAndPrivateKey(org.jclouds.ec2.compute.domain.PasswordDataAndPrivateKey) Nullable(javax.annotation.Nullable)

Example 22 with TimeUnit

use of java.util.concurrent.TimeUnit in project hibernate-orm by hibernate.

the class PutFromLoadStressTestCase method doTest.

private void doTest(boolean warmup) throws Exception {
    ExecutorService executor = Executors.newFixedThreadPool(NUM_THREADS);
    try {
        CyclicBarrier barrier = new CyclicBarrier(NUM_THREADS + 1);
        List<Future<String>> futures = new ArrayList<Future<String>>(NUM_THREADS);
        for (int i = 0; i < NUM_THREADS; i++) {
            Future<String> future = executor.submit(new SelectQueryRunner(barrier, warmup, i + 1));
            futures.add(future);
            Thread.sleep(LAUNCH_INTERVAL_MILLIS);
        }
        // wait for all threads to be ready
        barrier.await();
        long timeout = warmup ? WARMUP_TIME_SECS : RUNNING_TIME_SECS;
        TimeUnit unit = TimeUnit.SECONDS;
        // Wait for the duration of the test
        Thread.sleep(unit.toMillis(timeout));
        // Instruct tests to stop doing work
        run.set(false);
        // wait for all threads to finish
        barrier.await(2, TimeUnit.MINUTES);
        log.infof("[%s] All threads finished, check for exceptions", title(warmup));
        for (Future<String> future : futures) {
            String opsPerMS = future.get();
            if (!warmup)
                log.infof("[%s] Operations/ms: %s", title(warmup), opsPerMS);
        }
        log.infof("[%s] All future gets checked", title(warmup));
    } catch (Exception e) {
        log.errorf(e, "Error in one of the execution threads during %s", title(warmup));
        throw e;
    } finally {
        executor.shutdownNow();
    }
}
Also used : ExecutorService(java.util.concurrent.ExecutorService) ArrayList(java.util.ArrayList) Future(java.util.concurrent.Future) TimeUnit(java.util.concurrent.TimeUnit) CyclicBarrier(java.util.concurrent.CyclicBarrier)

Example 23 with TimeUnit

use of java.util.concurrent.TimeUnit in project hudson-2.x by hudson.

the class Request method callAsync.

/**
     * Makes an invocation but immediately returns without waiting for the completion
     * (AKA asynchronous invocation.)
     *
     * @param channel
     *      The channel from which the request will be sent.
     * @return
     *      The {@link Future} object that can be used to wait for the completion.
     * @throws IOException
     *      If there's an error during the communication.
     */
public final hudson.remoting.Future<RSP> callAsync(final Channel channel) throws IOException {
    response = null;
    channel.pendingCalls.put(id, this);
    channel.send(this);
    return new hudson.remoting.Future<RSP>() {

        private volatile boolean cancelled;

        public boolean cancel(boolean mayInterruptIfRunning) {
            if (cancelled || isDone()) {
                return false;
            }
            cancelled = true;
            if (mayInterruptIfRunning) {
                try {
                    channel.send(new Cancel(id));
                } catch (IOException x) {
                    return false;
                }
            }
            return true;
        }

        public boolean isCancelled() {
            return cancelled;
        }

        public boolean isDone() {
            return isCancelled() || response != null;
        }

        public RSP get() throws InterruptedException, ExecutionException {
            synchronized (Request.this) {
                try {
                    while (response == null) {
                        if (isCancelled()) {
                            throw new CancellationException();
                        }
                        // wait until the response arrives
                        Request.this.wait();
                    }
                } catch (InterruptedException e) {
                    try {
                        channel.send(new Cancel(id));
                    } catch (IOException e1) {
                    // couldn't cancel. ignore.
                    }
                    throw e;
                }
                if (response.exception != null)
                    throw new ExecutionException(response.exception);
                return response.returnValue;
            }
        }

        public RSP get(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException {
            synchronized (Request.this) {
                if (response == null) {
                    if (isCancelled()) {
                        throw new CancellationException();
                    }
                    // wait until the response arrives
                    Request.this.wait(unit.toMillis(timeout));
                }
                if (response == null)
                    throw new TimeoutException();
                if (response.exception != null)
                    throw new ExecutionException(response.exception);
                return response.returnValue;
            }
        }
    };
}
Also used : CancellationException(java.util.concurrent.CancellationException) Future(java.util.concurrent.Future) TimeUnit(java.util.concurrent.TimeUnit) IOException(java.io.IOException) ExecutionException(java.util.concurrent.ExecutionException) TimeoutException(java.util.concurrent.TimeoutException)

Example 24 with TimeUnit

use of java.util.concurrent.TimeUnit in project pinot by linkedin.

the class DetectionJobSchedulerUtils method getDateTimeFormatterForDataset.

/**
   * Get date time formatter according to granularity of dataset
   * This is to store the date in the db, in the correct SDF
   * @param timeSpec
   * @return
   */
public static DateTimeFormatter getDateTimeFormatterForDataset(DatasetConfigDTO datasetConfig, DateTimeZone dateTimeZone) {
    String pattern = null;
    TimeSpec timeSpec = ThirdEyeUtils.getTimeSpecFromDatasetConfig(datasetConfig);
    TimeUnit unit = timeSpec.getDataGranularity().getUnit();
    switch(unit) {
        case DAYS:
            pattern = DAY_FORMAT;
            break;
        case MINUTES:
        case SECONDS:
        case MILLISECONDS:
            pattern = MINUTE_FORMAT;
            break;
        case HOURS:
        default:
            pattern = HOUR_FORMAT;
            break;
    }
    DateTimeFormatter dateTimeFormatter = DateTimeFormat.forPattern(pattern).withZone(dateTimeZone);
    return dateTimeFormatter;
}
Also used : TimeUnit(java.util.concurrent.TimeUnit) DateTimeFormatter(org.joda.time.format.DateTimeFormatter) TimeSpec(com.linkedin.thirdeye.api.TimeSpec)

Example 25 with TimeUnit

use of java.util.concurrent.TimeUnit in project pinot by linkedin.

the class AnomaliesResource method getTimeseriesOffsetedTimes.

private TimeRange getTimeseriesOffsetedTimes(long anomalyStartTime, long anomalyEndTime, DatasetConfigDTO datasetConfig) {
    TimeUnit dataTimeunit = datasetConfig.getTimeUnit();
    Period offsetPeriod;
    switch(dataTimeunit) {
        case // 3 days
        DAYS:
            offsetPeriod = new Period(0, 0, 0, 3, 0, 0, 0, 0);
            break;
        case // 10 hours
        HOURS:
            offsetPeriod = new Period(0, 0, 0, 0, 10, 0, 0, 0);
            break;
        case // 60 minutes
        MINUTES:
            offsetPeriod = new Period(0, 0, 0, 0, 0, 60, 0, 0);
            break;
        default:
            offsetPeriod = new Period();
    }
    DateTimeZone dateTimeZone = DateTimeZone.forID(datasetConfig.getTimezone());
    DateTime anomalyStartDateTime = new DateTime(anomalyStartTime, dateTimeZone);
    DateTime anomalyEndDateTime = new DateTime(anomalyEndTime, dateTimeZone);
    anomalyStartDateTime = anomalyStartDateTime.minus(offsetPeriod);
    anomalyEndDateTime = anomalyEndDateTime.plus(offsetPeriod);
    anomalyStartTime = anomalyStartDateTime.getMillis();
    anomalyEndTime = anomalyEndDateTime.getMillis();
    try {
        Long maxDataTime = CACHE_REGISTRY.getCollectionMaxDataTimeCache().get(datasetConfig.getDataset());
        if (anomalyEndTime > maxDataTime) {
            anomalyEndTime = maxDataTime;
        }
    } catch (ExecutionException e) {
        LOG.error("Exception when reading max time for {}", datasetConfig.getDataset(), e);
    }
    TimeRange range = new TimeRange(anomalyStartTime, anomalyEndTime);
    return range;
}
Also used : TimeRange(com.linkedin.thirdeye.api.TimeRange) TimeUnit(java.util.concurrent.TimeUnit) Period(org.joda.time.Period) ExecutionException(java.util.concurrent.ExecutionException) DateTimeZone(org.joda.time.DateTimeZone) DateTime(org.joda.time.DateTime)

Aggregations

TimeUnit (java.util.concurrent.TimeUnit)190 Test (org.junit.Test)28 ExecutionException (java.util.concurrent.ExecutionException)16 IOException (java.io.IOException)11 TimeoutException (java.util.concurrent.TimeoutException)11 Future (java.util.concurrent.Future)10 HashMap (java.util.HashMap)7 TimeSpec (com.linkedin.thirdeye.api.TimeSpec)6 ArrayList (java.util.ArrayList)6 TimeValue (org.elasticsearch.common.unit.TimeValue)6 DataType (com.linkedin.pinot.common.data.FieldSpec.DataType)5 File (java.io.File)5 HashSet (java.util.HashSet)5 Matcher (java.util.regex.Matcher)5 WaitUntilGatewaySenderFlushedCoordinatorJUnitTest (org.apache.geode.internal.cache.wan.WaitUntilGatewaySenderFlushedCoordinatorJUnitTest)5 IntegrationTest (org.apache.geode.test.junit.categories.IntegrationTest)5 TimeGranularity (com.linkedin.thirdeye.api.TimeGranularity)4 GwtIncompatible (com.google.common.annotations.GwtIncompatible)3 RestException (com.linkedin.r2.message.rest.RestException)3 Map (java.util.Map)3