Return-Path: X-Original-To: apmail-brooklyn-commits-archive@minotaur.apache.org Delivered-To: apmail-brooklyn-commits-archive@minotaur.apache.org Received: from mail.apache.org (hermes.apache.org [140.211.11.3]) by minotaur.apache.org (Postfix) with SMTP id D87AB18795 for ; Tue, 18 Aug 2015 11:06:16 +0000 (UTC) Received: (qmail 84454 invoked by uid 500); 18 Aug 2015 11:06:16 -0000 Delivered-To: apmail-brooklyn-commits-archive@brooklyn.apache.org Received: (qmail 84430 invoked by uid 500); 18 Aug 2015 11:06:16 -0000 Mailing-List: contact commits-help@brooklyn.incubator.apache.org; run by ezmlm Precedence: bulk List-Help: List-Unsubscribe: List-Post: List-Id: Reply-To: dev@brooklyn.incubator.apache.org Delivered-To: mailing list commits@brooklyn.incubator.apache.org Received: (qmail 84421 invoked by uid 99); 18 Aug 2015 11:06:16 -0000 Received: from Unknown (HELO spamd4-us-west.apache.org) (209.188.14.142) by apache.org (qpsmtpd/0.29) with ESMTP; Tue, 18 Aug 2015 11:06:16 +0000 Received: from localhost (localhost [127.0.0.1]) by spamd4-us-west.apache.org (ASF Mail Server at spamd4-us-west.apache.org) with ESMTP id 2048AC1089 for ; Tue, 18 Aug 2015 11:06:16 +0000 (UTC) X-Virus-Scanned: Debian amavisd-new at spamd4-us-west.apache.org X-Spam-Flag: NO X-Spam-Score: 1.774 X-Spam-Level: * X-Spam-Status: No, score=1.774 tagged_above=-999 required=6.31 tests=[KAM_ASCII_DIVIDERS=0.8, KAM_LAZY_DOMAIN_SECURITY=1, RCVD_IN_MSPIKE_H3=-0.01, RCVD_IN_MSPIKE_WL=-0.01, RP_MATCHES_RCVD=-0.006] autolearn=disabled Received: from mx1-eu-west.apache.org ([10.40.0.8]) by localhost (spamd4-us-west.apache.org [10.40.0.11]) (amavisd-new, port 10024) with ESMTP id f8uzQEcfu1NG for ; Tue, 18 Aug 2015 11:06:02 +0000 (UTC) Received: from mail.apache.org (hermes.apache.org [140.211.11.3]) by mx1-eu-west.apache.org (ASF Mail Server at mx1-eu-west.apache.org) with SMTP id 2D4AE20F4F for ; Tue, 18 Aug 2015 11:06:00 +0000 (UTC) Received: (qmail 83592 invoked by uid 99); 18 Aug 2015 11:05:59 -0000 Received: from git1-us-west.apache.org (HELO git1-us-west.apache.org) (140.211.11.23) by apache.org (qpsmtpd/0.29) with ESMTP; Tue, 18 Aug 2015 11:05:59 +0000 Received: by git1-us-west.apache.org (ASF Mail Server at git1-us-west.apache.org, from userid 33) id 5A8F4DFFED; Tue, 18 Aug 2015 11:05:59 +0000 (UTC) Content-Type: text/plain; charset="us-ascii" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit From: heneveld@apache.org To: commits@brooklyn.incubator.apache.org Date: Tue, 18 Aug 2015 11:06:10 -0000 Message-Id: In-Reply-To: References: X-Mailer: ASF-Git Admin Mailer Subject: [12/24] incubator-brooklyn git commit: [BROOKLYN-162] Renaming package policy http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/d30ff597/policy/src/test/java/brooklyn/policy/autoscaling/AutoScalerPolicyMetricTest.java ---------------------------------------------------------------------- diff --git a/policy/src/test/java/brooklyn/policy/autoscaling/AutoScalerPolicyMetricTest.java b/policy/src/test/java/brooklyn/policy/autoscaling/AutoScalerPolicyMetricTest.java deleted file mode 100644 index 174b982..0000000 --- a/policy/src/test/java/brooklyn/policy/autoscaling/AutoScalerPolicyMetricTest.java +++ /dev/null @@ -1,274 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package brooklyn.policy.autoscaling; - -import static brooklyn.policy.autoscaling.AutoScalerPolicyTest.currentSizeAsserter; -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertFalse; -import static org.testng.Assert.assertTrue; - -import java.util.List; - -import org.apache.brooklyn.api.entity.proxying.EntitySpec; -import org.apache.brooklyn.api.event.AttributeSensor; -import org.apache.brooklyn.api.event.SensorEvent; -import org.apache.brooklyn.api.event.SensorEventListener; -import org.apache.brooklyn.test.entity.TestApplication; -import org.apache.brooklyn.test.entity.TestCluster; -import org.apache.brooklyn.test.entity.TestEntity; -import org.testng.annotations.AfterMethod; -import org.testng.annotations.BeforeMethod; -import org.testng.annotations.Test; - -import brooklyn.entity.basic.Entities; -import brooklyn.event.basic.BasicNotificationSensor; -import brooklyn.event.basic.Sensors; -import brooklyn.test.Asserts; - -import com.google.common.collect.ImmutableMap; -import com.google.common.collect.Lists; - -public class AutoScalerPolicyMetricTest { - - private static long TIMEOUT_MS = 10000; - private static long SHORT_WAIT_MS = 50; - - private static final AttributeSensor MY_ATTRIBUTE = Sensors.newIntegerSensor("autoscaler.test.intAttrib"); - TestApplication app; - TestCluster tc; - - @BeforeMethod(alwaysRun=true) - public void before() { - app = TestApplication.Factory.newManagedInstanceForTests(); - tc = app.createAndManageChild(EntitySpec.create(TestCluster.class) - .configure("initialSize", 1)); - } - - @AfterMethod(alwaysRun=true) - public void tearDown() throws Exception { - if (app != null) Entities.destroyAll(app.getManagementContext()); - } - - @Test - public void testIncrementsSizeIffUpperBoundExceeded() { - tc.resize(1); - - AutoScalerPolicy policy = new AutoScalerPolicy.Builder().metric(MY_ATTRIBUTE).metricLowerBound(50).metricUpperBound(100).build(); - tc.addPolicy(policy); - - tc.setAttribute(MY_ATTRIBUTE, 100); - Asserts.succeedsContinually(ImmutableMap.of("timeout", SHORT_WAIT_MS), currentSizeAsserter(tc, 1)); - - tc.setAttribute(MY_ATTRIBUTE, 101); - Asserts.succeedsEventually(ImmutableMap.of("timeout", TIMEOUT_MS), currentSizeAsserter(tc, 2)); - } - - @Test - public void testDecrementsSizeIffLowerBoundExceeded() { - tc.resize(2); - - AutoScalerPolicy policy = new AutoScalerPolicy.Builder().metric(MY_ATTRIBUTE).metricLowerBound(50).metricUpperBound(100).build(); - tc.addPolicy(policy); - - tc.setAttribute(MY_ATTRIBUTE, 50); - Asserts.succeedsContinually(ImmutableMap.of("timeout", SHORT_WAIT_MS), currentSizeAsserter(tc, 2)); - - tc.setAttribute(MY_ATTRIBUTE, 49); - Asserts.succeedsEventually(ImmutableMap.of("timeout", TIMEOUT_MS), currentSizeAsserter(tc, 1)); - } - - @Test(groups="Integration") - public void testIncrementsSizeInProportionToMetric() { - tc.resize(5); - - AutoScalerPolicy policy = new AutoScalerPolicy.Builder().metric(MY_ATTRIBUTE).metricLowerBound(50).metricUpperBound(100).build(); - tc.addPolicy(policy); - - // workload 200 so requires doubling size to 10 to handle: (200*5)/100 = 10 - tc.setAttribute(MY_ATTRIBUTE, 200); - Asserts.succeedsEventually(ImmutableMap.of("timeout", TIMEOUT_MS), currentSizeAsserter(tc, 10)); - - // workload 5, requires 1 entity: (10*110)/100 = 11 - tc.setAttribute(MY_ATTRIBUTE, 110); - Asserts.succeedsEventually(ImmutableMap.of("timeout", TIMEOUT_MS), currentSizeAsserter(tc, 11)); - } - - @Test(groups="Integration") - public void testDecrementsSizeInProportionToMetric() { - tc.resize(5); - - AutoScalerPolicy policy = new AutoScalerPolicy.Builder().metric(MY_ATTRIBUTE).metricLowerBound(50).metricUpperBound(100).build(); - tc.addPolicy(policy); - - // workload can be handled by 4 servers, within its valid range: (49*5)/50 = 4.9 - tc.setAttribute(MY_ATTRIBUTE, 49); - Asserts.succeedsEventually(ImmutableMap.of("timeout", TIMEOUT_MS), currentSizeAsserter(tc, 4)); - - // workload can be handled by 4 servers, within its valid range: (25*4)/50 = 2 - tc.setAttribute(MY_ATTRIBUTE, 25); - Asserts.succeedsEventually(ImmutableMap.of("timeout", TIMEOUT_MS), currentSizeAsserter(tc, 2)); - - tc.setAttribute(MY_ATTRIBUTE, 0); - Asserts.succeedsEventually(ImmutableMap.of("timeout", TIMEOUT_MS), currentSizeAsserter(tc, 1)); - } - - @Test(groups="Integration") - public void testObeysMinAndMaxSize() { - tc.resize(4); - - AutoScalerPolicy policy = new AutoScalerPolicy.Builder().metric(MY_ATTRIBUTE) - .metricLowerBound(50).metricUpperBound(100) - .minPoolSize(2).maxPoolSize(6) - .build(); - tc.addPolicy(policy); - - // Decreases to min-size only - tc.setAttribute(MY_ATTRIBUTE, 0); - Asserts.succeedsEventually(ImmutableMap.of("timeout", TIMEOUT_MS), currentSizeAsserter(tc, 2)); - - // Increases to max-size only - tc.setAttribute(MY_ATTRIBUTE, 100000); - Asserts.succeedsEventually(ImmutableMap.of("timeout", TIMEOUT_MS), currentSizeAsserter(tc, 6)); - } - - @Test(groups="Integration",invocationCount=20) - public void testWarnsWhenMaxCapReached() { - final List maxReachedEvents = Lists.newCopyOnWriteArrayList(); - tc.resize(1); - - BasicNotificationSensor maxSizeReachedSensor = AutoScalerPolicy.DEFAULT_MAX_SIZE_REACHED_SENSOR; - - app.subscribe(tc, maxSizeReachedSensor, new SensorEventListener() { - @Override public void onEvent(SensorEvent event) { - maxReachedEvents.add(event.getValue()); - }}); - - AutoScalerPolicy policy = new AutoScalerPolicy.Builder().metric(MY_ATTRIBUTE) - .metricLowerBound(50).metricUpperBound(100) - .maxPoolSize(6) - .maxSizeReachedSensor(maxSizeReachedSensor) - .build(); - tc.addPolicy(policy); - - // workload can be handled by 6 servers, so no need to notify: 6 <= (100*6)/50 - tc.setAttribute(MY_ATTRIBUTE, 600); - Asserts.succeedsEventually(ImmutableMap.of("timeout", TIMEOUT_MS), currentSizeAsserter(tc, 6)); - assertTrue(maxReachedEvents.isEmpty()); - - // Increases to above max capacity: would require (100000*6)/100 = 6000 - tc.setAttribute(MY_ATTRIBUTE, 100000); - - // Assert our listener gets notified (once) - Asserts.succeedsEventually(ImmutableMap.of("timeout", TIMEOUT_MS), new Runnable() { - public void run() { - assertEquals(maxReachedEvents.size(), 1); - assertEquals(maxReachedEvents.get(0).getMaxAllowed(), 6); - assertEquals(maxReachedEvents.get(0).getCurrentPoolSize(), 6); - assertEquals(maxReachedEvents.get(0).getCurrentUnbounded(), 6000); - assertEquals(maxReachedEvents.get(0).getMaxUnbounded(), 6000); - assertEquals(maxReachedEvents.get(0).getTimeWindow(), 0); - }}); - Asserts.succeedsContinually(new Runnable() { - @Override public void run() { - assertEquals(maxReachedEvents.size(), 1); - }}); - currentSizeAsserter(tc, 6).run(); - } - - @Test - public void testDestructionState() { - tc.resize(1); - - AutoScalerPolicy policy = new AutoScalerPolicy.Builder().metric(MY_ATTRIBUTE).metricLowerBound(50).metricUpperBound(100).build(); - tc.addPolicy(policy); - - policy.destroy(); - assertTrue(policy.isDestroyed()); - assertFalse(policy.isRunning()); - - tc.setAttribute(MY_ATTRIBUTE, 100000); - Asserts.succeedsContinually(ImmutableMap.of("timeout", SHORT_WAIT_MS), currentSizeAsserter(tc, 1)); - - // TODO Could assert all subscriptions have been de-registered as well, - // but that requires exposing more things just for testing... - } - - @Test - public void testSuspendState() { - AutoScalerPolicy policy = new AutoScalerPolicy.Builder().metric(MY_ATTRIBUTE).metricLowerBound(50).metricUpperBound(100).build(); - tc.addPolicy(policy); - - policy.suspend(); - assertFalse(policy.isRunning()); - assertFalse(policy.isDestroyed()); - - policy.resume(); - assertTrue(policy.isRunning()); - assertFalse(policy.isDestroyed()); - } - - @Test - public void testPostSuspendActions() { - tc.resize(1); - - AutoScalerPolicy policy = new AutoScalerPolicy.Builder().metric(MY_ATTRIBUTE).metricLowerBound(50).metricUpperBound(100).build(); - tc.addPolicy(policy); - - policy.suspend(); - - tc.setAttribute(MY_ATTRIBUTE, 100000); - Asserts.succeedsContinually(ImmutableMap.of("timeout", SHORT_WAIT_MS), currentSizeAsserter(tc, 1)); - } - - @Test - public void testPostResumeActions() { - tc.resize(1); - - AutoScalerPolicy policy = new AutoScalerPolicy.Builder().metric(MY_ATTRIBUTE).metricLowerBound(50).metricUpperBound(100).build(); - tc.addPolicy(policy); - - policy.suspend(); - policy.resume(); - tc.setAttribute(MY_ATTRIBUTE, 101); - Asserts.succeedsEventually(ImmutableMap.of("timeout", TIMEOUT_MS), currentSizeAsserter(tc, 2)); - } - - @Test - public void testSubscribesToMetricOnSpecifiedEntity() { - TestEntity entityWithMetric = app.createAndManageChild(EntitySpec.create(TestEntity.class)); - - tc.resize(1); - - AutoScalerPolicy policy = new AutoScalerPolicy.Builder() - .metric(TestEntity.SEQUENCE) - .entityWithMetric(entityWithMetric) - .metricLowerBound(50) - .metricUpperBound(100) - .build(); - tc.addPolicy(policy); - - // First confirm that tc is not being listened to for this entity - tc.setAttribute(TestEntity.SEQUENCE, 101); - Asserts.succeedsContinually(ImmutableMap.of("timeout", SHORT_WAIT_MS), currentSizeAsserter(tc, 1)); - - // Then confirm we listen to the correct "entityWithMetric" - entityWithMetric.setAttribute(TestEntity.SEQUENCE, 101); - Asserts.succeedsEventually(ImmutableMap.of("timeout", TIMEOUT_MS), currentSizeAsserter(tc, 2)); - } -} http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/d30ff597/policy/src/test/java/brooklyn/policy/autoscaling/AutoScalerPolicyRebindTest.java ---------------------------------------------------------------------- diff --git a/policy/src/test/java/brooklyn/policy/autoscaling/AutoScalerPolicyRebindTest.java b/policy/src/test/java/brooklyn/policy/autoscaling/AutoScalerPolicyRebindTest.java deleted file mode 100644 index 03f3f1d..0000000 --- a/policy/src/test/java/brooklyn/policy/autoscaling/AutoScalerPolicyRebindTest.java +++ /dev/null @@ -1,137 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package brooklyn.policy.autoscaling; - -import static org.testng.Assert.assertEquals; - -import java.util.Map; -import java.util.concurrent.TimeUnit; - -import org.apache.brooklyn.api.entity.proxying.EntitySpec; -import org.apache.brooklyn.api.event.AttributeSensor; -import org.apache.brooklyn.api.location.LocationSpec; -import org.apache.brooklyn.test.EntityTestUtils; -import org.apache.brooklyn.test.entity.TestApplication; -import org.apache.brooklyn.test.entity.TestEntity; -import org.testng.annotations.BeforeMethod; -import org.testng.annotations.Test; - -import brooklyn.entity.basic.EntityInternal; -import brooklyn.entity.group.DynamicCluster; -import brooklyn.entity.rebind.RebindTestFixtureWithApp; -import brooklyn.event.basic.BasicNotificationSensor; -import brooklyn.event.basic.Sensors; - -import org.apache.brooklyn.location.basic.SimulatedLocation; - -import brooklyn.util.time.Duration; - -import com.google.common.collect.ImmutableList; -import com.google.common.collect.Iterables; - -public class AutoScalerPolicyRebindTest extends RebindTestFixtureWithApp { - - public static BasicNotificationSensor POOL_HOT_SENSOR = new BasicNotificationSensor( - Map.class, "AutoScalerPolicyRebindTest.resizablepool.hot", "Pool is over-utilized; it has insufficient resource for current workload"); - public static BasicNotificationSensor POOL_COLD_SENSOR = new BasicNotificationSensor( - Map.class, "AutoScalerPolicyRebindTest.resizablepool.cold", "Pool is under-utilized; it has too much resource for current workload"); - public static BasicNotificationSensor POOL_OK_SENSOR = new BasicNotificationSensor( - Map.class, "AutoScalerPolicyRebindTest.resizablepool.cold", "Pool utilization is ok; the available resources are fine for the current workload"); - public static BasicNotificationSensor MAX_SIZE_REACHED_SENSOR = new BasicNotificationSensor( - MaxPoolSizeReachedEvent.class, "AutoScalerPolicyRebindTest.maxSizeReached"); - public static AttributeSensor METRIC_SENSOR = Sensors.newIntegerSensor("AutoScalerPolicyRebindTest.metric"); - - private DynamicCluster origCluster; - private SimulatedLocation origLoc; - - @BeforeMethod(alwaysRun=true) - @Override - public void setUp() throws Exception { - super.setUp(); - origLoc = origManagementContext.getLocationManager().createLocation(LocationSpec.create(SimulatedLocation.class)); - origCluster = origApp.createAndManageChild(EntitySpec.create(DynamicCluster.class) - .configure("memberSpec", EntitySpec.create(TestEntity.class))); - } - - @Test - public void testRestoresAutoScalerConfig() throws Exception { - origCluster.addPolicy(AutoScalerPolicy.builder() - .name("myname") - .metric(METRIC_SENSOR) - .entityWithMetric(origCluster) - .metricUpperBound(1) - .metricLowerBound(2) - .minPoolSize(0) - .maxPoolSize(3) - .minPeriodBetweenExecs(Duration.of(4, TimeUnit.MILLISECONDS)) - .resizeUpStabilizationDelay(Duration.of(5, TimeUnit.MILLISECONDS)) - .resizeDownStabilizationDelay(Duration.of(6, TimeUnit.MILLISECONDS)) - .poolHotSensor(POOL_HOT_SENSOR) - .poolColdSensor(POOL_COLD_SENSOR) - .poolOkSensor(POOL_OK_SENSOR) - .maxSizeReachedSensor(MAX_SIZE_REACHED_SENSOR) - .maxReachedNotificationDelay(Duration.of(7, TimeUnit.MILLISECONDS)) - .buildSpec()); - - TestApplication newApp = rebind(); - DynamicCluster newCluster = (DynamicCluster) Iterables.getOnlyElement(newApp.getChildren()); - AutoScalerPolicy newPolicy = (AutoScalerPolicy) Iterables.getOnlyElement(newCluster.getPolicies()); - - assertEquals(newPolicy.getDisplayName(), "myname"); - assertEquals(newPolicy.getConfig(AutoScalerPolicy.METRIC), METRIC_SENSOR); - assertEquals(newPolicy.getConfig(AutoScalerPolicy.ENTITY_WITH_METRIC), newCluster); - assertEquals(newPolicy.getConfig(AutoScalerPolicy.METRIC_UPPER_BOUND), 1); - assertEquals(newPolicy.getConfig(AutoScalerPolicy.METRIC_LOWER_BOUND), 2); - assertEquals(newPolicy.getConfig(AutoScalerPolicy.MIN_POOL_SIZE), (Integer)0); - assertEquals(newPolicy.getConfig(AutoScalerPolicy.MAX_POOL_SIZE), (Integer)3); - assertEquals(newPolicy.getConfig(AutoScalerPolicy.MIN_PERIOD_BETWEEN_EXECS), Duration.of(4, TimeUnit.MILLISECONDS)); - assertEquals(newPolicy.getConfig(AutoScalerPolicy.RESIZE_UP_STABILIZATION_DELAY), Duration.of(5, TimeUnit.MILLISECONDS)); - assertEquals(newPolicy.getConfig(AutoScalerPolicy.RESIZE_DOWN_STABILIZATION_DELAY), Duration.of(6, TimeUnit.MILLISECONDS)); - assertEquals(newPolicy.getConfig(AutoScalerPolicy.POOL_HOT_SENSOR), POOL_HOT_SENSOR); - assertEquals(newPolicy.getConfig(AutoScalerPolicy.POOL_COLD_SENSOR), POOL_COLD_SENSOR); - assertEquals(newPolicy.getConfig(AutoScalerPolicy.POOL_OK_SENSOR), POOL_OK_SENSOR); - assertEquals(newPolicy.getConfig(AutoScalerPolicy.MAX_SIZE_REACHED_SENSOR), MAX_SIZE_REACHED_SENSOR); - assertEquals(newPolicy.getConfig(AutoScalerPolicy.MAX_REACHED_NOTIFICATION_DELAY), Duration.of(7, TimeUnit.MILLISECONDS)); - } - - @Test - public void testAutoScalerResizesAfterRebind() throws Exception { - origCluster.start(ImmutableList.of(origLoc)); - origCluster.addPolicy(AutoScalerPolicy.builder() - .name("myname") - .metric(METRIC_SENSOR) - .entityWithMetric(origCluster) - .metricUpperBound(10) - .metricLowerBound(100) - .minPoolSize(1) - .maxPoolSize(3) - .buildSpec()); - - TestApplication newApp = rebind(); - DynamicCluster newCluster = (DynamicCluster) Iterables.getOnlyElement(newApp.getChildren()); - - assertEquals(newCluster.getCurrentSize(), (Integer)1); - - ((EntityInternal)newCluster).setAttribute(METRIC_SENSOR, 1000); - EntityTestUtils.assertGroupSizeEqualsEventually(newCluster, 3); - - ((EntityInternal)newCluster).setAttribute(METRIC_SENSOR, 1); - EntityTestUtils.assertGroupSizeEqualsEventually(newCluster, 1); - } -} http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/d30ff597/policy/src/test/java/brooklyn/policy/autoscaling/AutoScalerPolicyReconfigurationTest.java ---------------------------------------------------------------------- diff --git a/policy/src/test/java/brooklyn/policy/autoscaling/AutoScalerPolicyReconfigurationTest.java b/policy/src/test/java/brooklyn/policy/autoscaling/AutoScalerPolicyReconfigurationTest.java deleted file mode 100644 index e685735..0000000 --- a/policy/src/test/java/brooklyn/policy/autoscaling/AutoScalerPolicyReconfigurationTest.java +++ /dev/null @@ -1,190 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package brooklyn.policy.autoscaling; - -import static brooklyn.policy.autoscaling.AutoScalerPolicyTest.currentSizeAsserter; - -import org.apache.brooklyn.api.entity.proxying.EntitySpec; -import org.apache.brooklyn.api.event.AttributeSensor; -import org.apache.brooklyn.test.entity.TestApplication; -import org.apache.brooklyn.test.entity.TestCluster; -import org.testng.annotations.AfterMethod; -import org.testng.annotations.BeforeMethod; -import org.testng.annotations.Test; - -import brooklyn.entity.basic.Entities; -import brooklyn.event.basic.Sensors; -import brooklyn.test.Asserts; -import brooklyn.util.time.Duration; - -import com.google.common.collect.ImmutableMap; - -public class AutoScalerPolicyReconfigurationTest { - - private static long TIMEOUT_MS = 10000; - - private static final AttributeSensor MY_ATTRIBUTE = Sensors.newIntegerSensor("autoscaler.test.intAttrib"); - TestApplication app; - TestCluster tc; - - @BeforeMethod(alwaysRun=true) - public void before() throws Exception { - app = TestApplication.Factory.newManagedInstanceForTests(); - tc = app.createAndManageChild(EntitySpec.create(TestCluster.class) - .configure("initialSize", 1)); - } - - @AfterMethod(alwaysRun=true) - public void tearDown() throws Exception { - if (app != null) Entities.destroyAll(app.getManagementContext()); - } - - @Test - public void testIncreaseMinPoolSizeCausesImmediateGrowth() { - tc.resize(2); - - AutoScalerPolicy policy = new AutoScalerPolicy.Builder().metric(MY_ATTRIBUTE) - .metricLowerBound(50).metricUpperBound(100) - .minPoolSize(2) - .build(); - tc.addPolicy(policy); - - policy.config().set(AutoScalerPolicy.MIN_POOL_SIZE, 3); - - Asserts.succeedsEventually(ImmutableMap.of("timeout", TIMEOUT_MS), currentSizeAsserter(tc, 3)); - } - - @Test - public void testDecreaseMinPoolSizeAllowsSubsequentShrink() { - tc.resize(4); - - AutoScalerPolicy policy = new AutoScalerPolicy.Builder().metric(MY_ATTRIBUTE) - .metricLowerBound(50).metricUpperBound(100) - .minPoolSize(2) - .build(); - tc.addPolicy(policy); - - // 25*4 = 100 -> 2 nodes at 50 each - tc.setAttribute(MY_ATTRIBUTE, 25); - Asserts.succeedsEventually(ImmutableMap.of("timeout", TIMEOUT_MS), currentSizeAsserter(tc, 2)); - - // Decreases to new min-size - policy.config().set(AutoScalerPolicy.MIN_POOL_SIZE, 1); - tc.setAttribute(MY_ATTRIBUTE, 0); - Asserts.succeedsEventually(ImmutableMap.of("timeout", TIMEOUT_MS), currentSizeAsserter(tc, 1)); - } - - @Test - public void testDecreaseMaxPoolSizeCausesImmediateShrink() { - tc.resize(6); - - AutoScalerPolicy policy = new AutoScalerPolicy.Builder().metric(MY_ATTRIBUTE) - .metricLowerBound(50).metricUpperBound(100) - .maxPoolSize(6) - .build(); - tc.addPolicy(policy); - - policy.config().set(AutoScalerPolicy.MAX_POOL_SIZE, 4); - - Asserts.succeedsEventually(ImmutableMap.of("timeout", TIMEOUT_MS), currentSizeAsserter(tc, 4)); - } - - @Test - public void testIncreaseMaxPoolSizeAllowsSubsequentGrowth() { - tc.resize(3); - - AutoScalerPolicy policy = new AutoScalerPolicy.Builder().metric(MY_ATTRIBUTE) - .metricLowerBound(50).metricUpperBound(100) - .maxPoolSize(6) - .build(); - tc.addPolicy(policy); - - // 200*3 = 600 -> 6 nodes at 100 each - tc.setAttribute(MY_ATTRIBUTE, 200); - Asserts.succeedsEventually(ImmutableMap.of("timeout", TIMEOUT_MS), currentSizeAsserter(tc, 6)); - - policy.config().set(AutoScalerPolicy.MAX_POOL_SIZE, 8); - - // Increases to max-size only - tc.setAttribute(MY_ATTRIBUTE, 100000); - Asserts.succeedsEventually(ImmutableMap.of("timeout", TIMEOUT_MS), currentSizeAsserter(tc, 8)); - } - - @Test - public void testReconfigureMetricLowerBound() { - tc.resize(2); - - AutoScalerPolicy policy = new AutoScalerPolicy.Builder().metric(MY_ATTRIBUTE) - .metricLowerBound(50).metricUpperBound(100) - .build(); - tc.addPolicy(policy); - - policy.config().set(AutoScalerPolicy.METRIC_LOWER_BOUND, 51); - - tc.setAttribute(MY_ATTRIBUTE, 50); - Asserts.succeedsEventually(ImmutableMap.of("timeout", TIMEOUT_MS), currentSizeAsserter(tc, 1)); - } - - @Test - public void testReconfigureMetricUpperBound() { - tc.resize(1); - - AutoScalerPolicy policy = new AutoScalerPolicy.Builder().metric(MY_ATTRIBUTE) - .metricLowerBound(50).metricUpperBound(100) - .build(); - tc.addPolicy(policy); - - policy.config().set(AutoScalerPolicy.METRIC_UPPER_BOUND, 99); - - tc.setAttribute(MY_ATTRIBUTE, 100); - Asserts.succeedsEventually(ImmutableMap.of("timeout", TIMEOUT_MS), currentSizeAsserter(tc, 2)); - } - - @Test - public void testReconfigureResizeUpStabilizationDelay() { - tc.resize(1); - - AutoScalerPolicy policy = new AutoScalerPolicy.Builder().metric(MY_ATTRIBUTE) - .metricLowerBound(50).metricUpperBound(100) - .resizeUpStabilizationDelay(Duration.TWO_MINUTES) - .build(); - tc.addPolicy(policy); - - policy.config().set(AutoScalerPolicy.RESIZE_UP_STABILIZATION_DELAY, Duration.ZERO); - - tc.setAttribute(MY_ATTRIBUTE, 101); - Asserts.succeedsEventually(ImmutableMap.of("timeout", TIMEOUT_MS), currentSizeAsserter(tc, 2)); - } - - @Test - public void testReconfigureResizeDownStabilizationDelay() { - tc.resize(2); - - AutoScalerPolicy policy = new AutoScalerPolicy.Builder().metric(MY_ATTRIBUTE) - .metricLowerBound(50).metricUpperBound(100) - .resizeDownStabilizationDelay(Duration.TWO_MINUTES) - .build(); - tc.addPolicy(policy); - - policy.config().set(AutoScalerPolicy.RESIZE_DOWN_STABILIZATION_DELAY, Duration.ZERO); - - tc.setAttribute(MY_ATTRIBUTE, 1); - Asserts.succeedsEventually(ImmutableMap.of("timeout", TIMEOUT_MS), currentSizeAsserter(tc, 1)); - } -} http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/d30ff597/policy/src/test/java/brooklyn/policy/autoscaling/AutoScalerPolicyTest.java ---------------------------------------------------------------------- diff --git a/policy/src/test/java/brooklyn/policy/autoscaling/AutoScalerPolicyTest.java b/policy/src/test/java/brooklyn/policy/autoscaling/AutoScalerPolicyTest.java deleted file mode 100644 index a4724f1..0000000 --- a/policy/src/test/java/brooklyn/policy/autoscaling/AutoScalerPolicyTest.java +++ /dev/null @@ -1,649 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package brooklyn.policy.autoscaling; - -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertTrue; - -import java.lang.management.ManagementFactory; -import java.lang.management.MemoryMXBean; -import java.lang.management.MemoryUsage; -import java.lang.management.OperatingSystemMXBean; -import java.lang.management.ThreadInfo; -import java.lang.management.ThreadMXBean; -import java.util.List; -import java.util.Map; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.atomic.AtomicInteger; - -import org.apache.brooklyn.api.entity.Entity; -import org.apache.brooklyn.api.entity.proxying.EntitySpec; -import org.apache.brooklyn.api.policy.PolicySpec; -import org.apache.brooklyn.test.entity.TestApplication; -import org.apache.brooklyn.test.entity.TestCluster; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.testng.Assert; -import org.testng.annotations.AfterMethod; -import org.testng.annotations.BeforeMethod; -import org.testng.annotations.Test; - -import brooklyn.entity.basic.Entities; -import brooklyn.entity.trait.Resizable; -import brooklyn.event.basic.BasicNotificationSensor; -import brooklyn.test.Asserts; -import brooklyn.util.collections.MutableList; -import brooklyn.util.collections.MutableMap; -import brooklyn.util.time.Duration; - -import com.google.common.base.Stopwatch; -import com.google.common.collect.ImmutableList; -import com.google.common.collect.ImmutableMap; - -public class AutoScalerPolicyTest { - - private static final Logger log = LoggerFactory.getLogger(AutoScalerPolicyTest.class); - - private static long TIMEOUT_MS = 10*1000; - private static long SHORT_WAIT_MS = 250; - private static long OVERHEAD_DURATION_MS = 500; - private static long EARLY_RETURN_MS = 10; - - private static final int MANY_TIMES_INVOCATION_COUNT = 10; - - AutoScalerPolicy policy; - TestCluster cluster; - LocallyResizableEntity resizable; - TestApplication app; - List policyResizes = MutableList.of(); - - @BeforeMethod(alwaysRun=true) - public void setUp() throws Exception { - log.info("resetting "+getClass().getSimpleName()); - app = TestApplication.Factory.newManagedInstanceForTests(); - cluster = app.createAndManageChild(EntitySpec.create(TestCluster.class).configure(TestCluster.INITIAL_SIZE, 1)); - resizable = new LocallyResizableEntity(cluster, cluster); - Entities.manage(resizable); - PolicySpec policySpec = PolicySpec.create(AutoScalerPolicy.class).configure(AutoScalerPolicy.RESIZE_OPERATOR, new ResizeOperator() { - @Override - public Integer resize(Entity entity, Integer desiredSize) { - log.info("resizing to "+desiredSize); - policyResizes.add(desiredSize); - return ((Resizable)entity).resize(desiredSize); - } - }); - policy = resizable.addPolicy(policySpec); - policyResizes.clear(); - } - - @AfterMethod(alwaysRun=true) - public void tearDown() throws Exception { - if (policy != null) policy.destroy(); - if (app != null) Entities.destroyAll(app.getManagementContext()); - cluster = null; - resizable = null; - policy = null; - } - - public void assertSizeEventually(Integer targetSize) { - Asserts.succeedsEventually(ImmutableMap.of("timeout", TIMEOUT_MS), currentSizeAsserter(resizable, targetSize)); - assertEquals(policyResizes.get(policyResizes.size()-1), targetSize); - } - - @Test - public void testShrinkColdPool() throws Exception { - resizable.resize(4); - // all metrics as per-node here - resizable.emit(AutoScalerPolicy.DEFAULT_POOL_COLD_SENSOR, message(30d/4, 10, 20)); - - // expect pool to shrink to 3 (i.e. maximum to have >= 10 per container) - assertSizeEventually(3); - } - - @Test - public void testShrinkColdPoolTotals() throws Exception { - resizable.resize(4); - // all metrics as totals here - resizable.emit(AutoScalerPolicy.DEFAULT_POOL_COLD_SENSOR, message(30L, 4*10L, 4*20L)); - - // expect pool to shrink to 3 (i.e. maximum to have >= 10 per container) - assertSizeEventually(3); - } - - @Test - public void testShrinkColdPoolRoundsUpDesiredNumberOfContainers() throws Exception { - resizable.resize(4); - resizable.emit(AutoScalerPolicy.DEFAULT_POOL_COLD_SENSOR, message(1L, 4*10L, 4*20L)); - - Asserts.succeedsEventually(ImmutableMap.of("timeout", TIMEOUT_MS), currentSizeAsserter(resizable, 1)); - } - - @Test - public void testGrowHotPool() throws Exception { - resizable.resize(2); - // all metrics as per-node here - resizable.emit(AutoScalerPolicy.DEFAULT_POOL_HOT_SENSOR, message(21L, 10L, 20L)); - - // expect pool to grow to 3 (i.e. minimum to have <= 20 per container) - assertSizeEventually(3); - } - - @Test - public void testGrowHotPoolTotals() throws Exception { - resizable.resize(2); - // all metrics as totals here - resizable.emit(AutoScalerPolicy.DEFAULT_POOL_HOT_SENSOR, message(41L, 2*10L, 2*20L)); - - // expect pool to grow to 3 (i.e. minimum to have <= 20 per container) - assertSizeEventually(3); - } - - @Test - public void testGrowShrinkRespectsResizeIterationIncrementAndResizeIterationMax() throws Exception { - resizable.resize(2); - policy.config().set(AutoScalerPolicy.RESIZE_UP_ITERATION_INCREMENT, 2); - policy.config().set(AutoScalerPolicy.RESIZE_UP_ITERATION_MAX, 4); - policy.config().set(AutoScalerPolicy.RESIZE_DOWN_ITERATION_INCREMENT, 3); - policy.config().set(AutoScalerPolicy.RESIZE_DOWN_ITERATION_MAX, 3); - - resizable.emit(AutoScalerPolicy.DEFAULT_POOL_HOT_SENSOR, message(42/2, 10, 20)); - // expect pool to grow to 4 (i.e. to have <= 20 per container we need 3, but increment is 2) - assertSizeEventually(4); - - resizable.emit(AutoScalerPolicy.DEFAULT_POOL_HOT_SENSOR, message(200/4, 10, 20)); - // a single hot message can only make it go to 8 - assertSizeEventually(8); - assertEquals(policyResizes, MutableList.of(4, 8)); - resizable.emit(AutoScalerPolicy.DEFAULT_POOL_HOT_SENSOR, message(200/8, 10, 20)); - assertSizeEventually(10); - assertEquals(policyResizes, MutableList.of(4, 8, 10)); - - // now shrink - policyResizes.clear(); - policy.config().set(AutoScalerPolicy.MIN_POOL_SIZE, 2); - resizable.emit(AutoScalerPolicy.DEFAULT_POOL_COLD_SENSOR, message(1, 10, 20)); - assertSizeEventually(7); - resizable.emit(AutoScalerPolicy.DEFAULT_POOL_COLD_SENSOR, message(1, 10, 20)); - assertSizeEventually(4); - resizable.emit(AutoScalerPolicy.DEFAULT_POOL_COLD_SENSOR, message(1, 10, 20)); - assertSizeEventually(2); - assertEquals(policyResizes, MutableList.of(7, 4, 2)); - } - - @Test - public void testHasId() throws Exception { - resizable.removePolicy(policy); - policy = AutoScalerPolicy.builder() - .minPoolSize(2) - .build(); - resizable.addPolicy(policy); - Assert.assertTrue(policy.getId()!=null); - } - - @Test - public void testNeverShrinkBelowMinimum() throws Exception { - resizable.removePolicy(policy); - policy = AutoScalerPolicy.builder() - .minPoolSize(2) - .build(); - resizable.addPolicy(policy); - - resizable.resize(4); - resizable.emit(AutoScalerPolicy.DEFAULT_POOL_COLD_SENSOR, message(4, 0L, 4*10L, 4*20L)); - - // expect pool to shrink only to the minimum - Asserts.succeedsEventually(ImmutableMap.of("timeout", TIMEOUT_MS), currentSizeAsserter(resizable, 2)); - } - - @Test - public void testNeverGrowAboveMaximmum() throws Exception { - resizable.removePolicy(policy); - policy = AutoScalerPolicy.builder() - .maxPoolSize(5) - .build(); - resizable.addPolicy(policy); - - resizable.resize(4); - resizable.emit(AutoScalerPolicy.DEFAULT_POOL_HOT_SENSOR, message(4, 1000000L, 4*10L, 4*20L)); - - // expect pool to grow only to the maximum - Asserts.succeedsEventually(ImmutableMap.of("timeout", TIMEOUT_MS), currentSizeAsserter(resizable, 5)); - } - - @Test - public void testNeverGrowColdPool() throws Exception { - resizable.resize(2); - resizable.emit(AutoScalerPolicy.DEFAULT_POOL_COLD_SENSOR, message(2, 1000L, 2*10L, 2*20L)); - - Thread.sleep(SHORT_WAIT_MS); - assertEquals(resizable.getCurrentSize(), (Integer)2); - } - - @Test - public void testNeverShrinkHotPool() throws Exception { - resizable.resizeSleepTime = 0; - resizable.resize(2); - resizable.emit(AutoScalerPolicy.DEFAULT_POOL_HOT_SENSOR, message(2, 0L, 2*10L, 2*20L)); - - // if had been a POOL_COLD, would have shrunk to 3 - Thread.sleep(SHORT_WAIT_MS); - assertEquals(resizable.getCurrentSize(), (Integer)2); - } - - @Test(groups="Integration") - public void testConcurrentShrinkShrink() throws Exception { - resizable.resizeSleepTime = 250; - resizable.resize(4); - resizable.emit(AutoScalerPolicy.DEFAULT_POOL_COLD_SENSOR, message(4, 30L, 4*10L, 4*20L)); - // would cause pool to shrink to 3 - - resizable.emit(AutoScalerPolicy.DEFAULT_POOL_COLD_SENSOR, message(4, 1L, 4*10L, 4*20L)); - // now expect pool to shrink to 1 - - Asserts.succeedsEventually(ImmutableMap.of("timeout", TIMEOUT_MS), currentSizeAsserter(resizable, 1)); - } - - @Test(groups="Integration") - public void testConcurrentGrowGrow() throws Exception { - resizable.resizeSleepTime = 250; - resizable.resize(2); - resizable.emit(AutoScalerPolicy.DEFAULT_POOL_HOT_SENSOR, message(2, 41L, 2*10L, 2*20L)); - // would cause pool to grow to 3 - - resizable.emit(AutoScalerPolicy.DEFAULT_POOL_HOT_SENSOR, message(2, 81L, 2*10L, 2*20L)); - // now expect pool to grow to 5 - - Asserts.succeedsEventually(ImmutableMap.of("timeout", TIMEOUT_MS), currentSizeAsserter(resizable, 5)); - } - - @Test(groups="Integration") - public void testConcurrentGrowShrink() throws Exception { - resizable.resizeSleepTime = 250; - resizable.resize(2); - resizable.emit(AutoScalerPolicy.DEFAULT_POOL_HOT_SENSOR, message(2, 81L, 2*10L, 2*20L)); - // would cause pool to grow to 5 - - resizable.emit(AutoScalerPolicy.DEFAULT_POOL_COLD_SENSOR, message(2, 1L, 2*10L, 2*20L)); - // now expect pool to shrink to 1 - - Asserts.succeedsEventually(ImmutableMap.of("timeout", TIMEOUT_MS), currentSizeAsserter(resizable, 1)); - } - - @Test(groups="Integration") - public void testConcurrentShrinkGrow() throws Exception { - resizable.resizeSleepTime = 250; - resizable.resize(4); - resizable.emit(AutoScalerPolicy.DEFAULT_POOL_COLD_SENSOR, message(4, 1L, 4*10L, 4*20L)); - // would cause pool to shrink to 1 - - resizable.emit(AutoScalerPolicy.DEFAULT_POOL_HOT_SENSOR, message(4, 81L, 4*10L, 4*20L)); - // now expect pool to grow to 5 - - Asserts.succeedsEventually(ImmutableMap.of("timeout", TIMEOUT_MS), currentSizeAsserter(resizable, 5)); - } - - // FIXME failed in jenkins (e.g. #1035); with "lists don't have the same size expected:<3> but was:<2>" - // Is it just too time sensitive? But I'd have expected > 3 rather than less - @Test(groups="WIP") - public void testRepeatedQueuedResizeTakesLatestValueRatherThanIntermediateValues() throws Exception { - // TODO is this too time sensitive? the resize takes only 250ms so if it finishes before the next emit we'd also see size=2 - resizable.resizeSleepTime = 500; - resizable.resize(4); - resizable.emit(AutoScalerPolicy.DEFAULT_POOL_COLD_SENSOR, message(4, 30L, 4*10L, 4*20L)); // shrink to 3 - resizable.emit(AutoScalerPolicy.DEFAULT_POOL_COLD_SENSOR, message(4, 20L, 4*10L, 4*20L)); // shrink to 2 - resizable.emit(AutoScalerPolicy.DEFAULT_POOL_COLD_SENSOR, message(4, 10L, 4*10L, 4*20L)); // shrink to 1 - - Asserts.succeedsEventually(ImmutableMap.of("timeout", TIMEOUT_MS), currentSizeAsserter(resizable, 1)); - assertEquals(resizable.sizes, ImmutableList.of(4, 3, 1)); - } - - - @Test - public void testUsesResizeOperatorOverride() throws Exception { - resizable.removePolicy(policy); - - final AtomicInteger counter = new AtomicInteger(); - policy = AutoScalerPolicy.builder() - .resizeOperator(new ResizeOperator() { - @Override public Integer resize(Entity entity, Integer desiredSize) { - counter.incrementAndGet(); - return desiredSize; - }}) - .build(); - resizable.addPolicy(policy); - - resizable.emit(AutoScalerPolicy.DEFAULT_POOL_HOT_SENSOR, message(1, 21L, 1*10L, 1*20L)); // grow to 2 - - Asserts.succeedsEventually(MutableMap.of("timeout",TIMEOUT_MS), new Runnable() { - public void run() { - assertTrue(counter.get() >= 1, "cccounter="+counter); - }}); - } - - @Test - public void testUsesCustomSensorOverride() throws Exception { - resizable.removePolicy(policy); - - @SuppressWarnings("rawtypes") - BasicNotificationSensor customPoolHotSensor = new BasicNotificationSensor(Map.class, "custom.hot", ""); - @SuppressWarnings("rawtypes") - BasicNotificationSensor customPoolColdSensor = new BasicNotificationSensor(Map.class, "custom.cold", ""); - @SuppressWarnings("rawtypes") - BasicNotificationSensor customPoolOkSensor = new BasicNotificationSensor(Map.class, "custom.ok", ""); - policy = AutoScalerPolicy.builder() - .poolHotSensor(customPoolHotSensor) - .poolColdSensor(customPoolColdSensor) - .poolOkSensor(customPoolOkSensor) - .build(); - resizable.addPolicy(policy); - - resizable.emit(customPoolHotSensor, message(1, 21L, 1*10L, 1*20L)); // grow to 2 - Asserts.succeedsEventually(ImmutableMap.of("timeout", TIMEOUT_MS), currentSizeAsserter(resizable, 2)); - - resizable.emit(customPoolColdSensor, message(2, 1L, 1*10L, 1*20L)); // shrink to 1 - Asserts.succeedsEventually(ImmutableMap.of("timeout", TIMEOUT_MS), currentSizeAsserter(resizable, 1)); - } - - @Test(groups="Integration") - public void testResizeUpStabilizationDelayIgnoresBlip() throws Exception { - long resizeUpStabilizationDelay = 1000L; - Duration minPeriodBetweenExecs = Duration.ZERO; - resizable.removePolicy(policy); - - policy = AutoScalerPolicy.builder() - .resizeUpStabilizationDelay(Duration.of(resizeUpStabilizationDelay, TimeUnit.MILLISECONDS)) - .minPeriodBetweenExecs(minPeriodBetweenExecs) - .build(); - resizable.addPolicy(policy); - resizable.resize(1); - - // Ignores temporary blip - resizable.emit(AutoScalerPolicy.DEFAULT_POOL_HOT_SENSOR, message(1, 61L, 1*10L, 1*20L)); // would grow to 4 - Thread.sleep(resizeUpStabilizationDelay-OVERHEAD_DURATION_MS); - resizable.emit(AutoScalerPolicy.DEFAULT_POOL_OK_SENSOR, message(1, 11L, 4*10L, 4*20L)); // but 1 is still adequate - - assertEquals(resizable.getCurrentSize(), (Integer)1); - Asserts.succeedsContinually(MutableMap.of("duration", 2000L), new Runnable() { - @Override public void run() { - assertEquals(resizable.sizes, ImmutableList.of(1)); - }}); - } - - // FIXME failing in jenkins occassionally - have put it in the "Acceptance" group for now - // - // Error was things like it taking a couple of seconds too long to scale-up. This is *not* - // just caused by a slow GC (running with -verbose:gc shows during a failure several - // incremental GCs that usually don't amount to more than 0.2 of a second at most, often less). - // Doing a thread-dump etc immediately after the too-long delay shows no strange thread usage, - // and shows releng3 system load averages of numbers like 1.73, 2.87 and 1.22. - // - // Is healthy on normal machines. - @Test(groups={"Integration", "Acceptance"}, invocationCount=MANY_TIMES_INVOCATION_COUNT) - public void testRepeatedResizeUpStabilizationDelayTakesMaxSustainedDesired() throws Throwable { - try { - testResizeUpStabilizationDelayTakesMaxSustainedDesired(); - } catch (Throwable t) { - dumpThreadsEtc(); - throw t; - } - } - - @Test(groups="Integration") - public void testResizeUpStabilizationDelayTakesMaxSustainedDesired() throws Exception { - long resizeUpStabilizationDelay = 1100L; - Duration minPeriodBetweenExecs = Duration.ZERO; - resizable.removePolicy(policy); - - policy = AutoScalerPolicy.builder() - .resizeUpStabilizationDelay(Duration.of(resizeUpStabilizationDelay, TimeUnit.MILLISECONDS)) - .minPeriodBetweenExecs(minPeriodBetweenExecs) - .build(); - resizable.addPolicy(policy); - resizable.resize(1); - - // Will grow to only the max sustained in this time window - // (i.e. to 2 within the first $resizeUpStabilizationDelay milliseconds) - Stopwatch stopwatch = Stopwatch.createStarted(); - - resizable.emit(AutoScalerPolicy.DEFAULT_POOL_HOT_SENSOR, message(1, 61L, 1*10L, 1*20L)); // would grow to 4 - resizable.emit(AutoScalerPolicy.DEFAULT_POOL_HOT_SENSOR, message(1, 21L, 1*10L, 1*20L)); // would grow to 2 - Thread.sleep(resizeUpStabilizationDelay-OVERHEAD_DURATION_MS); - - long postSleepTime = stopwatch.elapsed(TimeUnit.MILLISECONDS); - - resizable.emit(AutoScalerPolicy.DEFAULT_POOL_HOT_SENSOR, message(1, 61L, 1*10L, 1*20L)); // would grow to 4 - - // Wait for it to reach size 2, and confirm take expected time - // TODO This is time sensitive, and sometimes fails in CI with size=4 if we wait for currentSize==2 (presumably GC kicking in?) - // Therefore do strong assertion of currentSize==2 later, so can write out times if it goes wrong. - Asserts.succeedsEventually(MutableMap.of("period", 1, "timeout", TIMEOUT_MS), new Runnable() { - public void run() { - assertTrue(resizable.getCurrentSize() >= 2, "currentSize="+resizable.getCurrentSize()); - }}); - assertEquals(resizable.getCurrentSize(), (Integer)2, - stopwatch.elapsed(TimeUnit.MILLISECONDS)+"ms after first emission; "+(stopwatch.elapsed(TimeUnit.MILLISECONDS)-postSleepTime)+"ms after last"); - - long timeToResizeTo2 = stopwatch.elapsed(TimeUnit.MILLISECONDS); - assertTrue(timeToResizeTo2 >= resizeUpStabilizationDelay-EARLY_RETURN_MS && - timeToResizeTo2 <= resizeUpStabilizationDelay+OVERHEAD_DURATION_MS, - "Resizing to 2: time="+timeToResizeTo2+"; resizeUpStabilizationDelay="+resizeUpStabilizationDelay); - - // Will then grow to 4 $resizeUpStabilizationDelay milliseconds after that emission - Asserts.succeedsEventually(MutableMap.of("period", 1, "timeout", TIMEOUT_MS), - currentSizeAsserter(resizable, 4)); - long timeToResizeTo4 = stopwatch.elapsed(TimeUnit.MILLISECONDS) - postSleepTime; - - assertTrue(timeToResizeTo4 >= resizeUpStabilizationDelay-EARLY_RETURN_MS && - timeToResizeTo4 <= resizeUpStabilizationDelay+OVERHEAD_DURATION_MS, - "Resizing to 4: timeToResizeTo4="+timeToResizeTo4+"; timeToResizeTo2="+timeToResizeTo2+"; resizeUpStabilizationDelay="+resizeUpStabilizationDelay); - } - - @Test(groups="Integration") - public void testResizeUpStabilizationDelayResizesAfterDelay() { - final long resizeUpStabilizationDelay = 1000L; - Duration minPeriodBetweenExecs = Duration.ZERO; - resizable.removePolicy(policy); - - policy = resizable.addPolicy(AutoScalerPolicy.builder() - .resizeUpStabilizationDelay(Duration.of(resizeUpStabilizationDelay, TimeUnit.MILLISECONDS)) - .minPeriodBetweenExecs(minPeriodBetweenExecs) - .buildSpec()); - resizable.resize(1); - - // After suitable delay, grows to desired - final long emitTime = System.currentTimeMillis(); - final Map need4 = message(1, 61L, 1*10L, 1*20L); - resizable.emit(AutoScalerPolicy.DEFAULT_POOL_HOT_SENSOR, need4); // would grow to 4 - final AtomicInteger emitCount = new AtomicInteger(0); - - Asserts.succeedsEventually(MutableMap.of("timeout", TIMEOUT_MS), new Runnable() { - public void run() { - if (System.currentTimeMillis() - emitTime > (2+emitCount.get())*resizeUpStabilizationDelay) { - //first one may not have been received, in a registration race - resizable.emit(AutoScalerPolicy.DEFAULT_POOL_HOT_SENSOR, need4); - emitCount.incrementAndGet(); - } - assertEquals(resizable.getCurrentSize(), (Integer)4); - }}); - - long resizeDelay = System.currentTimeMillis() - emitTime; - assertTrue(resizeDelay >= (resizeUpStabilizationDelay-EARLY_RETURN_MS), "resizeDelay="+resizeDelay); - } - - @Test(groups="Integration") - public void testResizeDownStabilizationDelayIgnoresBlip() throws Exception { - long resizeStabilizationDelay = 1000L; - Duration minPeriodBetweenExecs = Duration.ZERO; - resizable.removePolicy(policy); - - policy = AutoScalerPolicy.builder() - .resizeDownStabilizationDelay(Duration.of(resizeStabilizationDelay, TimeUnit.MILLISECONDS)) - .minPeriodBetweenExecs(minPeriodBetweenExecs) - .build(); - resizable.addPolicy(policy); - resizable.resize(2); - - // Ignores temporary blip - resizable.emit(AutoScalerPolicy.DEFAULT_POOL_COLD_SENSOR, message(2, 1L, 2*10L, 2*20L)); // would shrink to 1 - Thread.sleep(resizeStabilizationDelay-OVERHEAD_DURATION_MS); - resizable.emit(AutoScalerPolicy.DEFAULT_POOL_OK_SENSOR, message(2, 20L, 1*10L, 1*20L)); // but 2 is still adequate - - assertEquals(resizable.getCurrentSize(), (Integer)2); - Asserts.succeedsContinually(MutableMap.of("duration", 2000L), new Runnable() { - public void run() { - assertEquals(resizable.sizes, ImmutableList.of(2)); - }}); - } - - // FIXME Acceptance -- see comment against testRepeatedResizeUpStabilizationDelayTakesMaxSustainedDesired - @Test(groups={"Integration", "Acceptance"}, invocationCount=MANY_TIMES_INVOCATION_COUNT) - public void testRepeatedResizeDownStabilizationDelayTakesMinSustainedDesired() throws Throwable { - try { - testResizeDownStabilizationDelayTakesMinSustainedDesired(); - } catch (Throwable t) { - dumpThreadsEtc(); - throw t; - } - } - - @Test(groups="Integration") - public void testResizeDownStabilizationDelayTakesMinSustainedDesired() throws Exception { - long resizeDownStabilizationDelay = 1100L; - Duration minPeriodBetweenExecs = Duration.ZERO; - policy.suspend(); - resizable.removePolicy(policy); - - policy = AutoScalerPolicy.builder() - .resizeDownStabilizationDelay(Duration.of(resizeDownStabilizationDelay, TimeUnit.MILLISECONDS)) - .minPeriodBetweenExecs(minPeriodBetweenExecs) - .build(); - resizable.addPolicy(policy); - resizable.resize(3); - - // Will shrink to only the min sustained in this time window - // (i.e. to 2 within the first $resizeUpStabilizationDelay milliseconds) - Stopwatch stopwatch = Stopwatch.createStarted(); - - resizable.emit(AutoScalerPolicy.DEFAULT_POOL_COLD_SENSOR, message(3, 1L, 3*10L, 3*20L)); // would shrink to 1 - resizable.emit(AutoScalerPolicy.DEFAULT_POOL_COLD_SENSOR, message(3, 20L, 3*10L, 3*20L)); // would shrink to 2 - Thread.sleep(resizeDownStabilizationDelay-OVERHEAD_DURATION_MS); - - long postSleepTime = stopwatch.elapsed(TimeUnit.MILLISECONDS); - - resizable.emit(AutoScalerPolicy.DEFAULT_POOL_COLD_SENSOR, message(3, 1L, 3*10L, 3*20L)); // would shrink to 1 - - // Wait for it to reach size 2, and confirm take expected time - // TODO This is time sensitive, and sometimes fails in CI with size=1 if we wait for currentSize==2 (presumably GC kicking in?) - // Therefore do strong assertion of currentSize==2 later, so can write out times if it goes wrong. - Asserts.succeedsEventually(MutableMap.of("period", 1, "timeout", TIMEOUT_MS), new Runnable() { - public void run() { - assertTrue(resizable.getCurrentSize() <= 2, "currentSize="+resizable.getCurrentSize()); - }}); - assertEquals(resizable.getCurrentSize(), (Integer)2, - stopwatch.elapsed(TimeUnit.MILLISECONDS)+"ms after first emission; "+(stopwatch.elapsed(TimeUnit.MILLISECONDS)-postSleepTime)+"ms after last"); - - long timeToResizeTo2 = stopwatch.elapsed(TimeUnit.MILLISECONDS); - assertTrue(timeToResizeTo2 >= resizeDownStabilizationDelay-EARLY_RETURN_MS && - timeToResizeTo2 <= resizeDownStabilizationDelay+OVERHEAD_DURATION_MS, - "Resizing to 2: time="+timeToResizeTo2+"; resizeDownStabilizationDelay="+resizeDownStabilizationDelay); - - // Will then shrink to 1 $resizeUpStabilizationDelay milliseconds after that emission - Asserts.succeedsEventually(MutableMap.of("period", 1, "timeout", TIMEOUT_MS), - currentSizeAsserter(resizable, 1)); - long timeToResizeTo1 = stopwatch.elapsed(TimeUnit.MILLISECONDS) - postSleepTime; - - assertTrue(timeToResizeTo1 >= resizeDownStabilizationDelay-EARLY_RETURN_MS && - timeToResizeTo1 <= resizeDownStabilizationDelay+OVERHEAD_DURATION_MS, - "Resizing to 1: timeToResizeTo1="+timeToResizeTo1+"; timeToResizeTo2="+timeToResizeTo2+"; resizeDownStabilizationDelay="+resizeDownStabilizationDelay); - } - - @Test(groups="Integration") - public void testResizeDownStabilizationDelayResizesAfterDelay() throws Exception { - final long resizeDownStabilizationDelay = 1000L; - Duration minPeriodBetweenExecs = Duration.ZERO; - resizable.removePolicy(policy); - - policy = AutoScalerPolicy.builder() - .resizeDownStabilizationDelay(Duration.of(resizeDownStabilizationDelay, TimeUnit.MILLISECONDS)) - .minPeriodBetweenExecs(minPeriodBetweenExecs) - .build(); - resizable.addPolicy(policy); - resizable.resize(2); - - // After suitable delay, grows to desired - final long emitTime = System.currentTimeMillis(); - final Map needJust1 = message(2, 1L, 2*10L, 2*20L); - resizable.emit(AutoScalerPolicy.DEFAULT_POOL_COLD_SENSOR, needJust1); // would shrink to 1 - final AtomicInteger emitCount = new AtomicInteger(0); - - Asserts.succeedsEventually(MutableMap.of("timeout", TIMEOUT_MS), new Runnable() { - public void run() { - if (System.currentTimeMillis() - emitTime > (2+emitCount.get())*resizeDownStabilizationDelay) { - //first one may not have been received, in a registration race - resizable.emit(AutoScalerPolicy.DEFAULT_POOL_COLD_SENSOR, needJust1); // would shrink to 1 - emitCount.incrementAndGet(); - } - assertEquals(resizable.getCurrentSize(), (Integer)1); - }}); - - long resizeDelay = System.currentTimeMillis() - emitTime; - assertTrue(resizeDelay >= (resizeDownStabilizationDelay-EARLY_RETURN_MS), "resizeDelay="+resizeDelay); - } - - Map message(double currentWorkrate, double lowThreshold, double highThreshold) { - return message(resizable.getCurrentSize(), currentWorkrate, lowThreshold, highThreshold); - } - static Map message(int currentSize, double currentWorkrate, double lowThreshold, double highThreshold) { - return ImmutableMap.of( - AutoScalerPolicy.POOL_CURRENT_SIZE_KEY, currentSize, - AutoScalerPolicy.POOL_CURRENT_WORKRATE_KEY, currentWorkrate, - AutoScalerPolicy.POOL_LOW_THRESHOLD_KEY, lowThreshold, - AutoScalerPolicy.POOL_HIGH_THRESHOLD_KEY, highThreshold); - } - - public static Runnable currentSizeAsserter(final Resizable resizable, final Integer desired) { - return new Runnable() { - public void run() { - assertEquals(resizable.getCurrentSize(), desired); - } - }; - } - - public static void dumpThreadsEtc() { - ThreadMXBean threadMXBean = ManagementFactory.getThreadMXBean(); - ThreadInfo[] threads = threadMXBean.dumpAllThreads(true, true); - for (ThreadInfo thread : threads) { - System.out.println(thread.getThreadName()+" ("+thread.getThreadState()+")"); - for (StackTraceElement stackTraceElement : thread.getStackTrace()) { - System.out.println("\t"+stackTraceElement); - } - } - - MemoryMXBean memoryMXBean = ManagementFactory.getMemoryMXBean(); - MemoryUsage heapMemoryUsage = memoryMXBean.getHeapMemoryUsage(); - MemoryUsage nonHeapMemoryUsage = memoryMXBean.getNonHeapMemoryUsage(); - System.out.println("Memory:"); - System.out.println("\tHeap: used="+heapMemoryUsage.getUsed()+"; max="+heapMemoryUsage.getMax()+"; init="+heapMemoryUsage.getInit()+"; committed="+heapMemoryUsage.getCommitted()); - System.out.println("\tNon-heap: used="+nonHeapMemoryUsage.getUsed()+"; max="+nonHeapMemoryUsage.getMax()+"; init="+nonHeapMemoryUsage.getInit()+"; committed="+nonHeapMemoryUsage.getCommitted()); - - OperatingSystemMXBean operatingSystemMXBean = ManagementFactory.getOperatingSystemMXBean(); - System.out.println("OS:"); - System.out.println("\tsysLoadAvg="+operatingSystemMXBean.getSystemLoadAverage()+"; availableProcessors="+operatingSystemMXBean.getAvailableProcessors()+"; arch="+operatingSystemMXBean.getArch()); - } -} http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/d30ff597/policy/src/test/java/brooklyn/policy/autoscaling/LocallyResizableEntity.java ---------------------------------------------------------------------- diff --git a/policy/src/test/java/brooklyn/policy/autoscaling/LocallyResizableEntity.java b/policy/src/test/java/brooklyn/policy/autoscaling/LocallyResizableEntity.java deleted file mode 100644 index c6b3c09..0000000 --- a/policy/src/test/java/brooklyn/policy/autoscaling/LocallyResizableEntity.java +++ /dev/null @@ -1,73 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package brooklyn.policy.autoscaling; - -import java.util.List; - -import org.apache.brooklyn.api.entity.Entity; -import org.apache.brooklyn.test.entity.TestCluster; - -import brooklyn.entity.basic.AbstractEntity; -import brooklyn.entity.trait.Resizable; -import brooklyn.entity.trait.Startable; - -import com.google.common.base.Throwables; -import com.google.common.collect.Lists; - -/** - * Test class for providing a Resizable LocallyManagedEntity for policy testing - * It is hooked up to a TestCluster that can be used to make assertions against - */ -public class LocallyResizableEntity extends AbstractEntity implements Resizable { - List sizes = Lists.newArrayList(); - TestCluster cluster; - long resizeSleepTime = 0; - - public LocallyResizableEntity (TestCluster tc) { - this(null, tc); - } - @SuppressWarnings("deprecation") - public LocallyResizableEntity (Entity parent, TestCluster tc) { - super(parent); - this.cluster = tc; - setAttribute(Startable.SERVICE_UP, true); - } - - @Override - public Integer resize(Integer newSize) { - try { - Thread.sleep(resizeSleepTime); - sizes.add(newSize); - return cluster.resize(newSize); - } catch (InterruptedException e) { - Thread.currentThread().interrupt(); - throw Throwables.propagate(e); - } - } - - @Override - public Integer getCurrentSize() { - return cluster.getCurrentSize(); - } - - @Override - public String toString() { - return getDisplayName(); - } -} http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/d30ff597/policy/src/test/java/brooklyn/policy/followthesun/AbstractFollowTheSunPolicyTest.java ---------------------------------------------------------------------- diff --git a/policy/src/test/java/brooklyn/policy/followthesun/AbstractFollowTheSunPolicyTest.java b/policy/src/test/java/brooklyn/policy/followthesun/AbstractFollowTheSunPolicyTest.java deleted file mode 100644 index c8855f2..0000000 --- a/policy/src/test/java/brooklyn/policy/followthesun/AbstractFollowTheSunPolicyTest.java +++ /dev/null @@ -1,239 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package brooklyn.policy.followthesun; - -import static org.testng.Assert.assertEquals; - -import java.util.Collection; -import java.util.Map; -import java.util.Random; -import java.util.Set; - -import org.apache.brooklyn.api.entity.Entity; -import org.apache.brooklyn.api.entity.Group; -import org.apache.brooklyn.api.entity.basic.EntityLocal; -import org.apache.brooklyn.api.entity.proxying.EntitySpec; -import org.apache.brooklyn.api.location.Location; -import org.apache.brooklyn.api.location.LocationSpec; -import org.apache.brooklyn.api.management.ManagementContext; -import org.apache.brooklyn.test.entity.LocalManagementContextForTests; -import org.apache.brooklyn.test.entity.TestApplication; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.testng.annotations.AfterMethod; -import org.testng.annotations.BeforeMethod; - -import brooklyn.entity.basic.ApplicationBuilder; -import brooklyn.entity.basic.DynamicGroup; -import brooklyn.entity.basic.Entities; - -import org.apache.brooklyn.location.basic.SimulatedLocation; - -import brooklyn.policy.loadbalancing.BalanceableContainer; -import brooklyn.policy.loadbalancing.MockContainerEntity; -import brooklyn.policy.loadbalancing.MockItemEntity; -import brooklyn.policy.loadbalancing.MockItemEntityImpl; -import brooklyn.policy.loadbalancing.Movable; -import brooklyn.test.Asserts; -import brooklyn.util.collections.MutableMap; -import brooklyn.util.time.Time; - -import com.google.common.base.Function; -import com.google.common.base.Predicates; -import com.google.common.collect.ImmutableList; -import com.google.common.collect.ImmutableSet; -import com.google.common.collect.Iterables; -import com.google.common.collect.Maps; - -public class AbstractFollowTheSunPolicyTest { - - private static final Logger LOG = LoggerFactory.getLogger(AbstractFollowTheSunPolicyTest.class); - - protected static final long TIMEOUT_MS = 10*1000; - protected static final long SHORT_WAIT_MS = 250; - - protected static final long CONTAINER_STARTUP_DELAY_MS = 100; - - protected TestApplication app; - protected ManagementContext managementContext; - protected SimulatedLocation loc1; - protected SimulatedLocation loc2; - protected FollowTheSunPool pool; - protected DefaultFollowTheSunModel model; - protected FollowTheSunPolicy policy; - protected Group containerGroup; - protected Group itemGroup; - protected Random random = new Random(); - - @BeforeMethod(alwaysRun=true) - public void setUp() throws Exception { - LOG.debug("In AbstractFollowTheSunPolicyTest.setUp()"); - - MockItemEntityImpl.totalMoveCount.set(0); - MockItemEntityImpl.lastMoveTime.set(0); - - managementContext = LocalManagementContextForTests.newInstance(); - app = ApplicationBuilder.newManagedApp(TestApplication.class, managementContext); - - loc1 = managementContext.getLocationManager().createLocation(LocationSpec.create(SimulatedLocation.class).configure("name", "loc1")); - loc2 = managementContext.getLocationManager().createLocation(LocationSpec.create(SimulatedLocation.class).configure("name", "loc2")); - - containerGroup = app.createAndManageChild(EntitySpec.create(DynamicGroup.class) - .displayName("containerGroup") - .configure(DynamicGroup.ENTITY_FILTER, Predicates.instanceOf(MockContainerEntity.class))); - - itemGroup = app.createAndManageChild(EntitySpec.create(DynamicGroup.class) - .displayName("itemGroup") - .configure(DynamicGroup.ENTITY_FILTER, Predicates.instanceOf(MockItemEntity.class))); - model = new DefaultFollowTheSunModel("pool-model"); - pool = app.createAndManageChild(EntitySpec.create(FollowTheSunPool.class)); - pool.setContents(containerGroup, itemGroup); - policy = new FollowTheSunPolicy(MockItemEntity.ITEM_USAGE_METRIC, model, FollowTheSunParameters.newDefault()); - pool.addPolicy(policy); - app.start(ImmutableList.of(loc1, loc2)); - } - - @AfterMethod(alwaysRun=true) - public void tearDown() { - if (pool != null && policy != null) pool.removePolicy(policy); - if (app != null) Entities.destroyAll(app.getManagementContext()); - MockItemEntityImpl.totalMoveCount.set(0); - MockItemEntityImpl.lastMoveTime.set(0); - } - - /** - * Asserts that the given container have the given expected workrates (by querying the containers directly). - * Accepts an accuracy of "precision" for each container's workrate. - */ - protected void assertItemDistributionEventually(final Map> expected) { - try { - Asserts.succeedsEventually(MutableMap.of("timeout", TIMEOUT_MS), new Runnable() { - public void run() { - assertItemDistribution(expected); - }}); - } catch (AssertionError e) { - String errMsg = e.getMessage()+"; "+verboseDumpToString(); - throw new RuntimeException(errMsg, e); - } - } - - protected void assertItemDistributionContinually(final Map> expected) { - try { - Asserts.succeedsContinually(MutableMap.of("timeout", SHORT_WAIT_MS), new Runnable() { - public void run() { - assertItemDistribution(expected); - }}); - } catch (AssertionError e) { - String errMsg = e.getMessage()+"; "+verboseDumpToString(); - throw new RuntimeException(errMsg, e); - } - } - - protected void assertItemDistribution(Map> expected) { - String errMsg = verboseDumpToString(); - for (Map.Entry> entry : expected.entrySet()) { - MockContainerEntity container = entry.getKey(); - Collection expectedItems = entry.getValue(); - - assertEquals(ImmutableSet.copyOf(container.getBalanceableItems()), ImmutableSet.copyOf(expectedItems), errMsg); - } - } - - protected String verboseDumpToString() { - Iterable containers = Iterables.filter(app.getManagementContext().getEntityManager().getEntities(), MockContainerEntity.class); - Iterable items = Iterables.filter(app.getManagementContext().getEntityManager().getEntities(), MockItemEntity.class); - - Iterable containerRates = Iterables.transform(containers, new Function() { - @Override public Double apply(MockContainerEntity input) { - return (double) input.getWorkrate(); - }}); - - Iterable> containerItemUsages = Iterables.transform(containers, new Function>() { - @Override public Map apply(MockContainerEntity input) { - return input.getItemUsage(); - }}); - - Map> itemDistributionByContainer = Maps.newLinkedHashMap(); - for (MockContainerEntity container : containers) { - itemDistributionByContainer.put(container, container.getBalanceableItems()); - } - - Map> itemDistributionByItem = Maps.newLinkedHashMap(); - for (Movable item : items) { - itemDistributionByItem.put(item, item.getAttribute(Movable.CONTAINER)); - } - - String modelItemDistribution = model.itemDistributionToString(); - - return "containers="+containers+"; containerRates="+containerRates - +"; containerItemUsages="+containerItemUsages - +"; itemDistributionByContainer="+itemDistributionByContainer - +"; itemDistributionByItem="+itemDistributionByItem - +"; model="+modelItemDistribution - +"; totalMoves="+MockItemEntityImpl.totalMoveCount - +"; lastMoveTime="+Time.makeDateString(MockItemEntityImpl.lastMoveTime.get()); - } - - protected MockContainerEntity newContainer(TestApplication app, Location loc, String name) { - return newAsyncContainer(app, loc, name, 0); - } - - /** - * Creates a new container that will take "delay" millis to complete its start-up. - */ - protected MockContainerEntity newAsyncContainer(TestApplication app, Location loc, String name, long delay) { - // FIXME Is this comment true? - // Annoyingly, can't set parent until after the threshold config has been defined. - MockContainerEntity container = app.createAndManageChild(EntitySpec.create(MockContainerEntity.class) - .displayName(name) - .configure(MockContainerEntity.DELAY, delay)); - LOG.debug("Managed new container {}", container); - container.start(ImmutableList.of(loc)); - return container; - } - - protected static MockItemEntity newLockedItem(TestApplication app, MockContainerEntity container, String name) { - MockItemEntity item = app.createAndManageChild(EntitySpec.create(MockItemEntity.class) - .displayName(name) - .configure(MockItemEntity.IMMOVABLE, true)); - LOG.debug("Managed new locked item {}", container); - if (container != null) { - item.move(container); - } - return item; - } - - protected static MockItemEntity newItem(TestApplication app, MockContainerEntity container, String name) { - MockItemEntity item = app.createAndManageChild(EntitySpec.create(MockItemEntity.class) - .displayName(name)); - LOG.debug("Managed new item {} at {}", item, container); - if (container != null) { - item.move(container); - } - return item; - } - - protected static MockItemEntity newItem(TestApplication app, MockContainerEntity container, String name, Map workpattern) { - MockItemEntity item = newItem(app, container, name); - if (workpattern != null) { - ((EntityLocal)item).setAttribute(MockItemEntity.ITEM_USAGE_METRIC, (Map) workpattern); - } - return item; - } -} http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/d30ff597/policy/src/test/java/brooklyn/policy/followthesun/FollowTheSunModelTest.java ---------------------------------------------------------------------- diff --git a/policy/src/test/java/brooklyn/policy/followthesun/FollowTheSunModelTest.java b/policy/src/test/java/brooklyn/policy/followthesun/FollowTheSunModelTest.java deleted file mode 100644 index 9b16a2a..0000000 --- a/policy/src/test/java/brooklyn/policy/followthesun/FollowTheSunModelTest.java +++ /dev/null @@ -1,195 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package brooklyn.policy.followthesun; - -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertFalse; -import static org.testng.Assert.assertTrue; - -import org.testng.annotations.AfterMethod; -import org.testng.annotations.BeforeMethod; -import org.testng.annotations.Test; -import org.apache.brooklyn.api.location.Location; -import org.apache.brooklyn.location.basic.SimulatedLocation; - -import brooklyn.policy.loadbalancing.MockContainerEntity; -import brooklyn.policy.loadbalancing.MockContainerEntityImpl; -import brooklyn.policy.loadbalancing.MockItemEntity; -import brooklyn.policy.loadbalancing.MockItemEntityImpl; - -import com.google.common.collect.ImmutableMap; -import com.google.common.collect.ImmutableSet; - -public class FollowTheSunModelTest { - - private Location loc1 = new SimulatedLocation(DefaultFollowTheSunModel.newHashMap("name","loc1")); - private Location loc2 = new SimulatedLocation(DefaultFollowTheSunModel.newHashMap("name","loc2")); - private MockContainerEntity container1 = new MockContainerEntityImpl(); - private MockContainerEntity container2 = new MockContainerEntityImpl(); - private MockItemEntity item1 = new MockItemEntityImpl(); - private MockItemEntity item2 = new MockItemEntityImpl(); - private MockItemEntity item3 = new MockItemEntityImpl(); - - private DefaultFollowTheSunModel model; - - @BeforeMethod(alwaysRun=true) - public void setUp() throws Exception { - model = new DefaultFollowTheSunModel("myname"); - } - - @AfterMethod(alwaysRun=true) - public void tearDown() throws Exception { - // noting to tear down; no management context created - } - - @Test - public void testSimpleAddAndRemove() throws Exception { - model.onContainerAdded(container1, loc1); - model.onContainerAdded(container2, loc2); - model.onItemAdded(item1, container1, true); - model.onItemAdded(item2, container2, true); - - assertEquals(model.getContainerLocation(container1), loc1); - assertEquals(model.getContainerLocation(container2), loc2); - assertEquals(model.getItems(), ImmutableSet.of(item1, item2)); - assertEquals(model.getItemLocation(item1), loc1); - assertEquals(model.getItemLocation(item2), loc2); - assertEquals(model.getItemContainer(item1), container1); - assertEquals(model.getItemContainer(item2), container2); - - model.onContainerRemoved(container2); - model.onItemRemoved(item2); - - assertEquals(model.getContainerLocation(container1), loc1); - assertEquals(model.getContainerLocation(container2), null); - assertEquals(model.getItems(), ImmutableSet.of(item1)); - assertEquals(model.getItemLocation(item1), loc1); - assertEquals(model.getItemLocation(item2), null); - assertEquals(model.getItemContainer(item1), container1); - assertEquals(model.getItemContainer(item2), null); - } - - @Test - public void testItemUsageMetrics() throws Exception { - model.onContainerAdded(container1, loc1); - model.onContainerAdded(container2, loc2); - model.onItemAdded(item1, container1, true); - model.onItemAdded(item2, container2, true); - - model.onItemUsageUpdated(item1, ImmutableMap.of(item2, 12d)); - model.onItemUsageUpdated(item2, ImmutableMap.of(item1, 11d)); - - assertEquals(model.getDirectSendsToItemByLocation(), - ImmutableMap.of(item1, ImmutableMap.of(loc2, 12d), item2, ImmutableMap.of(loc1, 11d))); - } - - @Test - public void testItemUsageReportedIfLocationSetAfterUsageUpdate() throws Exception { - model.onContainerAdded(container1, null); - model.onContainerAdded(container2, null); - model.onItemAdded(item1, container1, true); - model.onItemAdded(item2, container2, true); - model.onItemUsageUpdated(item1, ImmutableMap.of(item2, 12d)); - model.onContainerLocationUpdated(container1, loc1); - model.onContainerLocationUpdated(container2, loc2); - - assertEquals(model.getDirectSendsToItemByLocation(), - ImmutableMap.of(item1, ImmutableMap.of(loc2, 12d))); - } - - @Test - public void testItemUsageMetricsSummedForActorsInSameLocation() throws Exception { - model.onContainerAdded(container1, loc1); - model.onContainerAdded(container2, loc2); - model.onItemAdded(item1, container1, true); - model.onItemAdded(item2, container2, true); - model.onItemAdded(item3, container2, true); - - model.onItemUsageUpdated(item1, ImmutableMap.of(item2, 12d, item3, 13d)); - - assertEquals(model.getDirectSendsToItemByLocation(), - ImmutableMap.of(item1, ImmutableMap.of(loc2, 12d+13d))); - } - - @Test - public void testItemMovedWillUpdateLocationUsage() throws Exception { - model.onContainerAdded(container1, loc1); - model.onContainerAdded(container2, loc2); - model.onItemAdded(item1, container1, false); - model.onItemAdded(item2, container2, false); - model.onItemUsageUpdated(item2, ImmutableMap.of(item1, 12d)); - - model.onItemMoved(item1, container2); - - assertEquals(model.getDirectSendsToItemByLocation(), - ImmutableMap.of(item2, ImmutableMap.of(loc2, 12d))); - assertEquals(model.getItemContainer(item1), container2); - assertEquals(model.getItemLocation(item1), loc2); - } - - @Test - public void testItemAddedWithNoContainer() throws Exception { - model.onItemAdded(item1, null, true); - - assertEquals(model.getItems(), ImmutableSet.of(item1)); - assertEquals(model.getItemContainer(item1), null); - assertEquals(model.getItemLocation(item1), null); - } - - @Test - public void testItemAddedBeforeContainer() throws Exception { - model.onItemAdded(item1, container1, true); - model.onContainerAdded(container1, loc1); - - assertEquals(model.getItems(), ImmutableSet.of(item1)); - assertEquals(model.getItemContainer(item1), container1); - assertEquals(model.getItemLocation(item1), loc1); - } - - @Test - public void testItemMovedBeforeContainerAdded() throws Exception { - model.onContainerAdded(container1, loc1); - model.onItemAdded(item1, container1, true); - model.onItemMoved(item1, container2); - model.onContainerAdded(container2, loc2); - - assertEquals(model.getItems(), ImmutableSet.of(item1)); - assertEquals(model.getItemContainer(item1), container2); - assertEquals(model.getItemLocation(item1), loc2); - } - - @Test - public void testItemAddedAnswersMovability() throws Exception { - model.onItemAdded(item1, container1, false); - model.onItemAdded(item2, container1, true); - assertTrue(model.isItemMoveable(item1)); - assertFalse(model.isItemMoveable(item2)); - } - - @Test - public void testWorkrateUpdateAfterItemRemovalIsNotRecorded() throws Exception { - model.onContainerAdded(container1, loc1); - model.onItemAdded(item1, container1, true); - model.onItemAdded(item2, container1, true); - model.onItemRemoved(item1); - model.onItemUsageUpdated(item1, ImmutableMap.of(item2, 123d)); - - assertFalse(model.getDirectSendsToItemByLocation().containsKey(item1)); - } -}