org.apache.brooklyn.util.time.Time Java Examples
The following examples show how to use
org.apache.brooklyn.util.time.Time.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: HttpAssertsTest.java From brooklyn-server with Apache License 2.0 | 6 votes |
@Test(expectedExceptions = ExecutionException.class) public void shouldAssertAsyncHttpStatusCodeContinuallyEqualsFails() throws Exception { stopServer(); ListeningExecutorService listeningExecutor = MoreExecutors.listeningDecorator(executor); final ListenableFuture<?> future = HttpAsserts.assertAsyncHttpStatusCodeContinuallyEquals(listeningExecutor, testUri("/missing"), 200); startAfter(DELAY_FOR_SERVER_TO_SETTLE.add(Duration.seconds(1))); Time.sleep(DELAY_FOR_SERVER_TO_SETTLE); if (future.isDone()) { Object result = future.get(); // should throw exception LOG.warn("Should have failed, instead gave "+result+" (accessing "+server+")"); } else { LOG.warn("Future should have been done"); } future.cancel(true); }
Example #2
Source File: UsageResourceTest.java From brooklyn-server with Apache License 2.0 | 6 votes |
private void assertUsage(Iterable<UsageStatistic> usages, String appId, String id, List<Status> states, Calendar pre, Calendar post, boolean allowGaps) throws Exception { String errMsg = "usages="+usages; Calendar now = new GregorianCalendar(); Calendar lowerBound = pre; Calendar strictStart = null; assertEquals(Iterables.size(usages), states.size(), errMsg); for (int i = 0; i < Iterables.size(usages); i++) { UsageStatistic usage = Iterables.get(usages, i); Calendar usageStart = Time.parseCalendar(usage.getStart()); Calendar usageEnd = Time.parseCalendar(usage.getEnd()); assertEquals(usage.getId(), id, errMsg); assertEquals(usage.getApplicationId(), appId, errMsg); assertEquals(usage.getStatus(), states.get(i), errMsg); assertCalendarOrders(usages, lowerBound, usageStart, post); assertCalendarOrders(usages, usageEnd, now); if (strictStart != null) { assertEquals(usageStart, strictStart, errMsg); } if (!allowGaps) { strictStart = usageEnd; } lowerBound = usageEnd; } }
Example #3
Source File: EntityExecutionManagerTest.java From brooklyn-server with Apache License 2.0 | 6 votes |
@Test(groups="Integration") public void testSubscriptionAndEffectorTasksGced() throws Exception { BasicExecutionManager em = (BasicExecutionManager) app.getManagementContext().getExecutionManager(); // allow background enrichers to complete Time.sleep(Duration.ONE_SECOND); forceGc(); Collection<Task<?>> t1 = em.getAllTasks(); TestEntity entity = app.createAndManageChild(EntitySpec.create(TestEntity.class)); entity.sensors().set(TestEntity.NAME, "bob"); entity.invoke(TestEntity.MY_EFFECTOR, ImmutableMap.<String,Object>of()).get(); Entities.destroy(entity); Time.sleep(Duration.ONE_SECOND); forceGc(); Collection<Task<?>> t2 = em.getAllTasks(); // no tasks from first batch were GC'd Asserts.assertSize(MutableList.builder().addAll(t1).removeAll(t2).build(), 0); // and we expect just the add/remove cycle at parent, and service problems Set<String> newOnes = MutableList.<Task<?>>builder().addAll(t2).removeAll(t1).build().stream().map( (t) -> t.getDisplayName()).collect(Collectors.toSet()); Function<String,String> prefix = (s) -> "sensor "+app.getId()+":"+s; Assert.assertEquals(newOnes, MutableSet.of( prefix.apply("entity.children.removed"), prefix.apply("entity.children.added"), prefix.apply("service.problems"))); }
Example #4
Source File: AbstractToyMySqlEntityTest.java From brooklyn-server with Apache License 2.0 | 6 votes |
protected void checkIsRunningAndStops(Entity mysql, SshMachineLocation lh) { Integer pid = getPid(mysql); Assert.assertNotNull(pid, "PID should be set as an attribute (or getPid() overridden to supply)"); Entities.submit(app, SshEffectorTasks.requirePidRunning(pid).machine(lh).newTask() ).get(); app.stop(); // let the kill -1 take effect Time.sleep(Duration.ONE_SECOND); // and assert it has died log.info("mysql in pid "+pid+" should be dead now"); // (app has stopped, so submit on mgmt context) ProcessTaskWrapper<Integer> t = SshEffectorTasks.codePidRunning(pid).machine(lh).newTask(); mgmt.getExecutionManager().submit(t); Assert.assertNotEquals(t.block().getExitCode(), 0); }
Example #5
Source File: BrooklynPropertiesSecurityFilterTest.java From brooklyn-server with Apache License 2.0 | 6 votes |
@Test(groups = {"Integration","Broken"}) public void testInteractionOfSecurityFilterAndFormMapProvider() throws Exception { Stopwatch stopwatch = Stopwatch.createStarted(); try { Server server = useServerForTest(baseLauncher() .forceUseOfDefaultCatalogWithJavaClassPath(true) .withoutJsgui() .start()); String appId = startAppAtNode(server); String entityId = getTestEntityInApp(server, appId); HttpClient client = HttpTool.httpClientBuilder() .uri(getBaseUriRest()) .build(); List<? extends NameValuePair> nvps = Lists.newArrayList( new BasicNameValuePair("arg", "bar")); String effector = String.format("/applications/%s/entities/%s/effectors/identityEffector", appId, entityId); HttpToolResponse response = HttpTool.httpPost(client, URI.create(getBaseUriRest() + effector), ImmutableMap.of(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_FORM_URLENCODED.getMimeType()), URLEncodedUtils.format(nvps, Charsets.UTF_8).getBytes()); LOG.info("Effector response: {}", response.getContentAsString()); assertTrue(HttpTool.isStatusCodeHealthy(response.getResponseCode()), "response code=" + response.getResponseCode()); } finally { LOG.info("testInteractionOfSecurityFilterAndFormMapProvider complete in " + Time.makeTimeStringRounded(stopwatch)); } }
Example #6
Source File: MiscClassesRebindTest.java From brooklyn-server with Apache License 2.0 | 6 votes |
/** Method to facilitate creation of memento files */ private void createMemento() throws Exception { setUp(); origApp = super.createApp(); // edit this, run this class's main method, then use the log output for your test case origApp.config().set(TEST_KEY, new VersionedName("foo", Version.parseVersion("1.0.0.foo"))); RebindTestUtils.stopPersistence(origApp); String fn = mementoDir + File.separator + "entities" + File.separator + origApp.getApplicationId(); log.info("Persisted to "+fn); String yyyyMM = Time.makeDateString(new Date(), "yyyy-MM"); log.info("Set up your tests by copying from the persistence dir "+mementoDir+"\n\n"+ "cp "+fn+" "+ "src/test/resources/"+getClass().getPackage().getName().replaceAll("\\.", "/")+"/"+ JavaClassNames.cleanSimpleClassName(this)+"-"+yyyyMM+"-entity-"+origApp.getApplicationId()+".memento\n"); String content = Streams.readFullyString(new FileInputStream(new File(fn))); log.info("Or paste the following contents there:\n"+content); log.info("Then add the apache comment header there, and write your test doing loadEntityMemento(\""+yyyyMM+"\", \""+origApp.getApplicationId()+"\")"); }
Example #7
Source File: ServiceFailureDetectorTest.java From brooklyn-server with Apache License 2.0 | 6 votes |
@Test(groups="Integration") // Has a 1 second wait public void testOnFireAfterDelay() throws Exception { e1.enrichers().add(EnricherSpec.create(ServiceFailureDetector.class) .configure(ServiceFailureDetector.SERVICE_ON_FIRE_STABILIZATION_DELAY, Duration.ONE_SECOND)); // Make the entity fail e1.sensors().set(TestEntity.SERVICE_UP, true); ServiceStateLogic.setExpectedState(e1, Lifecycle.RUNNING); EntityAsserts.assertAttributeEqualsEventually(e1, Attributes.SERVICE_STATE_ACTUAL, Lifecycle.RUNNING); e1.sensors().set(TestEntity.SERVICE_UP, false); assertEquals(e1.getAttribute(TestEntity.SERVICE_STATE_ACTUAL), Lifecycle.RUNNING); Time.sleep(Duration.millis(100)); assertEquals(e1.getAttribute(TestEntity.SERVICE_STATE_ACTUAL), Lifecycle.RUNNING); EntityAsserts.assertAttributeEqualsEventually(e1, TestEntity.SERVICE_STATE_ACTUAL, Lifecycle.ON_FIRE); }
Example #8
Source File: DeferredConfigTest.java From brooklyn-server with Apache License 2.0 | 6 votes |
void doTestDeferredConfigInList(final boolean delay) throws Exception { // Simulate a deferred value Task<Sensor<?>> sensorFuture = app.getExecutionContext().submit("deferred return sensor", () -> { if (delay) Time.sleep(Duration.FIVE_SECONDS); return TestApplication.MY_ATTRIBUTE; }); app.config().set(SENSORS_UNTYPED, (Object)ImmutableList.of(sensorFuture)); if (!delay) sensorFuture.get(Duration.ONE_SECOND); // should resolve if future completed Maybe<List<? extends Sensor<?>>> sensors = app.config().getNonBlocking(SENSORS); if (delay) { Assert.assertFalse(sensors.isPresent(), "value shouldn't be available"); } else { Assert.assertTrue(sensors.isPresent(), "value should be available"); Sensor<?> sensor = Iterables.getOnlyElement(sensors.get()); assertEquals(sensor, TestApplication.MY_ATTRIBUTE); } }
Example #9
Source File: PersistenceStoreObjectAccessorWriterTestFixture.java From brooklyn-server with Apache License 2.0 | 6 votes |
@Test public void testLastModifiedTime() throws Exception { accessor.delete(); Assert.assertNull(accessor.getLastModifiedDate()); accessor.put("abc"); accessor.waitForCurrentWrites(TIMEOUT); Date write1 = accessor.getLastModifiedDate(); Assert.assertNotNull(write1); Time.sleep(getLastModifiedResolution().multiply(2)); accessor.put("abc"); accessor.waitForCurrentWrites(TIMEOUT); Date write2 = accessor.getLastModifiedDate(); Assert.assertNotNull(write2); Assert.assertTrue(write2.after(write1), "dates are "+write1+" ("+write1.getTime()+") and "+write2+" ("+write2.getTime()+") "); }
Example #10
Source File: HttpTool.java From brooklyn-server with Apache License 2.0 | 6 votes |
public static String getErrorContent(String url) { try { HttpURLConnection connection = (HttpURLConnection) connectToUrl(url); long startTime = System.currentTimeMillis(); String err; int status; try { InputStream errStream = connection.getErrorStream(); err = Streams.readFullyStringAndClose(errStream); status = connection.getResponseCode(); } finally { closeQuietly(connection); } if (LOG.isDebugEnabled()) LOG.debug("read of err {} ({}ms) complete; http code {}", new Object[] { url, Time.makeTimeStringRounded(System.currentTimeMillis() - startTime), status}); return err; } catch (Exception e) { throw Exceptions.propagate(e); } }
Example #11
Source File: Histogram.java From brooklyn-server with Apache License 2.0 | 6 votes |
@Override public String toString() { if (counts.isEmpty()) return "<empty>"; StringBuilder result = new StringBuilder("{"); List<Integer> sortedPows = MutableList.copyOf(counts.keySet()); Collections.sort(sortedPows); int minPow = sortedPows.get(0); int maxPow = sortedPows.get(sortedPows.size()-1); for (int i = minPow; i <= maxPow; i++) { if (i != minPow) result.append(", "); long lower = i == 0 ? 0 : (long) Math.pow(2, i-1); long upper = (long) Math.pow(2, i); Integer count = counts.get(i); result.append(Time.makeTimeStringRounded(lower, TimeUnit.NANOSECONDS) + "-" + Time.makeTimeStringRounded(upper, TimeUnit.NANOSECONDS) + ": " + (count == null ? 0 : count)); } result.append("}"); return result.toString(); }
Example #12
Source File: HttpToolResponse.java From brooklyn-server with Apache License 2.0 | 6 votes |
public HttpToolResponse(HttpResponse response, long startTime) { this.response = response; this.startTime = startTime; try { ByteArrayOutputStream out = new ByteArrayOutputStream(); HttpEntity entity = response.getEntity(); if (entity != null) { entity.getContentLength(); durationMillisOfFirstResponse = Duration.sinceUtc(startTime).toMilliseconds(); ByteStreams.copy(entity.getContent(), out); content = out.toByteArray(); entity.getContentLength(); } else { durationMillisOfFirstResponse = Duration.sinceUtc(startTime).toMilliseconds(); content = new byte[0]; } durationMillisOfFullContent = Duration.sinceUtc(startTime).toMilliseconds(); if (log.isTraceEnabled()) log.trace("HttpPollValue latency "+Time.makeTimeStringRounded(durationMillisOfFirstResponse)+" / "+Time.makeTimeStringRounded(durationMillisOfFullContent)+", content size "+content.length); } catch (IOException e) { throw Throwables.propagate(e); } }
Example #13
Source File: JavaAppUtils.java From brooklyn-server with Apache License 2.0 | 6 votes |
/** Setup renderer hints for the MXBean attributes. */ public static void init() { if (initialized.getAndSet(true)) return; RendererHints.register(UsesJavaMXBeans.USED_HEAP_MEMORY, RendererHints.displayValue(ByteSizeStrings.metric())); RendererHints.register(UsesJavaMXBeans.INIT_HEAP_MEMORY, RendererHints.displayValue(ByteSizeStrings.metric())); RendererHints.register(UsesJavaMXBeans.MAX_HEAP_MEMORY, RendererHints.displayValue(ByteSizeStrings.metric())); RendererHints.register(UsesJavaMXBeans.COMMITTED_HEAP_MEMORY, RendererHints.displayValue(ByteSizeStrings.metric())); RendererHints.register(UsesJavaMXBeans.NON_HEAP_MEMORY_USAGE, RendererHints.displayValue(ByteSizeStrings.metric())); RendererHints.register(UsesJavaMXBeans.TOTAL_PHYSICAL_MEMORY_SIZE, RendererHints.displayValue(ByteSizeStrings.metric())); RendererHints.register(UsesJavaMXBeans.FREE_PHYSICAL_MEMORY_SIZE, RendererHints.displayValue(ByteSizeStrings.metric())); RendererHints.register(UsesJavaMXBeans.START_TIME, RendererHints.displayValue(Time.toDateString())); RendererHints.register(UsesJavaMXBeans.UP_TIME, RendererHints.displayValue(Duration.millisToStringRounded())); RendererHints.register(UsesJavaMXBeans.PROCESS_CPU_TIME, RendererHints.displayValue(Duration.millisToStringRounded())); RendererHints.register(UsesJavaMXBeans.PROCESS_CPU_TIME_FRACTION_LAST, RendererHints.displayValue(MathFunctions.percent(4))); RendererHints.register(UsesJavaMXBeans.PROCESS_CPU_TIME_FRACTION_IN_WINDOW, RendererHints.displayValue(MathFunctions.percent(4))); }
Example #14
Source File: HttpTestUtils.java From brooklyn-server with Apache License 2.0 | 6 votes |
public static String getErrorContent(String url) { try { HttpURLConnection connection = (HttpURLConnection) connectToUrl(url); long startTime = System.currentTimeMillis(); String err; int status; try { InputStream errStream = connection.getErrorStream(); err = Streams.readFullyStringAndClose(errStream); status = connection.getResponseCode(); } finally { closeQuietly(connection); } if (LOG.isDebugEnabled()) LOG.debug("read of err {} ({}ms) complete; http code {}", new Object[] { url, Time.makeTimeStringRounded(System.currentTimeMillis()-startTime), status}); return err; } catch (Exception e) { throw Exceptions.propagate(e); } }
Example #15
Source File: RebindIteration.java From brooklyn-server with Apache License 2.0 | 6 votes |
protected void finishingUp() { checkContinuingPhase(8); if (!isEmpty) { BrooklynLogging.log(LOG, shouldLogRebinding() ? LoggingLevel.INFO : LoggingLevel.DEBUG, "Rebind complete " + "("+mode+(readOnlyRebindCount.get()>=0 ? ", iteration "+readOnlyRebindCount : "")+")" + " in {}: {} app{}, {} entit{}, {} location{}, {} polic{}, {} enricher{}, {} feed{}, {} catalog item{}, {} catalog bundle{}", Time.makeTimeStringRounded(timer), applications.size(), Strings.s(applications), rebindContext.getEntities().size(), Strings.ies(rebindContext.getEntities()), rebindContext.getLocations().size(), Strings.s(rebindContext.getLocations()), rebindContext.getPolicies().size(), Strings.ies(rebindContext.getPolicies()), rebindContext.getEnrichers().size(), Strings.s(rebindContext.getEnrichers()), rebindContext.getFeeds().size(), Strings.s(rebindContext.getFeeds()), rebindContext.getCatalogItems().size(), Strings.s(rebindContext.getCatalogItems()), rebindContext.getBundles().size(), Strings.s(rebindContext.getBundles()) ); } // Return the top-level applications logRebindingDebug("RebindManager complete; apps: {}", getMementoRootEntities()); }
Example #16
Source File: HotStandbyTest.java From brooklyn-server with Apache License 2.0 | 5 votes |
public void assertUsedMemoryLessThan(String event, long max) { noteUsedMemory(event); long nowUsed = usedMemory.peekLast(); if (nowUsed > max) { // aggressively try to force GC Time.sleep(Duration.ONE_SECOND); usedMemory.removeLast(); noteUsedMemory(event+" (extra GC)"); nowUsed = usedMemory.peekLast(); if (nowUsed > max) { Assert.fail("Too much memory used - "+ByteSizeStrings.java().apply(nowUsed)+" > max "+ByteSizeStrings.java().apply(max)); } } }
Example #17
Source File: EntityExecutionManagerTest.java From brooklyn-server with Apache License 2.0 | 5 votes |
/** * Invoke effector many times, where each would claim 10MB because it stores the return value. * If it didn't gc the tasks promptly, it would consume 10GB ram (so would OOME before that). */ @Test(groups="Integration") public void testEffectorTasksGcedSoNoOome() throws Exception { String classAndMethodName = JavaClassNames.niceClassAndMethod(); BrooklynProperties brooklynProperties = BrooklynProperties.Factory.newEmpty(); brooklynProperties.put(BrooklynGarbageCollector.GC_PERIOD, Duration.ONE_MILLISECOND); brooklynProperties.put(BrooklynGarbageCollector.MAX_TASKS_PER_TAG, 2); replaceManagementContext(LocalManagementContextForTests.newInstance(brooklynProperties)); setUpApp(); TestEntity entity = app.createAndManageChild(EntitySpec.create(TestEntity.class)); for (int i = 0; i < 1000; i++) { if (i%100==0) LOG.info(classAndMethodName+": iteration "+i); try { LOG.debug("testEffectorTasksGced: iteration="+i); entity.invoke(TestEntity.IDENTITY_EFFECTOR, ImmutableMap.of("arg", new BigObject(10*1000*1000))).get(); Time.sleep(Duration.ONE_MILLISECOND); // Give GC thread a chance to run forceGc(); } catch (OutOfMemoryError e) { LOG.warn(classAndMethodName+": OOME at iteration="+i); throw e; } } }
Example #18
Source File: PerformanceTestUtils.java From brooklyn-server with Apache License 2.0 | 5 votes |
public static Future<?> sampleProcessCpuTime(final Duration period, final String loggingContext, final List<Double> cpuFractions) { final ExecutorService executor = Executors.newSingleThreadExecutor(new ThreadFactory() { @Override public Thread newThread(Runnable r) { Thread thread = new Thread(r, "brooklyn-sampleProcessCpuTime-"+loggingContext); thread.setDaemon(true); // let the JVM exit return thread; }}); Future<?> future = executor.submit(new Runnable() { @Override public void run() { try { if (getProcessCpuTime() == -1) { LOG.warn("ProcessCPuTime not available; cannot sample; aborting"); return; } while (true) { Stopwatch timerForReporting = Stopwatch.createStarted(); double fractionCpu = getProcessCpuTime(period); long elapsedTime = timerForReporting.elapsed(TimeUnit.MILLISECONDS); LOG.info("CPU fraction over last {} was {} ({})", new Object[] { Time.makeTimeStringRounded(elapsedTime), ((int)(1000*fractionCpu))/1000.0, loggingContext}); if (cpuFractions != null) { cpuFractions.add(fractionCpu); } } } catch (RuntimeInterruptedException e) { return; // graceful termination } finally { executor.shutdownNow(); } }}); return future; }
Example #19
Source File: RebindEnricherTest.java From brooklyn-server with Apache License 2.0 | 5 votes |
@Test public void testRollingTimeWindowMeanEnricher() throws Exception { origApp.enrichers().add(EnricherSpec.create(RollingTimeWindowMeanEnricher.class) .configure("producer", origApp) .configure("source", INT_METRIC) .configure("target", DOUBLE_METRIC) .configure("timePeriod", Duration.millis(10))); TestApplication newApp = rebind(); newApp.sensors().set(INT_METRIC, 10); Time.sleep(Duration.millis(10)); newApp.sensors().set(INT_METRIC, 10); EntityAsserts.assertAttributeEqualsEventually(newApp, DOUBLE_METRIC, 10d); }
Example #20
Source File: SoftwareProcessEntityLatchTest.java From brooklyn-server with Apache License 2.0 | 5 votes |
private void assertCount(int newCnt) { synchronized(maxCnt) { maxCnt.set(Math.max(newCnt, maxCnt.get())); } assertTrue(newCnt <= maxConcurrency, "maxConcurrency limit failed at " + newCnt + " (max " + maxConcurrency + ")"); if (newCnt < maxConcurrency) { Time.sleep(sleepBeforeMaxCnt); } else { Time.sleep(Duration.millis(20)); } }
Example #21
Source File: ValueResolverTest.java From brooklyn-server with Apache License 2.0 | 5 votes |
public static final Task<String> newThrowTask(final Duration timeout) { return Tasks.<String>builder().body(new Callable<String>() { @Override public String call() { Time.sleep(timeout); throw new IllegalStateException("intended, during tests"); }} ).build(); }
Example #22
Source File: ApplicationUsageTrackingTest.java From brooklyn-server with Apache License 2.0 | 5 votes |
private void assertApplicationEvent(ApplicationEvent event, Lifecycle expectedState, long preEvent, long postEvent) { // Saw times differ by 1ms - perhaps different threads calling currentTimeMillis() can get out-of-order times?! final int TIMING_GRACE = 5; assertEquals(event.getState(), expectedState); long eventTime = event.getDate().getTime(); if (eventTime < (preEvent - TIMING_GRACE) || eventTime > (postEvent + TIMING_GRACE)) { fail("for "+expectedState+": event=" + Time.makeDateString(eventTime) + "("+eventTime + "); " + "pre=" + Time.makeDateString(preEvent) + " ("+preEvent+ "); " + "post=" + Time.makeDateString(postEvent) + " ("+postEvent + ")"); } }
Example #23
Source File: JmxHelper.java From brooklyn-server with Apache License 2.0 | 5 votes |
/** * Gets a usable MBeanServerConnection. * * Method is threadsafe. * * @returns the MBeanServerConnection * @throws IllegalStateException if not connected. */ private synchronized MBeanServerConnection getConnectionOrFail() { if (isConnected()) return getConnection(); if (triedConnecting) { throw new IllegalStateException("Failed to connect to JMX at "+url); } else { String msg = "Not connected (and not attempted to connect) to JMX at "+url+ (failedReconnecting ? (" (last reconnect failure at "+ Time.makeDateString(failedReconnectingTime) + ")") : ""); throw new IllegalStateException(msg); } }
Example #24
Source File: LocationUsageTrackingTest.java From brooklyn-server with Apache License 2.0 | 5 votes |
private void assertLocationEvent(LocationEvent event, String expectedAppId, String expectedEntityId, String expectedEntityType, Lifecycle expectedState, long preEvent, long postEvent) { // Saw times differ by 1ms - perhaps different threads calling currentTimeMillis() can get out-of-order times?! final int TIMING_GRACE = 5; assertEquals(event.getApplicationId(), expectedAppId); assertEquals(event.getEntityId(), expectedEntityId); assertEquals(event.getEntityType(), expectedEntityType); assertEquals(event.getState(), expectedState); long eventTime = event.getDate().getTime(); if (eventTime < (preEvent - TIMING_GRACE) || eventTime > (postEvent + TIMING_GRACE)) { fail("for "+expectedState+": event=" + Time.makeDateString(eventTime) + "("+eventTime + "); " + "pre=" + Time.makeDateString(preEvent) + " ("+preEvent+ "); " + "post=" + Time.makeDateString(postEvent) + " ("+postEvent + ")"); } }
Example #25
Source File: JcloudsLocationUsageTrackingTest.java From brooklyn-server with Apache License 2.0 | 5 votes |
private void assertLocationEvent(LocationEvent event, String expectedAppId, String expectedEntityId, String expectedEntityType, Lifecycle expectedState, long preEvent, long postEvent) { // Saw times differ by 1ms - perhaps different threads calling currentTimeMillis() can get out-of-order times?! final int TIMING_GRACE = 5; assertEquals(event.getApplicationId(), expectedAppId); assertEquals(event.getEntityId(), expectedEntityId); assertEquals(event.getEntityType(), expectedEntityType); assertEquals(event.getState(), expectedState); long eventTime = event.getDate().getTime(); if (eventTime < (preEvent - TIMING_GRACE) || eventTime > (postEvent + TIMING_GRACE)) { fail("for "+expectedState+": event=" + Time.makeDateString(eventTime) + "("+eventTime + "); " + "pre=" + Time.makeDateString(preEvent) + " ("+preEvent+ "); " + "post=" + Time.makeDateString(postEvent) + " ("+postEvent + ")"); } }
Example #26
Source File: BrooklynNodeTest.java From brooklyn-server with Apache License 2.0 | 5 votes |
@Override protected void postStop() { super.postStop(); //Make sure UnmanageTask will wait for the STOP effector to complete. Time.sleep(Duration.FIVE_SECONDS); }
Example #27
Source File: BrooklynNodeImpl.java From brooklyn-server with Apache License 2.0 | 5 votes |
@Override public void run() { if (latchTask != null) { latchTask.blockUntilEnded(); } else { log.debug("No latch task provided for UnmanageTask, falling back to fixed wait"); Time.sleep(Duration.FIVE_SECONDS); } synchronized (this) { Entities.unmanage(unmanageEntity); } }
Example #28
Source File: ServiceFailureDetector.java From brooklyn-server with Apache License 2.0 | 5 votes |
protected String getExplanation(Maybe<Lifecycle> state) { Duration serviceFailedStabilizationDelay = getConfig(ENTITY_FAILED_STABILIZATION_DELAY); Duration serviceRecoveredStabilizationDelay = getConfig(ENTITY_RECOVERED_STABILIZATION_DELAY); return String.format("location=%s; status=%s; lastPublished=%s; timeNow=%s; "+ "currentFailurePeriod=%s; currentRecoveryPeriod=%s", entity.getLocations(), (state.orNull() != null ? state : "<unreported>"), config().get(LAST_PUBLISHED), Time.makeDateString(System.currentTimeMillis()), (currentFailureStartTime != null ? getTimeStringSince(currentFailureStartTime) : "<none>") + " (stabilization "+Time.makeTimeStringRounded(serviceFailedStabilizationDelay) + ")", (currentRecoveryStartTime != null ? getTimeStringSince(currentRecoveryStartTime) : "<none>") + " (stabilization "+Time.makeTimeStringRounded(serviceRecoveredStabilizationDelay) + ")"); }
Example #29
Source File: ReachableSocketFinderTest.java From brooklyn-server with Apache License 2.0 | 5 votes |
@Test public void testSocketResultIgnoredIfGracePeriodExpiresAfterFirstResultAvailable() { reachabilityResults.put(socket1, false); reachabilityResults.put(socket2, true); // Override the default test grace period. finder = new ReachableSocketFinder(socketTester, Duration.ZERO); final Iterable<HostAndPort> actual = finder.findOpenSocketsOnNode(ImmutableList.of(socket1, socket2), TIMEOUT); // Sleep through the grace period. Time.sleep(50); reachabilityResults.put(socket1, true); assertEquals(actual, ImmutableList.of(socket2)); }
Example #30
Source File: MockContainerEntityImpl.java From brooklyn-server with Apache License 2.0 | 5 votes |
@Override public void start(Collection<? extends Location> locs) { if (LOG.isDebugEnabled()) LOG.debug("Mocks: starting container {}", this); _lock.lock(); try { Time.sleep(getDelay()); running = true; addLocations(locs); sensors().emit(Attributes.LOCATION_CHANGED, null); sensors().set(SERVICE_UP, true); } finally { _lock.unlock(); } }