index
int64
0
0
repo_id
stringlengths
26
205
file_path
stringlengths
51
246
content
stringlengths
8
433k
__index_level_0__
int64
0
10k
0
Create_ds/SimianArmy/src/test/java/com/netflix
Create_ds/SimianArmy/src/test/java/com/netflix/simianarmy/TestMonkey.java
/* * * Copyright 2012 Netflix, Inc. * * Licensed 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. * */ // CHECKSTYLE IGNORE Javadoc package com.netflix.simianarmy; import org.testng.annotations.Test; import org.testng.Assert; public class TestMonkey extends Monkey { public TestMonkey() { super(new TestMonkeyContext(Type.TEST)); } public enum Type implements MonkeyType { TEST }; public Type type() { return Type.TEST; } public void doMonkeyBusiness() { Assert.assertTrue(true, "ran monkey business"); } @Test public void testStart() { this.start(); } @Test public void testStop() { this.stop(); } }
4,700
0
Create_ds/SimianArmy/src/test/java/com/netflix
Create_ds/SimianArmy/src/test/java/com/netflix/simianarmy/TestMonkeyRunner.java
/* * * Copyright 2012 Netflix, Inc. * * Licensed 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. * */ // CHECKSTYLE IGNORE Javadoc package com.netflix.simianarmy; import java.util.List; import org.testng.annotations.Test; import org.testng.Assert; public class TestMonkeyRunner { private static boolean monkeyARan = false; private static class MonkeyA extends TestMonkey { public void doMonkeyBusiness() { monkeyARan = true; } } private static boolean monkeyBRan = false; private static class MonkeyB extends Monkey { public enum Type implements MonkeyType { B }; public Type type() { return Type.B; } public interface Context extends Monkey.Context { boolean getTrue(); } private Context ctx; public MonkeyB(Context ctx) { super(ctx); this.ctx = ctx; } public void doMonkeyBusiness() { monkeyBRan = ctx.getTrue(); } } private static class MonkeyBContext extends TestMonkeyContext implements MonkeyB.Context { public MonkeyBContext() { super(MonkeyB.Type.B); } public boolean getTrue() { return true; } } @Test void testInstance() { Assert.assertEquals(MonkeyRunner.getInstance(), MonkeyRunner.INSTANCE); } @Test void testRunner() { MonkeyRunner runner = MonkeyRunner.getInstance(); runner.addMonkey(MonkeyA.class); runner.replaceMonkey(MonkeyA.class); runner.addMonkey(MonkeyB.class, MonkeyBContext.class); runner.replaceMonkey(MonkeyB.class, MonkeyBContext.class); List<Monkey> monkeys = runner.getMonkeys(); Assert.assertEquals(monkeys.size(), 2); Assert.assertEquals(monkeys.get(0).type().name(), "TEST"); Assert.assertEquals(monkeys.get(1).type().name(), "B"); Monkey a = runner.factory(MonkeyA.class); Assert.assertEquals(a.type().name(), "TEST"); Monkey b = runner.factory(MonkeyB.class, MonkeyBContext.class); Assert.assertEquals(b.type().name(), "B"); Assert.assertNull(runner.getContextClass(MonkeyA.class)); Assert.assertEquals(runner.getContextClass(MonkeyB.class), MonkeyBContext.class); runner.start(); Assert.assertEquals(monkeyARan, true, "monkeyA ran"); Assert.assertEquals(monkeyBRan, true, "monkeyB ran"); runner.stop(); runner.removeMonkey(MonkeyA.class); Assert.assertEquals(monkeys.size(), 1); Assert.assertEquals(monkeys.get(0).type().name(), "B"); runner.removeMonkey(MonkeyB.class); Assert.assertEquals(monkeys.size(), 0); } }
4,701
0
Create_ds/SimianArmy/src/test/java/com/netflix
Create_ds/SimianArmy/src/test/java/com/netflix/simianarmy/TestMonkeyContext.java
/* * * Copyright 2012 Netflix, Inc. * * Licensed 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. * */ // CHECKSTYLE IGNORE Javadoc /* * * Copyright 2012 Netflix, Inc. * * Licensed 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 com.netflix.simianarmy; import com.netflix.simianarmy.MonkeyRecorder.Event; import com.netflix.simianarmy.basic.BasicConfiguration; import com.netflix.simianarmy.basic.BasicRecorderEvent; import org.jclouds.compute.ComputeService; import org.jclouds.domain.LoginCredentials; import org.jclouds.ssh.SshClient; import org.testng.Assert; import java.util.*; import java.util.concurrent.TimeUnit; public class TestMonkeyContext implements Monkey.Context { private final MonkeyType monkeyType; private final LinkedList<Event> eventReport = new LinkedList<Event>(); public TestMonkeyContext(MonkeyType monkeyType) { this.monkeyType = monkeyType; } @Override public MonkeyConfiguration configuration() { return new BasicConfiguration(new Properties()); } @Override public MonkeyScheduler scheduler() { return new MonkeyScheduler() { @Override public int frequency() { return 1; } @Override public TimeUnit frequencyUnit() { return TimeUnit.HOURS; } @Override public void start(Monkey monkey, Runnable run) { Assert.assertEquals(monkey.type().name(), monkeyType.name(), "starting monkey"); run.run(); } @Override public void stop(Monkey monkey) { Assert.assertEquals(monkey.type().name(), monkeyType.name(), "stopping monkey"); } }; } @Override public MonkeyCalendar calendar() { // CHECKSTYLE IGNORE MagicNumberCheck return new MonkeyCalendar() { @Override public boolean isMonkeyTime(Monkey monkey) { return true; } @Override public int openHour() { return 10; } @Override public int closeHour() { return 11; } @Override public Calendar now() { return Calendar.getInstance(); } @Override public Date getBusinessDay(Date date, int n) { throw new RuntimeException("Not implemented."); } }; } @Override public CloudClient cloudClient() { return new CloudClient() { @Override public void terminateInstance(String instanceId) { } @Override public void createTagsForResources(Map<String, String> keyValueMap, String... resourceIds) { } @Override public void deleteAutoScalingGroup(String asgName) { } @Override public void deleteVolume(String volumeId) { } @Override public void deleteSnapshot(String snapshotId) { } @Override public void deleteImage(String imageId) { } @Override public void deleteElasticLoadBalancer(String elbId) { } @Override public void deleteDNSRecord(String dnsname, String dnstype, String hostedzoneid) { } @Override public void deleteLaunchConfiguration(String launchConfigName) { } @Override public List<String> listAttachedVolumes(String instanceId, boolean includeRoot) { throw new UnsupportedOperationException(); } @Override public void detachVolume(String instanceId, String volumeId, boolean force) { throw new UnsupportedOperationException(); } @Override public ComputeService getJcloudsComputeService() { throw new UnsupportedOperationException(); } @Override public String getJcloudsId(String instanceId) { throw new UnsupportedOperationException(); } @Override public SshClient connectSsh(String instanceId, LoginCredentials credentials) { throw new UnsupportedOperationException(); } @Override public String findSecurityGroup(String instanceId, String groupName) { throw new UnsupportedOperationException(); } @Override public String createSecurityGroup(String instanceId, String groupName, String description) { throw new UnsupportedOperationException(); } @Override public boolean canChangeInstanceSecurityGroups(String instanceId) { throw new UnsupportedOperationException(); } @Override public void setInstanceSecurityGroups(String instanceId, List<String> groupIds) { throw new UnsupportedOperationException(); } }; } private final MonkeyRecorder recorder = new MonkeyRecorder() { private final List<Event> events = new LinkedList<Event>(); @Override public Event newEvent(MonkeyType mkType, EventType eventType, String region, String id) { return new BasicRecorderEvent(mkType, eventType, region, id); } @Override public void recordEvent(Event evt) { events.add(evt); } @Override public List<Event> findEvents(Map<String, String> query, Date after) { return events; } @Override public List<Event> findEvents(MonkeyType mkeyType, Map<String, String> query, Date after) { // used from BasicScheduler return events; } @Override public List<Event> findEvents(MonkeyType mkeyType, EventType eventType, Map<String, String> query, Date after) { // used from ChaosMonkey List<Event> evts = new LinkedList<Event>(); for (Event evt : events) { if (query.get("groupName").equals(evt.field("groupName")) && evt.monkeyType() == mkeyType && evt.eventType() == eventType && evt.eventTime().after(after)) { evts.add(evt); } } return evts; } }; @Override public MonkeyRecorder recorder() { return recorder; } @Override public void reportEvent(Event evt) { eventReport.add(evt); } @Override public void resetEventReport() { eventReport.clear(); } @Override public String getEventReport() { StringBuilder report = new StringBuilder(); for (Event event : eventReport) { report.append(event.eventType()); report.append(" "); report.append(event.id()); } return report.toString(); } }
4,702
0
Create_ds/SimianArmy/src/test/java/com/netflix/simianarmy
Create_ds/SimianArmy/src/test/java/com/netflix/simianarmy/conformity/TestSameZonesInElbAndAsg.java
/* * * Copyright 2013 Netflix, Inc. * * Licensed 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. * */ // CHECKSTYLE IGNORE Javadoc package com.netflix.simianarmy.conformity; import com.google.common.collect.Maps; import com.netflix.simianarmy.aws.conformity.rule.SameZonesInElbAndAsg; import junit.framework.Assert; import org.apache.commons.lang.StringUtils; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; import java.util.Arrays; import java.util.List; import java.util.Map; public class TestSameZonesInElbAndAsg extends SameZonesInElbAndAsg { private final Map<String, String> asgToElbs = Maps.newHashMap(); private final Map<String, String> asgToZones = Maps.newHashMap(); private final Map<String, String> elbToZones = Maps.newHashMap(); @BeforeClass private void init() { asgToElbs.put("asg1", "elb1,elb2"); asgToElbs.put("asg2", "elb2"); asgToElbs.put("asg3", ""); asgToZones.put("asg1", "us-east-1a,us-east-1b"); asgToZones.put("asg2", "us-east-1a"); asgToZones.put("asg3", "us-east-1b"); elbToZones.put("elb1", "us-east-1a,us-east-1b"); elbToZones.put("elb2", "us-east-1a"); } @Test public void testZoneMismatch() { Cluster cluster = new Cluster("cluster1", "us-east-1", new AutoScalingGroup("asg1")); Conformity result = check(cluster); Assert.assertEquals(result.getRuleId(), getName()); Assert.assertEquals(result.getFailedComponents().size(), 1); Assert.assertEquals(result.getFailedComponents().iterator().next(), "elb2"); } @Test public void testZoneMatch() { Cluster cluster = new Cluster("cluster2", "us-east-1", new AutoScalingGroup("asg2")); Conformity result = check(cluster); Assert.assertEquals(result.getRuleId(), getName()); Assert.assertEquals(result.getFailedComponents().size(), 0); } @Test public void testAsgWithoutElb() { Cluster cluster = new Cluster("cluster3", "us-east-1", new AutoScalingGroup("asg3")); Conformity result = check(cluster); Assert.assertEquals(result.getRuleId(), getName()); Assert.assertEquals(result.getFailedComponents().size(), 0); } @Override protected List<String> getLoadBalancerNamesForAsg(String region, String asgName) { return Arrays.asList(StringUtils.split(asgToElbs.get(asgName), ",")); } @Override protected List<String> getAvailabilityZonesForAsg(String region, String asgName) { return Arrays.asList(StringUtils.split(asgToZones.get(asgName), ",")); } @Override protected List<String> getAvailabilityZonesForLoadBalancer(String region, String lbName) { return Arrays.asList(StringUtils.split(elbToZones.get(lbName), ",")); } }
4,703
0
Create_ds/SimianArmy/src/test/java/com/netflix/simianarmy
Create_ds/SimianArmy/src/test/java/com/netflix/simianarmy/conformity/TestCrossZoneLoadBalancing.java
/* * * Copyright 2013 Netflix, Inc. * * Licensed 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. * */ // CHECKSTYLE IGNORE Javadoc package com.netflix.simianarmy.conformity; import java.util.Arrays; import java.util.List; import java.util.Map; import junit.framework.Assert; import org.apache.commons.lang.StringUtils; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; import com.google.common.collect.Maps; import com.netflix.simianarmy.aws.conformity.rule.CrossZoneLoadBalancing; public class TestCrossZoneLoadBalancing extends CrossZoneLoadBalancing { private final Map<String, String> asgToElbs = Maps.newHashMap(); private final Map<String, Boolean> elbsToCZLB = Maps.newHashMap(); @BeforeClass private void init() { asgToElbs.put("asg1", "elb1,elb2"); asgToElbs.put("asg2", "elb1"); asgToElbs.put("asg3", ""); elbsToCZLB.put("elb1", true); } @Test public void testDisabledCrossZoneLoadBalancing() { Cluster cluster = new Cluster("cluster1", "us-east-1", new AutoScalingGroup("asg1")); Conformity result = check(cluster); Assert.assertEquals(result.getRuleId(), getName()); Assert.assertEquals(result.getFailedComponents().size(), 1); Assert.assertEquals(result.getFailedComponents().iterator().next(), "elb2"); } @Test public void testEnabledCrossZoneLoadBalancing() { Cluster cluster = new Cluster("cluster1", "us-east-1", new AutoScalingGroup("asg2")); Conformity result = check(cluster); Assert.assertEquals(result.getRuleId(), getName()); Assert.assertEquals(result.getFailedComponents().size(), 0); } @Test public void testAsgWithoutElb() { Cluster cluster = new Cluster("cluster3", "us-east-1", new AutoScalingGroup("asg3")); Conformity result = check(cluster); Assert.assertEquals(result.getRuleId(), getName()); Assert.assertEquals(result.getFailedComponents().size(), 0); } @Override protected List<String> getLoadBalancerNamesForAsg(String region, String asgName) { return Arrays.asList(StringUtils.split(asgToElbs.get(asgName), ",")); } @Override protected boolean isCrossZoneLoadBalancingEnabled(String region, String lbName) { Boolean enabled = elbsToCZLB.get(lbName); return (enabled == null) ? false : enabled; } }
4,704
0
Create_ds/SimianArmy/src/test/java/com/netflix/simianarmy/resources
Create_ds/SimianArmy/src/test/java/com/netflix/simianarmy/resources/chaos/TestChaosMonkeyResource.java
/* * * Copyright 2012 Netflix, Inc. * * Licensed 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. * */ // CHECKSTYLE IGNORE Javadoc //CHECKSTYLE IGNORE MagicNumber package com.netflix.simianarmy.resources.chaos; import static org.mockito.Matchers.any; import static org.mockito.Matchers.anyMap; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import java.util.Arrays; import java.util.Date; import java.util.Map; import java.util.Scanner; import javax.ws.rs.core.MultivaluedMap; import javax.ws.rs.core.Response; import javax.ws.rs.core.UriInfo; import org.mockito.ArgumentCaptor; import org.mockito.Captor; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.testng.Assert; import org.testng.annotations.BeforeTest; import org.testng.annotations.Test; import com.netflix.simianarmy.EventType; import com.netflix.simianarmy.MonkeyRecorder; import com.netflix.simianarmy.MonkeyRunner; import com.netflix.simianarmy.MonkeyType; import com.netflix.simianarmy.basic.BasicRecorderEvent; import com.netflix.simianarmy.basic.chaos.BasicChaosMonkey; import com.netflix.simianarmy.chaos.ChaosMonkey; import com.netflix.simianarmy.chaos.TestChaosMonkeyContext; import com.sun.jersey.core.util.MultivaluedMapImpl; public class TestChaosMonkeyResource { private static final Logger LOGGER = LoggerFactory.getLogger(TestChaosMonkeyResource.class); @Captor private ArgumentCaptor<MonkeyType> monkeyTypeArg; @Captor private ArgumentCaptor<EventType> eventTypeArg; @Captor private ArgumentCaptor<Map<String, String>> queryArg; @Captor private ArgumentCaptor<Date> dateArg; @Mock private UriInfo mockUriInfo; @Mock private static MonkeyRecorder mockRecorder; @BeforeTest public void init() { MockitoAnnotations.initMocks(this); } @Test void testTerminateNow() { TestChaosMonkeyContext ctx = new TestChaosMonkeyContext("ondemandTermination.properties"); String input = "{\"eventType\":\"CHAOS_TERMINATION\",\"groupType\":\"TYPE_C\",\"groupName\":\"name4\"}"; Assert.assertEquals(ctx.selectedOn().size(), 0); Assert.assertEquals(ctx.terminated().size(), 0); ChaosMonkeyResource resource = new ChaosMonkeyResource(new BasicChaosMonkey(ctx)); validateAddEventResult(resource, input, Response.Status.OK); Assert.assertEquals(ctx.selectedOn().size(), 1); Assert.assertEquals(ctx.terminated().size(), 1); validateAddEventResult(resource, input, Response.Status.OK); Assert.assertEquals(ctx.selectedOn().size(), 2); Assert.assertEquals(ctx.terminated().size(), 2); // TYPE_C.name4 only has two instances, so the 3rd ondemand termination // will not terminate anything. validateAddEventResult(resource, input, Response.Status.GONE); Assert.assertEquals(ctx.selectedOn().size(), 3); Assert.assertEquals(ctx.terminated().size(), 2); // Try a different type will work input = "{\"eventType\":\"CHAOS_TERMINATION\",\"groupType\":\"TYPE_C\",\"groupName\":\"name5\"}"; validateAddEventResult(resource, input, Response.Status.OK); Assert.assertEquals(ctx.selectedOn().size(), 4); Assert.assertEquals(ctx.terminated().size(), 3); } @Test void testTerminateNowDisabled() { TestChaosMonkeyContext ctx = new TestChaosMonkeyContext("ondemandTerminationDisabled.properties"); String input = "{\"eventType\":\"CHAOS_TERMINATION\",\"groupType\":\"TYPE_C\",\"groupName\":\"name4\"}"; Assert.assertEquals(ctx.selectedOn().size(), 0); Assert.assertEquals(ctx.terminated().size(), 0); ChaosMonkeyResource resource = new ChaosMonkeyResource(new BasicChaosMonkey(ctx)); validateAddEventResult(resource, input, Response.Status.FORBIDDEN); Assert.assertEquals(ctx.selectedOn().size(), 0); Assert.assertEquals(ctx.terminated().size(), 0); } @Test void testTerminateNowBadInput() { TestChaosMonkeyContext ctx = new TestChaosMonkeyContext("ondemandTermination.properties"); String input = "{\"groupType\":\"TYPE_C\",\"groupName\":\"name4\"}"; ChaosMonkeyResource resource = new ChaosMonkeyResource(new BasicChaosMonkey(ctx)); validateAddEventResult(resource, input, Response.Status.BAD_REQUEST); input = "{\"eventType\":\"CHAOS_TERMINATION\",\"groupName\":\"name4\"}"; resource = new ChaosMonkeyResource(new BasicChaosMonkey(ctx)); validateAddEventResult(resource, input, Response.Status.BAD_REQUEST); input = "{\"eventType\":\"CHAOS_TERMINATION\",\"groupType\":\"TYPE_C\"}"; resource = new ChaosMonkeyResource(new BasicChaosMonkey(ctx)); validateAddEventResult(resource, input, Response.Status.BAD_REQUEST); } @Test void testTerminateNowBadGroupNotExist() { TestChaosMonkeyContext ctx = new TestChaosMonkeyContext("ondemandTermination.properties"); String input = "{\"eventType\":\"CHAOS_TERMINATION\",\"groupType\":\"INVALID\",\"groupName\":\"name4\"}"; ChaosMonkeyResource resource = new ChaosMonkeyResource(new BasicChaosMonkey(ctx)); validateAddEventResult(resource, input, Response.Status.NOT_FOUND); input = "{\"eventType\":\"CHAOS_TERMINATION\",\"groupType\":\"TYPE_C\",\"groupName\":\"INVALID\"}"; resource = new ChaosMonkeyResource(new BasicChaosMonkey(ctx)); validateAddEventResult(resource, input, Response.Status.NOT_FOUND); } @Test void testTerminateNowBadEventType() { TestChaosMonkeyContext ctx = new TestChaosMonkeyContext("ondemandTermination.properties"); String input = "{\"eventType\":\"INVALID\",\"groupType\":\"TYPE_C\",\"groupName\":\"name4\"}"; ChaosMonkeyResource resource = new ChaosMonkeyResource(new BasicChaosMonkey(ctx)); validateAddEventResult(resource, input, Response.Status.BAD_REQUEST); } @Test public void testResource() { MonkeyRunner.getInstance().replaceMonkey(BasicChaosMonkey.class, MockTestChaosMonkeyContext.class); ChaosMonkeyResource resource = new ChaosMonkeyResource(); MultivaluedMap<String, String> queryParams = new MultivaluedMapImpl(); queryParams.add("groupType", "ASG"); Date queryDate = new Date(); queryParams.add("since", String.valueOf(queryDate.getTime())); when(mockUriInfo.getQueryParameters()).thenReturn(queryParams); @SuppressWarnings("unchecked") // fix when Matcher.anyMapOf is available Map<String, String> anyMap = anyMap(); when(mockRecorder.findEvents(any(MonkeyType.class), any(EventType.class), anyMap, any(Date.class))).thenReturn( Arrays.asList(mkEvent("i-123456789012345670"), mkEvent("i-123456789012345671"))); try { Response resp = resource.getChaosEvents(mockUriInfo); Assert.assertEquals(resp.getEntity().toString(), getResource("getChaosEventsResponse.json")); } catch (Exception e) { LOGGER.error("exception from getChaosEvents", e); Assert.fail("getChaosEvents throws exception"); } verify(mockRecorder).findEvents(monkeyTypeArg.capture(), eventTypeArg.capture(), queryArg.capture(), dateArg.capture()); Assert.assertEquals(monkeyTypeArg.getValue(), ChaosMonkey.Type.CHAOS); Assert.assertEquals(eventTypeArg.getValue(), ChaosMonkey.EventTypes.CHAOS_TERMINATION); Map<String, String> query = queryArg.getValue(); Assert.assertEquals(query.size(), 1); Assert.assertEquals(query.get("groupType"), "ASG"); Assert.assertEquals(dateArg.getValue(), queryDate); } private MonkeyRecorder.Event mkEvent(String instance) { final MonkeyType monkeyType = ChaosMonkey.Type.CHAOS; final EventType eventType = ChaosMonkey.EventTypes.CHAOS_TERMINATION; // SUPPRESS CHECKSTYLE MagicNumber return new BasicRecorderEvent(monkeyType, eventType, "region", instance, 1330538400000L) .addField("groupType", "ASG").addField("groupName", "testGroup"); } public static class MockTestChaosMonkeyContext extends TestChaosMonkeyContext { @Override public MonkeyRecorder recorder() { return mockRecorder; } } String getResource(String name) { // get resource as stream, use Scanner to read stream as one token return new Scanner(TestChaosMonkeyResource.class.getResourceAsStream(name), "UTF-8").useDelimiter("\\A").next(); } private void validateAddEventResult(ChaosMonkeyResource resource, String input, Response.Status responseStatus) { try { Response resp = resource.addEvent(input); Assert.assertEquals(resp.getStatus(), responseStatus.getStatusCode()); } catch (Exception e) { LOGGER.error("exception from addEvent", e); Assert.fail("addEvent throws exception"); } } }
4,705
0
Create_ds/SimianArmy/src/test/java/com/netflix/simianarmy
Create_ds/SimianArmy/src/test/java/com/netflix/simianarmy/basic/TestBasicMonkeyServer.java
/* * * Copyright 2012 Netflix, Inc. * * Licensed 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. * */ // CHECKSTYLE IGNORE Javadoc package com.netflix.simianarmy.basic; import org.testng.Assert; import org.testng.annotations.Test; import com.netflix.simianarmy.MonkeyRunner; import com.netflix.simianarmy.TestMonkey; import com.netflix.simianarmy.basic.chaos.BasicChaosMonkey; import com.netflix.simianarmy.chaos.TestChaosMonkeyContext; @SuppressWarnings("serial") public class TestBasicMonkeyServer extends BasicMonkeyServer { private static final MonkeyRunner RUNNER = MonkeyRunner.getInstance(); private static boolean monkeyRan = false; public static class SillyMonkey extends TestMonkey { @Override public void doMonkeyBusiness() { monkeyRan = true; } } @Override public void addMonkeysToRun() { MonkeyRunner.getInstance().replaceMonkey(BasicChaosMonkey.class, TestChaosMonkeyContext.class); MonkeyRunner.getInstance().addMonkey(SillyMonkey.class); } @Test public void testServer() { BasicMonkeyServer server = new TestBasicMonkeyServer(); try { server.init(); } catch (Exception e) { Assert.fail("failed to init server", e); } // there is a race condition since the monkeys will run // in a different thread. On some systems we might // need to add a sleep Assert.assertTrue(monkeyRan, "silly monkey ran"); try { server.destroy(); } catch (Exception e) { Assert.fail("failed to destroy server", e); } Assert.assertEquals(RUNNER.getMonkeys().size(), 1); Assert.assertEquals(RUNNER.getMonkeys().get(0).getClass(), SillyMonkey.class); } }
4,706
0
Create_ds/SimianArmy/src/test/java/com/netflix/simianarmy
Create_ds/SimianArmy/src/test/java/com/netflix/simianarmy/basic/TestBasicConfiguration.java
/* * * Copyright 2012 Netflix, Inc. * * Licensed 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. * */ // CHECKSTYLE IGNORE Javadoc package com.netflix.simianarmy.basic; import org.testng.annotations.Test; import org.testng.Assert; import java.util.Properties; public class TestBasicConfiguration extends BasicConfiguration { private static final Properties PROPS = new Properties(); public TestBasicConfiguration() { super(PROPS); } @Test public void testGetBool() { PROPS.clear(); Assert.assertFalse(getBool("foobar.enabled")); PROPS.setProperty("foobar.enabled", "true"); Assert.assertTrue(getBool("foobar.enabled")); PROPS.setProperty("foobar.enabled", "false"); Assert.assertFalse(getBool("foobar.enabled")); } @Test public void testGetBoolOrElse() { PROPS.clear(); Assert.assertFalse(getBoolOrElse("foobar.enabled", false)); Assert.assertTrue(getBoolOrElse("foobar.enabled", true)); PROPS.setProperty("foobar.enabled", "true"); Assert.assertTrue(getBoolOrElse("foobar.enabled", false)); Assert.assertTrue(getBoolOrElse("foobar.enabled", true)); PROPS.setProperty("foobar.enabled", "false"); Assert.assertFalse(getBoolOrElse("foobar.enabled", false)); Assert.assertFalse(getBoolOrElse("foobar.enabled", true)); } @Test public void testGetNumOrElse() { // CHECKSTYLE IGNORE MagicNumberCheck PROPS.clear(); Assert.assertEquals(getNumOrElse("foobar.number", 42), 42D); PROPS.setProperty("foobar.number", "0"); Assert.assertEquals(getNumOrElse("foobar.number", 42), 0D); } @Test public void testGetStr() { PROPS.clear(); Assert.assertNull(getStr("foobar")); PROPS.setProperty("foobar", "string"); Assert.assertEquals(getStr("foobar"), "string"); } @Test public void testGetStrOrElse() { PROPS.clear(); Assert.assertEquals(getStrOrElse("foobar", "default"), "default"); PROPS.setProperty("foobar", "string"); Assert.assertEquals(getStrOrElse("foobar", "default"), "string"); PROPS.setProperty("foobar", ""); Assert.assertEquals(getStrOrElse("foobar", "default"), ""); } }
4,707
0
Create_ds/SimianArmy/src/test/java/com/netflix/simianarmy
Create_ds/SimianArmy/src/test/java/com/netflix/simianarmy/basic/TestBasicScheduler.java
/* * * Copyright 2012 Netflix, Inc. * * Licensed 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. * */ // CHECKSTYLE IGNORE Javadoc package com.netflix.simianarmy.basic; import static org.mockito.Mockito.when; import static org.mockito.Mockito.mock; import java.util.Calendar; import java.util.concurrent.FutureTask; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import java.util.concurrent.atomic.AtomicLong; import org.testng.Assert; import org.testng.annotations.Test; import com.google.common.util.concurrent.Callables; import com.netflix.simianarmy.EventType; import com.netflix.simianarmy.Monkey; import com.netflix.simianarmy.MonkeyType; import com.netflix.simianarmy.TestMonkeyContext; // CHECKSTYLE IGNORE MagicNumber public class TestBasicScheduler { @Test public void testConstructors() { BasicScheduler sched = new BasicScheduler(); Assert.assertNotNull(sched); Assert.assertEquals(sched.frequency(), 1); Assert.assertEquals(sched.frequencyUnit(), TimeUnit.HOURS); BasicScheduler sched2 = new BasicScheduler(12, TimeUnit.MINUTES, 2); Assert.assertEquals(sched2.frequency(), 12); Assert.assertEquals(sched2.frequencyUnit(), TimeUnit.MINUTES); } private enum Enums implements MonkeyType { MONKEY }; private enum EventEnums implements EventType { EVENT } @Test public void testRunner() throws InterruptedException { BasicScheduler sched = new BasicScheduler(200, TimeUnit.MILLISECONDS, 1); Monkey mockMonkey = mock(Monkey.class); when(mockMonkey.context()).thenReturn(new TestMonkeyContext(Enums.MONKEY)); when(mockMonkey.type()).thenReturn(Enums.MONKEY).thenReturn(Enums.MONKEY); final AtomicLong counter = new AtomicLong(0L); sched.start(mockMonkey, new Runnable() { @Override public void run() { counter.incrementAndGet(); } }); Thread.sleep(100); Assert.assertEquals(counter.get(), 1); Thread.sleep(200); Assert.assertEquals(counter.get(), 2); sched.stop(mockMonkey); Thread.sleep(200); Assert.assertEquals(counter.get(), 2); } @Test public void testDelayedStart() throws Exception { BasicScheduler sched = new BasicScheduler(1, TimeUnit.HOURS, 1); TestMonkeyContext context = new TestMonkeyContext(Enums.MONKEY); Monkey mockMonkey = mock(Monkey.class); when(mockMonkey.context()).thenReturn(context).thenReturn(context); when(mockMonkey.type()).thenReturn(Enums.MONKEY).thenReturn(Enums.MONKEY); // first monkey has no previous events, so it runs practically immediately FutureTask<Void> task = new FutureTask<Void>(Callables.<Void>returning(null)); sched.start(mockMonkey, task); // make sure that the task gets completed within 100ms task.get(100L, TimeUnit.MILLISECONDS); sched.stop(mockMonkey); // create an event 5 min ago Calendar cal = Calendar.getInstance(); cal.add(Calendar.MINUTE, -5); BasicRecorderEvent evt = new BasicRecorderEvent( Enums.MONKEY, EventEnums.EVENT, "region", "test-id", cal.getTime().getTime()); context.recorder().recordEvent(evt); // this time when it runs it will not run immediately since it should be scheduled for 55m from now. task = new FutureTask<Void>(Callables.<Void>returning(null)); sched.start(mockMonkey, task); try { task.get(100, TimeUnit.MILLISECONDS); Assert.fail("The task shouldn't have been completed in 100ms"); } catch (TimeoutException e) { // NOPMD - This is an expected exception } sched.stop(mockMonkey); } }
4,708
0
Create_ds/SimianArmy/src/test/java/com/netflix/simianarmy
Create_ds/SimianArmy/src/test/java/com/netflix/simianarmy/basic/TestBasicContext.java
/* * * Copyright 2012 Netflix, Inc. * * Licensed 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. * */ // CHECKSTYLE IGNORE Javadoc package com.netflix.simianarmy.basic; import com.amazonaws.ClientConfiguration; import org.testng.Assert; import org.testng.annotations.Test; public class TestBasicContext { @Test public void testContext() { BasicChaosMonkeyContext ctx = new BasicChaosMonkeyContext(); Assert.assertNotNull(ctx.scheduler()); Assert.assertNotNull(ctx.calendar()); Assert.assertNotNull(ctx.configuration()); Assert.assertNotNull(ctx.cloudClient()); Assert.assertNotNull(ctx.chaosCrawler()); Assert.assertNotNull(ctx.chaosInstanceSelector()); Assert.assertTrue(ctx.configuration().getBool("simianarmy.calendar.isMonkeyTime")); Assert.assertEquals(ctx.configuration().getStr("simianarmy.client.aws.assumeRoleArn"), "arn:aws:iam::fakeAccount:role/fakeRole"); // Verify that the property in chaos.properties overrides the same property in simianarmy.properties Assert.assertFalse(ctx.configuration().getBool("simianarmy.chaos.enabled")); } @Test public void testIsSafeToLogProperty() { BasicChaosMonkeyContext ctx = new BasicChaosMonkeyContext(); Assert.assertTrue(ctx.isSafeToLog("simianarmy.client.aws.region")); } @Test public void testIsNotSafeToLogProperty() { BasicChaosMonkeyContext ctx = new BasicChaosMonkeyContext(); Assert.assertFalse(ctx.isSafeToLog("simianarmy.client.aws.secretKey")); } @Test public void testIsNotSafeToLogVsphereProperty() { BasicChaosMonkeyContext ctx = new BasicChaosMonkeyContext(); Assert.assertFalse(ctx.isSafeToLog("simianarmy.client.vsphere.password")); } @Test public void testIsNotUsingProxyByDefault() { BasicSimianArmyContext ctx = new BasicSimianArmyContext(); ClientConfiguration awsClientConfig = ctx.getAwsClientConfig(); Assert.assertNull(awsClientConfig.getProxyHost()); Assert.assertEquals(awsClientConfig.getProxyPort(), -1); Assert.assertNull(awsClientConfig.getProxyUsername()); Assert.assertNull(awsClientConfig.getProxyPassword()); } @Test public void testIsAbleToUseProxyByConfiguration() { BasicSimianArmyContext ctx = new BasicSimianArmyContext("proxy.properties"); ClientConfiguration awsClientConfig = ctx.getAwsClientConfig(); Assert.assertEquals(awsClientConfig.getProxyHost(), "127.0.0.1"); Assert.assertEquals(awsClientConfig.getProxyPort(), 80); Assert.assertEquals(awsClientConfig.getProxyUsername(), "fakeUser"); Assert.assertEquals(awsClientConfig.getProxyPassword(), "fakePassword"); } }
4,709
0
Create_ds/SimianArmy/src/test/java/com/netflix/simianarmy
Create_ds/SimianArmy/src/test/java/com/netflix/simianarmy/basic/TestBasicRecorderEvent.java
/* * * Copyright 2012 Netflix, Inc. * * Licensed 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. * */ // CHECKSTYLE IGNORE Javadoc package com.netflix.simianarmy.basic; import java.util.HashMap; import java.util.Map; import org.testng.Assert; import org.testng.annotations.Test; import com.netflix.simianarmy.EventType; import com.netflix.simianarmy.MonkeyType; public class TestBasicRecorderEvent { public enum Types implements MonkeyType { MONKEY }; public enum EventTypes implements EventType { EVENT } @Test public void test() { MonkeyType monkeyType = Types.MONKEY; EventType eventType = EventTypes.EVENT; BasicRecorderEvent evt = new BasicRecorderEvent(monkeyType, eventType, "region", "test-id"); testEvent(evt); // CHECKSTYLE IGNORE MagicNumberCheck long time = 1330538400000L; evt = new BasicRecorderEvent(monkeyType, eventType, "region", "test-id", time); testEvent(evt); Assert.assertEquals(evt.eventTime().getTime(), time); } void testEvent(BasicRecorderEvent evt) { Assert.assertEquals(evt.id(), "test-id"); Assert.assertEquals(evt.monkeyType(), Types.MONKEY); Assert.assertEquals(evt.eventType(), EventTypes.EVENT); Assert.assertEquals(evt.region(), "region"); Assert.assertEquals(evt.addField("a", "1"), evt); Map<String, String> map = new HashMap<String, String>(); map.put("b", "2"); map.put("c", "3"); Assert.assertEquals(evt.addFields(map), evt); Assert.assertEquals(evt.field("a"), "1"); Assert.assertEquals(evt.field("b"), "2"); Assert.assertEquals(evt.field("c"), "3"); Map<String, String> f = evt.fields(); Assert.assertEquals(f.get("a"), "1"); Assert.assertEquals(f.get("b"), "2"); Assert.assertEquals(f.get("c"), "3"); } }
4,710
0
Create_ds/SimianArmy/src/test/java/com/netflix/simianarmy
Create_ds/SimianArmy/src/test/java/com/netflix/simianarmy/basic/TestBasicCalendar.java
/* * * Copyright 2012 Netflix, Inc. * * Licensed 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. * */ // CHECKSTYLE IGNORE Javadoc package com.netflix.simianarmy.basic; import java.util.Calendar; import java.util.Properties; import java.util.TimeZone; import org.testng.Assert; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; import com.netflix.simianarmy.Monkey; import com.netflix.simianarmy.TestMonkey; // CHECKSTYLE IGNORE MagicNumberCheck public class TestBasicCalendar extends BasicCalendar { private static final Properties PROPS = new Properties(); private static final BasicConfiguration CFG = new BasicConfiguration(PROPS); public TestBasicCalendar() { super(CFG); } @Test public void testConstructors() { BasicCalendar cal = new BasicCalendar(CFG); Assert.assertEquals(cal.openHour(), 9); Assert.assertEquals(cal.closeHour(), 15); Assert.assertEquals(cal.now().getTimeZone(), TimeZone.getTimeZone("America/Los_Angeles")); cal = new BasicCalendar(11, 12, TimeZone.getTimeZone("Europe/Stockholm")); Assert.assertEquals(cal.openHour(), 11); Assert.assertEquals(cal.closeHour(), 12); Assert.assertEquals(cal.now().getTimeZone(), TimeZone.getTimeZone("Europe/Stockholm")); } private Calendar now = super.now(); @Override public Calendar now() { return (Calendar) now.clone(); } private void setNow(Calendar now) { this.now = now; } @Test void testMonkeyTime() { Calendar test = Calendar.getInstance(); Monkey monkey = new TestMonkey(); // using leap day b/c it is not a holiday & not a weekend test.set(Calendar.YEAR, 2012); test.set(Calendar.MONTH, Calendar.FEBRUARY); test.set(Calendar.DAY_OF_MONTH, 29); test.set(Calendar.HOUR_OF_DAY, 8); // 8am leap day setNow(test); Assert.assertFalse(isMonkeyTime(monkey)); test.set(Calendar.HOUR_OF_DAY, 10); // 10am leap day setNow(test); Assert.assertTrue(isMonkeyTime(monkey)); test.set(Calendar.HOUR_OF_DAY, 17); // 5pm leap day setNow(test); Assert.assertFalse(isMonkeyTime(monkey)); // set to the following Saturday so we can test we dont run on weekends // even though within "business hours" test.set(Calendar.DAY_OF_WEEK, Calendar.SATURDAY); test.set(Calendar.HOUR_OF_DAY, 10); setNow(test); Assert.assertFalse(isMonkeyTime(monkey)); // test config overrides PROPS.setProperty("simianarmy.calendar.isMonkeyTime", Boolean.toString(true)); Assert.assertTrue(isMonkeyTime(monkey)); PROPS.setProperty("simianarmy.calendar.isMonkeyTime", Boolean.toString(false)); Assert.assertFalse(isMonkeyTime(monkey)); } @DataProvider public Object[][] holidayDataProvider() { return new Object[][] {{Calendar.JANUARY, 2}, // New Year's Day {Calendar.JANUARY, 16}, // MLK day {Calendar.FEBRUARY, 20}, // Washington's Birthday {Calendar.MAY, 28}, // Memorial Day {Calendar.JULY, 4}, // Independence Day {Calendar.SEPTEMBER, 3}, // Labor Day {Calendar.OCTOBER, 8}, // Columbus Day {Calendar.NOVEMBER, 12}, // Veterans Day {Calendar.NOVEMBER, 22}, // Thanksgiving Day {Calendar.DECEMBER, 25} // Christmas Day }; } @Test(dataProvider = "holidayDataProvider") public void testHolidays(int month, int dayOfMonth) { Calendar test = Calendar.getInstance(); test.set(Calendar.YEAR, 2012); test.set(Calendar.MONTH, month); test.set(Calendar.DAY_OF_MONTH, dayOfMonth); test.set(Calendar.HOUR_OF_DAY, 10); setNow(test); Assert.assertTrue(isHoliday(test), test.getTime().toString() + " is a holiday?"); } @Test public void testGetBusinessDayWihoutGap() { // the days from 12/3/2012 to 12/7/2012 are all business days int hour = 10; Calendar test = now(); test.set(Calendar.YEAR, 2012); test.set(Calendar.MONTH, Calendar.DECEMBER); test.set(Calendar.DAY_OF_MONTH, 3); test.set(Calendar.HOUR_OF_DAY, hour); int day = test.get(Calendar.DAY_OF_MONTH); for (int n = 0; n <= 4; n++) { Calendar businessDay = now(); businessDay.setTime(getBusinessDay(test.getTime(), n)); Assert.assertEquals(businessDay.get(Calendar.DAY_OF_MONTH), day + n); Assert.assertEquals(businessDay.get(Calendar.HOUR_OF_DAY), hour); } } @Test public void testGetBusinessDayWihWeekend() { // 12/7/2012 is Friday int hour = 10; Calendar test = now(); test.set(Calendar.YEAR, 2012); test.set(Calendar.MONTH, Calendar.DECEMBER); test.set(Calendar.DAY_OF_MONTH, 7); test.set(Calendar.HOUR_OF_DAY, hour); int day = test.get(Calendar.DAY_OF_MONTH); for (int n = 1; n <= 5; n++) { Calendar businessDay = now(); businessDay.setTime(getBusinessDay(test.getTime(), n)); Assert.assertEquals(businessDay.get(Calendar.DAY_OF_MONTH), day + n + 2); Assert.assertEquals(businessDay.get(Calendar.HOUR_OF_DAY), hour); } } @Test public void testGetBusinessDayWihHoliday() { // 12/23/2012 is Monday and 12/24 - 12/26 are holidays int hour = 10; Calendar test = now(); test.set(Calendar.YEAR, 2012); test.set(Calendar.MONTH, Calendar.DECEMBER); test.set(Calendar.DAY_OF_MONTH, 24); test.set(Calendar.HOUR_OF_DAY, hour); int day = test.get(Calendar.DAY_OF_MONTH); Calendar businessDay = now(); businessDay.setTime(getBusinessDay(test.getTime(), 1)); Assert.assertEquals(businessDay.get(Calendar.DAY_OF_MONTH), day + 4); Assert.assertEquals(businessDay.get(Calendar.HOUR_OF_DAY), hour); } @Test public void testGetBusinessDayWihHolidayNextYear() { // 12/28/2012 is Friday and 12/31 - 1/1 are holidays int hour = 10; Calendar test = now(); test.set(Calendar.YEAR, 2012); test.set(Calendar.MONTH, Calendar.DECEMBER); test.set(Calendar.DAY_OF_MONTH, 28); test.set(Calendar.HOUR_OF_DAY, hour); Calendar businessDay = now(); businessDay.setTime(getBusinessDay(test.getTime(), 1)); // The next business day should be 1/2/2013 Assert.assertEquals(businessDay.get(Calendar.YEAR), 2013); Assert.assertEquals(businessDay.get(Calendar.MONTH), Calendar.JANUARY); Assert.assertEquals(businessDay.get(Calendar.DAY_OF_MONTH), 2); Assert.assertEquals(businessDay.get(Calendar.HOUR_OF_DAY), hour); } }
4,711
0
Create_ds/SimianArmy/src/test/java/com/netflix/simianarmy/basic
Create_ds/SimianArmy/src/test/java/com/netflix/simianarmy/basic/calendar/TestBavarianCalendar.java
/* * * Copyright 2012 Netflix, Inc. * * Licensed 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. * */ // CHECKSTYLE IGNORE Javadoc package com.netflix.simianarmy.basic.calendar; import com.netflix.simianarmy.basic.BasicConfiguration; import com.netflix.simianarmy.basic.calendars.BavarianCalendar; import org.testng.Assert; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; import java.util.Calendar; import java.util.Properties; // CHECKSTYLE IGNORE MagicNumberCheck public class TestBavarianCalendar extends BavarianCalendar { private static final Properties PROPS = new Properties(); private static final BasicConfiguration CFG = new BasicConfiguration(PROPS); public TestBavarianCalendar() { super(CFG); } private Calendar now = super.now(); @Override public Calendar now() { return (Calendar) now.clone(); } private void setNow(Calendar now) { this.now = now; } @DataProvider public Object[][] easterDataProvider() { return new Object[][] { {1996, Calendar.APRIL, 7}, {1997, Calendar.MARCH, 30}, {1998, Calendar.APRIL, 12}, {1999, Calendar.APRIL, 4}, {2000, Calendar.APRIL, 23}, {2001, Calendar.APRIL, 15}, {2002, Calendar.MARCH, 31}, {2003, Calendar.APRIL, 20}, {2004, Calendar.APRIL, 11}, {2005, Calendar.MARCH, 27}, {2006, Calendar.APRIL, 16}, {2007, Calendar.APRIL, 8}, {2008, Calendar.MARCH, 23}, {2009, Calendar.APRIL, 12}, {2010, Calendar.APRIL, 4}, {2011, Calendar.APRIL, 24}, {2012, Calendar.APRIL, 8}, {2013, Calendar.MARCH, 31}, {2014, Calendar.APRIL, 20}, {2015, Calendar.APRIL, 5}, {2016, Calendar.MARCH, 27}, {2017, Calendar.APRIL, 16}, {2018, Calendar.APRIL, 1}, {2019, Calendar.APRIL, 21}, {2020, Calendar.APRIL, 12}, {2021, Calendar.APRIL, 4}, {2022, Calendar.APRIL, 17}, {2023, Calendar.APRIL, 9}, {2024, Calendar.MARCH, 31}, {2025, Calendar.APRIL, 20}, {2026, Calendar.APRIL, 5}, {2027, Calendar.MARCH, 28}, {2028, Calendar.APRIL, 16}, {2029, Calendar.APRIL, 1}, {2030, Calendar.APRIL, 21}, {2031, Calendar.APRIL, 13}, {2032, Calendar.MARCH, 28}, {2033, Calendar.APRIL, 17}, {2034, Calendar.APRIL, 9}, {2035, Calendar.MARCH, 25}, {2036, Calendar.APRIL, 13}, }; } @Test(dataProvider = "easterDataProvider") public void testEaster(int year, int month, int dayOfMonth) { Assert.assertEquals(dayOfYear(year, month, dayOfMonth), westernEasterDayOfYear(year)); } @DataProvider public Object[][] holidayDataProvider() { return new Object[][] { {2016, Calendar.JANUARY, 1}, // new year {2016, Calendar.JANUARY, 6}, // epiphanie {2016, Calendar.MARCH, 25}, // good friday {2016, Calendar.MARCH, 28}, // easter monday {2016, Calendar.MAY, 1}, // labor day {2016, Calendar.MAY, 5}, // ascension day {2016, Calendar.MAY, 6}, // friday after ascension day {2016, Calendar.MAY, 16}, // whit monday {2016, Calendar.MAY, 26}, // corpus christi {2016, Calendar.AUGUST, 15}, // assumption day {2016, Calendar.OCTOBER, 3}, // german unity day {2016, Calendar.DECEMBER, 24}, // christmas holidays {2016, Calendar.DECEMBER, 25}, {2016, Calendar.DECEMBER, 26}, {2016, Calendar.DECEMBER, 27}, {2016, Calendar.DECEMBER, 28}, {2016, Calendar.DECEMBER, 29}, {2016, Calendar.DECEMBER, 30}, {2016, Calendar.DECEMBER, 31}, // now, "bridge days" {2015, Calendar.JANUARY, 2}, // friday after new year {2015, Calendar.JANUARY, 5}, // monday before epiphanie {2011, Calendar.JANUARY, 7}, // friday after epiphanie {2012, Calendar.APRIL, 30}, // monday before labor day {2014, Calendar.MAY, 2}, // friday after labor day {2006, Calendar.AUGUST, 14}, // monday before assumption day {2013, Calendar.AUGUST, 16}, // friday after assumption day {2006, Calendar.OCTOBER, 2}, // monday before german unity day {2013, Calendar.OCTOBER, 4}, // friday after german unity day {2011, Calendar.OCTOBER, 31}, // monday before all saints {2012, Calendar.NOVEMBER, 2}, // friday after all saints {2013, Calendar.DECEMBER, 23} // monday before christas eve }; } @Test(dataProvider = "holidayDataProvider") public void testHolidays(int year, int month, int dayOfMonth) { Calendar test = Calendar.getInstance(); test.set(Calendar.YEAR, year); test.set(Calendar.MONTH, month); test.set(Calendar.DAY_OF_MONTH, dayOfMonth); test.set(Calendar.HOUR_OF_DAY, 10); setNow(test); Assert.assertTrue(isHoliday(test), test.getTime().toString() + " is a holiday?"); } }
4,712
0
Create_ds/SimianArmy/src/test/java/com/netflix/simianarmy/basic
Create_ds/SimianArmy/src/test/java/com/netflix/simianarmy/basic/janitor/TestBasicJanitorRuleEngine.java
/* * * Copyright 2012 Netflix, Inc. * * Licensed 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. * */ // CHECKSTYLE IGNORE Javadoc // CHECKSTYLE IGNORE MagicNumberCheck package com.netflix.simianarmy.basic.janitor; import com.netflix.simianarmy.Resource; import com.netflix.simianarmy.aws.AWSResource; import com.netflix.simianarmy.janitor.Rule; import org.joda.time.DateTime; import org.testng.Assert; import org.testng.annotations.Test; import java.util.Date; public class TestBasicJanitorRuleEngine { @Test public void testEmptyRuleSet() { Resource resource = new AWSResource().withId("id"); BasicJanitorRuleEngine engine = new BasicJanitorRuleEngine(); Assert.assertTrue(engine.isValid(resource)); } @Test public void testAllValid() { Resource resource = new AWSResource().withId("id"); BasicJanitorRuleEngine engine = new BasicJanitorRuleEngine() .addRule(new AlwaysValidRule()) .addRule(new AlwaysValidRule()) .addRule(new AlwaysValidRule()); Assert.assertTrue(engine.isValid(resource)); } @Test public void testMixed() { Resource resource = new AWSResource().withId("id"); DateTime now = DateTime.now(); BasicJanitorRuleEngine engine = new BasicJanitorRuleEngine() .addRule(new AlwaysValidRule()) .addRule(new AlwaysInvalidRule(now, 1)) .addRule(new AlwaysValidRule()); Assert.assertFalse(engine.isValid(resource)); } @Test public void testIsValidWithNearestTerminationTime() { int[][] permutaions = {{1, 2, 3}, {1, 3, 2}, {2, 1, 3}, {2, 3, 1}, {3, 1, 2}, {3, 2, 1}}; for (int[] perm : permutaions) { Resource resource = new AWSResource().withId("id"); DateTime now = DateTime.now(); BasicJanitorRuleEngine engine = new BasicJanitorRuleEngine() .addRule(new AlwaysInvalidRule(now, perm[0])) .addRule(new AlwaysInvalidRule(now, perm[1])) .addRule(new AlwaysInvalidRule(now, perm[2])); Assert.assertFalse(engine.isValid(resource)); Assert.assertEquals( resource.getExpectedTerminationTime().getTime(), now.plusDays(1).getMillis()); Assert.assertEquals(resource.getTerminationReason(), "1"); } } @Test void testWithExclusionRuleMatch1() { Resource resource = new AWSResource().withId("id"); DateTime now = DateTime.now(); BasicJanitorRuleEngine engine = new BasicJanitorRuleEngine() .addExclusionRule(new AlwaysValidRule()) .addRule(new AlwaysInvalidRule(now, 1)); Assert.assertTrue(engine.isValid(resource)); } @Test void testWithExclusionRuleMatch2() { Resource resource = new AWSResource().withId("id"); DateTime now = DateTime.now(); BasicJanitorRuleEngine engine = new BasicJanitorRuleEngine() .addExclusionRule(new AlwaysValidRule()) .addRule(new AlwaysValidRule()); Assert.assertTrue(engine.isValid(resource)); } @Test void testWithExclusionRuleNotMatch1() { Resource resource = new AWSResource().withId("id"); DateTime now = DateTime.now(); BasicJanitorRuleEngine engine = new BasicJanitorRuleEngine() .addExclusionRule(new AlwaysInvalidRule(now, 1)) .addRule(new AlwaysInvalidRule(now, 1)); Assert.assertFalse(engine.isValid(resource)); } @Test void testWithExclusionRuleNotMatch2() { Resource resource = new AWSResource().withId("id"); DateTime now = DateTime.now(); BasicJanitorRuleEngine engine = new BasicJanitorRuleEngine() .addExclusionRule(new AlwaysInvalidRule(now, 1)) .addRule(new AlwaysValidRule()); Assert.assertTrue(engine.isValid(resource)); } } class AlwaysValidRule implements Rule { @Override public boolean isValid(Resource resource) { return true; } } class AlwaysInvalidRule implements Rule { private final int retentionDays; private final DateTime now; public AlwaysInvalidRule(DateTime now, int retentionDays) { this.retentionDays = retentionDays; this.now = now; } @Override public boolean isValid(Resource resource) { resource.setExpectedTerminationTime( new Date(now.plusDays(retentionDays).getMillis())); resource.setTerminationReason(String.valueOf(retentionDays)); return false; } }
4,713
0
Create_ds/SimianArmy/src/test/java/com/netflix/simianarmy/basic
Create_ds/SimianArmy/src/test/java/com/netflix/simianarmy/basic/chaos/TestBasicChaosMonkey.java
/* * * Copyright 2012 Netflix, Inc. * * Licensed 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. * */ // CHECKSTYLE IGNORE Javadoc package com.netflix.simianarmy.basic.chaos; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.concurrent.TimeUnit; import javax.ws.rs.core.Response; import com.netflix.simianarmy.GroupType; import org.testng.Assert; import org.testng.annotations.Test; import com.netflix.simianarmy.Monkey; import com.netflix.simianarmy.MonkeyScheduler; import com.netflix.simianarmy.chaos.ChaosCrawler.InstanceGroup; import com.netflix.simianarmy.chaos.ChaosMonkey; import com.netflix.simianarmy.chaos.TestChaosMonkeyContext; import com.netflix.simianarmy.resources.chaos.ChaosMonkeyResource; import com.amazonaws.services.autoscaling.model.TagDescription; // CHECKSTYLE IGNORE MagicNumberCheck public class TestBasicChaosMonkey { private enum GroupTypes implements GroupType { TYPE_A, TYPE_B }; @Test public void testDisabled() { TestChaosMonkeyContext ctx = new TestChaosMonkeyContext("disabled.properties"); ChaosMonkey chaos = new BasicChaosMonkey(ctx); chaos.start(); chaos.stop(); List<InstanceGroup> selectedOn = ctx.selectedOn(); List<String> terminated = ctx.terminated(); Assert.assertEquals(selectedOn.size(), 0, "no groups selected on"); Assert.assertEquals(terminated.size(), 0, "nothing terminated"); } @Test public void testEnabledA() { TestChaosMonkeyContext ctx = new TestChaosMonkeyContext("enabledA.properties"); ChaosMonkey chaos = new BasicChaosMonkey(ctx); chaos.start(); chaos.stop(); List<InstanceGroup> selectedOn = ctx.selectedOn(); List<String> terminated = ctx.terminated(); Assert.assertEquals(selectedOn.size(), 2); Assert.assertEquals(selectedOn.get(0).type(), TestChaosMonkeyContext.CrawlerTypes.TYPE_A); Assert.assertEquals(selectedOn.get(0).name(), "name0"); Assert.assertEquals(selectedOn.get(1).type(), TestChaosMonkeyContext.CrawlerTypes.TYPE_A); Assert.assertEquals(selectedOn.get(1).name(), "name1"); Assert.assertEquals(terminated.size(), 0, "nothing terminated"); } @Test public void testUnleashedEnabledA() { TestChaosMonkeyContext ctx = new TestChaosMonkeyContext("unleashedEnabledA.properties"); ChaosMonkey chaos = new BasicChaosMonkey(ctx); chaos.start(); chaos.stop(); List<InstanceGroup> selectedOn = ctx.selectedOn(); List<String> terminated = ctx.terminated(); Assert.assertEquals(selectedOn.size(), 2); Assert.assertEquals(selectedOn.get(0).type(), TestChaosMonkeyContext.CrawlerTypes.TYPE_A); Assert.assertEquals(selectedOn.get(0).name(), "name0"); Assert.assertEquals(selectedOn.get(1).type(), TestChaosMonkeyContext.CrawlerTypes.TYPE_A); Assert.assertEquals(selectedOn.get(1).name(), "name1"); Assert.assertEquals(terminated.size(), 2); Assert.assertEquals(terminated.get(0), "0:i-123456789012345670"); Assert.assertEquals(terminated.get(1), "1:i-123456789012345671"); } @Test public void testEnabledB() { TestChaosMonkeyContext ctx = new TestChaosMonkeyContext("enabledB.properties"); ChaosMonkey chaos = new BasicChaosMonkey(ctx); chaos.start(); chaos.stop(); List<InstanceGroup> selectedOn = ctx.selectedOn(); List<String> terminated = ctx.terminated(); Assert.assertEquals(selectedOn.size(), 2); Assert.assertEquals(selectedOn.get(0).type(), TestChaosMonkeyContext.CrawlerTypes.TYPE_B); Assert.assertEquals(selectedOn.get(0).name(), "name2"); Assert.assertEquals(selectedOn.get(1).type(), TestChaosMonkeyContext.CrawlerTypes.TYPE_B); Assert.assertEquals(selectedOn.get(1).name(), "name3"); Assert.assertEquals(terminated.size(), 0, "nothing terminated"); } @Test public void testUnleashedEnabledB() { TestChaosMonkeyContext ctx = new TestChaosMonkeyContext("unleashedEnabledB.properties"); ChaosMonkey chaos = new BasicChaosMonkey(ctx); chaos.start(); chaos.stop(); List<InstanceGroup> selectedOn = ctx.selectedOn(); List<String> terminated = ctx.terminated(); Assert.assertEquals(selectedOn.size(), 2); Assert.assertEquals(selectedOn.get(0).type(), TestChaosMonkeyContext.CrawlerTypes.TYPE_B); Assert.assertEquals(selectedOn.get(0).name(), "name2"); Assert.assertEquals(selectedOn.get(1).type(), TestChaosMonkeyContext.CrawlerTypes.TYPE_B); Assert.assertEquals(selectedOn.get(1).name(), "name3"); Assert.assertEquals(terminated.size(), 2); Assert.assertEquals(terminated.get(0), "2:i-123456789012345672"); Assert.assertEquals(terminated.get(1), "3:i-123456789012345673"); } @Test public void testEnabledAwithout1() { TestChaosMonkeyContext ctx = new TestChaosMonkeyContext("enabledAwithout1.properties"); ChaosMonkey chaos = new BasicChaosMonkey(ctx); chaos.start(); chaos.stop(); List<InstanceGroup> selectedOn = ctx.selectedOn(); List<String> terminated = ctx.terminated(); Assert.assertEquals(selectedOn.size(), 1); Assert.assertEquals(selectedOn.get(0).type(), TestChaosMonkeyContext.CrawlerTypes.TYPE_A); Assert.assertEquals(selectedOn.get(0).name(), "name0"); Assert.assertEquals(terminated.size(), 1); Assert.assertEquals(terminated.get(0), "0:i-123456789012345670"); } @Test public void testEnabledAwith0() { TestChaosMonkeyContext ctx = new TestChaosMonkeyContext("enabledAwith0.properties"); ChaosMonkey chaos = new BasicChaosMonkey(ctx); chaos.start(); chaos.stop(); List<InstanceGroup> selectedOn = ctx.selectedOn(); List<String> terminated = ctx.terminated(); Assert.assertEquals(selectedOn.size(), 1); Assert.assertEquals(selectedOn.get(0).type(), TestChaosMonkeyContext.CrawlerTypes.TYPE_A); Assert.assertEquals(selectedOn.get(0).name(), "name0"); Assert.assertEquals(terminated.size(), 1); Assert.assertEquals(terminated.get(0), "0:i-123456789012345670"); } @Test public void testAll() { TestChaosMonkeyContext ctx = new TestChaosMonkeyContext("all.properties"); ChaosMonkey chaos = new BasicChaosMonkey(ctx); chaos.start(); chaos.stop(); List<InstanceGroup> selectedOn = ctx.selectedOn(); List<String> terminated = ctx.terminated(); Assert.assertEquals(selectedOn.size(), 4); Assert.assertEquals(selectedOn.get(0).type(), TestChaosMonkeyContext.CrawlerTypes.TYPE_A); Assert.assertEquals(selectedOn.get(0).name(), "name0"); Assert.assertEquals(selectedOn.get(1).type(), TestChaosMonkeyContext.CrawlerTypes.TYPE_A); Assert.assertEquals(selectedOn.get(1).name(), "name1"); Assert.assertEquals(selectedOn.get(2).type(), TestChaosMonkeyContext.CrawlerTypes.TYPE_B); Assert.assertEquals(selectedOn.get(2).name(), "name2"); Assert.assertEquals(selectedOn.get(3).type(), TestChaosMonkeyContext.CrawlerTypes.TYPE_B); Assert.assertEquals(selectedOn.get(3).name(), "name3"); Assert.assertEquals(terminated.size(), 4); Assert.assertEquals(terminated.get(0), "0:i-123456789012345670"); Assert.assertEquals(terminated.get(1), "1:i-123456789012345671"); Assert.assertEquals(terminated.get(2), "2:i-123456789012345672"); Assert.assertEquals(terminated.get(3), "3:i-123456789012345673"); } @Test public void testNoProbability() { TestChaosMonkeyContext ctx = new TestChaosMonkeyContext("noProbability.properties"); ChaosMonkey chaos = new BasicChaosMonkey(ctx); chaos.start(); chaos.stop(); List<InstanceGroup> selectedOn = ctx.selectedOn(); List<String> terminated = ctx.terminated(); Assert.assertEquals(selectedOn.size(), 4); Assert.assertEquals(selectedOn.get(0).type(), TestChaosMonkeyContext.CrawlerTypes.TYPE_A); Assert.assertEquals(selectedOn.get(0).name(), "name0"); Assert.assertEquals(selectedOn.get(1).type(), TestChaosMonkeyContext.CrawlerTypes.TYPE_A); Assert.assertEquals(selectedOn.get(1).name(), "name1"); Assert.assertEquals(selectedOn.get(2).type(), TestChaosMonkeyContext.CrawlerTypes.TYPE_B); Assert.assertEquals(selectedOn.get(2).name(), "name2"); Assert.assertEquals(selectedOn.get(3).type(), TestChaosMonkeyContext.CrawlerTypes.TYPE_B); Assert.assertEquals(selectedOn.get(3).name(), "name3"); Assert.assertEquals(terminated.size(), 0); } @Test public void testFullProbability() { TestChaosMonkeyContext ctx = new TestChaosMonkeyContext("fullProbability.properties") { @Override public MonkeyScheduler scheduler() { return new MonkeyScheduler() { @Override public int frequency() { return 1; } @Override public TimeUnit frequencyUnit() { return TimeUnit.DAYS; } @Override public void start(Monkey monkey, Runnable run) { Assert.assertEquals(monkey.type().name(), monkey.type().name(), "starting monkey"); run.run(); } @Override public void stop(Monkey monkey) { Assert.assertEquals(monkey.type().name(), monkey.type().name(), "stopping monkey"); } }; } }; ChaosMonkey chaos = new BasicChaosMonkey(ctx); chaos.start(); chaos.stop(); List<InstanceGroup> selectedOn = ctx.selectedOn(); List<String> terminated = ctx.terminated(); Assert.assertEquals(selectedOn.size(), 4); Assert.assertEquals(selectedOn.get(0).type(), TestChaosMonkeyContext.CrawlerTypes.TYPE_A); Assert.assertEquals(selectedOn.get(0).name(), "name0"); Assert.assertEquals(selectedOn.get(1).type(), TestChaosMonkeyContext.CrawlerTypes.TYPE_A); Assert.assertEquals(selectedOn.get(1).name(), "name1"); Assert.assertEquals(selectedOn.get(2).type(), TestChaosMonkeyContext.CrawlerTypes.TYPE_B); Assert.assertEquals(selectedOn.get(2).name(), "name2"); Assert.assertEquals(selectedOn.get(3).type(), TestChaosMonkeyContext.CrawlerTypes.TYPE_B); Assert.assertEquals(selectedOn.get(3).name(), "name3"); Assert.assertEquals(terminated.size(), 4); } @Test public void testNoProbabilityByName() { TestChaosMonkeyContext ctx = new TestChaosMonkeyContext("noProbabilityByName.properties"); ChaosMonkey chaos = new BasicChaosMonkey(ctx); chaos.start(); chaos.stop(); List<InstanceGroup> selectedOn = ctx.selectedOn(); List<String> terminated = ctx.terminated(); Assert.assertEquals(selectedOn.size(), 4); Assert.assertEquals(selectedOn.get(0).type(), TestChaosMonkeyContext.CrawlerTypes.TYPE_A); Assert.assertEquals(selectedOn.get(0).name(), "name0"); Assert.assertEquals(selectedOn.get(1).type(), TestChaosMonkeyContext.CrawlerTypes.TYPE_A); Assert.assertEquals(selectedOn.get(1).name(), "name1"); Assert.assertEquals(selectedOn.get(2).type(), TestChaosMonkeyContext.CrawlerTypes.TYPE_B); Assert.assertEquals(selectedOn.get(2).name(), "name2"); Assert.assertEquals(selectedOn.get(3).type(), TestChaosMonkeyContext.CrawlerTypes.TYPE_B); Assert.assertEquals(selectedOn.get(3).name(), "name3"); Assert.assertEquals(terminated.size(), 0); } @Test public void testMaxTerminationCountPerDayAsZero() { TestChaosMonkeyContext ctx = new TestChaosMonkeyContext("terminationPerDayAsZero.properties"); ChaosMonkey chaos = new BasicChaosMonkey(ctx); chaos.start(); chaos.stop(); Assert.assertEquals(ctx.selectedOn().size(), 0); Assert.assertEquals(ctx.terminated().size(), 0); } @Test public void testMaxTerminationCountPerDayAsOne() { TestChaosMonkeyContext ctx = new TestChaosMonkeyContext("terminationPerDayAsOne.properties"); ChaosMonkey chaos = new BasicChaosMonkey(ctx); chaos.start(); chaos.stop(); Assert.assertEquals(ctx.selectedOn().size(), 1); Assert.assertEquals(ctx.terminated().size(), 1); // Run the chaos the second time will NOT trigger another termination chaos.start(); chaos.stop(); Assert.assertEquals(ctx.selectedOn().size(), 1); Assert.assertEquals(ctx.terminated().size(), 1); } @Test public void testMaxTerminationCountPerDayAsBiggerThanOne() { TestChaosMonkeyContext ctx = new TestChaosMonkeyContext("terminationPerDayAsBiggerThanOne.properties"); ChaosMonkey chaos = new BasicChaosMonkey(ctx); chaos.start(); chaos.stop(); Assert.assertEquals(ctx.selectedOn().size(), 1); Assert.assertEquals(ctx.terminated().size(), 1); // Run the chaos the second time will trigger another termination chaos.start(); chaos.stop(); Assert.assertEquals(ctx.selectedOn().size(), 2); Assert.assertEquals(ctx.terminated().size(), 2); } @Test public void testMaxTerminationCountPerDayAsSmallerThanOne() { TestChaosMonkeyContext ctx = new TestChaosMonkeyContext("terminationPerDayAsSmallerThanOne.properties"); ChaosMonkey chaos = new BasicChaosMonkey(ctx); chaos.start(); chaos.stop(); Assert.assertEquals(ctx.selectedOn().size(), 1); Assert.assertEquals(ctx.terminated().size(), 1); // Run the chaos the second time will NOT trigger another termination chaos.start(); chaos.stop(); Assert.assertEquals(ctx.selectedOn().size(), 1); Assert.assertEquals(ctx.terminated().size(), 1); } @Test public void testMaxTerminationCountPerDayAsNegative() { TestChaosMonkeyContext ctx = new TestChaosMonkeyContext("terminationPerDayAsNegative.properties"); ChaosMonkey chaos = new BasicChaosMonkey(ctx); chaos.start(); chaos.stop(); Assert.assertEquals(ctx.selectedOn().size(), 0); Assert.assertEquals(ctx.terminated().size(), 0); } @Test public void testMaxTerminationCountPerDayAsVerySmall() { TestChaosMonkeyContext ctx = new TestChaosMonkeyContext("terminationPerDayAsVerySmall.properties"); ChaosMonkey chaos = new BasicChaosMonkey(ctx); chaos.start(); chaos.stop(); Assert.assertEquals(ctx.selectedOn().size(), 0); Assert.assertEquals(ctx.terminated().size(), 0); } @Test public void testMaxTerminationCountPerDayGroupLevel() { TestChaosMonkeyContext ctx = new TestChaosMonkeyContext("terminationPerDayGroupLevel.properties"); ChaosMonkey chaos = new BasicChaosMonkey(ctx); for (int i = 1; i <= 3; i++) { chaos.start(); chaos.stop(); Assert.assertEquals(ctx.selectedOn().size(), i); Assert.assertEquals(ctx.terminated().size(), i); } // Run the chaos the second time will NOT trigger another termination chaos.start(); chaos.stop(); Assert.assertEquals(ctx.selectedOn().size(), 3); Assert.assertEquals(ctx.terminated().size(), 3); } @Test public void testGetValueFromCfgWithDefault() { TestChaosMonkeyContext ctx = new TestChaosMonkeyContext("propertiesWithDefaults.properties"); BasicChaosMonkey chaos = new BasicChaosMonkey(ctx); // named 1 has actual values in config InstanceGroup named1 = new BasicInstanceGroup("named1", GroupTypes.TYPE_A, "test-dev-1", Collections.<TagDescription>emptyList()); // named 2 doesn't have values but it's group has values InstanceGroup named2 = new BasicInstanceGroup("named2", GroupTypes.TYPE_A, "test-dev-1", Collections.<TagDescription>emptyList()); // named 3 doesn't have values and it's group doesn't have values InstanceGroup named3 = new BasicInstanceGroup("named3", GroupTypes.TYPE_B, "test-dev-1", Collections.<TagDescription>emptyList()); Assert.assertEquals(chaos.getBoolFromCfgOrDefault(named1, "enabled", true), false); Assert.assertEquals(chaos.getNumFromCfgOrDefault(named1, "probability", 3.0), 1.1); Assert.assertEquals(chaos.getNumFromCfgOrDefault(named1, "maxTerminationsPerDay", 4.0), 2.1); Assert.assertEquals(chaos.getBoolFromCfgOrDefault(named2, "enabled", true), true); Assert.assertEquals(chaos.getNumFromCfgOrDefault(named2, "probability", 3.0), 1.0); Assert.assertEquals(chaos.getNumFromCfgOrDefault(named2, "maxTerminationsPerDay", 4.0), 2.0); Assert.assertEquals(chaos.getBoolFromCfgOrDefault(named3, "enabled", true), true); Assert.assertEquals(chaos.getNumFromCfgOrDefault(named3, "probability", 3.0), 3.0); Assert.assertEquals(chaos.getNumFromCfgOrDefault(named3, "maxTerminationsPerDay", 4.0), 4.0); } @Test public void testMandatoryTerminationDisabled() { TestChaosMonkeyContext ctx = new TestChaosMonkeyContext("mandatoryTerminationDisabled.properties"); ChaosMonkey chaos = new BasicChaosMonkey(ctx); chaos.start(); chaos.stop(); Assert.assertEquals(ctx.selectedOn().size(), 1); Assert.assertEquals(ctx.terminated().size(), 0); } @Test public void testMandatoryTerminationNotDefined() { TestChaosMonkeyContext ctx = new TestChaosMonkeyContext("mandatoryTerminationNotDefined.properties"); ChaosMonkey chaos = new BasicChaosMonkey(ctx); chaos.start(); chaos.stop(); Assert.assertEquals(ctx.selectedOn().size(), 1); Assert.assertEquals(ctx.terminated().size(), 0); } @Test public void testMandatoryTerminationNoOptInTime() { TestChaosMonkeyContext ctx = new TestChaosMonkeyContext("mandatoryTerminationNoOptInTime.properties"); ChaosMonkey chaos = new BasicChaosMonkey(ctx); chaos.start(); chaos.stop(); Assert.assertEquals(ctx.selectedOn().size(), 1); Assert.assertEquals(ctx.terminated().size(), 0); } @Test public void testMandatoryTerminationInsideWindow() { TestChaosMonkeyContext ctx = new TestChaosMonkeyContext("mandatoryTerminationInsideWindow.properties"); ChaosMonkey chaos = new BasicChaosMonkey(ctx); chaos.start(); chaos.stop(); // The last opt-in time is within the window, so no mandatory termination is triggered Assert.assertEquals(ctx.selectedOn().size(), 1); Assert.assertEquals(ctx.terminated().size(), 0); } @Test public void testMandatoryTerminationOutsideWindow() { TestChaosMonkeyContext ctx = new TestChaosMonkeyContext("mandatoryTerminationOutsideWindow.properties"); ChaosMonkey chaos = new BasicChaosMonkey(ctx); chaos.start(); chaos.stop(); // There was no termination in the last window, so one mandatory termination is triggered Assert.assertEquals(ctx.selectedOn().size(), 1); Assert.assertEquals(ctx.terminated().size(), 1); } @Test public void testMandatoryTerminationOutsideWindowWithPreviousTermination() { TestChaosMonkeyContext ctx = new TestChaosMonkeyContext("mandatoryTerminationOutsideWindow.properties"); terminateOnDemand(ctx, "TYPE_C", "name4"); Assert.assertEquals(ctx.selectedOn().size(), 1); Assert.assertEquals(ctx.terminated().size(), 1); ChaosMonkey chaos = new BasicChaosMonkey(ctx); chaos.start(); chaos.stop(); // There was termination in the last window, so no mandatory termination is triggered Assert.assertEquals(ctx.selectedOn().size(), 2); Assert.assertEquals(ctx.terminated().size(), 1); } @Test public void testMandatoryTerminationInsideWindowWithPreviousTermination() { TestChaosMonkeyContext ctx = new TestChaosMonkeyContext("mandatoryTerminationInsideWindow.properties"); terminateOnDemand(ctx, "TYPE_C", "name4"); Assert.assertEquals(ctx.selectedOn().size(), 1); Assert.assertEquals(ctx.terminated().size(), 1); ChaosMonkey chaos = new BasicChaosMonkey(ctx); chaos.start(); chaos.stop(); // There was termination in the last window, so no mandatory termination is triggered Assert.assertEquals(ctx.selectedOn().size(), 2); Assert.assertEquals(ctx.terminated().size(), 1); } @Test public void testNotificationEnabled() { TestChaosMonkeyContext ctx = new TestChaosMonkeyContext("notificationEnabled.properties"); ChaosMonkey chaos = new BasicChaosMonkey(ctx); chaos.start(); chaos.stop(); Assert.assertEquals(ctx.selectedOn().size(), 4); Assert.assertEquals(ctx.terminated().size(), 4); // Notification is enabled only for 2 terminations. Assert.assertEquals(ctx.getNotified(), 2); } @Test public void testGlobalNotificationEnabled() { TestChaosMonkeyContext ctx = new TestChaosMonkeyContext("globalNotificationEnabled.properties"); ChaosMonkey chaos = new BasicChaosMonkey(ctx); chaos.start(); chaos.stop(); Assert.assertEquals(ctx.selectedOn().size(), 4); Assert.assertEquals(ctx.terminated().size(), 4); Assert.assertEquals(ctx.getNotified(), 1); Assert.assertEquals(ctx.getGloballyNotified(), 4); } private void terminateOnDemand(TestChaosMonkeyContext ctx, String groupType, String groupName) { String input = String.format("{\"eventType\":\"CHAOS_TERMINATION\",\"groupType\":\"%s\",\"groupName\":\"%s\"}", groupType, groupName); int currentSelectedOn = ctx.selectedOn().size(); int currentTerminated = ctx.terminated().size(); ChaosMonkeyResource resource = new ChaosMonkeyResource(new BasicChaosMonkey(ctx)); validateAddEventResult(resource, input, Response.Status.OK); Assert.assertEquals(ctx.selectedOn().size(), currentSelectedOn + 1); Assert.assertEquals(ctx.terminated().size(), currentTerminated + 1); } private void validateAddEventResult(ChaosMonkeyResource resource, String input, Response.Status responseStatus) { try { Response resp = resource.addEvent(input); Assert.assertEquals(resp.getStatus(), responseStatus.getStatusCode()); } catch (Exception e) { Assert.fail("addEvent throws exception"); } } }
4,714
0
Create_ds/SimianArmy/src/test/java/com/netflix/simianarmy/basic
Create_ds/SimianArmy/src/test/java/com/netflix/simianarmy/basic/chaos/TestCloudFormationChaosMonkey.java
/* * * Copyright 2012 Netflix, Inc. * * Licensed 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. * */ // CHECKSTYLE IGNORE Javadoc package com.netflix.simianarmy.basic.chaos; import com.amazonaws.services.autoscaling.model.TagDescription; import org.testng.Assert; import org.testng.annotations.Test; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertTrue; import static org.testng.Assert.assertFalse; import com.netflix.simianarmy.chaos.TestChaosMonkeyContext; import com.netflix.simianarmy.chaos.ChaosCrawler.InstanceGroup; import java.util.Collections; public class TestCloudFormationChaosMonkey { public static final long EXPECTED_MILLISECONDS = 2000; @Test public void testIsGroupEnabled() { TestChaosMonkeyContext ctx = new TestChaosMonkeyContext("cloudformation.properties"); CloudFormationChaosMonkey chaos = new CloudFormationChaosMonkey(ctx); InstanceGroup group1 = new BasicInstanceGroup("new-group-TestGroup1-XCFNFNFNF", TestChaosMonkeyContext.CrawlerTypes.TYPE_D, "region", Collections.<TagDescription>emptyList()); InstanceGroup group2 = new BasicInstanceGroup("new-group-TestGroup2-XCFNGHFNF", TestChaosMonkeyContext.CrawlerTypes.TYPE_D, "region", Collections.<TagDescription>emptyList()); assertTrue(chaos.isGroupEnabled(group1)); assertFalse(chaos.isGroupEnabled(group2)); } @Test public void testIsMaxTerminationCountExceeded() { TestChaosMonkeyContext ctx = new TestChaosMonkeyContext("cloudformation.properties"); CloudFormationChaosMonkey chaos = new CloudFormationChaosMonkey(ctx); InstanceGroup group1 = new BasicInstanceGroup("new-group-TestGroup1-XCFNFNFNF", TestChaosMonkeyContext.CrawlerTypes.TYPE_D, "region", Collections.<TagDescription>emptyList()); assertFalse(chaos.isMaxTerminationCountExceeded(group1)); } @Test public void testGetEffectiveProbability() { TestChaosMonkeyContext ctx = new TestChaosMonkeyContext("cloudformation.properties"); CloudFormationChaosMonkey chaos = new CloudFormationChaosMonkey(ctx); InstanceGroup group1 = new BasicInstanceGroup("new-group-TestGroup1-XCFNFNFNF", TestChaosMonkeyContext.CrawlerTypes.TYPE_D, "region", Collections.<TagDescription>emptyList()); assertEquals(1.0, chaos.getEffectiveProbability(group1)); } @Test public void testNoSuffixInstanceGroup() { TestChaosMonkeyContext ctx = new TestChaosMonkeyContext("disabled.properties"); CloudFormationChaosMonkey chaos = new CloudFormationChaosMonkey(ctx); InstanceGroup group = new BasicInstanceGroup("new-group-TestGroup-XCFNFNFNF", TestChaosMonkeyContext.CrawlerTypes.TYPE_D, "region", Collections.<TagDescription>emptyList()); InstanceGroup newGroup = chaos.noSuffixInstanceGroup(group); assertEquals(newGroup.name(), "new-group-TestGroup"); } @Test public void testGetLastOptInMilliseconds() { TestChaosMonkeyContext ctx = new TestChaosMonkeyContext("cloudformation.properties"); CloudFormationChaosMonkey chaos = new CloudFormationChaosMonkey(ctx); InstanceGroup group = new BasicInstanceGroup("new-group-TestGroup1-XCFNFNFNF", TestChaosMonkeyContext.CrawlerTypes.TYPE_D, "region", Collections.<TagDescription>emptyList()); assertEquals(chaos.getLastOptInMilliseconds(group), EXPECTED_MILLISECONDS); } @Test public void testCloudFormationChaosMonkeyIntegration() { TestChaosMonkeyContext ctx = new TestChaosMonkeyContext("cloudformation.properties"); CloudFormationChaosMonkey chaos = new CloudFormationChaosMonkey(ctx); chaos.start(); chaos.stop(); Assert.assertEquals(ctx.selectedOn().size(), 1); Assert.assertEquals(ctx.terminated().size(), 1); Assert.assertEquals(ctx.getNotified(), 1); } }
4,715
0
Create_ds/SimianArmy/src/test/java/com/netflix/simianarmy/basic
Create_ds/SimianArmy/src/test/java/com/netflix/simianarmy/basic/chaos/TestBasicChaosEmailNotifier.java
/* * * Copyright 2013 Netflix, Inc. * * Licensed 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. * */ // CHECKSTYLE IGNORE Javadoc package com.netflix.simianarmy.basic.chaos; import static org.mockito.Mockito.doNothing; import static org.mockito.Mockito.spy; import static org.mockito.Mockito.verify; import java.util.Properties; import org.testng.Assert; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; import com.amazonaws.services.simpleemail.AmazonSimpleEmailServiceClient; import com.netflix.simianarmy.GroupType; import com.netflix.simianarmy.basic.BasicConfiguration; import com.netflix.simianarmy.chaos.TestChaosMonkeyContext.TestInstanceGroup; public class TestBasicChaosEmailNotifier { private final AmazonSimpleEmailServiceClient sesClient = new AmazonSimpleEmailServiceClient(); private BasicChaosEmailNotifier basicChaosEmailNotifier; private Properties properties; private enum GroupTypes implements GroupType { TYPE_A }; private String name = "name0"; private String region = "reg1"; private String to = "foo@bar.com"; private String instanceId = "i-12345678901234567"; private String subjectPrefix = "Subject Prefix - "; private String subjectSuffix = " - Subject Suffix "; private String bodyPrefix = "Body Prefix - "; private String bodySuffix = " - Body Suffix"; private final TestInstanceGroup testInstanceGroup = new TestInstanceGroup(GroupTypes.TYPE_A, name, region, "0:" + instanceId); private String defaultBody = "Instance " + instanceId + " of " + GroupTypes.TYPE_A + " " + name + " is being terminated by Chaos monkey."; private String defaultSubject = "Chaos Monkey Termination Notification for " + to; @BeforeMethod public void beforeMethod() { properties = new Properties(); } @Test public void testInvalidEmailAddresses() { String[] invalidEmails = new String[] { "username", "username@.com.my", "username123@example.a", "username123@.com", "username123@.com.com", "username()*@example.com", "username@%*.com"}; basicChaosEmailNotifier = new BasicChaosEmailNotifier(new BasicConfiguration(properties), sesClient, null); for (String emailAddress : invalidEmails) { Assert.assertFalse(basicChaosEmailNotifier.isValidEmail(emailAddress)); } } @Test public void testValidEmailAddresses() { String[] validEmails = new String[] { "username-100@example.com", "name.surname+ml-info@example.com", "username.100@example.com", "username111@example.com", "username-100@username.net", "username.100@example.com.au", "username@1.com", "username@example.com", "username+100@example.com", "username-100@example-test.com" }; basicChaosEmailNotifier = new BasicChaosEmailNotifier(new BasicConfiguration(properties), sesClient, null); for (String emailAddress : validEmails) { Assert.assertTrue(basicChaosEmailNotifier.isValidEmail(emailAddress)); } } @Test public void testbuildEmailSubject() { basicChaosEmailNotifier = new BasicChaosEmailNotifier(new BasicConfiguration(properties), sesClient, null); String subject = basicChaosEmailNotifier.buildEmailSubject(to); Assert.assertEquals(subject, defaultSubject); } @Test public void testbuildEmailSubjectWithSubjectPrefix() { properties.setProperty("simianarmy.chaos.notification.subject.prefix", subjectPrefix); basicChaosEmailNotifier = new BasicChaosEmailNotifier(new BasicConfiguration(properties), sesClient, null); String subject = basicChaosEmailNotifier.buildEmailSubject(to); Assert.assertEquals(subject, subjectPrefix + defaultSubject); } @Test public void testbuildEmailSubjectWithSubjectSuffix() { properties.setProperty("simianarmy.chaos.notification.subject.suffix", subjectSuffix); basicChaosEmailNotifier = new BasicChaosEmailNotifier(new BasicConfiguration(properties), sesClient, null); String subject = basicChaosEmailNotifier.buildEmailSubject(to); Assert.assertEquals(subject, defaultSubject + subjectSuffix); } @Test public void testbuildEmailSubjectWithSubjectPrefixSuffix() { properties.setProperty("simianarmy.chaos.notification.subject.prefix", subjectPrefix); properties.setProperty("simianarmy.chaos.notification.subject.suffix", subjectSuffix); basicChaosEmailNotifier = new BasicChaosEmailNotifier(new BasicConfiguration(properties), sesClient, null); String subject = basicChaosEmailNotifier.buildEmailSubject(to); Assert.assertEquals(subject, subjectPrefix + defaultSubject + subjectSuffix); } @Test public void testbuildEmailBody() { basicChaosEmailNotifier = new BasicChaosEmailNotifier(new BasicConfiguration(properties), sesClient, null); String subject = basicChaosEmailNotifier.buildEmailBody(testInstanceGroup, instanceId, null); Assert.assertEquals(subject, defaultBody); } @Test public void testbuildEmailBodyPrefix() { properties.setProperty("simianarmy.chaos.notification.body.prefix", bodyPrefix); basicChaosEmailNotifier = new BasicChaosEmailNotifier(new BasicConfiguration(properties), sesClient, null); String subject = basicChaosEmailNotifier.buildEmailBody(testInstanceGroup, instanceId, null); Assert.assertEquals(subject, bodyPrefix + defaultBody); } @Test public void testbuildEmailBodySuffix() { properties.setProperty("simianarmy.chaos.notification.body.suffix", bodySuffix); basicChaosEmailNotifier = new BasicChaosEmailNotifier(new BasicConfiguration(properties), sesClient, null); String subject = basicChaosEmailNotifier.buildEmailBody(testInstanceGroup, instanceId, null); Assert.assertEquals(subject, defaultBody + bodySuffix); } @Test public void testbuildEmailBodyPrefixSuffix() { properties.setProperty("simianarmy.chaos.notification.body.prefix", bodyPrefix); properties.setProperty("simianarmy.chaos.notification.body.suffix", bodySuffix); basicChaosEmailNotifier = new BasicChaosEmailNotifier(new BasicConfiguration(properties), sesClient, null); String subject = basicChaosEmailNotifier.buildEmailBody(testInstanceGroup, instanceId, null); Assert.assertEquals(subject, bodyPrefix + defaultBody + bodySuffix); } @Test public void testBuildAndSendEmail() { properties.setProperty("simianarmy.chaos.notification.sourceEmail", to); BasicChaosEmailNotifier spyBasicChaosEmailNotifier = spy(new BasicChaosEmailNotifier(new BasicConfiguration( properties), sesClient, null)); doNothing().when(spyBasicChaosEmailNotifier).sendEmail(to, defaultSubject, defaultBody); spyBasicChaosEmailNotifier.buildAndSendEmail(to, testInstanceGroup, instanceId, null); verify(spyBasicChaosEmailNotifier).sendEmail(to, defaultSubject, defaultBody); } @Test public void testBuildAndSendEmailSubjectIsBody() { properties.setProperty("simianarmy.chaos.notification.subject.isBody", "true"); properties.setProperty("simianarmy.chaos.notification.sourceEmail", to); BasicChaosEmailNotifier spyBasicChaosEmailNotifier = spy(new BasicChaosEmailNotifier(new BasicConfiguration( properties), sesClient, null)); doNothing().when(spyBasicChaosEmailNotifier).sendEmail(to, defaultBody, defaultBody); spyBasicChaosEmailNotifier.buildAndSendEmail(to, testInstanceGroup, instanceId, null); verify(spyBasicChaosEmailNotifier).sendEmail(to, defaultBody, defaultBody); } }
4,716
0
Create_ds/SimianArmy/src/test/java/com/netflix/simianarmy/basic
Create_ds/SimianArmy/src/test/java/com/netflix/simianarmy/basic/chaos/TestBasicChaosInstanceSelector.java
/* * * Copyright 2012 Netflix, Inc. * * Licensed 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. * */ // CHECKSTYLE IGNORE Javadoc package com.netflix.simianarmy.basic.chaos; import java.util.*; import com.amazonaws.services.autoscaling.model.TagDescription; import com.netflix.simianarmy.GroupType; import com.netflix.simianarmy.chaos.ChaosInstanceSelector; import com.netflix.simianarmy.chaos.ChaosCrawler.InstanceGroup; import org.testng.annotations.Test; import org.testng.annotations.DataProvider; import org.testng.Assert; import org.slf4j.Logger; import static org.slf4j.helpers.NOPLogger.NOP_LOGGER; // CHECKSTYLE IGNORE MagicNumberCheck public class TestBasicChaosInstanceSelector { private ChaosInstanceSelector selector = new BasicChaosInstanceSelector() { // turn off selector logger for this test since we call it ~1M times protected Logger logger() { return NOP_LOGGER; } }; public enum Types implements GroupType { TEST } private InstanceGroup group = new InstanceGroup() { public GroupType type() { return Types.TEST; } public String name() { return "TestGroup"; } public String region() { return "region"; } public List<TagDescription> tags() { return Collections.<TagDescription>emptyList(); } public List<String> instances() { return Arrays.asList("i-123456789012345670", "i-123456789012345671", "i-123456789012345672", "i-123456789012345673", "i-123456789012345674", "i-123456789012345675", "i-123456789012345676", "i-123456789012345677", "i-123456789012345678", "i-123456789012345679"); } public void addInstance(String ignored) { } @Override public InstanceGroup copyAs(String name) { return this; } }; @Test public void testSelect() { Assert.assertTrue(selector.select(group, 0).isEmpty(), "select disabled group is always null"); Assert.assertTrue(selector.select(group, 0.0).isEmpty(), "select disabled group is always null"); int selected = 0; for (int i = 0; i < 100; i++) { selected += selector.select(group, 1.0).size(); } Assert.assertEquals(selected, 100, "1.0 probability always selects an instance"); } @DataProvider public Object[][] evenSelectionDataProvider() { return new Object[][] {{1.0}, {0.9}, {0.8}, {0.7}, {0.6}, {0.5}, {0.4}, {0.3}, {0.2}, {0.1} }; } static final int RUNS = 1000000; @Test(dataProvider = "evenSelectionDataProvider") public void testEvenSelections(double probability) { Map<String, Integer> selectMap = new HashMap<String, Integer>(); for (int i = 0; i < RUNS; i++) { Collection<String> instances = selector.select(group, probability); for (String inst : instances) { if (selectMap.containsKey(inst)) { selectMap.put(inst, selectMap.get(inst) + 1); } else { selectMap.put(inst, 1); } } } Assert.assertEquals(selectMap.size(), group.instances().size(), "verify we selected all instances"); // allow for 4% variation over all the selection runs int avg = Double.valueOf((RUNS / (double) group.instances().size()) * probability).intValue(); int max = Double.valueOf(avg + (avg * 0.04)).intValue(); int min = Double.valueOf(avg - (avg * 0.04)).intValue(); for (Map.Entry<String, Integer> pair : selectMap.entrySet()) { Assert.assertTrue(pair.getValue() > min && pair.getValue() < max, pair.getKey() + " selected " + avg + " +- 4% times for prob: " + probability + " [got: " + pair.getValue() + "]"); } } @Test public void testSelectWithProbMoreThanOne() { // The number of selected instances should always be p when the prob is an integer. for (int p = 0; p <= group.instances().size(); p++) { Assert.assertEquals(selector.select(group, p).size(), p); } // When the prob is bigger than the size of the group, we get the whole group. for (int p = group.instances().size(); p <= group.instances().size() * 2; p++) { Assert.assertEquals(selector.select(group, p).size(), group.instances().size()); } } @Test public void testSelectWithProbMoreThanOneWithFraction() { // The number of selected instances can be p or p+1, depending on whether the fraction part // can get a instance selected. for (int p = 0; p <= group.instances().size(); p++) { Collection<String> selected = selector.select(group, p + 0.5); Assert.assertTrue(selected.size() >= p && selected.size() <= p + 1); } // When the prob is bigger than the size of the group, we get the whole group. for (int p = group.instances().size(); p <= group.instances().size() * 2; p++) { Collection<String> selected = selector.select(group, p + 0.5); Assert.assertEquals(selected.size(), group.instances().size()); } } }
4,717
0
Create_ds/SimianArmy/src/test/java/com/netflix/simianarmy
Create_ds/SimianArmy/src/test/java/com/netflix/simianarmy/janitor/TestBasicJanitorMonkeyContext.java
/* * * Copyright 2012 Netflix, Inc. * * Licensed 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 com.netflix.simianarmy.janitor; import com.netflix.simianarmy.aws.janitor.rule.generic.UntaggedRule; import com.netflix.simianarmy.basic.TestBasicCalendar; import com.netflix.simianarmy.basic.janitor.BasicJanitorRuleEngine; import org.apache.commons.lang.StringUtils; import org.testng.Assert; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; import java.util.Arrays; import java.util.HashSet; import java.util.Set; /** * The basic implementation of the context class for Janitor monkey. */ public class TestBasicJanitorMonkeyContext { private static final int SIMIANARMY_JANITOR_RULE_UNTAGGEDRULE_RETENTIONDAYSWITHOWNER = 3; private static final int SIMIANARMY_JANITOR_RULE_UNTAGGEDRULE_RETENTIONDAYSWITHOUTOWNER = 8; private static final Boolean SIMIANARMY_JANITOR_RULE_UNTAGGEDRULE_ENABLED = true; private static final Set<String> SIMIANARMY_JANITOR_RULE_UNTAGGEDRULE_REQUIREDTAGS = new HashSet<String>(Arrays.asList("owner", "costcenter")); private static final String SIMIANARMY_JANITOR_RULE_UNTAGGEDRULE_RESOURCES = "Instance"; private String monkeyRegion; private TestBasicCalendar monkeyCalendar; public TestBasicJanitorMonkeyContext() { super(); } @BeforeMethod public void before() { monkeyRegion = "us-east-1"; monkeyCalendar = new TestBasicCalendar(); } @Test public void testAddRuleWithUntaggedRuleResource() { JanitorRuleEngine ruleEngine = new BasicJanitorRuleEngine(); Boolean untaggedRuleEnabled = new Boolean(true); Rule rule = new UntaggedRule(monkeyCalendar, SIMIANARMY_JANITOR_RULE_UNTAGGEDRULE_REQUIREDTAGS, SIMIANARMY_JANITOR_RULE_UNTAGGEDRULE_RETENTIONDAYSWITHOWNER, SIMIANARMY_JANITOR_RULE_UNTAGGEDRULE_RETENTIONDAYSWITHOUTOWNER); if (untaggedRuleEnabled && getUntaggedRuleResourceSet().contains("INSTANCE")) { ruleEngine.addRule(rule); } Assert.assertTrue(ruleEngine.getRules().contains(rule)); } @Test public void testAddRuleWithoutUntaggedRuleResource() { JanitorRuleEngine ruleEngine = new BasicJanitorRuleEngine(); Boolean untaggedRuleEnabled = new Boolean(true); Rule rule = new UntaggedRule(monkeyCalendar, SIMIANARMY_JANITOR_RULE_UNTAGGEDRULE_REQUIREDTAGS, SIMIANARMY_JANITOR_RULE_UNTAGGEDRULE_RETENTIONDAYSWITHOWNER, SIMIANARMY_JANITOR_RULE_UNTAGGEDRULE_RETENTIONDAYSWITHOUTOWNER); if (untaggedRuleEnabled && getUntaggedRuleResourceSet().contains("ASG")) { ruleEngine.addRule(rule); } Assert.assertFalse(ruleEngine.getRules().contains(rule)); } private Set<String> getUntaggedRuleResourceSet() { Set<String> untaggedRuleResourceSet = new HashSet<String>(); if (SIMIANARMY_JANITOR_RULE_UNTAGGEDRULE_ENABLED) { String untaggedRuleResources = SIMIANARMY_JANITOR_RULE_UNTAGGEDRULE_RESOURCES; if (StringUtils.isNotBlank(untaggedRuleResources)) { for (String resourceType : untaggedRuleResources.split(",")) { untaggedRuleResourceSet.add(resourceType.trim().toUpperCase()); } } } return untaggedRuleResourceSet; } }
4,718
0
Create_ds/SimianArmy/src/test/java/com/netflix/simianarmy
Create_ds/SimianArmy/src/test/java/com/netflix/simianarmy/janitor/TestAbstractJanitor.java
/* * * Copyright 2012 Netflix, Inc. * * Licensed 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. * */ // CHECKSTYLE IGNORE Javadoc // CHECKSTYLE IGNORE MagicNumberCheck package com.netflix.simianarmy.janitor; import com.netflix.simianarmy.*; import com.netflix.simianarmy.Resource.CleanupState; import com.netflix.simianarmy.aws.AWSResource; import com.netflix.simianarmy.aws.janitor.rule.TestMonkeyCalendar; import com.netflix.simianarmy.basic.BasicConfiguration; import com.netflix.simianarmy.basic.janitor.BasicJanitorRuleEngine; import org.joda.time.DateTime; import org.testng.Assert; import org.testng.annotations.Test; import java.util.*; public class TestAbstractJanitor extends AbstractJanitor { private static final String TEST_REGION = "test-region"; public TestAbstractJanitor(AbstractJanitor.Context ctx, ResourceType resourceType) { super(ctx, resourceType); this.idToResource = new HashMap<>(); for (Resource r : ((TestJanitorCrawler) (ctx.janitorCrawler())).getCrawledResources()) { this.idToResource.put(r.getId(), r); } } // The collection of all resources for testing. private final Map<String, Resource> idToResource; private final HashSet<String> markedResourceIds = new HashSet<>(); private final HashSet<String> cleanedResourceIds = new HashSet<>(); @Override protected void postMark(Resource resource) { markedResourceIds.add(resource.getId()); } @Override protected void cleanup(Resource resource) { if (!idToResource.containsKey(resource.getId())) { throw new RuntimeException(); } // add a special case to throw exception if (resource.getId().equals("11")) { throw new RuntimeException("Magic number of id."); } idToResource.remove(resource.getId()); } @Override public void cleanupDryRun(Resource resource) throws DryRunnableJanitorException { // simulates a dryRun try { if (!idToResource.containsKey(resource.getId())) { throw new RuntimeException(); } if (resource.getId().equals("11")) { throw new RuntimeException("Magic number of id."); } } catch (Exception e) { throw new DryRunnableJanitorException("Exception during dry run", e); } } @Override protected void postCleanup(Resource resource) { cleanedResourceIds.add(resource.getId()); } private static List<Resource> generateTestingResources(int n) { List<Resource> resources = new ArrayList<Resource>(n); for (int i = 1; i <= n; i++) { resources.add(new AWSResource().withId(String.valueOf(i)) .withRegion(TEST_REGION) .withResourceType(TestResourceType.TEST_RESOURCE_TYPE) .withOptOutOfJanitor(false)); } return resources; } @Test public static void testJanitor() { int n = 10; Collection<Resource> crawledResources = new ArrayList<>(generateTestingResources(n)); TestJanitorCrawler crawler = new TestJanitorCrawler(crawledResources); TestJanitorResourceTracker resourceTracker = new TestJanitorResourceTracker(new HashMap<>()); TestAbstractJanitor janitor = new TestAbstractJanitor( new TestJanitorContext(TEST_REGION, new BasicJanitorRuleEngine().addRule(new IsEvenRule()), crawler, resourceTracker, new TestMonkeyCalendar()), TestResourceType.TEST_RESOURCE_TYPE); janitor.setLeashed(false); Assert.assertEquals(crawler.resources(TestResourceType.TEST_RESOURCE_TYPE).size(), n); Assert.assertEquals(janitor.markedResourceIds.size(), 0); janitor.markResources(); Assert.assertEquals(janitor.getMarkedResources().size(), n / 2); Assert.assertEquals(janitor.markedResourceIds.size(), n / 2); for (int i = 1; i <= n; i += 2) { Assert.assertTrue(janitor.markedResourceIds.contains(String.valueOf(i))); } Assert.assertEquals(janitor.cleanedResourceIds.size(), 0); janitor.cleanupResources(); Assert.assertEquals(janitor.getCleanedResources().size(), n / 2); Assert.assertEquals(janitor.getFailedToCleanResources().size(), 0); Assert.assertEquals(resourceTracker.getResources( TestResourceType.TEST_RESOURCE_TYPE, CleanupState.JANITOR_TERMINATED, TEST_REGION).size(), n / 2); Assert.assertEquals(janitor.cleanedResourceIds.size(), n / 2); for (int i = 1; i <= n; i += 2) { Assert.assertTrue(janitor.cleanedResourceIds.contains(String.valueOf(i))); } Assert.assertEquals(janitor.getResourcesCleanedCount(), janitor.cleanedResourceIds.size()); Assert.assertEquals(janitor.getMarkedResourcesCount(), janitor.markedResourceIds.size()); Assert.assertEquals(janitor.getFailedToCleanResourcesCount(), 0); } @Test public static void testJanitorWithOptedOutResources() { Collection<Resource> crawledResources = new ArrayList<Resource>(); int n = 10; for (Resource r : generateTestingResources(n)) { crawledResources.add(r); } TestJanitorCrawler crawler = new TestJanitorCrawler(crawledResources); // set some resources in the tracker as opted out Date now = new Date(DateTime.now().minusDays(1).getMillis()); Map<String, Resource> trackedResources = new HashMap<String, Resource>(); for (Resource r : generateTestingResources(n)) { int id = Integer.parseInt(r.getId()); if (id % 4 == 1 || id % 4 == 2) { r.setOptOutOfJanitor(true); r.setState(CleanupState.MARKED); r.setExpectedTerminationTime(now); r.setMarkTime(now); } trackedResources.put(r.getId(), r); } TestJanitorResourceTracker resourceTracker = new TestJanitorResourceTracker( trackedResources); TestAbstractJanitor janitor = new TestAbstractJanitor( new TestJanitorContext(TEST_REGION, new BasicJanitorRuleEngine().addRule(new IsEvenRule()), crawler, resourceTracker, new TestMonkeyCalendar()), TestResourceType.TEST_RESOURCE_TYPE); janitor.setLeashed(false); Assert.assertEquals( crawler.resources(TestResourceType.TEST_RESOURCE_TYPE).size(), 10); Assert.assertEquals(resourceTracker.getResources( TestResourceType.TEST_RESOURCE_TYPE, CleanupState.MARKED, TEST_REGION).size(), 6); // 1, 2, 5, 6, 9, 10 are marked Assert.assertEquals(janitor.markedResourceIds.size(), 0); janitor.markResources(); Assert.assertEquals(resourceTracker.getResources( TestResourceType.TEST_RESOURCE_TYPE, CleanupState.MARKED, TEST_REGION).size(), 5); // 1, 3, 5, 7, 9 are marked Assert.assertEquals(janitor.getMarkedResources().size(), 2); // 3, 7 are newly marked. Assert.assertEquals(janitor.markedResourceIds.size(), 2); Assert.assertEquals(janitor.cleanedResourceIds.size(), 0); Assert.assertEquals(resourceTracker.getResources( TestResourceType.TEST_RESOURCE_TYPE, CleanupState.MARKED, TEST_REGION).size(), 5); // 1, 3, 5, 7, 9 are marked Assert.assertEquals(janitor.getUnmarkedResources().size(), 3); // 2, 6, 10 got unmarked Assert.assertEquals(resourceTracker.getResources( TestResourceType.TEST_RESOURCE_TYPE, CleanupState.UNMARKED, TEST_REGION).size(), 3); janitor.cleanupResources(); Assert.assertEquals(janitor.getCleanedResources().size(), 2); // 3, 7 are cleaned Assert.assertEquals(janitor.getFailedToCleanResources().size(), 0); Assert.assertEquals(resourceTracker.getResources( TestResourceType.TEST_RESOURCE_TYPE, CleanupState.JANITOR_TERMINATED, TEST_REGION).size(), 2); Assert.assertEquals(janitor.getResourcesCleanedCount(), janitor.cleanedResourceIds.size()); Assert.assertEquals(janitor.getMarkedResourcesCount(), janitor.markedResourceIds.size()); Assert.assertEquals(janitor.getFailedToCleanResourcesCount(), 0); Assert.assertEquals(janitor.getUnmarkedResourcesCount(), 3); } @Test public static void testJanitorWithCleanupFailure() { Collection<Resource> crawledResources = new ArrayList<Resource>(); int n = 20; for (Resource r : generateTestingResources(n)) { crawledResources.add(r); } TestJanitorCrawler crawler = new TestJanitorCrawler(crawledResources); TestAbstractJanitor janitor = new TestAbstractJanitor( new TestJanitorContext(TEST_REGION, new BasicJanitorRuleEngine().addRule(new IsEvenRule()), crawler, new TestJanitorResourceTracker(new HashMap<String, Resource>()), new TestMonkeyCalendar()), TestResourceType.TEST_RESOURCE_TYPE); janitor.setLeashed(false); Assert.assertEquals( crawler.resources(TestResourceType.TEST_RESOURCE_TYPE).size(), n); janitor.markResources(); Assert.assertEquals(janitor.getMarkedResources().size(), n / 2); janitor.cleanupResources(); Assert.assertEquals(janitor.getCleanedResources().size(), n / 2 - 1); Assert.assertEquals(janitor.getFailedToCleanResources().size(), 1); Assert.assertEquals(janitor.getResourcesCleanedCount(), janitor.cleanedResourceIds.size()); Assert.assertEquals(janitor.getMarkedResourcesCount(), janitor.markedResourceIds.size()); Assert.assertEquals(janitor.getFailedToCleanResourcesCount(), 1); } private static TestAbstractJanitor getJanitor(int numberOfCrawledResources, boolean leashed) { TestJanitorCrawler crawler = new TestJanitorCrawler(generateTestingResources(numberOfCrawledResources)); JanitorRuleEngine rulesEngine = new BasicJanitorRuleEngine().addRule(new IsEvenRule()); JanitorResourceTracker resourceTracker = new TestJanitorResourceTracker(new HashMap<>()); TestJanitorContext janitorContext = new TestJanitorContext(TEST_REGION, rulesEngine, crawler, resourceTracker, new TestMonkeyCalendar()); TestAbstractJanitor janitor = new TestAbstractJanitor(janitorContext, TestResourceType.TEST_RESOURCE_TYPE); janitor.setLeashed(leashed); return janitor; } @Test public static void testCleanupDryRunOnWithJanitorOnLeashWithAFailure() { int n = 20; TestAbstractJanitor janitor = getJanitor(n, true); janitor.markResources(); Assert.assertEquals(janitor.getMarkedResources().size(), n / 2); janitor.cleanupResources(); Assert.assertEquals(janitor.getCleanedResources().size(), 0); Assert.assertEquals(janitor.getFailedToCleanResources().size(), 0); Assert.assertEquals(janitor.getResourcesCleanedCount(), 0); Assert.assertEquals(janitor.getFailedToCleanResourcesCount(), 0); Assert.assertEquals(janitor.getCleanupDryRunFailureCount().getValue().intValue(), 1); } @Test public static void testJanitorWithUnmarking() { Collection<Resource> crawledResources = new ArrayList<Resource>(); Map<String, Resource> trackedResources = new HashMap<String, Resource>(); int n = 10; DateTime now = DateTime.now(); Date markTime = new Date(now.minusDays(5).getMillis()); Date notifyTime = new Date(now.minusDays(4).getMillis()); Date terminationTime = new Date(now.minusDays(1).getMillis()); for (Resource r : generateTestingResources(n)) { if (Integer.parseInt(r.getId()) % 3 == 0) { trackedResources.put(r.getId(), r); r.setState(CleanupState.MARKED); r.setMarkTime(markTime); r.setExpectedTerminationTime(terminationTime); r.setNotificationTime(notifyTime); } } for (Resource r : generateTestingResources(n)) { crawledResources.add(r); } TestJanitorCrawler crawler = new TestJanitorCrawler(crawledResources); TestJanitorResourceTracker resourceTracker = new TestJanitorResourceTracker(trackedResources); TestAbstractJanitor janitor = new TestAbstractJanitor( new TestJanitorContext(TEST_REGION, new BasicJanitorRuleEngine().addRule(new IsEvenRule()), crawler, resourceTracker, new TestMonkeyCalendar()), TestResourceType.TEST_RESOURCE_TYPE); janitor.setLeashed(false); Assert.assertEquals( crawler.resources(TestResourceType.TEST_RESOURCE_TYPE).size(), n); Assert.assertEquals(resourceTracker.getResources( TestResourceType.TEST_RESOURCE_TYPE, CleanupState.MARKED, TEST_REGION).size(), n / 3); janitor.markResources(); // (n/3-n/6) resources were already marked, so in the last run the marked resources // should be n/2 - n/3 + n/6. Assert.assertEquals(janitor.getMarkedResources().size(), n / 2 - n / 3 + n / 6); Assert.assertEquals(janitor.getUnmarkedResources().size(), n / 6); janitor.cleanupResources(); Assert.assertEquals(janitor.getCleanedResources().size(), n / 2); Assert.assertEquals(janitor.getFailedToCleanResources().size(), 0); Assert.assertEquals(janitor.getResourcesCleanedCount(), janitor.cleanedResourceIds.size()); Assert.assertEquals(janitor.getMarkedResourcesCount(), janitor.markedResourceIds.size()); Assert.assertEquals(janitor.getFailedToCleanResourcesCount(), 0); Assert.assertEquals(janitor.getUnmarkedResourcesCount(), n/6); } @Test public static void testJanitorWithFutureTerminationTime() { Collection<Resource> crawledResources = new ArrayList<Resource>(); Map<String, Resource> trackedResources = new HashMap<String, Resource>(); int n = 10; DateTime now = DateTime.now(); Date markTime = new Date(now.minusDays(5).getMillis()); Date notifyTime = new Date(now.minusDays(4).getMillis()); Date terminationTime = new Date(now.plusDays(10).getMillis()); for (Resource r : generateTestingResources(n)) { trackedResources.put(r.getId(), r); r.setState(CleanupState.MARKED); r.setNotificationTime(notifyTime); r.setMarkTime(markTime); r.setExpectedTerminationTime(terminationTime); } for (Resource r : generateTestingResources(n)) { crawledResources.add(r); } TestJanitorCrawler crawler = new TestJanitorCrawler(crawledResources); TestJanitorResourceTracker resourceTracker = new TestJanitorResourceTracker(trackedResources); TestAbstractJanitor janitor = new TestAbstractJanitor( new TestJanitorContext(TEST_REGION, new BasicJanitorRuleEngine().addRule(new IsEvenRule()), crawler, resourceTracker, new TestMonkeyCalendar()), TestResourceType.TEST_RESOURCE_TYPE); janitor.setLeashed(false); Assert.assertEquals(resourceTracker.getResources( TestResourceType.TEST_RESOURCE_TYPE, CleanupState.MARKED, TEST_REGION).size(), n); janitor.cleanupResources(); Assert.assertEquals(janitor.getCleanedResources().size(), 0); Assert.assertEquals(janitor.getFailedToCleanResources().size(), 0); Assert.assertEquals(janitor.getResourcesCleanedCount(), janitor.cleanedResourceIds.size()); Assert.assertEquals(janitor.getMarkedResourcesCount(), janitor.markedResourceIds.size()); Assert.assertEquals(janitor.getFailedToCleanResourcesCount(), 0); } @Test public static void testJanitorWithoutNotification() { Collection<Resource> crawledResources = new ArrayList<Resource>(); Map<String, Resource> trackedResources = new HashMap<String, Resource>(); int n = 10; for (Resource r : generateTestingResources(n)) { trackedResources.put(r.getId(), r); r.setState(CleanupState.MARKED); // The marking/cleanup is not notified so we the Janitor won't clean it up. // r.setNotificationTime(new Date()); r.setMarkTime(new Date()); r.setExpectedTerminationTime(new Date(DateTime.now().plusDays(10).getMillis())); } for (Resource r : generateTestingResources(n)) { crawledResources.add(r); } TestJanitorCrawler crawler = new TestJanitorCrawler(crawledResources); TestJanitorResourceTracker resourceTracker = new TestJanitorResourceTracker(trackedResources); TestAbstractJanitor janitor = new TestAbstractJanitor( new TestJanitorContext(TEST_REGION, new BasicJanitorRuleEngine().addRule(new IsEvenRule()), crawler, resourceTracker, new TestMonkeyCalendar()), TestResourceType.TEST_RESOURCE_TYPE); janitor.setLeashed(false); Assert.assertEquals(resourceTracker.getResources( TestResourceType.TEST_RESOURCE_TYPE, CleanupState.MARKED, TEST_REGION).size(), n); janitor.cleanupResources(); Assert.assertEquals(janitor.getCleanedResources().size(), 0); Assert.assertEquals(janitor.getFailedToCleanResources().size(), 0); Assert.assertEquals(janitor.getResourcesCleanedCount(), janitor.cleanedResourceIds.size()); Assert.assertEquals(janitor.getMarkedResourcesCount(), janitor.markedResourceIds.size()); Assert.assertEquals(janitor.getFailedToCleanResourcesCount(), 0); } @Test public static void testLeashedJanitorForMarking() { Collection<Resource> crawledResources = new ArrayList<Resource>(); int n = 10; for (Resource r : generateTestingResources(n)) { crawledResources.add(r); } TestJanitorCrawler crawler = new TestJanitorCrawler(crawledResources); TestJanitorResourceTracker resourceTracker = new TestJanitorResourceTracker( new HashMap<String, Resource>()); TestAbstractJanitor janitor = new TestAbstractJanitor( new TestJanitorContext(TEST_REGION, new BasicJanitorRuleEngine().addRule(new IsEvenRule()), crawler, resourceTracker, new TestMonkeyCalendar()), TestResourceType.TEST_RESOURCE_TYPE); janitor.setLeashed(true); Assert.assertEquals( crawler.resources(TestResourceType.TEST_RESOURCE_TYPE).size(), n); janitor.markResources(); Assert.assertEquals(janitor.getMarkedResources().size(), n / 2); Assert.assertEquals(janitor.getResourcesCleanedCount(), janitor.cleanedResourceIds.size()); Assert.assertEquals(janitor.getMarkedResourcesCount(), n / 2); } @Test public static void testJanitorWithoutHoldingOffCleanup() { Collection<Resource> crawledResources = new ArrayList<Resource>(); int n = 10; for (Resource r : generateTestingResources(n)) { crawledResources.add(r); } TestJanitorCrawler crawler = new TestJanitorCrawler(crawledResources); TestJanitorResourceTracker resourceTracker = new TestJanitorResourceTracker(new HashMap<String, Resource>()); DateTime now = DateTime.now(); TestAbstractJanitor janitor = new TestAbstractJanitor( new TestJanitorContext(TEST_REGION, new BasicJanitorRuleEngine().addRule(new ImmediateCleanupRule(now)), crawler, resourceTracker, new TestMonkeyCalendar()), TestResourceType.TEST_RESOURCE_TYPE); janitor.setLeashed(false); Assert.assertEquals( crawler.resources(TestResourceType.TEST_RESOURCE_TYPE).size(), n); Assert.assertEquals(janitor.markedResourceIds.size(), 0); janitor.markResources(); Assert.assertEquals(janitor.getMarkedResources().size(), n); Assert.assertEquals(janitor.markedResourceIds.size(), n); for (int i = 1; i <= n; i++) { Assert.assertTrue(janitor.markedResourceIds.contains(String.valueOf(i))); } Assert.assertEquals(janitor.cleanedResourceIds.size(), 0); janitor.cleanupResources(); // No resource is cleaned since the notification is later than expected termination time. Assert.assertEquals(janitor.getCleanedResources().size(), n); Assert.assertEquals(janitor.getFailedToCleanResources().size(), 0); Assert.assertEquals(resourceTracker.getResources( TestResourceType.TEST_RESOURCE_TYPE, CleanupState.JANITOR_TERMINATED, TEST_REGION).size(), n); Assert.assertEquals(janitor.cleanedResourceIds.size(), n); Assert.assertEquals(janitor.getResourcesCleanedCount(), janitor.cleanedResourceIds.size()); Assert.assertEquals(janitor.getMarkedResourcesCount(), janitor.markedResourceIds.size()); Assert.assertEquals(janitor.getFailedToCleanResourcesCount(), 0); } // @Test TODO: disable while debugging issues with this functionality public static void testJanitorWithUnmarkingUserTerminated() { Collection<Resource> crawledResources = new ArrayList<Resource>(); Map<String, Resource> trackedResources = new HashMap<String, Resource>(); int n = 10; DateTime now = DateTime.now(); Date markTime = new Date(now.minusDays(5).getMillis()); Date notifyTime = new Date(now.minusDays(4).getMillis()); Date terminationTime = new Date(now.minusDays(1).getMillis()); for (Resource r : generateTestingResources(n)) { if (Integer.parseInt(r.getId()) % 3 != 0) { crawledResources.add(r); } else { trackedResources.put(r.getId(), r); r.setState(CleanupState.MARKED); r.setMarkTime(markTime); r.setNotificationTime(notifyTime); r.setExpectedTerminationTime(terminationTime); } } TestJanitorCrawler crawler = new TestJanitorCrawler(crawledResources); TestJanitorResourceTracker resourceTracker = new TestJanitorResourceTracker(trackedResources); TestAbstractJanitor janitor = new TestAbstractJanitor( new TestJanitorContext(TEST_REGION, new BasicJanitorRuleEngine().addRule(new IsEvenRule()), crawler, resourceTracker, new TestMonkeyCalendar()), TestResourceType.TEST_RESOURCE_TYPE); janitor.setLeashed(false); Assert.assertEquals( crawler.resources(TestResourceType.TEST_RESOURCE_TYPE).size(), n - n / 3); Assert.assertEquals(resourceTracker.getResources( TestResourceType.TEST_RESOURCE_TYPE, CleanupState.MARKED, TEST_REGION).size(), n / 3); janitor.markResources(); // n/3 resources should be considered user terminated Assert.assertEquals(janitor.getMarkedResources().size(), n / 2 - n / 3 + n / 6); Assert.assertEquals(janitor.getUnmarkedResources().size(), n / 3); janitor.cleanupResources(); Assert.assertEquals(janitor.getCleanedResources().size(), n / 2 - n / 3 + n / 6); Assert.assertEquals(janitor.getFailedToCleanResources().size(), 0); Assert.assertEquals(janitor.getResourcesCleanedCount(), janitor.cleanedResourceIds.size()); Assert.assertEquals(janitor.getMarkedResourcesCount(), janitor.markedResourceIds.size()); Assert.assertEquals(janitor.getFailedToCleanResourcesCount(), 0); Assert.assertEquals(janitor.getUnmarkedResourcesCount(), n / 3); } } class TestJanitorCrawler implements JanitorCrawler { private final Collection<Resource> crawledResources; public Collection<Resource> getCrawledResources() { return crawledResources; } public TestJanitorCrawler(Collection<Resource> crawledResources) { this.crawledResources = crawledResources; } @Override public EnumSet<? extends ResourceType> resourceTypes() { return EnumSet.of(TestResourceType.TEST_RESOURCE_TYPE); } @Override public List<Resource> resources(ResourceType resourceType) { return new ArrayList<Resource>(crawledResources); } @Override public List<Resource> resources(String... resourceIds) { List<Resource> result = new ArrayList<Resource>(resourceIds.length); Set<String> idSet = new HashSet<String>(Arrays.asList(resourceIds)); for (Resource r : crawledResources) { if (idSet.contains(r.getId())) { result.add(r); } } return result; } @Override public String getOwnerEmailForResource(Resource resource) { return null; } } enum TestResourceType implements ResourceType { TEST_RESOURCE_TYPE } class TestJanitorResourceTracker implements JanitorResourceTracker { private final Map<String, Resource> resources; public TestJanitorResourceTracker(Map<String, Resource> trackedResources) { this.resources = trackedResources; } @Override public void addOrUpdate(Resource resource) { resources.put(resource.getId(), resource); } @Override public List<Resource> getResources(ResourceType resourceType, CleanupState state, String region) { List<Resource> result = new ArrayList<Resource>(); for (Resource r : resources.values()) { if (r.getResourceType().equals(resourceType) && (r.getState() != null && r.getState().equals(state)) && r.getRegion().equals(region)) { result.add(r.cloneResource()); } } return result; } @Override public Resource getResource(String resourceId) { return resources.get(resourceId); } @Override public Resource getResource(String resourceId, String region) { return resources.get(resourceId); } } /** * The rule considers all resources with an odd number as the id as cleanup candidate. */ class IsEvenRule implements Rule { @Override public boolean isValid(Resource resource) { // returns true if the resource's id is an even integer int id; try { id = Integer.parseInt(resource.getId()); } catch (Exception e) { return true; } DateTime now = DateTime.now(); resource.setExpectedTerminationTime(new Date(now.minusDays(1).getMillis())); // Set the resource as notified so it can be cleaned // set the notification time at more than 1 day before the termination time resource.setNotificationTime(new Date(now.minusDays(4).getMillis())); return id % 2 == 0; } } /** * The rule considers all resources as cleanup candidate and sets notification time * after the termination time. */ class ImmediateCleanupRule implements Rule { private final DateTime now; public ImmediateCleanupRule(DateTime now) { this.now = now; } @Override public boolean isValid(Resource resource) { resource.setExpectedTerminationTime(new Date(now.minusMinutes(10).getMillis())); resource.setNotificationTime(new Date(now.getMillis()-5000)); return false; } } class TestJanitorContext implements AbstractJanitor.Context { private final String region; private final JanitorRuleEngine ruleEngine; private final JanitorCrawler crawler; private final JanitorResourceTracker resourceTracker; private final MonkeyCalendar calendar; public TestJanitorContext(String region, JanitorRuleEngine ruleEngine, JanitorCrawler crawler, JanitorResourceTracker resourceTracker, MonkeyCalendar calendar) { this.region = region; this.resourceTracker = resourceTracker; this.ruleEngine = ruleEngine; this.crawler = crawler; this.calendar = calendar; } @Override public String region() { return region; } @Override public MonkeyCalendar calendar() { return calendar; } @Override public JanitorRuleEngine janitorRuleEngine() { return ruleEngine; } @Override public JanitorCrawler janitorCrawler() { return crawler; } @Override public JanitorResourceTracker janitorResourceTracker() { return resourceTracker; } @Override public MonkeyConfiguration configuration() { return new BasicConfiguration(new Properties()); } @Override public MonkeyRecorder recorder() { // No events to be recorded return null; } }
4,719
0
Create_ds/SimianArmy/src/test/java/com/netflix/simianarmy
Create_ds/SimianArmy/src/test/java/com/netflix/simianarmy/aws/TestRDSRecorder.java
/* * * Copyright 2012 Netflix, Inc. * * Licensed 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. * */ // CHECKSTYLE IGNORE Javadoc package com.netflix.simianarmy.aws; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import org.mockito.ArgumentCaptor; import org.mockito.ArgumentMatcher; import org.mockito.Matchers; import org.mockito.Mockito; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.core.RowMapper; import org.testng.Assert; import org.testng.annotations.Test; import com.netflix.simianarmy.EventType; import com.netflix.simianarmy.MonkeyType; import com.netflix.simianarmy.basic.BasicRecorderEvent; // CHECKSTYLE IGNORE MagicNumberCheck public class TestRDSRecorder extends RDSRecorder { private static final String REGION = "us-west-1"; public TestRDSRecorder() { super(mock(JdbcTemplate.class), "recordertable", REGION); } public enum Type implements MonkeyType { MONKEY } public enum EventTypes implements EventType { EVENT } @Test public void testInit() { TestRDSRecorder recorder = new TestRDSRecorder(); ArgumentCaptor<String> sqlCap = ArgumentCaptor.forClass(String.class); Mockito.doNothing().when(recorder.getJdbcTemplate()).execute(sqlCap.capture()); recorder.init(); Assert.assertEquals(sqlCap.getValue(), "create table if not exists recordertable ( eventId varchar(255), eventTime BIGINT, monkeyType varchar(255), eventType varchar(255), region varchar(255), dataJson varchar(4096) )"); } @SuppressWarnings("unchecked") @Test public void testInsertNewRecordEvent() { // mock the select query that is issued to see if the record already exists ArrayList<Event> events = new ArrayList<>(); TestRDSRecorder recorder = new TestRDSRecorder(); when(recorder.getJdbcTemplate().query(Matchers.anyString(), Matchers.any(Object[].class), Matchers.any(RowMapper.class))).thenReturn(events); Event evt = newEvent(Type.MONKEY, EventTypes.EVENT, "region", "testId"); evt.addField("field1", "value1"); evt.addField("field2", "value2"); // this will be ignored as it conflicts with reserved key evt.addField("id", "ignoreThis"); ArgumentCaptor<Object> objCap = ArgumentCaptor.forClass(Object.class); ArgumentCaptor<String> sqlCap = ArgumentCaptor.forClass(String.class); when(recorder.getJdbcTemplate().update(sqlCap.capture(), objCap.capture(), objCap.capture(), objCap.capture(), objCap.capture(), objCap.capture(), objCap.capture())).thenReturn(1); recorder.recordEvent(evt); List<Object> args = objCap.getAllValues(); Assert.assertEquals(sqlCap.getValue(), "insert into recordertable (eventId,eventTime,monkeyType,eventType,region,dataJson) values (?,?,?,?,?,?)"); Assert.assertEquals(args.size(), 6); Assert.assertEquals(args.get(0).toString(), evt.id()); Assert.assertEquals(args.get(1).toString(), evt.eventTime().getTime() + ""); Assert.assertEquals(args.get(2).toString(), SimpleDBRecorder.enumToValue(evt.monkeyType())); Assert.assertEquals(args.get(3).toString(), SimpleDBRecorder.enumToValue(evt.eventType())); Assert.assertEquals(args.get(4).toString(), evt.region()); } private Event mkSelectResult(String id, Event evt) { evt.addField("field1", "value1"); evt.addField("field2", "value2"); return evt; } @SuppressWarnings("unchecked") @Test public void testFindEvent() { Event evt1 = new BasicRecorderEvent(Type.MONKEY, EventTypes.EVENT, "region", "testId1", 1330538400000L); mkSelectResult("testId1", evt1); Event evt2 = new BasicRecorderEvent(Type.MONKEY, EventTypes.EVENT, "region", "testId2", 1330538400000L); mkSelectResult("testId2", evt2); ArrayList<Event> events = new ArrayList<>(); TestRDSRecorder recorder = new TestRDSRecorder(); events.add(evt1); events.add(evt2); when(recorder.getJdbcTemplate().query(Matchers.anyString(), Matchers.argThat(new ArgumentMatcher<Object []>(){ @Override public boolean matches(Object argument) { Object [] args = (Object [])argument; Assert.assertTrue(args[0] instanceof String); Assert.assertEquals((String)args[0],REGION); return true; } }), Matchers.any(RowMapper.class))).thenReturn(events); Map<String, String> query = new LinkedHashMap<String, String>(); query.put("instanceId", "testId1"); verifyEvents(recorder.findEvents(query, new Date(0))); } void verifyEvents(List<Event> events) { Assert.assertEquals(events.size(), 2); Assert.assertEquals(events.get(0).id(), "testId1"); Assert.assertEquals(events.get(0).eventTime().getTime(), 1330538400000L); Assert.assertEquals(events.get(0).monkeyType(), Type.MONKEY); Assert.assertEquals(events.get(0).eventType(), EventTypes.EVENT); Assert.assertEquals(events.get(0).field("field1"), "value1"); Assert.assertEquals(events.get(0).field("field2"), "value2"); Assert.assertEquals(events.get(0).fields().size(), 2); Assert.assertEquals(events.get(1).id(), "testId2"); Assert.assertEquals(events.get(1).eventTime().getTime(), 1330538400000L); Assert.assertEquals(events.get(1).monkeyType(), Type.MONKEY); Assert.assertEquals(events.get(1).eventType(), EventTypes.EVENT); Assert.assertEquals(events.get(1).field("field1"), "value1"); Assert.assertEquals(events.get(1).field("field2"), "value2"); Assert.assertEquals(events.get(1).fields().size(), 2); } @SuppressWarnings("unchecked") @Test public void testFindEventNotFound() { ArrayList<Event> events = new ArrayList<>(); TestRDSRecorder recorder = new TestRDSRecorder(); when(recorder.getJdbcTemplate().query(Matchers.anyString(), Matchers.argThat(new ArgumentMatcher<Object []>(){ @Override public boolean matches(Object argument) { Object [] args = (Object [])argument; Assert.assertTrue(args[0] instanceof String); Assert.assertEquals((String)args[0],REGION); return true; } }), Matchers.any(RowMapper.class))).thenReturn(events); List<Event> results = recorder.findEvents(new HashMap<String, String>(), new Date()); Assert.assertEquals(results.size(), 0); } }
4,720
0
Create_ds/SimianArmy/src/test/java/com/netflix/simianarmy
Create_ds/SimianArmy/src/test/java/com/netflix/simianarmy/aws/TestSimpleDBRecorder.java
/* * * Copyright 2012 Netflix, Inc. * * Licensed 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. * */ // CHECKSTYLE IGNORE Javadoc package com.netflix.simianarmy.aws; import static org.mockito.Matchers.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import java.util.Arrays; import java.util.Date; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import org.mockito.ArgumentCaptor; import org.testng.Assert; import org.testng.annotations.Test; import com.amazonaws.services.simpledb.AmazonSimpleDB; import com.amazonaws.services.simpledb.model.Attribute; import com.amazonaws.services.simpledb.model.Item; import com.amazonaws.services.simpledb.model.PutAttributesRequest; import com.amazonaws.services.simpledb.model.ReplaceableAttribute; import com.amazonaws.services.simpledb.model.SelectRequest; import com.amazonaws.services.simpledb.model.SelectResult; import com.netflix.simianarmy.EventType; import com.netflix.simianarmy.MonkeyType; import com.netflix.simianarmy.client.aws.AWSClient; // CHECKSTYLE IGNORE MagicNumberCheck public class TestSimpleDBRecorder extends SimpleDBRecorder { private static AWSClient makeMockAWSClient() { AmazonSimpleDB sdbMock = mock(AmazonSimpleDB.class); AWSClient awsClient = mock(AWSClient.class); when(awsClient.sdbClient()).thenReturn(sdbMock); when(awsClient.region()).thenReturn("region"); return awsClient; } public TestSimpleDBRecorder() { super(makeMockAWSClient(), "DOMAIN"); sdbMock = super.sdbClient(); } private final AmazonSimpleDB sdbMock; @Override protected AmazonSimpleDB sdbClient() { return sdbMock; } protected AmazonSimpleDB superSdbClient() { return super.sdbClient(); } @Test public void testClients() { TestSimpleDBRecorder recorder1 = new TestSimpleDBRecorder(); Assert.assertNotNull(recorder1.superSdbClient(), "non null super sdbClient"); TestSimpleDBRecorder recorder2 = new TestSimpleDBRecorder(); Assert.assertNotNull(recorder2.superSdbClient(), "non null super sdbClient"); } public enum Type implements MonkeyType { MONKEY } public enum EventTypes implements EventType { EVENT } @Test public void testRecordEvent() { ArgumentCaptor<PutAttributesRequest> arg = ArgumentCaptor.forClass(PutAttributesRequest.class); Event evt = newEvent(Type.MONKEY, EventTypes.EVENT, "region", "testId"); evt.addField("field1", "value1"); evt.addField("field2", "value2"); // this will be ignored as it conflicts with reserved key evt.addField("id", "ignoreThis"); recordEvent(evt); verify(sdbMock).putAttributes(arg.capture()); PutAttributesRequest req = arg.getValue(); Assert.assertEquals(req.getDomainName(), "DOMAIN"); Assert.assertEquals(req.getItemName(), "MONKEY-testId-region-" + evt.eventTime().getTime()); Map<String, String> map = new HashMap<String, String>(); for (ReplaceableAttribute attr : req.getAttributes()) { map.put(attr.getName(), attr.getValue()); } Assert.assertEquals(map.remove("id"), "testId"); Assert.assertEquals(map.remove("eventTime"), String.valueOf(evt.eventTime().getTime())); Assert.assertEquals(map.remove("region"), "region"); Assert.assertEquals(map.remove("recordType"), "MonkeyEvent"); Assert.assertEquals(map.remove("monkeyType"), "MONKEY|com.netflix.simianarmy.aws.TestSimpleDBRecorder$Type"); Assert.assertEquals(map.remove("eventType"), "EVENT|com.netflix.simianarmy.aws.TestSimpleDBRecorder$EventTypes"); Assert.assertEquals(map.remove("field1"), "value1"); Assert.assertEquals(map.remove("field2"), "value2"); Assert.assertEquals(map.size(), 0); } private SelectResult mkSelectResult(String id) { Item item = new Item(); List<Attribute> attrs = new LinkedList<Attribute>(); attrs.add(new Attribute("id", id)); attrs.add(new Attribute("eventTime", "1330538400000")); attrs.add(new Attribute("region", "region")); attrs.add(new Attribute("recordType", "MonkeyEvent")); attrs.add(new Attribute("monkeyType", "MONKEY|com.netflix.simianarmy.aws.TestSimpleDBRecorder$Type")); attrs.add(new Attribute("eventType", "EVENT|com.netflix.simianarmy.aws.TestSimpleDBRecorder$EventTypes")); attrs.add(new Attribute("field1", "value1")); attrs.add(new Attribute("field2", "value2")); item.setAttributes(attrs); item.setName("MONKEY-" + id + "-region"); SelectResult result = new SelectResult(); result.setItems(Arrays.asList(item)); return result; } @Test public void testFindEvent() { SelectResult result1 = mkSelectResult("testId1"); result1.setNextToken("nextToken"); SelectResult result2 = mkSelectResult("testId2"); ArgumentCaptor<SelectRequest> arg = ArgumentCaptor.forClass(SelectRequest.class); when(sdbMock.select(any(SelectRequest.class))).thenReturn(result1).thenReturn(result2); Map<String, String> query = new LinkedHashMap<String, String>(); query.put("instanceId", "testId1"); verifyEvents(findEvents(query, new Date(0))); verify(sdbMock, times(2)).select(arg.capture()); SelectRequest req = arg.getValue(); StringBuilder sb = new StringBuilder(); sb.append("select * from `DOMAIN` where region = 'region'"); sb.append(" and instanceId = 'testId1'"); Assert.assertEquals(req.getSelectExpression(), sb.toString() + " and eventTime > '0' order by eventTime desc"); // reset for next test when(sdbMock.select(any(SelectRequest.class))).thenReturn(result1).thenReturn(result2); verifyEvents(findEvents(Type.MONKEY, query, new Date(0))); verify(sdbMock, times(4)).select(arg.capture()); req = arg.getValue(); sb.append(" and monkeyType = 'MONKEY|com.netflix.simianarmy.aws.TestSimpleDBRecorder$Type'"); Assert.assertEquals(req.getSelectExpression(), sb.toString() + " and eventTime > '0' order by eventTime desc"); // reset for next test when(sdbMock.select(any(SelectRequest.class))).thenReturn(result1).thenReturn(result2); verifyEvents(findEvents(Type.MONKEY, EventTypes.EVENT, query, new Date(0))); verify(sdbMock, times(6)).select(arg.capture()); req = arg.getValue(); sb.append(" and eventType = 'EVENT|com.netflix.simianarmy.aws.TestSimpleDBRecorder$EventTypes'"); Assert.assertEquals(req.getSelectExpression(), sb.toString() + " and eventTime > '0' order by eventTime desc"); // reset for next test when(sdbMock.select(any(SelectRequest.class))).thenReturn(result1).thenReturn(result2); verifyEvents(findEvents(Type.MONKEY, EventTypes.EVENT, query, new Date(1330538400000L))); verify(sdbMock, times(8)).select(arg.capture()); req = arg.getValue(); sb.append(" and eventTime > '1330538400000' order by eventTime desc"); Assert.assertEquals(req.getSelectExpression(), sb.toString()); } void verifyEvents(List<Event> events) { Assert.assertEquals(events.size(), 2); Assert.assertEquals(events.get(0).id(), "testId1"); Assert.assertEquals(events.get(0).eventTime().getTime(), 1330538400000L); Assert.assertEquals(events.get(0).monkeyType(), Type.MONKEY); Assert.assertEquals(events.get(0).eventType(), EventTypes.EVENT); Assert.assertEquals(events.get(0).field("field1"), "value1"); Assert.assertEquals(events.get(0).field("field2"), "value2"); Assert.assertEquals(events.get(0).fields().size(), 2); Assert.assertEquals(events.get(1).id(), "testId2"); Assert.assertEquals(events.get(1).eventTime().getTime(), 1330538400000L); Assert.assertEquals(events.get(1).monkeyType(), Type.MONKEY); Assert.assertEquals(events.get(1).eventType(), EventTypes.EVENT); Assert.assertEquals(events.get(1).field("field1"), "value1"); Assert.assertEquals(events.get(1).field("field2"), "value2"); Assert.assertEquals(events.get(1).fields().size(), 2); } }
4,721
0
Create_ds/SimianArmy/src/test/java/com/netflix/simianarmy
Create_ds/SimianArmy/src/test/java/com/netflix/simianarmy/aws/TestAWSEmailNotifier.java
/* * * Copyright 2012 Netflix, Inc. * * Licensed 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 com.netflix.simianarmy.aws; import org.testng.Assert; import org.testng.annotations.Test; // CHECKSTYLE IGNORE MagicNumberCheck public class TestAWSEmailNotifier extends AWSEmailNotifier { public TestAWSEmailNotifier() { super(null); } @Override public String buildEmailSubject(String to) { return null; } @Override public String[] getCcAddresses(String to) { return new String[0]; } @Override public String getSourceAddress(String to) { return null; } @Test public void testEmailWithHashIsValid() { TestAWSEmailNotifier emailNotifier = new TestAWSEmailNotifier(); Assert.assertTrue(emailNotifier.isValidEmail("#bla-#name@domain-test.com"), "Email with hash is not valid"); } }
4,722
0
Create_ds/SimianArmy/src/test/java/com/netflix/simianarmy/aws
Create_ds/SimianArmy/src/test/java/com/netflix/simianarmy/aws/conformity/TestASGOwnerEmailTag.java
/* * * Copyright 2012 Netflix, Inc. * * Licensed 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. * */ // CHECKSTYLE IGNORE Javadoc package com.netflix.simianarmy.aws.conformity; import com.amazonaws.services.autoscaling.model.AutoScalingGroup; import com.amazonaws.services.autoscaling.model.TagDescription; import com.google.common.collect.Maps; import com.netflix.simianarmy.aws.conformity.crawler.AWSClusterCrawler; import com.netflix.simianarmy.basic.BasicConfiguration; import com.netflix.simianarmy.basic.conformity.BasicConformityMonkeyContext; import com.netflix.simianarmy.client.aws.AWSClient; import com.netflix.simianarmy.conformity.Cluster; import junit.framework.Assert; import org.testng.annotations.Test; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Properties; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; public class TestASGOwnerEmailTag { private static final String ASG1 = "asg1"; private static final String ASG2 = "asg2"; private static final String OWNER_TAG_KEY = "owner"; private static final String OWNER_TAG_VALUE = "tyler@paperstreet.com"; private static final String REGION = "eu-west-1"; @Test public void testForOwnerTag() { Properties properties = new Properties(); BasicConformityMonkeyContext ctx = new BasicConformityMonkeyContext(); List<AutoScalingGroup> asgList = createASGList(); String[] asgNames = {ASG1, ASG2}; AWSClient awsMock = createMockAWSClient(asgList, asgNames); Map<String, AWSClient> regionToAwsClient = Maps.newHashMap(); regionToAwsClient.put("us-east-1", awsMock); AWSClusterCrawler clusterCrawler = new AWSClusterCrawler(regionToAwsClient, new BasicConfiguration(properties)); List<Cluster> clusters = clusterCrawler.clusters(asgNames); Assert.assertTrue(OWNER_TAG_VALUE.equalsIgnoreCase(clusters.get(0).getOwnerEmail())); Assert.assertNull(clusters.get(1).getOwnerEmail()); } private List<AutoScalingGroup> createASGList() { List<AutoScalingGroup> asgList = new LinkedList<AutoScalingGroup>(); asgList.add(makeASG(ASG1, OWNER_TAG_VALUE)); asgList.add(makeASG(ASG2, null)); return asgList; } private AutoScalingGroup makeASG(String asgName, String ownerEmail) { TagDescription tag = new TagDescription().withKey(OWNER_TAG_KEY).withValue(ownerEmail); AutoScalingGroup asg = new AutoScalingGroup() .withAutoScalingGroupName(asgName) .withTags(tag); return asg; } private AWSClient createMockAWSClient(List<AutoScalingGroup> asgList, String... asgNames) { AWSClient awsMock = mock(AWSClient.class); when(awsMock.describeAutoScalingGroups(asgNames)).thenReturn(asgList); return awsMock; } }
4,723
0
Create_ds/SimianArmy/src/test/java/com/netflix/simianarmy/aws
Create_ds/SimianArmy/src/test/java/com/netflix/simianarmy/aws/conformity/TestRDSConformityClusterTracker.java
/* * * Copyright 2012 Netflix, Inc. * * Licensed 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. * */ // CHECKSTYLE IGNORE Javadoc // CHECKSTYLE IGNORE MagicNumberCheck // CHECKSTYLE IGNORE ParameterNumber package com.netflix.simianarmy.aws.conformity; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import java.util.ArrayList; import java.util.Date; import java.util.List; import org.mockito.ArgumentCaptor; import org.mockito.Matchers; import org.mockito.Mockito; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.core.RowMapper; import org.testng.Assert; import org.testng.annotations.Test; import com.netflix.simianarmy.conformity.Cluster; import com.netflix.simianarmy.conformity.Conformity; public class TestRDSConformityClusterTracker extends RDSConformityClusterTracker { public TestRDSConformityClusterTracker() { super(mock(JdbcTemplate.class), "conformitytable"); } @Test public void testInit() { TestRDSConformityClusterTracker recorder = new TestRDSConformityClusterTracker(); ArgumentCaptor<String> sqlCap = ArgumentCaptor.forClass(String.class); Mockito.doNothing().when(recorder.getJdbcTemplate()).execute(sqlCap.capture()); recorder.init(); Assert.assertEquals(sqlCap.getValue(), "create table if not exists conformitytable ( cluster varchar(255), region varchar(25), ownerEmail varchar(255), isConforming varchar(10), isOptedOut varchar(10), updateTimestamp BIGINT, excludedRules varchar(4096), conformities varchar(4096), conformityRules varchar(4096) )"); } @SuppressWarnings("unchecked") @Test public void testInsertNewCluster() { // mock the select query that is issued to see if the record already exists ArrayList<Cluster> clusters = new ArrayList<>(); TestRDSConformityClusterTracker tracker = new TestRDSConformityClusterTracker(); when(tracker.getJdbcTemplate().query(Matchers.anyString(), Matchers.any(Object[].class), Matchers.any(RowMapper.class))).thenReturn(clusters); Cluster cluster1 = new Cluster("clustername1", "us-west-1"); cluster1.setUpdateTime(new Date()); ArrayList<String> list = new ArrayList<>(); list.add("one"); list.add("two"); cluster1.updateConformity(new Conformity("rule1",list)); list.add("three"); cluster1.updateConformity(new Conformity("rule2",list)); ArgumentCaptor<Object> objCap = ArgumentCaptor.forClass(Object.class); ArgumentCaptor<String> sqlCap = ArgumentCaptor.forClass(String.class); when(tracker.getJdbcTemplate().update(sqlCap.capture(), objCap.capture(), objCap.capture(), objCap.capture(), objCap.capture(), objCap.capture(), objCap.capture(), objCap.capture(), objCap.capture(), objCap.capture())).thenReturn(1); tracker.addOrUpdate(cluster1); List<Object> args = objCap.getAllValues(); Assert.assertEquals(args.size(), 9); Assert.assertEquals(args.get(0).toString(), "clustername1"); Assert.assertEquals(args.get(1).toString(), "us-west-1"); Assert.assertEquals(args.get(7).toString(), "{\"rule1\":\"one,two\",\"rule2\":\"one,two,three\"}"); Assert.assertEquals(args.get(8).toString(), "rule1,rule2"); } @SuppressWarnings("unchecked") @Test public void testUpdateCluster() { Cluster cluster1 = new Cluster("clustername1", "us-west-1"); Date date = new Date(); cluster1.setUpdateTime(date); // mock the select query that is issued to see if the record already exists ArrayList<Cluster> clusters = new ArrayList<>(); clusters.add(cluster1); TestRDSConformityClusterTracker tracker = new TestRDSConformityClusterTracker(); when(tracker.getJdbcTemplate().query(Matchers.anyString(), Matchers.any(Object[].class), Matchers.any(RowMapper.class))).thenReturn(clusters); cluster1.setOwnerEmail("newemail@test.com"); ArgumentCaptor<Object> objCap = ArgumentCaptor.forClass(Object.class); ArgumentCaptor<String> sqlCap = ArgumentCaptor.forClass(String.class); when(tracker.getJdbcTemplate().update(sqlCap.capture(), objCap.capture(), objCap.capture(), objCap.capture(), objCap.capture(), objCap.capture(), objCap.capture(), objCap.capture(), objCap.capture(), objCap.capture())).thenReturn(1); tracker.addOrUpdate(cluster1); List<Object> args = objCap.getAllValues(); Assert.assertEquals(sqlCap.getValue(), "update conformitytable set ownerEmail=?,isConforming=?,isOptedOut=?,updateTimestamp=?,excludedRules=?,conformities=?,conformityRules=? where cluster=? and region=?"); Assert.assertEquals(args.size(), 9); Assert.assertEquals(args.get(0).toString(), "newemail@test.com"); Assert.assertEquals(args.get(1).toString(), "false"); Assert.assertEquals(args.get(2).toString(), "false"); Assert.assertEquals(args.get(3).toString(), date.getTime() + ""); Assert.assertEquals(args.get(7).toString(), "clustername1"); Assert.assertEquals(args.get(8).toString(), "us-west-1"); } @SuppressWarnings("unchecked") @Test public void testGetCluster() { Cluster cluster1 = new Cluster("clustername1", "us-west-1"); ArrayList<Cluster> clusters = new ArrayList<>(); clusters.add(cluster1); TestRDSConformityClusterTracker tracker = new TestRDSConformityClusterTracker(); ArgumentCaptor<String> sqlCap = ArgumentCaptor.forClass(String.class); when(tracker.getJdbcTemplate().query(sqlCap.capture(), Matchers.any(Object[].class), Matchers.any(RowMapper.class))).thenReturn(clusters); Cluster result = tracker.getCluster("clustername1", "us-west-1"); Assert.assertNotNull(result); Assert.assertEquals(sqlCap.getValue(), "select * from conformitytable where cluster = ? and region = ?"); } @SuppressWarnings("unchecked") @Test public void testGetClusters() { Cluster cluster1 = new Cluster("clustername1", "us-west-1"); Cluster cluster2 = new Cluster("clustername1", "us-west-2"); Cluster cluster3 = new Cluster("clustername1", "us-east-1"); ArrayList<Cluster> clusters = new ArrayList<>(); clusters.add(cluster1); clusters.add(cluster2); clusters.add(cluster3); TestRDSConformityClusterTracker tracker = new TestRDSConformityClusterTracker(); ArgumentCaptor<String> sqlCap = ArgumentCaptor.forClass(String.class); when(tracker.getJdbcTemplate().query(sqlCap.capture(), Matchers.any(RowMapper.class))).thenReturn(clusters); List<Cluster> results = tracker.getAllClusters("us-west-1", "us-west-2", "us-east-1"); Assert.assertEquals(results.size(), 3); Assert.assertEquals(sqlCap.getValue().toString().trim(), "select * from conformitytable where cluster is not null and region in ('us-west-1','us-west-2','us-east-1')"); } @SuppressWarnings("unchecked") @Test public void testGetClusterNotFound() { ArrayList<Cluster> clusters = new ArrayList<>(); TestRDSConformityClusterTracker tracker = new TestRDSConformityClusterTracker(); when(tracker.getJdbcTemplate().query(Matchers.anyString(), Matchers.any(Object[].class), Matchers.any(RowMapper.class))).thenReturn(clusters); Cluster cluster = tracker.getCluster("clustername", "us-west-1"); Assert.assertNull(cluster); } }
4,724
0
Create_ds/SimianArmy/src/test/java/com/netflix/simianarmy/aws/conformity
Create_ds/SimianArmy/src/test/java/com/netflix/simianarmy/aws/conformity/rule/TestInstanceInVPC.java
/* * * Copyright 2013 Netflix, Inc. * * Licensed 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. * */ // CHECKSTYLE IGNORE Javadoc package com.netflix.simianarmy.aws.conformity.rule; import com.amazonaws.services.ec2.model.Instance; import com.google.common.collect.Lists; import com.google.common.collect.Sets; import com.netflix.simianarmy.conformity.AutoScalingGroup; import com.netflix.simianarmy.conformity.Cluster; import com.netflix.simianarmy.conformity.Conformity; import junit.framework.Assert; import org.mockito.MockitoAnnotations; import org.mockito.Spy; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; import java.util.List; import java.util.Set; import static org.mockito.Mockito.doReturn; public class TestInstanceInVPC { private static final String VPC_INSTANCE_ID = "abc-123"; private static final String INSTANCE_ID = "zxy-098"; private static final String REGION = "eu-west-1"; @Spy private InstanceInVPC instanceInVPC = new InstanceInVPC(); @BeforeMethod public void setUp() throws Exception { MockitoAnnotations.initMocks(this); List<Instance> instanceList = Lists.newArrayList(); Instance instance = new Instance().withInstanceId(VPC_INSTANCE_ID).withVpcId("12345"); instanceList.add(instance); doReturn(instanceList).when(instanceInVPC).getAWSInstances(REGION, VPC_INSTANCE_ID); List<Instance> instanceList2 = Lists.newArrayList(); Instance instance2 = new Instance().withInstanceId(INSTANCE_ID); instanceList2.add(instance2); doReturn(instanceList2).when(instanceInVPC).getAWSInstances(REGION, INSTANCE_ID); } @Test public void testCheckSoloInstances() throws Exception { Set<String> list = Sets.newHashSet(); list.add(VPC_INSTANCE_ID); list.add(INSTANCE_ID); Cluster cluster = new Cluster("SoloInstances", REGION, list); Conformity result = instanceInVPC.check(cluster); Assert.assertNotNull(result); Assert.assertEquals(result.getRuleId(), instanceInVPC.getName()); Assert.assertEquals(result.getFailedComponents().size(), 1); Assert.assertEquals(result.getFailedComponents().iterator().next(), INSTANCE_ID); } @Test public void testAsgInstances() throws Exception { AutoScalingGroup autoScalingGroup = new AutoScalingGroup("Conforming", VPC_INSTANCE_ID); Cluster conformingCluster = new Cluster("Conforming", REGION, autoScalingGroup); Conformity result = instanceInVPC.check(conformingCluster); Assert.assertNotNull(result); Assert.assertEquals(result.getRuleId(), instanceInVPC.getName()); Assert.assertEquals(result.getFailedComponents().size(), 0); autoScalingGroup = new AutoScalingGroup("NonConforming", INSTANCE_ID); Cluster nonConformingCluster = new Cluster("NonConforming", REGION, autoScalingGroup); result = instanceInVPC.check(nonConformingCluster); Assert.assertNotNull(result); Assert.assertEquals(result.getRuleId(), instanceInVPC.getName()); Assert.assertEquals(result.getFailedComponents().size(), 1); Assert.assertEquals(result.getFailedComponents().iterator().next(), INSTANCE_ID); } }
4,725
0
Create_ds/SimianArmy/src/test/java/com/netflix/simianarmy/aws
Create_ds/SimianArmy/src/test/java/com/netflix/simianarmy/aws/janitor/TestAWSResource.java
/* * * Copyright 2012 Netflix, Inc. * * Licensed 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. * */ // CHECKSTYLE IGNORE Javadoc // CHECKSTYLE IGNORE MagicNumberCheck package com.netflix.simianarmy.aws.janitor; import java.lang.reflect.Field; import java.util.Collection; import java.util.Date; import java.util.HashMap; import java.util.Map; import org.testng.Assert; import org.testng.annotations.Test; import com.netflix.simianarmy.Resource; import com.netflix.simianarmy.aws.AWSResource; import com.netflix.simianarmy.aws.AWSResourceType; public class TestAWSResource { /** Make sure the getFieldToValue returns the right field and values. * @throws Exception **/ @Test public void testFieldToValueMapWithoutNullForInstance() throws Exception { Date now = new Date(); Resource resource = getTestingResource(now); Map<String, String> resourceFieldValueMap = resource.getFieldToValueMap(); verifyMapsAreEqual(resourceFieldValueMap, getTestingFieldValueMap(now, getTestingFields())); } /** * When all fields are null, the map returned is empty. */ @Test public void testFieldToValueMapWithNull() { Resource resource = new AWSResource(); Map<String, String> resourceFieldValueMap = resource.getFieldToValueMap(); // The only value in the map is the boolean of opt out Assert.assertEquals(resourceFieldValueMap.size(), 1); } @Test public void testParseFieldToValueMap() throws Exception { Date now = new Date(); Map<String, String> map = getTestingFieldValueMap(now, getTestingFields()); AWSResource resource = AWSResource.parseFieldtoValueMap(map); Map<String, String> resourceFieldValueMap = resource.getFieldToValueMap(); verifyMapsAreEqual(resourceFieldValueMap, map); } @Test public void testClone() { Date now = new Date(); Resource resource = getTestingResource(now); Resource clone = resource.cloneResource(); verifyMapsAreEqual(clone.getFieldToValueMap(), resource.getFieldToValueMap()); verifyTagsAreEqual(clone, resource); } private void verifyMapsAreEqual(Map<String, String> map1, Map<String, String> map2) { Assert.assertFalse(map1 == null ^ map2 == null); Assert.assertEquals(map1.size(), map2.size()); for (Map.Entry<String, String> entry : map1.entrySet()) { Assert.assertEquals(entry.getValue(), map2.get(entry.getKey())); } } private void verifyTagsAreEqual(Resource r1, Resource r2) { Collection<String> keys1 = r1.getAllTagKeys(); Collection<String> keys2 = r2.getAllTagKeys(); Assert.assertEquals(keys1.size(), keys2.size()); for (String key : keys1) { Assert.assertEquals(r1.getTag(key), r2.getTag(key)); } } private Map<String, String> getTestingFieldValueMap(Date defaultDate, Map<String, String> additionalFields) throws Exception { Field[] fields = AWSResource.class.getFields(); Map<String, String> fieldToValue = new HashMap<String, String>(); String dateString = AWSResource.DATE_FORMATTER.print(defaultDate.getTime()); for (Field field : fields) { if (field.getName().startsWith("FIELD_")) { String value; String key = (String) (field.get(null)); if (field.getName().endsWith("TIME")) { value = dateString; } else if (field.getName().equals("FIELD_STATE")) { value = "MARKED"; } else if (field.getName().equals("FIELD_RESOURCE_TYPE")) { value = "INSTANCE"; } else if (field.getName().equals("FIELD_OPT_OUT_OF_JANITOR")) { value = "false"; } else { value = (String) (field.get(null)); } fieldToValue.put(key, value); } } if (additionalFields != null) { fieldToValue.putAll(additionalFields); } return fieldToValue; } private Resource getTestingResource(Date now) { String id = "resourceId"; Resource resource = new AWSResource().withId(id).withRegion("region").withResourceType(AWSResourceType.INSTANCE) .withState(Resource.CleanupState.MARKED).withDescription("description") .withExpectedTerminationTime(now).withActualTerminationTime(now) .withLaunchTime(now).withMarkTime(now).withNnotificationTime(now).withOwnerEmail("ownerEmail") .withTerminationReason("terminationReason").withOptOutOfJanitor(false); ((AWSResource) resource).setAWSResourceState("awsResourceState"); for (Map.Entry<String, String> field : getTestingFields().entrySet()) { resource.setAdditionalField(field.getKey(), field.getValue()); } for (int i = 1; i < 10; i++) { resource.setTag("tagKey_" + i, "tagValue_" + i); } return resource; } private Map<String, String> getTestingFields() { Map<String, String> map = new HashMap<String, String>(); for (int i = 0; i < 10; i++) { map.put("name" + i, "value" + i); } return map; } }
4,726
0
Create_ds/SimianArmy/src/test/java/com/netflix/simianarmy/aws
Create_ds/SimianArmy/src/test/java/com/netflix/simianarmy/aws/janitor/TestSimpleDBJanitorResourceTracker.java
/* * * Copyright 2012 Netflix, Inc. * * Licensed 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. * */ // CHECKSTYLE IGNORE Javadoc // CHECKSTYLE IGNORE MagicNumberCheck // CHECKSTYLE IGNORE ParameterNumber package com.netflix.simianarmy.aws.janitor; import static org.mockito.Matchers.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import java.util.Arrays; import java.util.Date; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import org.joda.time.DateTime; import org.mockito.ArgumentCaptor; import org.testng.Assert; import org.testng.annotations.Test; import com.amazonaws.services.simpledb.AmazonSimpleDB; import com.amazonaws.services.simpledb.model.Attribute; import com.amazonaws.services.simpledb.model.Item; import com.amazonaws.services.simpledb.model.PutAttributesRequest; import com.amazonaws.services.simpledb.model.ReplaceableAttribute; import com.amazonaws.services.simpledb.model.SelectRequest; import com.amazonaws.services.simpledb.model.SelectResult; import com.netflix.simianarmy.Resource; import com.netflix.simianarmy.aws.AWSResource; import com.netflix.simianarmy.aws.AWSResourceType; import com.netflix.simianarmy.client.aws.AWSClient; public class TestSimpleDBJanitorResourceTracker extends SimpleDBJanitorResourceTracker { private static AWSClient makeMockAWSClient() { AmazonSimpleDB sdbMock = mock(AmazonSimpleDB.class); AWSClient awsClient = mock(AWSClient.class); when(awsClient.sdbClient()).thenReturn(sdbMock); return awsClient; } public TestSimpleDBJanitorResourceTracker() { super(makeMockAWSClient(), "DOMAIN"); sdbMock = super.getSimpleDBClient(); } private final AmazonSimpleDB sdbMock; @Test public void testAddResource() { String id = "i-12345678901234567"; AWSResourceType resourceType = AWSResourceType.INSTANCE; Resource.CleanupState state = Resource.CleanupState.MARKED; String description = "This is a test resource."; String ownerEmail = "owner@test.com"; String region = "us-east-1"; String terminationReason = "This is a test termination reason."; DateTime now = DateTime.now(); Date expectedTerminationTime = new Date(now.plusDays(10).getMillis()); Date markTime = new Date(now.getMillis()); String fieldName = "fieldName123"; String fieldValue = "fieldValue456"; Resource resource = new AWSResource().withId(id).withResourceType(resourceType) .withDescription(description).withOwnerEmail(ownerEmail).withRegion(region) .withState(state).withTerminationReason(terminationReason) .withExpectedTerminationTime(expectedTerminationTime) .withMarkTime(markTime).withOptOutOfJanitor(false) .setAdditionalField(fieldName, fieldValue); ArgumentCaptor<PutAttributesRequest> arg = ArgumentCaptor.forClass(PutAttributesRequest.class); TestSimpleDBJanitorResourceTracker tracker = new TestSimpleDBJanitorResourceTracker(); tracker.addOrUpdate(resource); verify(tracker.sdbMock).putAttributes(arg.capture()); PutAttributesRequest req = arg.getValue(); Assert.assertEquals(req.getDomainName(), "DOMAIN"); Assert.assertEquals(req.getItemName(), getSimpleDBItemName(resource)); Map<String, String> map = new HashMap<String, String>(); for (ReplaceableAttribute attr : req.getAttributes()) { map.put(attr.getName(), attr.getValue()); } Assert.assertEquals(map.remove(AWSResource.FIELD_RESOURCE_ID), id); Assert.assertEquals(map.remove(AWSResource.FIELD_DESCRIPTION), description); Assert.assertEquals(map.remove(AWSResource.FIELD_EXPECTED_TERMINATION_TIME), AWSResource.DATE_FORMATTER.print(expectedTerminationTime.getTime())); Assert.assertEquals(map.remove(AWSResource.FIELD_MARK_TIME), AWSResource.DATE_FORMATTER.print(markTime.getTime())); Assert.assertEquals(map.remove(AWSResource.FIELD_REGION), region); Assert.assertEquals(map.remove(AWSResource.FIELD_OWNER_EMAIL), ownerEmail); Assert.assertEquals(map.remove(AWSResource.FIELD_RESOURCE_TYPE), resourceType.name()); Assert.assertEquals(map.remove(AWSResource.FIELD_STATE), state.name()); Assert.assertEquals(map.remove(AWSResource.FIELD_TERMINATION_REASON), terminationReason); Assert.assertEquals(map.remove(AWSResource.FIELD_OPT_OUT_OF_JANITOR), "false"); Assert.assertEquals(map.remove(fieldName), fieldValue); Assert.assertEquals(map.size(), 0); } @Test public void testGetResources() { String id1 = "id-1"; String id2 = "id-2"; AWSResourceType resourceType = AWSResourceType.INSTANCE; Resource.CleanupState state = Resource.CleanupState.MARKED; String description = "This is a test resource."; String ownerEmail = "owner@test.com"; String region = "us-east-1"; String terminationReason = "This is a test termination reason."; DateTime now = DateTime.now(); Date expectedTerminationTime = new Date(now.plusDays(10).getMillis()); Date markTime = new Date(now.getMillis()); String fieldName = "fieldName123"; String fieldValue = "fieldValue456"; SelectResult result1 = mkSelectResult(id1, resourceType, state, description, ownerEmail, region, terminationReason, expectedTerminationTime, markTime, false, fieldName, fieldValue); result1.setNextToken("nextToken"); SelectResult result2 = mkSelectResult(id2, resourceType, state, description, ownerEmail, region, terminationReason, expectedTerminationTime, markTime, true, fieldName, fieldValue); ArgumentCaptor<SelectRequest> arg = ArgumentCaptor.forClass(SelectRequest.class); TestSimpleDBJanitorResourceTracker tracker = new TestSimpleDBJanitorResourceTracker(); when(tracker.sdbMock.select(any(SelectRequest.class))).thenReturn(result1).thenReturn(result2); verifyResources(tracker.getResources(resourceType, state, region), id1, id2, resourceType, state, description, ownerEmail, region, terminationReason, expectedTerminationTime, markTime, fieldName, fieldValue); verify(tracker.sdbMock, times(2)).select(arg.capture()); } private void verifyResources(List<Resource> resources, String id1, String id2, AWSResourceType resourceType, Resource.CleanupState state, String description, String ownerEmail, String region, String terminationReason, Date expectedTerminationTime, Date markTime, String fieldName, String fieldValue) { Assert.assertEquals(resources.size(), 2); Assert.assertEquals(resources.get(0).getId(), id1); Assert.assertEquals(resources.get(0).getResourceType(), resourceType); Assert.assertEquals(resources.get(0).getState(), state); Assert.assertEquals(resources.get(0).getDescription(), description); Assert.assertEquals(resources.get(0).getOwnerEmail(), ownerEmail); Assert.assertEquals(resources.get(0).getRegion(), region); Assert.assertEquals(resources.get(0).getTerminationReason(), terminationReason); Assert.assertEquals( AWSResource.DATE_FORMATTER.print(resources.get(0).getExpectedTerminationTime().getTime()), AWSResource.DATE_FORMATTER.print(expectedTerminationTime.getTime())); Assert.assertEquals( AWSResource.DATE_FORMATTER.print(resources.get(0).getMarkTime().getTime()), AWSResource.DATE_FORMATTER.print(markTime.getTime())); Assert.assertEquals(resources.get(0).getAdditionalField(fieldName), fieldValue); Assert.assertEquals(resources.get(0).isOptOutOfJanitor(), false); Assert.assertEquals(resources.get(1).getId(), id2); Assert.assertEquals(resources.get(1).getResourceType(), resourceType); Assert.assertEquals(resources.get(1).getState(), state); Assert.assertEquals(resources.get(1).getDescription(), description); Assert.assertEquals(resources.get(1).getOwnerEmail(), ownerEmail); Assert.assertEquals(resources.get(1).getRegion(), region); Assert.assertEquals(resources.get(1).getTerminationReason(), terminationReason); Assert.assertEquals( AWSResource.DATE_FORMATTER.print(resources.get(1).getExpectedTerminationTime().getTime()), AWSResource.DATE_FORMATTER.print(expectedTerminationTime.getTime())); Assert.assertEquals( AWSResource.DATE_FORMATTER.print(resources.get(1).getMarkTime().getTime()), AWSResource.DATE_FORMATTER.print(markTime.getTime())); Assert.assertEquals(resources.get(1).isOptOutOfJanitor(), true); Assert.assertEquals(resources.get(1).getAdditionalField(fieldName), fieldValue); } private SelectResult mkSelectResult(String id, AWSResourceType resourceType, Resource.CleanupState state, String description, String ownerEmail, String region, String terminationReason, Date expectedTerminationTime, Date markTime, boolean optOut, String fieldName, String fieldValue) { Item item = new Item(); List<Attribute> attrs = new LinkedList<Attribute>(); attrs.add(new Attribute(AWSResource.FIELD_RESOURCE_ID, id)); attrs.add(new Attribute(AWSResource.FIELD_RESOURCE_TYPE, resourceType.name())); attrs.add(new Attribute(AWSResource.FIELD_DESCRIPTION, description)); attrs.add(new Attribute(AWSResource.FIELD_REGION, region)); attrs.add(new Attribute(AWSResource.FIELD_STATE, state.name())); attrs.add(new Attribute(AWSResource.FIELD_OWNER_EMAIL, ownerEmail)); attrs.add(new Attribute(AWSResource.FIELD_TERMINATION_REASON, terminationReason)); attrs.add(new Attribute(AWSResource.FIELD_EXPECTED_TERMINATION_TIME, AWSResource.DATE_FORMATTER.print(expectedTerminationTime.getTime()))); attrs.add(new Attribute(AWSResource.FIELD_MARK_TIME, AWSResource.DATE_FORMATTER.print(markTime.getTime()))); attrs.add(new Attribute(AWSResource.FIELD_OPT_OUT_OF_JANITOR, String.valueOf(optOut))); attrs.add(new Attribute(fieldName, fieldValue)); item.setAttributes(attrs); item.setName(String.format("%s-%s-%s", resourceType.name(), id, region)); SelectResult result = new SelectResult(); result.setItems(Arrays.asList(item)); return result; } }
4,727
0
Create_ds/SimianArmy/src/test/java/com/netflix/simianarmy/aws
Create_ds/SimianArmy/src/test/java/com/netflix/simianarmy/aws/janitor/TestRDSJanitorResourceTracker.java
/* * * Copyright 2012 Netflix, Inc. * * Licensed 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. * */ // CHECKSTYLE IGNORE Javadoc // CHECKSTYLE IGNORE MagicNumberCheck // CHECKSTYLE IGNORE ParameterNumber package com.netflix.simianarmy.aws.janitor; import com.netflix.simianarmy.Resource; import com.netflix.simianarmy.aws.AWSResource; import com.netflix.simianarmy.aws.AWSResourceType; import org.joda.time.DateTime; import org.mockito.ArgumentCaptor; import org.mockito.Matchers; import org.mockito.Mockito; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.core.RowMapper; import org.testng.Assert; import org.testng.annotations.Test; import java.util.*; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; public class TestRDSJanitorResourceTracker extends RDSJanitorResourceTracker { public TestRDSJanitorResourceTracker() { super(mock(JdbcTemplate.class), "janitortable"); } @Test public void testInit() { TestRDSJanitorResourceTracker recorder = new TestRDSJanitorResourceTracker(); ArgumentCaptor<String> sqlCap = ArgumentCaptor.forClass(String.class); Mockito.doNothing().when(recorder.getJdbcTemplate()).execute(sqlCap.capture()); recorder.init(); Assert.assertEquals(sqlCap.getValue(), "create table if not exists janitortable ( resourceId varchar(255), resourceType varchar(255), region varchar(25), ownerEmail varchar(255), description varchar(255), state varchar(25), terminationReason varchar(255), expectedTerminationTime BIGINT, actualTerminationTime BIGINT, notificationTime BIGINT, launchTime BIGINT, markTime BIGINT, optOutOfJanitor varchar(8), additionalFields varchar(4096) )"); } @SuppressWarnings("unchecked") @Test public void testInsertNewResource() { // mock the select query that is issued to see if the record already exists ArrayList<AWSResource> resources = new ArrayList<>(); TestRDSJanitorResourceTracker tracker = new TestRDSJanitorResourceTracker(); when(tracker.getJdbcTemplate().query(Matchers.anyString(), Matchers.any(Object[].class), Matchers.any(RowMapper.class))).thenReturn(resources); String id = "i-12345678901234567"; AWSResourceType resourceType = AWSResourceType.INSTANCE; Resource.CleanupState state = Resource.CleanupState.MARKED; String description = "This is a test resource."; String ownerEmail = "owner@test.com"; String region = "us-east-1"; String terminationReason = "This is a test termination reason."; DateTime now = DateTime.now(); Date expectedTerminationTime = new Date(now.plusDays(10).getMillis()); Date markTime = new Date(now.getMillis()); String fieldName = "fieldName123"; String fieldValue = "fieldValue456"; Resource resource = new AWSResource().withId(id).withResourceType(resourceType) .withDescription(description).withOwnerEmail(ownerEmail).withRegion(region) .withState(state).withTerminationReason(terminationReason) .withExpectedTerminationTime(expectedTerminationTime) .withMarkTime(markTime).withOptOutOfJanitor(false) .setAdditionalField(fieldName, fieldValue); ArgumentCaptor<Object> objCap = ArgumentCaptor.forClass(Object.class); ArgumentCaptor<String> sqlCap = ArgumentCaptor.forClass(String.class); when(tracker.getJdbcTemplate().update(sqlCap.capture(), objCap.capture(), objCap.capture(), objCap.capture(), objCap.capture(), objCap.capture(), objCap.capture(), objCap.capture(), objCap.capture(), objCap.capture(), objCap.capture(), objCap.capture(), objCap.capture(), objCap.capture(), objCap.capture())).thenReturn(1); tracker.addOrUpdate(resource); List<Object> args = objCap.getAllValues(); Assert.assertEquals(sqlCap.getValue(), "insert into janitortable (resourceId,resourceType,region,ownerEmail,description,state,terminationReason,expectedTerminationTime,actualTerminationTime,notificationTime,launchTime,markTime,optOutOfJanitor,additionalFields) values (?,?,?,?,?,?,?,?,?,?,?,?,?,?)"); Assert.assertEquals(args.size(), 14); Assert.assertEquals(args.get(0).toString(), id); Assert.assertEquals(args.get(1).toString(), AWSResourceType.INSTANCE.toString()); Assert.assertEquals(args.get(2).toString(), region); Assert.assertEquals(args.get(3).toString(), ownerEmail); Assert.assertEquals(args.get(4).toString(), description); Assert.assertEquals(args.get(5).toString(), state.toString()); Assert.assertEquals(args.get(6).toString(), terminationReason); Assert.assertEquals(args.get(7).toString(), expectedTerminationTime.getTime() + ""); Assert.assertEquals(args.get(8).toString(), "0"); Assert.assertEquals(args.get(9).toString(), "0"); Assert.assertEquals(args.get(10).toString(), "0"); Assert.assertEquals(args.get(11).toString(), markTime.getTime() + ""); Assert.assertEquals(args.get(12).toString(), "false"); Assert.assertEquals(args.get(13).toString(), "{\"fieldName123\":\"fieldValue456\"}"); } @SuppressWarnings("unchecked") @Test public void testUpdateResource() { String id = "i-12345678901234567"; AWSResourceType resourceType = AWSResourceType.INSTANCE; Resource.CleanupState state = Resource.CleanupState.MARKED; String description = "This is a test resource."; String ownerEmail = "owner@test.com"; String region = "us-east-1"; String terminationReason = "This is a test termination reason."; DateTime now = DateTime.now(); Date expectedTerminationTime = new Date(now.plusDays(10).getMillis()); Date markTime = new Date(now.getMillis()); String fieldName = "fieldName123"; String fieldValue = "fieldValue456"; Resource resource = new AWSResource().withId(id).withResourceType(resourceType) .withDescription(description).withOwnerEmail(ownerEmail).withRegion(region) .withState(state).withTerminationReason(terminationReason) .withExpectedTerminationTime(expectedTerminationTime) .withMarkTime(markTime).withOptOutOfJanitor(false) .setAdditionalField(fieldName, fieldValue); // mock the select query that is issued to see if the record already exists ArrayList<Resource> resources = new ArrayList<>(); resources.add(resource); TestRDSJanitorResourceTracker tracker = new TestRDSJanitorResourceTracker(); when(tracker.getJdbcTemplate().query(Matchers.anyString(), Matchers.any(Object[].class), Matchers.any(RowMapper.class))).thenReturn(resources); // update the ownerEmail ownerEmail = "owner2@test.com"; Resource newResource = new AWSResource().withId(id).withResourceType(resourceType) .withDescription(description).withOwnerEmail(ownerEmail).withRegion(region) .withState(state).withTerminationReason(terminationReason) .withExpectedTerminationTime(expectedTerminationTime) .withMarkTime(markTime).withOptOutOfJanitor(false) .setAdditionalField(fieldName, fieldValue); ArgumentCaptor<Object> objCap = ArgumentCaptor.forClass(Object.class); ArgumentCaptor<String> sqlCap = ArgumentCaptor.forClass(String.class); when(tracker.getJdbcTemplate().update(sqlCap.capture(), objCap.capture(), objCap.capture(), objCap.capture(), objCap.capture(), objCap.capture(), objCap.capture(), objCap.capture(), objCap.capture(), objCap.capture(), objCap.capture(), objCap.capture(), objCap.capture(), objCap.capture(), objCap.capture(), objCap.capture())).thenReturn(1); tracker.addOrUpdate(newResource); List<Object> args = objCap.getAllValues(); Assert.assertEquals(sqlCap.getValue(), "update janitortable set resourceType=?,region=?,ownerEmail=?,description=?,state=?,terminationReason=?,expectedTerminationTime=?,actualTerminationTime=?,notificationTime=?,launchTime=?,markTime=?,optOutOfJanitor=?,additionalFields=? where resourceId=? and region=?"); Assert.assertEquals(args.size(), 15); Assert.assertEquals(args.get(0).toString(), AWSResourceType.INSTANCE.toString()); Assert.assertEquals(args.get(1).toString(), region); Assert.assertEquals(args.get(2).toString(), ownerEmail); Assert.assertEquals(args.get(3).toString(), description); Assert.assertEquals(args.get(4).toString(), state.toString()); Assert.assertEquals(args.get(5).toString(), terminationReason); Assert.assertEquals(args.get(6).toString(), expectedTerminationTime.getTime() + ""); Assert.assertEquals(args.get(7).toString(), "0"); Assert.assertEquals(args.get(8).toString(), "0"); Assert.assertEquals(args.get(9).toString(), "0"); Assert.assertEquals(args.get(10).toString(), markTime.getTime() + ""); Assert.assertEquals(args.get(11).toString(), "false"); Assert.assertEquals(args.get(12).toString(), "{\"fieldName123\":\"fieldValue456\"}"); Assert.assertEquals(args.get(13).toString(), id); Assert.assertEquals(args.get(14).toString(), region); } @SuppressWarnings("unchecked") @Test public void testGetResource() { String id1 = "id-1"; AWSResourceType resourceType = AWSResourceType.INSTANCE; Resource.CleanupState state = Resource.CleanupState.MARKED; String description = "This is a test resource."; String ownerEmail = "owner@test.com"; String region = "us-east-1"; String terminationReason = "This is a test termination reason."; DateTime now = DateTime.now(); Date expectedTerminationTime = new Date(now.plusDays(10).getMillis()); Date markTime = new Date(now.getMillis()); String fieldName = "fieldName123"; String fieldValue = "fieldValue456"; AWSResource result1 = mkResource(id1, resourceType, state, description, ownerEmail, region, terminationReason, expectedTerminationTime, markTime, false, fieldName, fieldValue); ArrayList<AWSResource> resources = new ArrayList<>(); resources.add(result1); TestRDSJanitorResourceTracker tracker = new TestRDSJanitorResourceTracker(); when(tracker.getJdbcTemplate().query(Matchers.anyString(), Matchers.any(Object[].class), Matchers.any(RowMapper.class))).thenReturn(resources); Resource resource = tracker.getResource(id1); ArrayList<Resource> returnResources = new ArrayList<>(); returnResources.add(resource); verifyResources(returnResources, id1, null, resourceType, state, description, ownerEmail, region, terminationReason, expectedTerminationTime, markTime, fieldName, fieldValue); } @SuppressWarnings("unchecked") @Test public void testGetResourceNotFound() { ArrayList<AWSResource> resources = new ArrayList<>(); TestRDSJanitorResourceTracker tracker = new TestRDSJanitorResourceTracker(); when(tracker.getJdbcTemplate().query(Matchers.anyString(), Matchers.any(Object[].class), Matchers.any(RowMapper.class))).thenReturn(resources); Resource resource = tracker.getResource("id-2"); Assert.assertNull(resource); } @SuppressWarnings("unchecked") @Test public void testGetResources() { String id1 = "id-1"; String id2 = "id-2"; AWSResourceType resourceType = AWSResourceType.INSTANCE; Resource.CleanupState state = Resource.CleanupState.MARKED; String description = "This is a test resource."; String ownerEmail = "owner@test.com"; String region = "us-east-1"; String terminationReason = "This is a test termination reason."; DateTime now = DateTime.now(); Date expectedTerminationTime = new Date(now.plusDays(10).getMillis()); Date markTime = new Date(now.getMillis()); String fieldName = "fieldName123"; String fieldValue = "fieldValue456"; AWSResource result1 = mkResource(id1, resourceType, state, description, ownerEmail, region, terminationReason, expectedTerminationTime, markTime, false, fieldName, fieldValue); AWSResource result2 = mkResource(id2, resourceType, state, description, ownerEmail, region, terminationReason, expectedTerminationTime, markTime, true, fieldName, fieldValue); ArrayList<AWSResource> resources = new ArrayList<>(); resources.add(result1); resources.add(result2); TestRDSJanitorResourceTracker tracker = new TestRDSJanitorResourceTracker(); when(tracker.getJdbcTemplate().query(Matchers.anyString(), Matchers.any(Object[].class), Matchers.any(RowMapper.class))).thenReturn(resources); verifyResources(tracker.getResources(resourceType, state, region), id1, id2, resourceType, state, description, ownerEmail, region, terminationReason, expectedTerminationTime, markTime, fieldName, fieldValue); } private void verifyResources(List<Resource> resources, String id1, String id2, AWSResourceType resourceType, Resource.CleanupState state, String description, String ownerEmail, String region, String terminationReason, Date expectedTerminationTime, Date markTime, String fieldName, String fieldValue) { if (id2 == null) { Assert.assertEquals(resources.size(), 1); } else { Assert.assertEquals(resources.size(), 2); } Assert.assertEquals(resources.get(0).getId(), id1); Assert.assertEquals(resources.get(0).getResourceType(), resourceType); Assert.assertEquals(resources.get(0).getState(), state); Assert.assertEquals(resources.get(0).getDescription(), description); Assert.assertEquals(resources.get(0).getOwnerEmail(), ownerEmail); Assert.assertEquals(resources.get(0).getRegion(), region); Assert.assertEquals(resources.get(0).getTerminationReason(), terminationReason); Assert.assertEquals( AWSResource.DATE_FORMATTER.print(resources.get(0).getExpectedTerminationTime().getTime()), AWSResource.DATE_FORMATTER.print(expectedTerminationTime.getTime())); Assert.assertEquals( AWSResource.DATE_FORMATTER.print(resources.get(0).getMarkTime().getTime()), AWSResource.DATE_FORMATTER.print(markTime.getTime())); Assert.assertEquals(resources.get(0).getAdditionalField(fieldName), fieldValue); Assert.assertEquals(resources.get(0).isOptOutOfJanitor(), false); if (id2 != null) { Assert.assertEquals(resources.get(1).getId(), id2); Assert.assertEquals(resources.get(1).getResourceType(), resourceType); Assert.assertEquals(resources.get(1).getState(), state); Assert.assertEquals(resources.get(1).getDescription(), description); Assert.assertEquals(resources.get(1).getOwnerEmail(), ownerEmail); Assert.assertEquals(resources.get(1).getRegion(), region); Assert.assertEquals(resources.get(1).getTerminationReason(), terminationReason); Assert.assertEquals( AWSResource.DATE_FORMATTER.print(resources.get(1).getExpectedTerminationTime().getTime()), AWSResource.DATE_FORMATTER.print(expectedTerminationTime.getTime())); Assert.assertEquals( AWSResource.DATE_FORMATTER.print(resources.get(1).getMarkTime().getTime()), AWSResource.DATE_FORMATTER.print(markTime.getTime())); Assert.assertEquals(resources.get(1).isOptOutOfJanitor(), true); Assert.assertEquals(resources.get(1).getAdditionalField(fieldName), fieldValue); } } private AWSResource mkResource(String id, AWSResourceType resourceType, Resource.CleanupState state, String description, String ownerEmail, String region, String terminationReason, Date expectedTerminationTime, Date markTime, boolean optOut, String fieldName, String fieldValue) { Map<String, String> attrs = new HashMap<>(); attrs.put(AWSResource.FIELD_RESOURCE_ID, id); attrs.put(AWSResource.FIELD_RESOURCE_TYPE, resourceType.name()); attrs.put(AWSResource.FIELD_DESCRIPTION, description); attrs.put(AWSResource.FIELD_REGION, region); attrs.put(AWSResource.FIELD_STATE, state.name()); attrs.put(AWSResource.FIELD_OWNER_EMAIL, ownerEmail); attrs.put(AWSResource.FIELD_TERMINATION_REASON, terminationReason); attrs.put(AWSResource.FIELD_EXPECTED_TERMINATION_TIME, AWSResource.DATE_FORMATTER.print(expectedTerminationTime.getTime())); attrs.put(AWSResource.FIELD_MARK_TIME, AWSResource.DATE_FORMATTER.print(markTime.getTime())); attrs.put(AWSResource.FIELD_OPT_OUT_OF_JANITOR, String.valueOf(optOut)); attrs.put(fieldName, fieldValue); return AWSResource.parseFieldtoValueMap(attrs); } }
4,728
0
Create_ds/SimianArmy/src/test/java/com/netflix/simianarmy/aws/janitor
Create_ds/SimianArmy/src/test/java/com/netflix/simianarmy/aws/janitor/crawler/TestLaunchConfigJanitorCrawler.java
/* * * Copyright 2012 Netflix, Inc. * * Licensed 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. * */ // CHECKSTYLE IGNORE Javadoc package com.netflix.simianarmy.aws.janitor.crawler; import com.amazonaws.services.autoscaling.model.AutoScalingGroup; import com.amazonaws.services.autoscaling.model.LaunchConfiguration; import com.google.common.collect.Lists; import com.netflix.simianarmy.Resource; import com.netflix.simianarmy.aws.AWSResourceType; import com.netflix.simianarmy.client.aws.AWSClient; import org.apache.commons.lang.Validate; import org.testng.Assert; import org.testng.annotations.Test; import java.util.EnumSet; import java.util.List; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; public class TestLaunchConfigJanitorCrawler { @Test public void testResourceTypes() { int n = 2; String[] lcNames = {"launchConfig1", "launchConfig2"}; LaunchConfigJanitorCrawler crawler = new LaunchConfigJanitorCrawler(createMockAWSClient( createASGList(n), createLaunchConfigList(n), lcNames)); EnumSet<?> types = crawler.resourceTypes(); Assert.assertEquals(types.size(), 1); Assert.assertEquals(types.iterator().next().name(), "LAUNCH_CONFIG"); } @Test public void testInstancesWithNullNames() { int n = 2; List<LaunchConfiguration> lcList = createLaunchConfigList(n); LaunchConfigJanitorCrawler crawler = new LaunchConfigJanitorCrawler(createMockAWSClient( createASGList(n), lcList)); List<Resource> resources = crawler.resources(); verifyLaunchConfigList(resources, lcList); } @Test public void testInstancesWithNames() { int n = 2; String[] lcNames = {"launchConfig1", "launchConfig2"}; List<LaunchConfiguration> lcList = createLaunchConfigList(n); LaunchConfigJanitorCrawler crawler = new LaunchConfigJanitorCrawler(createMockAWSClient( createASGList(n), lcList, lcNames)); List<Resource> resources = crawler.resources(lcNames); verifyLaunchConfigList(resources, lcList); } @Test public void testInstancesWithResourceType() { int n = 2; List<LaunchConfiguration> lcList = createLaunchConfigList(n); LaunchConfigJanitorCrawler crawler = new LaunchConfigJanitorCrawler(createMockAWSClient( createASGList(n), lcList)); for (AWSResourceType resourceType : AWSResourceType.values()) { List<Resource> resources = crawler.resources(resourceType); if (resourceType == AWSResourceType.LAUNCH_CONFIG) { verifyLaunchConfigList(resources, lcList); } else { Assert.assertTrue(resources.isEmpty()); } } } private void verifyLaunchConfigList(List<Resource> resources, List<LaunchConfiguration> lcList) { Assert.assertEquals(resources.size(), lcList.size()); for (int i = 0; i < resources.size(); i++) { LaunchConfiguration lc = lcList.get(i); if (i % 2 == 0) { verifyLaunchConfig(resources.get(i), lc.getLaunchConfigurationName(), true); } else { verifyLaunchConfig(resources.get(i), lc.getLaunchConfigurationName(), null); } } } private void verifyLaunchConfig(Resource launchConfig, String lcName, Boolean usedByASG) { Assert.assertEquals(launchConfig.getResourceType(), AWSResourceType.LAUNCH_CONFIG); Assert.assertEquals(launchConfig.getId(), lcName); Assert.assertEquals(launchConfig.getRegion(), "us-east-1"); if (usedByASG != null) { Assert.assertEquals(launchConfig.getAdditionalField( LaunchConfigJanitorCrawler.LAUNCH_CONFIG_FIELD_USED_BY_ASG), usedByASG.toString()); } } private AWSClient createMockAWSClient(List<AutoScalingGroup> asgList, List<LaunchConfiguration> lcList, String... lcNames) { AWSClient awsMock = mock(AWSClient.class); when(awsMock.describeAutoScalingGroups()).thenReturn(asgList); when(awsMock.describeLaunchConfigurations(lcNames)).thenReturn(lcList); when(awsMock.region()).thenReturn("us-east-1"); return awsMock; } private List<LaunchConfiguration> createLaunchConfigList(int n) { List<LaunchConfiguration> lcList = Lists.newArrayList(); for (int i = 1; i <= n; i++) { lcList.add(mkLaunchConfig("launchConfig" + i)); } return lcList; } private LaunchConfiguration mkLaunchConfig(String lcName) { return new LaunchConfiguration().withLaunchConfigurationName(lcName); } private List<AutoScalingGroup> createASGList(int n) { Validate.isTrue(n > 0); List<AutoScalingGroup> asgList = Lists.newArrayList(); for (int i = 1; i <= n; i += 2) { asgList.add(mkASG("asg" + i, "launchConfig" + i)); } return asgList; } private AutoScalingGroup mkASG(String asgName, String lcName) { return new AutoScalingGroup().withAutoScalingGroupName(asgName).withLaunchConfigurationName(lcName); } }
4,729
0
Create_ds/SimianArmy/src/test/java/com/netflix/simianarmy/aws/janitor
Create_ds/SimianArmy/src/test/java/com/netflix/simianarmy/aws/janitor/crawler/TestEBSSnapshotJanitorCrawler.java
/* * * Copyright 2012 Netflix, Inc. * * Licensed 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. * */ //CHECKSTYLE IGNORE Javadoc package com.netflix.simianarmy.aws.janitor.crawler; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import java.util.Date; import java.util.EnumSet; import java.util.LinkedList; import java.util.List; import org.testng.Assert; import org.testng.annotations.Test; import com.amazonaws.services.ec2.model.Snapshot; import com.netflix.simianarmy.Resource; import com.netflix.simianarmy.aws.AWSResource; import com.netflix.simianarmy.aws.AWSResourceType; import com.netflix.simianarmy.client.aws.AWSClient; public class TestEBSSnapshotJanitorCrawler { @Test public void testResourceTypes() { Date startTime = new Date(); List<Snapshot> snapshotList = createSnapshotList(startTime); EBSSnapshotJanitorCrawler crawler = new EBSSnapshotJanitorCrawler(createMockAWSClient(snapshotList)); EnumSet<?> types = crawler.resourceTypes(); Assert.assertEquals(types.size(), 1); Assert.assertEquals(types.iterator().next().name(), "EBS_SNAPSHOT"); } @Test public void testSnapshotsWithNullIds() { Date startTime = new Date(); List<Snapshot> snapshotList = createSnapshotList(startTime); EBSSnapshotJanitorCrawler crawler = new EBSSnapshotJanitorCrawler(createMockAWSClient(snapshotList)); List<Resource> resources = crawler.resources(); verifySnapshotList(resources, snapshotList, startTime); } @Test public void testSnapshotsWithIds() { Date startTime = new Date(); List<Snapshot> snapshotList = createSnapshotList(startTime); String[] ids = {"snap-12345678901234567", "snap-12345678901234567"}; EBSSnapshotJanitorCrawler crawler = new EBSSnapshotJanitorCrawler(createMockAWSClient(snapshotList, ids)); List<Resource> resources = crawler.resources(ids); verifySnapshotList(resources, snapshotList, startTime); } @Test public void testSnapshotsWithResourceType() { Date startTime = new Date(); List<Snapshot> snapshotList = createSnapshotList(startTime); EBSSnapshotJanitorCrawler crawler = new EBSSnapshotJanitorCrawler(createMockAWSClient(snapshotList)); for (AWSResourceType resourceType : AWSResourceType.values()) { List<Resource> resources = crawler.resources(resourceType); if (resourceType == AWSResourceType.EBS_SNAPSHOT) { verifySnapshotList(resources, snapshotList, startTime); } else { Assert.assertTrue(resources.isEmpty()); } } } private void verifySnapshotList(List<Resource> resources, List<Snapshot> snapshotList, Date startTime) { Assert.assertEquals(resources.size(), snapshotList.size()); for (int i = 0; i < resources.size(); i++) { Snapshot snapshot = snapshotList.get(i); verifySnapshot(resources.get(i), snapshot.getSnapshotId(), startTime); } } private void verifySnapshot(Resource snapshot, String snapshotId, Date startTime) { Assert.assertEquals(snapshot.getResourceType(), AWSResourceType.EBS_SNAPSHOT); Assert.assertEquals(snapshot.getId(), snapshotId); Assert.assertEquals(snapshot.getRegion(), "us-east-1"); Assert.assertEquals(((AWSResource) snapshot).getAWSResourceState(), "completed"); Assert.assertEquals(snapshot.getLaunchTime(), startTime); } private AWSClient createMockAWSClient(List<Snapshot> snapshotList, String... ids) { AWSClient awsMock = mock(AWSClient.class); when(awsMock.describeSnapshots(ids)).thenReturn(snapshotList); when(awsMock.region()).thenReturn("us-east-1"); return awsMock; } private List<Snapshot> createSnapshotList(Date startTime) { List<Snapshot> snapshotList = new LinkedList<Snapshot>(); snapshotList.add(mkSnapshot("snap-12345678901234567", startTime)); snapshotList.add(mkSnapshot("snap-12345678901234567", startTime)); return snapshotList; } private Snapshot mkSnapshot(String snapshotId, Date startTime) { return new Snapshot().withSnapshotId(snapshotId).withState("completed").withStartTime(startTime); } }
4,730
0
Create_ds/SimianArmy/src/test/java/com/netflix/simianarmy/aws/janitor
Create_ds/SimianArmy/src/test/java/com/netflix/simianarmy/aws/janitor/crawler/TestASGJanitorCrawler.java
/* * * Copyright 2012 Netflix, Inc. * * Licensed 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. * */ // CHECKSTYLE IGNORE Javadoc package com.netflix.simianarmy.aws.janitor.crawler; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import java.util.ArrayList; import java.util.EnumSet; import java.util.LinkedList; import java.util.List; import org.testng.Assert; import org.testng.annotations.Test; import com.amazonaws.services.autoscaling.model.AutoScalingGroup; import com.amazonaws.services.autoscaling.model.SuspendedProcess; import com.netflix.simianarmy.Resource; import com.netflix.simianarmy.aws.AWSResourceType; import com.netflix.simianarmy.client.aws.AWSClient; public class TestASGJanitorCrawler { @Test public void testResourceTypes() { ASGJanitorCrawler crawler = new ASGJanitorCrawler(createMockAWSClient(createASGList())); EnumSet<?> types = crawler.resourceTypes(); Assert.assertEquals(types.size(), 1); Assert.assertEquals(types.iterator().next().name(), "ASG"); } @Test public void testInstancesWithNullNames() { List<AutoScalingGroup> asgList = createASGList(); AWSClient awsMock = createMockAWSClient(asgList); ASGJanitorCrawler crawler = new ASGJanitorCrawler(awsMock); List<Resource> resources = crawler.resources(); verifyASGList(resources, asgList); } @Test public void testInstancesWithNames() { List<AutoScalingGroup> asgList = createASGList(); String[] asgNames = {"asg1", "asg2"}; AWSClient awsMock = createMockAWSClient(asgList, asgNames); ASGJanitorCrawler crawler = new ASGJanitorCrawler(awsMock); List<Resource> resources = crawler.resources(asgNames); verifyASGList(resources, asgList); } @Test public void testInstancesWithResourceType() { List<AutoScalingGroup> asgList = createASGList(); AWSClient awsMock = createMockAWSClient(asgList); ASGJanitorCrawler crawler = new ASGJanitorCrawler(awsMock); for (AWSResourceType resourceType : AWSResourceType.values()) { List<Resource> resources = crawler.resources(resourceType); if (resourceType == AWSResourceType.ASG) { verifyASGList(resources, asgList); } else { Assert.assertTrue(resources.isEmpty()); } } } private void verifyASGList(List<Resource> resources, List<AutoScalingGroup> asgList) { Assert.assertEquals(resources.size(), asgList.size()); for (int i = 0; i < resources.size(); i++) { AutoScalingGroup asg = asgList.get(i); verifyASG(resources.get(i), asg.getAutoScalingGroupName()); } } private void verifyASG(Resource asg, String asgName) { Assert.assertEquals(asg.getResourceType(), AWSResourceType.ASG); Assert.assertEquals(asg.getId(), asgName); Assert.assertEquals(asg.getRegion(), "us-east-1"); Assert.assertEquals(asg.getAdditionalField(ASGJanitorCrawler.ASG_FIELD_SUSPENSION_TIME), "2012-12-03T23:00:03"); } private AWSClient createMockAWSClient(List<AutoScalingGroup> asgList, String... asgNames) { AWSClient awsMock = mock(AWSClient.class); when(awsMock.describeAutoScalingGroups(asgNames)).thenReturn(asgList); when(awsMock.region()).thenReturn("us-east-1"); return awsMock; } private List<AutoScalingGroup> createASGList() { List<AutoScalingGroup> asgList = new LinkedList<AutoScalingGroup>(); asgList.add(mkASG("asg1")); asgList.add(mkASG("asg2")); return asgList; } private AutoScalingGroup mkASG(String asgName) { AutoScalingGroup asg = new AutoScalingGroup().withAutoScalingGroupName(asgName); // set the suspended processes List<SuspendedProcess> sps = new ArrayList<SuspendedProcess>(); sps.add(new SuspendedProcess().withProcessName("Launch") .withSuspensionReason("User suspended at 2012-12-02T23:00:03")); sps.add(new SuspendedProcess().withProcessName("AddToLoadBalancer") .withSuspensionReason("User suspended at 2012-12-03T23:00:03")); asg.setSuspendedProcesses(sps); return asg; } }
4,731
0
Create_ds/SimianArmy/src/test/java/com/netflix/simianarmy/aws/janitor
Create_ds/SimianArmy/src/test/java/com/netflix/simianarmy/aws/janitor/crawler/TestInstanceJanitorCrawler.java
/* * * Copyright 2012 Netflix, Inc. * * Licensed 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. * */ // CHECKSTYLE IGNORE Javadoc package com.netflix.simianarmy.aws.janitor.crawler; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import java.util.Collections; import java.util.EnumSet; import java.util.LinkedList; import java.util.List; import org.testng.Assert; import org.testng.annotations.Test; import com.amazonaws.services.autoscaling.model.AutoScalingInstanceDetails; import com.amazonaws.services.ec2.model.Instance; import com.amazonaws.services.ec2.model.InstanceState; import com.netflix.simianarmy.Resource; import com.netflix.simianarmy.aws.AWSResource; import com.netflix.simianarmy.aws.AWSResourceType; import com.netflix.simianarmy.client.aws.AWSClient; public class TestInstanceJanitorCrawler { @Test public void testResourceTypes() { List<AutoScalingInstanceDetails> instanceDetailsList = createInstanceDetailsList(); List<Instance> instanceList = createInstanceList(); InstanceJanitorCrawler crawler = new InstanceJanitorCrawler(createMockAWSClient( instanceDetailsList, instanceList)); EnumSet<?> types = crawler.resourceTypes(); Assert.assertEquals(types.size(), 1); Assert.assertEquals(types.iterator().next().name(), "INSTANCE"); } @Test public void testInstancesWithNullIds() { List<AutoScalingInstanceDetails> instanceDetailsList = createInstanceDetailsList(); List<Instance> instanceList = createInstanceList(); AWSClient awsMock = createMockAWSClient(instanceDetailsList, instanceList); InstanceJanitorCrawler crawler = new InstanceJanitorCrawler(awsMock); List<Resource> resources = crawler.resources(); verifyInstanceList(resources, instanceDetailsList); } @Test public void testInstancesWithIds() { List<AutoScalingInstanceDetails> instanceDetailsList = createInstanceDetailsList(); List<Instance> instanceList = createInstanceList(); String[] ids = {"i-12345678901234560", "i-12345678901234561"}; AWSClient awsMock = createMockAWSClient(instanceDetailsList, instanceList, ids); InstanceJanitorCrawler crawler = new InstanceJanitorCrawler(awsMock); List<Resource> resources = crawler.resources(ids); verifyInstanceList(resources, instanceDetailsList); } @Test public void testInstancesWithResourceType() { List<AutoScalingInstanceDetails> instanceDetailsList = createInstanceDetailsList(); List<Instance> instanceList = createInstanceList(); AWSClient awsMock = createMockAWSClient(instanceDetailsList, instanceList); InstanceJanitorCrawler crawler = new InstanceJanitorCrawler(awsMock); for (AWSResourceType resourceType : AWSResourceType.values()) { List<Resource> resources = crawler.resources(resourceType); if (resourceType == AWSResourceType.INSTANCE) { verifyInstanceList(resources, instanceDetailsList); } else { Assert.assertTrue(resources.isEmpty()); } } } @Test public void testInstancesNotExistingInASG() { List<AutoScalingInstanceDetails> instanceDetailsList = Collections.emptyList(); List<Instance> instanceList = createInstanceList(); AWSClient awsMock = createMockAWSClient(instanceDetailsList, instanceList); InstanceJanitorCrawler crawler = new InstanceJanitorCrawler(awsMock); List<Resource> resources = crawler.resources(); Assert.assertEquals(resources.size(), instanceList.size()); } private void verifyInstanceList(List<Resource> resources, List<AutoScalingInstanceDetails> instanceList) { Assert.assertEquals(resources.size(), instanceList.size()); for (int i = 0; i < resources.size(); i++) { AutoScalingInstanceDetails instance = instanceList.get(i); verifyInstance(resources.get(i), instance.getInstanceId(), instance.getAutoScalingGroupName()); } } private void verifyInstance(Resource instance, String instanceId, String asgName) { Assert.assertEquals(instance.getResourceType(), AWSResourceType.INSTANCE); Assert.assertEquals(instance.getId(), instanceId); Assert.assertEquals(instance.getRegion(), "us-east-1"); Assert.assertEquals(instance.getAdditionalField(InstanceJanitorCrawler.INSTANCE_FIELD_ASG_NAME), asgName); Assert.assertEquals(((AWSResource) instance).getAWSResourceState(), "running"); } private AWSClient createMockAWSClient(List<AutoScalingInstanceDetails> instanceDetailsList, List<Instance> instanceList, String... ids) { AWSClient awsMock = mock(AWSClient.class); when(awsMock.describeAutoScalingInstances(ids)).thenReturn(instanceDetailsList); when(awsMock.describeInstances(ids)).thenReturn(instanceList); when(awsMock.region()).thenReturn("us-east-1"); return awsMock; } private List<AutoScalingInstanceDetails> createInstanceDetailsList() { List<AutoScalingInstanceDetails> instanceList = new LinkedList<AutoScalingInstanceDetails>(); instanceList.add(mkInstanceDetails("i-12345678901234560", "asg1")); instanceList.add(mkInstanceDetails("i-12345678901234561", "asg2")); return instanceList; } private AutoScalingInstanceDetails mkInstanceDetails(String instanceId, String asgName) { return new AutoScalingInstanceDetails().withInstanceId(instanceId).withAutoScalingGroupName(asgName); } private List<Instance> createInstanceList() { List<Instance> instanceList = new LinkedList<Instance>(); instanceList.add(mkInstance("i-12345678901234560")); instanceList.add(mkInstance("i-12345678901234561")); return instanceList; } private Instance mkInstance(String instanceId) { return new Instance().withInstanceId(instanceId) .withState(new InstanceState().withName("running")); } }
4,732
0
Create_ds/SimianArmy/src/test/java/com/netflix/simianarmy/aws/janitor
Create_ds/SimianArmy/src/test/java/com/netflix/simianarmy/aws/janitor/crawler/TestEBSVolumeJanitorCrawler.java
/* * * Copyright 2012 Netflix, Inc. * * Licensed 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. * */ //CHECKSTYLE IGNORE Javadoc package com.netflix.simianarmy.aws.janitor.crawler; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import java.util.Date; import java.util.EnumSet; import java.util.LinkedList; import java.util.List; import org.testng.Assert; import org.testng.annotations.Test; import com.amazonaws.services.ec2.model.Volume; import com.netflix.simianarmy.Resource; import com.netflix.simianarmy.aws.AWSResource; import com.netflix.simianarmy.aws.AWSResourceType; import com.netflix.simianarmy.client.aws.AWSClient; public class TestEBSVolumeJanitorCrawler { @Test public void testResourceTypes() { Date createTime = new Date(); List<Volume> volumeList = createVolumeList(createTime); EBSVolumeJanitorCrawler crawler = new EBSVolumeJanitorCrawler(createMockAWSClient(volumeList)); EnumSet<?> types = crawler.resourceTypes(); Assert.assertEquals(types.size(), 1); Assert.assertEquals(types.iterator().next().name(), "EBS_VOLUME"); } @Test public void testVolumesWithNullIds() { Date createTime = new Date(); List<Volume> volumeList = createVolumeList(createTime); EBSVolumeJanitorCrawler crawler = new EBSVolumeJanitorCrawler(createMockAWSClient(volumeList)); List<Resource> resources = crawler.resources(); verifyVolumeList(resources, volumeList, createTime); } @Test public void testVolumesWithIds() { Date createTime = new Date(); List<Volume> volumeList = createVolumeList(createTime); String[] ids = {"vol-12345678901234567", "vol-12345678901234567"}; EBSVolumeJanitorCrawler crawler = new EBSVolumeJanitorCrawler(createMockAWSClient(volumeList, ids)); List<Resource> resources = crawler.resources(ids); verifyVolumeList(resources, volumeList, createTime); } @Test public void testVolumesWithResourceType() { Date createTime = new Date(); List<Volume> volumeList = createVolumeList(createTime); EBSVolumeJanitorCrawler crawler = new EBSVolumeJanitorCrawler(createMockAWSClient(volumeList)); for (AWSResourceType resourceType : AWSResourceType.values()) { List<Resource> resources = crawler.resources(resourceType); if (resourceType == AWSResourceType.EBS_VOLUME) { verifyVolumeList(resources, volumeList, createTime); } else { Assert.assertTrue(resources.isEmpty()); } } } private void verifyVolumeList(List<Resource> resources, List<Volume> volumeList, Date createTime) { Assert.assertEquals(resources.size(), volumeList.size()); for (int i = 0; i < resources.size(); i++) { Volume volume = volumeList.get(i); verifyVolume(resources.get(i), volume.getVolumeId(), createTime); } } private void verifyVolume(Resource volume, String volumeId, Date createTime) { Assert.assertEquals(volume.getResourceType(), AWSResourceType.EBS_VOLUME); Assert.assertEquals(volume.getId(), volumeId); Assert.assertEquals(volume.getRegion(), "us-east-1"); Assert.assertEquals(((AWSResource) volume).getAWSResourceState(), "available"); Assert.assertEquals(volume.getLaunchTime(), createTime); } private AWSClient createMockAWSClient(List<Volume> volumeList, String... ids) { AWSClient awsMock = mock(AWSClient.class); when(awsMock.describeVolumes(ids)).thenReturn(volumeList); when(awsMock.region()).thenReturn("us-east-1"); return awsMock; } private List<Volume> createVolumeList(Date createTime) { List<Volume> volumeList = new LinkedList<Volume>(); volumeList.add(mkVolume("vol-12345678901234567", createTime)); volumeList.add(mkVolume("vol-12345678901234567", createTime)); return volumeList; } private Volume mkVolume(String volumeId, Date createTime) { return new Volume().withVolumeId(volumeId).withState("available").withCreateTime(createTime); } }
4,733
0
Create_ds/SimianArmy/src/test/java/com/netflix/simianarmy/aws/janitor
Create_ds/SimianArmy/src/test/java/com/netflix/simianarmy/aws/janitor/crawler/TestELBJanitorCrawler.java
/* * * Copyright 2012 Netflix, Inc. * * Licensed 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. * */ // CHECKSTYLE IGNORE Javadoc package com.netflix.simianarmy.aws.janitor.crawler; import com.amazonaws.services.autoscaling.model.AutoScalingGroup; import com.amazonaws.services.elasticloadbalancing.model.Instance; import com.amazonaws.services.elasticloadbalancing.model.LoadBalancerDescription; import com.netflix.simianarmy.Resource; import com.netflix.simianarmy.aws.AWSResourceType; import com.netflix.simianarmy.client.aws.AWSClient; import org.apache.commons.lang.math.NumberUtils; import org.testng.Assert; import org.testng.annotations.Test; import java.util.Arrays; import java.util.EnumSet; import java.util.LinkedList; import java.util.List; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; public class TestELBJanitorCrawler { @Test public void testResourceTypes() { boolean includeInstances = false; AWSClient client = createMockAWSClient(); addELBsToMock(client, createELBList(includeInstances)); ELBJanitorCrawler crawler = new ELBJanitorCrawler(client); EnumSet<?> types = crawler.resourceTypes(); Assert.assertEquals(types.size(), 1); Assert.assertEquals(types.iterator().next().name(), "ELB"); } @Test public void testElbsWithNoInstances() { boolean includeInstances = false; AWSClient client = createMockAWSClient(); List<LoadBalancerDescription> elbs = createELBList(includeInstances); addELBsToMock(client, elbs); ELBJanitorCrawler crawler = new ELBJanitorCrawler(client); List<Resource> resources = crawler.resources(); verifyELBList(resources, elbs); } @Test public void testElbsWithInstances() { boolean includeInstances = true; AWSClient client = createMockAWSClient(); List<LoadBalancerDescription> elbs = createELBList(includeInstances); addELBsToMock(client, elbs); ELBJanitorCrawler crawler = new ELBJanitorCrawler(client); List<Resource> resources = crawler.resources(); verifyELBList(resources, elbs); } @Test public void testElbsWithReferencedASGs() { boolean includeInstances = true; boolean includeELbs = true; AWSClient client = createMockAWSClient(); List<LoadBalancerDescription> elbs = createELBList(includeInstances); List<AutoScalingGroup> asgs = createASGList(includeELbs); addELBsToMock(client, elbs); addASGsToMock(client, asgs); ELBJanitorCrawler crawler = new ELBJanitorCrawler(client); List<Resource> resources = crawler.resources(); verifyELBList(resources, elbs, 1); } @Test public void testElbsWithNoReferencedASGs() { boolean includeInstances = true; boolean includeELbs = false; AWSClient client = createMockAWSClient(); List<LoadBalancerDescription> elbs = createELBList(includeInstances); List<AutoScalingGroup> asgs = createASGList(includeELbs); addELBsToMock(client, elbs); addASGsToMock(client, asgs); ELBJanitorCrawler crawler = new ELBJanitorCrawler(client); List<Resource> resources = crawler.resources(); verifyELBList(resources, elbs, 0); } @Test public void testElbsWithMultipleReferencedASGs() { boolean includeInstances = true; boolean includeELbs = false; AWSClient client = createMockAWSClient(); List<LoadBalancerDescription> elbs = createELBList(includeInstances); List<AutoScalingGroup> asgs = createASGList(includeELbs); asgs.get(0).setLoadBalancerNames(Arrays.asList("elb1", "elb2")); addELBsToMock(client, elbs); addASGsToMock(client, asgs); ELBJanitorCrawler crawler = new ELBJanitorCrawler(client); List<Resource> resources = crawler.resources(); verifyELBList(resources, elbs, 1); } private void verifyELBList(List<Resource> resources, List<LoadBalancerDescription> elbList) { verifyELBList(resources, elbList, 0); } private void verifyELBList(List<Resource> resources, List<LoadBalancerDescription> elbList, int asgCount) { Assert.assertEquals(resources.size(), elbList.size()); for (int i = 0; i < resources.size(); i++) { LoadBalancerDescription elb = elbList.get(i); verifyELB(resources.get(i), elb, asgCount); } } private void verifyELB(Resource asg, LoadBalancerDescription elb, int asgCount) { Assert.assertEquals(asg.getResourceType(), AWSResourceType.ELB); Assert.assertEquals(asg.getId(), elb.getLoadBalancerName()); Assert.assertEquals(asg.getRegion(), "us-east-1"); int instanceCount = elb.getInstances().size(); int resourceInstanceCount = NumberUtils.toInt(asg.getAdditionalField("instanceCount")); Assert.assertEquals(instanceCount, resourceInstanceCount); int resourceASGCount = NumberUtils.toInt(asg.getAdditionalField("referencedASGCount")); Assert.assertEquals(resourceASGCount, asgCount); } private AWSClient createMockAWSClient() { AWSClient awsMock = mock(AWSClient.class); return awsMock; } private void addELBsToMock(AWSClient awsMock, List<LoadBalancerDescription> elbList, String... elbNames) { when(awsMock.describeElasticLoadBalancers(elbNames)).thenReturn(elbList); when(awsMock.region()).thenReturn("us-east-1"); } private void addASGsToMock(AWSClient awsMock, List<AutoScalingGroup> asgList) { when(awsMock.describeAutoScalingGroups()).thenReturn(asgList); when(awsMock.region()).thenReturn("us-east-1"); } private List<LoadBalancerDescription> createELBList(boolean includeInstances) { List<LoadBalancerDescription> elbList = new LinkedList<>(); elbList.add(mkELB("elb1", includeInstances)); elbList.add(mkELB("elb2", includeInstances)); return elbList; } private LoadBalancerDescription mkELB(String elbName, boolean includeInstances) { LoadBalancerDescription elb = new LoadBalancerDescription().withLoadBalancerName(elbName); if (includeInstances) { List<Instance> instances = new LinkedList<>(); Instance i1 = new Instance().withInstanceId("i-000001"); Instance i2 = new Instance().withInstanceId("i-000002"); elb.setInstances(instances); } return elb; } private List<AutoScalingGroup> createASGList(boolean includeElbs) { List<AutoScalingGroup> asgList = new LinkedList<AutoScalingGroup>(); if (includeElbs) { asgList.add(mkASG("asg1", "elb1")); asgList.add(mkASG("asg2", "elb2")); } else { asgList.add(mkASG("asg1", null)); asgList.add(mkASG("asg2", null)); } return asgList; } private AutoScalingGroup mkASG(String asgName, String elb) { AutoScalingGroup asg = new AutoScalingGroup().withAutoScalingGroupName(asgName); asg.setLoadBalancerNames(Arrays.asList(elb)); return asg; } }
4,734
0
Create_ds/SimianArmy/src/test/java/com/netflix/simianarmy/aws/janitor
Create_ds/SimianArmy/src/test/java/com/netflix/simianarmy/aws/janitor/rule/TestMonkeyCalendar.java
/* * * Copyright 2012 Netflix, Inc. * * Licensed 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. * */ // CHECKSTYLE IGNORE Javadoc // CHECKSTYLE IGNORE MagicNumberCheck package com.netflix.simianarmy.aws.janitor.rule; import java.util.Calendar; import java.util.Date; import org.joda.time.DateTime; import com.netflix.simianarmy.Monkey; import com.netflix.simianarmy.MonkeyCalendar; /** * The class is an implementation of MonkeyCalendar that can always run and * considers calendar days only when calculating the termination date. * */ public class TestMonkeyCalendar implements MonkeyCalendar { @Override public boolean isMonkeyTime(Monkey monkey) { return true; } @Override public int openHour() { return 0; } @Override public int closeHour() { return 24; } @Override public Calendar now() { return Calendar.getInstance(); } @Override public Date getBusinessDay(Date date, int n) { DateTime target = new DateTime(date.getTime()).plusDays(n); return new Date(target.getMillis()); } }
4,735
0
Create_ds/SimianArmy/src/test/java/com/netflix/simianarmy/aws/janitor/rule
Create_ds/SimianArmy/src/test/java/com/netflix/simianarmy/aws/janitor/rule/snapshot/TestNoGeneratedAMIRule.java
/* * * Copyright 2012 Netflix, Inc. * * Licensed 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. * */ //CHECKSTYLE IGNORE Javadoc //CHECKSTYLE IGNORE MagicNumberCheck package com.netflix.simianarmy.aws.janitor.rule.snapshot; import java.util.Date; import org.joda.time.DateTime; import org.testng.Assert; import org.testng.annotations.Test; import com.netflix.simianarmy.Resource; import com.netflix.simianarmy.TestUtils; import com.netflix.simianarmy.aws.AWSResource; import com.netflix.simianarmy.aws.AWSResourceType; import com.netflix.simianarmy.aws.janitor.crawler.EBSSnapshotJanitorCrawler; import com.netflix.simianarmy.aws.janitor.rule.TestMonkeyCalendar; import com.netflix.simianarmy.janitor.JanitorMonkey; public class TestNoGeneratedAMIRule { @Test public void testNonSnapshotResource() { Resource resource = new AWSResource().withId("asg1").withResourceType(AWSResourceType.ASG); ((AWSResource) resource).setAWSResourceState("completed"); NoGeneratedAMIRule rule = new NoGeneratedAMIRule(new TestMonkeyCalendar(), 0, 0); Assert.assertTrue(rule.isValid(resource)); Assert.assertNull(resource.getExpectedTerminationTime()); } @Test public void testUncompletedVolume() { Resource resource = new AWSResource().withId("snap-12345678901234567").withResourceType(AWSResourceType.EBS_SNAPSHOT); ((AWSResource) resource).setAWSResourceState("stopped"); NoGeneratedAMIRule rule = new NoGeneratedAMIRule(new TestMonkeyCalendar(), 0, 0); Assert.assertTrue(rule.isValid(resource)); Assert.assertNull(resource.getExpectedTerminationTime()); } @Test public void testTaggedAsNotMark() { int ageThreshold = 5; DateTime now = DateTime.now(); Resource resource = new AWSResource().withId("snap-12345678901234567").withResourceType(AWSResourceType.EBS_SNAPSHOT) .withLaunchTime(new Date(now.minusDays(ageThreshold + 1).getMillis())); ((AWSResource) resource).setAWSResourceState("completed"); int retentionDays = 4; NoGeneratedAMIRule rule = new NoGeneratedAMIRule(new TestMonkeyCalendar(), ageThreshold, retentionDays); resource.setTag(JanitorMonkey.JANITOR_TAG, "donotmark"); Assert.assertTrue(rule.isValid(resource)); Assert.assertNull(resource.getExpectedTerminationTime()); } @Test public void testUserSpecifiedTerminationDate() { int ageThreshold = 5; DateTime now = DateTime.now(); Resource resource = new AWSResource().withId("snap-12345678901234567").withResourceType(AWSResourceType.EBS_SNAPSHOT) .withLaunchTime(new Date(now.minusDays(ageThreshold + 1).getMillis())); ((AWSResource) resource).setAWSResourceState("completed"); int retentionDays = 4; DateTime userDate = new DateTime(now.plusDays(3).withTimeAtStartOfDay()); resource.setTag(JanitorMonkey.JANITOR_TAG, NoGeneratedAMIRule.TERMINATION_DATE_FORMATTER.print(userDate)); NoGeneratedAMIRule rule = new NoGeneratedAMIRule(new TestMonkeyCalendar(), ageThreshold, retentionDays); Assert.assertFalse(rule.isValid(resource)); Assert.assertEquals(resource.getExpectedTerminationTime().getTime(), userDate.getMillis()); } @Test public void testOldSnapshotWithoutAMI() { int ageThreshold = 5; DateTime now = DateTime.now(); Resource resource = new AWSResource().withId("snap-12345678901234567").withResourceType(AWSResourceType.EBS_SNAPSHOT) .withLaunchTime(new Date(now.minusDays(ageThreshold + 1).getMillis())); ((AWSResource) resource).setAWSResourceState("completed"); int retentionDays = 4; NoGeneratedAMIRule rule = new NoGeneratedAMIRule(new TestMonkeyCalendar(), ageThreshold, retentionDays); Assert.assertFalse(rule.isValid(resource)); TestUtils.verifyTerminationTimeRough(resource, retentionDays, now); } @Test public void testSnapshotWithoutAMINotOld() { int ageThreshold = 5; DateTime now = DateTime.now(); Resource resource = new AWSResource().withId("snap-12345678901234567").withResourceType(AWSResourceType.EBS_SNAPSHOT) .withLaunchTime(new Date(now.minusDays(ageThreshold - 1).getMillis())); ((AWSResource) resource).setAWSResourceState("completed"); int retentionDays = 4; NoGeneratedAMIRule rule = new NoGeneratedAMIRule(new TestMonkeyCalendar(), ageThreshold, retentionDays); Assert.assertTrue(rule.isValid(resource)); Assert.assertNull(resource.getExpectedTerminationTime()); } @Test public void testWithAMIs() { int ageThreshold = 5; DateTime now = DateTime.now(); Resource resource = new AWSResource().withId("snap-12345678901234567").withResourceType(AWSResourceType.EBS_SNAPSHOT) .withLaunchTime(new Date(now.minusDays(ageThreshold + 1).getMillis())); ((AWSResource) resource).setAWSResourceState("completed"); resource.setAdditionalField(EBSSnapshotJanitorCrawler.SNAPSHOT_FIELD_AMIS, "ami-123"); int retentionDays = 4; NoGeneratedAMIRule rule = new NoGeneratedAMIRule(new TestMonkeyCalendar(), ageThreshold, retentionDays); Assert.assertTrue(rule.isValid(resource)); Assert.assertNull(resource.getExpectedTerminationTime()); } @Test public void testSnapshotsWithoutLauchTime() { int ageThreshold = 5; Resource resource = new AWSResource().withId("snap-12345678901234567").withResourceType(AWSResourceType.EBS_SNAPSHOT); ((AWSResource) resource).setAWSResourceState("completed"); int retentionDays = 4; NoGeneratedAMIRule rule = new NoGeneratedAMIRule(new TestMonkeyCalendar(), ageThreshold, retentionDays); Assert.assertTrue(rule.isValid(resource)); Assert.assertNull(resource.getExpectedTerminationTime()); } @Test public void testResourceWithExpectedTerminationTimeSet() { int ageThreshold = 5; DateTime now = DateTime.now(); Resource resource = new AWSResource().withId("snap-12345678901234567").withResourceType(AWSResourceType.EBS_SNAPSHOT) .withLaunchTime(new Date(now.minusDays(ageThreshold + 1).getMillis())); ((AWSResource) resource).setAWSResourceState("completed"); Date oldTermDate = new Date(now.plusDays(10).getMillis()); String oldTermReason = "Foo"; int retentionDays = 4; NoGeneratedAMIRule rule = new NoGeneratedAMIRule(new TestMonkeyCalendar(), ageThreshold, retentionDays); resource.setExpectedTerminationTime(oldTermDate); resource.setTerminationReason(oldTermReason); Assert.assertFalse(rule.isValid(resource)); Assert.assertEquals(oldTermDate, resource.getExpectedTerminationTime()); Assert.assertEquals(oldTermReason, resource.getTerminationReason()); } @Test public void testOldSnapshotWithoutAMIWithOwnerOverride() { int ageThreshold = 5; DateTime now = DateTime.now(); Resource resource = new AWSResource().withId("snap-12345678901234567").withOwnerEmail("owner@netflix.com").withResourceType(AWSResourceType.EBS_SNAPSHOT) .withLaunchTime(new Date(now.minusDays(ageThreshold + 1).getMillis())); ((AWSResource) resource).setAWSResourceState("completed"); int retentionDays = 4; NoGeneratedAMIRule rule = new NoGeneratedAMIRule(new TestMonkeyCalendar(), ageThreshold, retentionDays, "new_owner@netflix.com"); Assert.assertFalse(rule.isValid(resource)); Assert.assertEquals(resource.getOwnerEmail(), "new_owner@netflix.com"); TestUtils.verifyTerminationTimeRough(resource, retentionDays, now); } @Test public void testOldSnapshotWithoutAMIWithoutOwnerOverride() { int ageThreshold = 5; DateTime now = DateTime.now(); Resource resource = new AWSResource().withId("snap-12345678901234567").withOwnerEmail("owner@netflix.com").withResourceType(AWSResourceType.EBS_SNAPSHOT) .withLaunchTime(new Date(now.minusDays(ageThreshold + 1).getMillis())); ((AWSResource) resource).setAWSResourceState("completed"); int retentionDays = 4; NoGeneratedAMIRule rule = new NoGeneratedAMIRule(new TestMonkeyCalendar(), ageThreshold, retentionDays); Assert.assertFalse(rule.isValid(resource)); Assert.assertEquals(resource.getOwnerEmail(), "owner@netflix.com"); TestUtils.verifyTerminationTimeRough(resource, retentionDays, now); } @Test(expectedExceptions = IllegalArgumentException.class) public void testNullResource() { NoGeneratedAMIRule rule = new NoGeneratedAMIRule(new TestMonkeyCalendar(), 5, 4); rule.isValid(null); } @Test(expectedExceptions = IllegalArgumentException.class) public void testNgativeAgeThreshold() { new NoGeneratedAMIRule(new TestMonkeyCalendar(), -1, 4); } @Test(expectedExceptions = IllegalArgumentException.class) public void testNgativeRetentionDaysWithOwner() { new NoGeneratedAMIRule(new TestMonkeyCalendar(), 5, -4); } @Test(expectedExceptions = IllegalArgumentException.class) public void testNullCalendar() { new NoGeneratedAMIRule(null, 5, 4); } }
4,736
0
Create_ds/SimianArmy/src/test/java/com/netflix/simianarmy/aws/janitor/rule
Create_ds/SimianArmy/src/test/java/com/netflix/simianarmy/aws/janitor/rule/elb/TestOrphanedELBRule.java
/* * * Copyright 2012 Netflix, Inc. * * Licensed 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. * */ // CHECKSTYLE IGNORE Javadoc // CHECKSTYLE IGNORE MagicNumberCheck package com.netflix.simianarmy.aws.janitor.rule.elb; import com.netflix.simianarmy.Resource; import com.netflix.simianarmy.TestUtils; import com.netflix.simianarmy.aws.AWSResource; import com.netflix.simianarmy.aws.AWSResourceType; import com.netflix.simianarmy.aws.janitor.rule.TestMonkeyCalendar; import org.joda.time.DateTime; import org.testng.Assert; import org.testng.annotations.Test; public class TestOrphanedELBRule { @Test public void testELBWithNoInstancesNoASGs() { DateTime now = DateTime.now(); Resource resource = new AWSResource().withId("test-elb").withResourceType(AWSResourceType.ELB) .withOwnerEmail("owner@foo.com"); resource.setAdditionalField("referencedASGCount", "0"); resource.setAdditionalField("instanceCount", "0"); OrphanedELBRule rule = new OrphanedELBRule(new TestMonkeyCalendar(), 7); Assert.assertFalse(rule.isValid(resource)); TestUtils.verifyTerminationTimeRough(resource, 7, now); } @Test public void testELBWithInstancesNoASGs() { DateTime now = DateTime.now(); Resource resource = new AWSResource().withId("test-elb").withResourceType(AWSResourceType.ELB) .withOwnerEmail("owner@foo.com"); resource.setAdditionalField("referencedASGCount", "0"); resource.setAdditionalField("instanceCount", "4"); OrphanedELBRule rule = new OrphanedELBRule(new TestMonkeyCalendar(), 7); Assert.assertTrue(rule.isValid(resource)); } @Test public void testELBWithReferencedASGsNoInstances() { DateTime now = DateTime.now(); Resource resource = new AWSResource().withId("test-elb").withResourceType(AWSResourceType.ELB) .withOwnerEmail("owner@foo.com"); resource.setAdditionalField("referencedASGCount", "4"); resource.setAdditionalField("instanceCount", "0"); OrphanedELBRule rule = new OrphanedELBRule(new TestMonkeyCalendar(), 7); Assert.assertTrue(rule.isValid(resource)); } @Test public void testMissingInstanceCountCheck() { DateTime now = DateTime.now(); Resource resource = new AWSResource().withId("test-elb").withResourceType(AWSResourceType.ELB) .withOwnerEmail("owner@foo.com"); resource.setAdditionalField("referencedASGCount", "0"); OrphanedELBRule rule = new OrphanedELBRule(new TestMonkeyCalendar(), 7); Assert.assertTrue(rule.isValid(resource)); } @Test public void testMissingReferencedASGCountCheck() { DateTime now = DateTime.now(); Resource resource = new AWSResource().withId("test-elb").withResourceType(AWSResourceType.ELB) .withOwnerEmail("owner@foo.com"); resource.setAdditionalField("instanceCount", "0"); OrphanedELBRule rule = new OrphanedELBRule(new TestMonkeyCalendar(), 7); Assert.assertTrue(rule.isValid(resource)); } @Test public void testMissingCountsCheck() { DateTime now = DateTime.now(); Resource resource = new AWSResource().withId("test-elb").withResourceType(AWSResourceType.ELB) .withOwnerEmail("owner@foo.com"); OrphanedELBRule rule = new OrphanedELBRule(new TestMonkeyCalendar(), 7); Assert.assertTrue(rule.isValid(resource)); } @Test public void testMissingCountsCheckWithExtraFields() { DateTime now = DateTime.now(); Resource resource = new AWSResource().withId("test-elb").withResourceType(AWSResourceType.ELB) .withOwnerEmail("owner@foo.com"); resource.setAdditionalField("bogusField1", "0"); resource.setAdditionalField("bogusField2", "0"); OrphanedELBRule rule = new OrphanedELBRule(new TestMonkeyCalendar(), 7); Assert.assertTrue(rule.isValid(resource)); } }
4,737
0
Create_ds/SimianArmy/src/test/java/com/netflix/simianarmy/aws/janitor/rule
Create_ds/SimianArmy/src/test/java/com/netflix/simianarmy/aws/janitor/rule/launchconfig/TestOldUnusedLaunchConfigRule.java
/* * * Copyright 2012 Netflix, Inc. * * Licensed 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. * */ // CHECKSTYLE IGNORE Javadoc // CHECKSTYLE IGNORE MagicNumberCheck package com.netflix.simianarmy.aws.janitor.rule.launchconfig; import com.netflix.simianarmy.MonkeyCalendar; import com.netflix.simianarmy.Resource; import com.netflix.simianarmy.TestUtils; import com.netflix.simianarmy.aws.AWSResource; import com.netflix.simianarmy.aws.AWSResourceType; import com.netflix.simianarmy.aws.janitor.crawler.LaunchConfigJanitorCrawler; import com.netflix.simianarmy.aws.janitor.rule.TestMonkeyCalendar; import org.joda.time.DateTime; import org.testng.Assert; import org.testng.annotations.Test; import java.util.Date; public class TestOldUnusedLaunchConfigRule { @Test public void testOldUnsedLaunchConfig() { Resource resource = new AWSResource().withId("launchConfig1").withResourceType(AWSResourceType.LAUNCH_CONFIG); resource.setAdditionalField(LaunchConfigJanitorCrawler.LAUNCH_CONFIG_FIELD_USED_BY_ASG, "false"); MonkeyCalendar calendar = new TestMonkeyCalendar(); int ageThreshold = 3; DateTime now = new DateTime(calendar.now().getTimeInMillis()); resource.setLaunchTime(new Date(now.minusDays(ageThreshold + 1).getMillis())); int retentionDays = 3; OldUnusedLaunchConfigRule rule = new OldUnusedLaunchConfigRule(calendar, ageThreshold, retentionDays); Assert.assertFalse(rule.isValid(resource)); TestUtils.verifyTerminationTimeRough(resource, retentionDays, now); } @Test public void testOldLaunchConfigWithNullFlag() { Resource resource = new AWSResource().withId("launchConfig1").withResourceType(AWSResourceType.LAUNCH_CONFIG); MonkeyCalendar calendar = new TestMonkeyCalendar(); int ageThreshold = 3; DateTime now = new DateTime(calendar.now().getTimeInMillis()); resource.setLaunchTime(new Date(now.minusDays(ageThreshold + 1).getMillis())); int retentionDays = 3; OldUnusedLaunchConfigRule rule = new OldUnusedLaunchConfigRule(calendar, ageThreshold, retentionDays); Assert.assertTrue(rule.isValid(resource)); Assert.assertNull(resource.getExpectedTerminationTime()); } @Test public void testUnsedLaunchConfigNotOld() { Resource resource = new AWSResource().withId("launchConfig1").withResourceType(AWSResourceType.LAUNCH_CONFIG); resource.setAdditionalField(LaunchConfigJanitorCrawler.LAUNCH_CONFIG_FIELD_USED_BY_ASG, "false"); MonkeyCalendar calendar = new TestMonkeyCalendar(); int ageThreshold = 3; DateTime now = new DateTime(calendar.now().getTimeInMillis()); resource.setLaunchTime(new Date(now.minusDays(ageThreshold - 1).getMillis())); int retentionDays = 3; OldUnusedLaunchConfigRule rule = new OldUnusedLaunchConfigRule(calendar, ageThreshold, retentionDays); Assert.assertTrue(rule.isValid(resource)); Assert.assertNull(resource.getExpectedTerminationTime()); } @Test public void testUsedLaunchConfig() { Resource resource = new AWSResource().withId("launchConfig1").withResourceType(AWSResourceType.LAUNCH_CONFIG); resource.setAdditionalField(LaunchConfigJanitorCrawler.LAUNCH_CONFIG_FIELD_USED_BY_ASG, "true"); MonkeyCalendar calendar = new TestMonkeyCalendar(); int ageThreshold = 3; DateTime now = new DateTime(calendar.now().getTimeInMillis()); resource.setLaunchTime(new Date(now.minusDays(ageThreshold + 1).getMillis())); int retentionDays = 3; OldUnusedLaunchConfigRule rule = new OldUnusedLaunchConfigRule(calendar, ageThreshold, retentionDays); Assert.assertTrue(rule.isValid(resource)); Assert.assertNull(resource.getExpectedTerminationTime()); } @Test public void testUsedLaunchConfigNoLaunchTimeSet() { Resource resource = new AWSResource().withId("launchConfig1").withResourceType(AWSResourceType.LAUNCH_CONFIG); resource.setAdditionalField(LaunchConfigJanitorCrawler.LAUNCH_CONFIG_FIELD_USED_BY_ASG, "true"); MonkeyCalendar calendar = new TestMonkeyCalendar(); int ageThreshold = 3; int retentionDays = 3; OldUnusedLaunchConfigRule rule = new OldUnusedLaunchConfigRule(calendar, ageThreshold, retentionDays); Assert.assertTrue(rule.isValid(resource)); Assert.assertNull(resource.getExpectedTerminationTime()); } @Test public void testResourceWithExpectedTerminationTimeSet() { Resource resource = new AWSResource().withId("launchConfig1").withResourceType(AWSResourceType.LAUNCH_CONFIG); resource.setAdditionalField(LaunchConfigJanitorCrawler.LAUNCH_CONFIG_FIELD_USED_BY_ASG, "false"); MonkeyCalendar calendar = new TestMonkeyCalendar(); int ageThreshold = 3; DateTime now = new DateTime(calendar.now().getTimeInMillis()); resource.setLaunchTime(new Date(now.minusDays(ageThreshold + 1).getMillis())); Date oldTermDate = new Date(now.minusDays(10).getMillis()); String oldTermReason = "Foo"; resource.setExpectedTerminationTime(oldTermDate); resource.setTerminationReason(oldTermReason); int retentionDays = 3; OldUnusedLaunchConfigRule rule = new OldUnusedLaunchConfigRule(calendar, ageThreshold, retentionDays); Assert.assertFalse(rule.isValid(resource)); Assert.assertEquals(oldTermDate, resource.getExpectedTerminationTime()); Assert.assertEquals(oldTermReason, resource.getTerminationReason()); } @Test(expectedExceptions = IllegalArgumentException.class) public void testNullResource() { OldUnusedLaunchConfigRule rule = new OldUnusedLaunchConfigRule(new TestMonkeyCalendar(), 3, 3); rule.isValid(null); } @Test(expectedExceptions = IllegalArgumentException.class) public void testNgativeRetentionDays() { new OldUnusedLaunchConfigRule(new TestMonkeyCalendar(), -1, 60); } @Test(expectedExceptions = IllegalArgumentException.class) public void testNgativeLaunchConfigAgeThreshold() { new OldUnusedLaunchConfigRule(new TestMonkeyCalendar(), 3, -1); } @Test(expectedExceptions = IllegalArgumentException.class) public void testNullCalendar() { new OldUnusedLaunchConfigRule(null, 3, 60); } @Test public void testNonLaunchConfigResource() { Resource resource = new AWSResource().withId("i-12345678901234567").withResourceType(AWSResourceType.INSTANCE); OldUnusedLaunchConfigRule rule = new OldUnusedLaunchConfigRule(new TestMonkeyCalendar(), 3, 60); Assert.assertTrue(rule.isValid(resource)); Assert.assertNull(resource.getExpectedTerminationTime()); } }
4,738
0
Create_ds/SimianArmy/src/test/java/com/netflix/simianarmy/aws/janitor/rule
Create_ds/SimianArmy/src/test/java/com/netflix/simianarmy/aws/janitor/rule/asg/TestSuspendedASGRule.java
/* * * Copyright 2012 Netflix, Inc. * * Licensed 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. * */ //CHECKSTYLE IGNORE Javadoc //CHECKSTYLE IGNORE MagicNumberCheck package com.netflix.simianarmy.aws.janitor.rule.asg; import java.util.Date; import org.joda.time.DateTime; import org.testng.Assert; import org.testng.annotations.Test; import com.netflix.simianarmy.MonkeyCalendar; import com.netflix.simianarmy.Resource; import com.netflix.simianarmy.TestUtils; import com.netflix.simianarmy.aws.AWSResource; import com.netflix.simianarmy.aws.AWSResourceType; import com.netflix.simianarmy.aws.janitor.crawler.ASGJanitorCrawler; import com.netflix.simianarmy.aws.janitor.rule.TestMonkeyCalendar; public class TestSuspendedASGRule { @Test public void testEmptyASGSuspendedMoreThanThreshold() { Resource resource = new AWSResource().withId("asg1").withResourceType(AWSResourceType.ASG); resource.setAdditionalField(ASGJanitorCrawler.ASG_FIELD_MAX_SIZE, "0"); MonkeyCalendar calendar = new TestMonkeyCalendar(); DateTime now = new DateTime(calendar.now().getTimeInMillis()); int suspensionAgeThreshold = 2; DateTime suspensionTime = now.minusDays(suspensionAgeThreshold + 1); resource.setAdditionalField(ASGJanitorCrawler.ASG_FIELD_SUSPENSION_TIME, ASGJanitorCrawler.SUSPENSION_TIME_FORMATTER.print(suspensionTime)); int retentionDays = 3; SuspendedASGRule rule = new SuspendedASGRule(calendar, suspensionAgeThreshold, retentionDays, new DummyASGInstanceValidator()); Assert.assertFalse(rule.isValid(resource)); TestUtils.verifyTerminationTimeRough(resource, retentionDays, now); } @Test public void testEmptyASGSuspendedLessThanThreshold() { Resource resource = new AWSResource().withId("asg1").withResourceType(AWSResourceType.ASG); resource.setAdditionalField(ASGJanitorCrawler.ASG_FIELD_LC_NAME, "launchConfig"); resource.setAdditionalField(ASGJanitorCrawler.ASG_FIELD_MAX_SIZE, "0"); int suspensionAgeThreshold = 2; MonkeyCalendar calendar = new TestMonkeyCalendar(); DateTime now = new DateTime(calendar.now().getTimeInMillis()); resource.setAdditionalField(ASGJanitorCrawler.ASG_FIELD_LC_CREATION_TIME, String.valueOf(now.minusDays(suspensionAgeThreshold + 1).getMillis())); int retentionDays = 3; SuspendedASGRule rule = new SuspendedASGRule(calendar, suspensionAgeThreshold, retentionDays, new DummyASGInstanceValidator()); Assert.assertTrue(rule.isValid(resource)); Assert.assertNull(resource.getExpectedTerminationTime()); } @Test public void testASGWithInstances() { Resource resource = new AWSResource().withId("asg1").withResourceType(AWSResourceType.ASG); resource.setAdditionalField(ASGJanitorCrawler.ASG_FIELD_MAX_SIZE, "2"); resource.setAdditionalField(ASGJanitorCrawler.ASG_FIELD_INSTANCES, "123456789012345671,i-123456789012345672"); int suspensionAgeThreshold = 2; MonkeyCalendar calendar = new TestMonkeyCalendar(); DateTime now = new DateTime(calendar.now().getTimeInMillis()); DateTime suspensionTime = now.minusDays(suspensionAgeThreshold + 1); resource.setAdditionalField(ASGJanitorCrawler.ASG_FIELD_SUSPENSION_TIME, ASGJanitorCrawler.SUSPENSION_TIME_FORMATTER.print(suspensionTime)); int retentionDays = 3; SuspendedASGRule rule = new SuspendedASGRule(calendar, suspensionAgeThreshold, retentionDays, new DummyASGInstanceValidator()); Assert.assertTrue(rule.isValid(resource)); Assert.assertNull(resource.getExpectedTerminationTime()); } @Test public void testASGWithoutInstanceAndNonZeroSize() { Resource resource = new AWSResource().withId("asg1").withResourceType(AWSResourceType.ASG); resource.setAdditionalField(ASGJanitorCrawler.ASG_FIELD_MAX_SIZE, "2"); int suspensionAgeThreshold = 2; MonkeyCalendar calendar = new TestMonkeyCalendar(); DateTime now = new DateTime(calendar.now().getTimeInMillis()); DateTime suspensionTime = now.minusDays(suspensionAgeThreshold + 1); resource.setAdditionalField(ASGJanitorCrawler.ASG_FIELD_SUSPENSION_TIME, ASGJanitorCrawler.SUSPENSION_TIME_FORMATTER.print(suspensionTime)); int retentionDays = 3; SuspendedASGRule rule = new SuspendedASGRule(calendar, suspensionAgeThreshold, retentionDays, new DummyASGInstanceValidator()); Assert.assertTrue(rule.isValid(resource)); Assert.assertNull(resource.getExpectedTerminationTime()); } @Test public void testEmptyASGNotSuspended() { Resource resource = new AWSResource().withId("asg1").withResourceType(AWSResourceType.ASG); resource.setAdditionalField(ASGJanitorCrawler.ASG_FIELD_MAX_SIZE, "0"); int suspensionAgeThreshold = 2; MonkeyCalendar calendar = new TestMonkeyCalendar(); int retentionDays = 3; SuspendedASGRule rule = new SuspendedASGRule(calendar, suspensionAgeThreshold, retentionDays, new DummyASGInstanceValidator()); Assert.assertTrue(rule.isValid(resource)); Assert.assertNull(resource.getExpectedTerminationTime()); } @Test public void testResourceWithExpectedTerminationTimeSet() { Resource resource = new AWSResource().withId("asg1").withResourceType(AWSResourceType.ASG); resource.setAdditionalField(ASGJanitorCrawler.ASG_FIELD_MAX_SIZE, "0"); MonkeyCalendar calendar = new TestMonkeyCalendar(); DateTime now = new DateTime(calendar.now().getTimeInMillis()); int suspensionAgeThreshold = 2; DateTime suspensionTime = now.minusDays(suspensionAgeThreshold + 1); resource.setAdditionalField(ASGJanitorCrawler.ASG_FIELD_SUSPENSION_TIME, ASGJanitorCrawler.SUSPENSION_TIME_FORMATTER.print(suspensionTime)); int retentionDays = 3; SuspendedASGRule rule = new SuspendedASGRule(calendar, suspensionAgeThreshold, retentionDays, new DummyASGInstanceValidator()); Date oldTermDate = new Date(now.plusDays(10).getMillis()); String oldTermReason = "Foo"; resource.setExpectedTerminationTime(oldTermDate); resource.setTerminationReason(oldTermReason); Assert.assertFalse(rule.isValid(resource)); Assert.assertEquals(oldTermDate, resource.getExpectedTerminationTime()); Assert.assertEquals(oldTermReason, resource.getTerminationReason()); } @Test(expectedExceptions = IllegalArgumentException.class) public void testNullResource() { SuspendedASGRule rule = new SuspendedASGRule(new TestMonkeyCalendar(), 3, 2, new DummyASGInstanceValidator()); rule.isValid(null); } @Test(expectedExceptions = IllegalArgumentException.class) public void testNullValidator() { new SuspendedASGRule(new TestMonkeyCalendar(), 3, 2, null); } @Test(expectedExceptions = IllegalArgumentException.class) public void testNgativeRetentionDays() { new SuspendedASGRule(new TestMonkeyCalendar(), -1, 2, new DummyASGInstanceValidator()); } @Test(expectedExceptions = IllegalArgumentException.class) public void testNgativeLaunchConfigAgeThreshold() { new SuspendedASGRule(new TestMonkeyCalendar(), 3, -1, new DummyASGInstanceValidator()); } @Test(expectedExceptions = IllegalArgumentException.class) public void testSuspensionTimeIncorrectFormat() { Resource resource = new AWSResource().withId("asg1").withResourceType(AWSResourceType.ASG); resource.setAdditionalField(ASGJanitorCrawler.ASG_FIELD_MAX_SIZE, "0"); MonkeyCalendar calendar = new TestMonkeyCalendar(); int suspensionAgeThreshold = 2; resource.setAdditionalField(ASGJanitorCrawler.ASG_FIELD_SUSPENSION_TIME, "foo"); int retentionDays = 3; SuspendedASGRule rule = new SuspendedASGRule(calendar, suspensionAgeThreshold, retentionDays, new DummyASGInstanceValidator()); Assert.assertFalse(rule.isValid(resource)); } @Test public void testNonASGResource() { Resource resource = new AWSResource().withId("i-12345678901234567").withResourceType(AWSResourceType.INSTANCE); SuspendedASGRule rule = new SuspendedASGRule(new TestMonkeyCalendar(), 3, 2, new DummyASGInstanceValidator()); Assert.assertTrue(rule.isValid(resource)); Assert.assertNull(resource.getExpectedTerminationTime()); } @Test(expectedExceptions = IllegalArgumentException.class) public void testNullCalendar() { new SuspendedASGRule(null, 3, 2, null); } }
4,739
0
Create_ds/SimianArmy/src/test/java/com/netflix/simianarmy/aws/janitor/rule
Create_ds/SimianArmy/src/test/java/com/netflix/simianarmy/aws/janitor/rule/asg/TestOldEmptyASGRule.java
/* * * Copyright 2012 Netflix, Inc. * * Licensed 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. * */ // CHECKSTYLE IGNORE Javadoc // CHECKSTYLE IGNORE MagicNumberCheck package com.netflix.simianarmy.aws.janitor.rule.asg; import java.util.Date; import org.joda.time.DateTime; import org.testng.Assert; import org.testng.annotations.Test; import com.netflix.simianarmy.MonkeyCalendar; import com.netflix.simianarmy.Resource; import com.netflix.simianarmy.TestUtils; import com.netflix.simianarmy.aws.AWSResource; import com.netflix.simianarmy.aws.AWSResourceType; import com.netflix.simianarmy.aws.janitor.crawler.ASGJanitorCrawler; import com.netflix.simianarmy.aws.janitor.rule.TestMonkeyCalendar; public class TestOldEmptyASGRule { @Test public void testEmptyASGWithObsoleteLaunchConfig() { Resource resource = new AWSResource().withId("asg1").withResourceType(AWSResourceType.ASG); resource.setAdditionalField(ASGJanitorCrawler.ASG_FIELD_LC_NAME, "launchConfig"); resource.setAdditionalField(ASGJanitorCrawler.ASG_FIELD_MAX_SIZE, "0"); int launchConfiguAgeThreshold = 60; MonkeyCalendar calendar = new TestMonkeyCalendar(); DateTime now = new DateTime(calendar.now().getTimeInMillis()); resource.setAdditionalField(ASGJanitorCrawler.ASG_FIELD_LC_CREATION_TIME, String.valueOf(now.minusDays(launchConfiguAgeThreshold + 1).getMillis())); int retentionDays = 3; OldEmptyASGRule rule = new OldEmptyASGRule(calendar, launchConfiguAgeThreshold, retentionDays, new DummyASGInstanceValidator()); Assert.assertFalse(rule.isValid(resource)); TestUtils.verifyTerminationTimeRough(resource, retentionDays, now); } @Test public void testEmptyASGWithValidLaunchConfig() { Resource resource = new AWSResource().withId("asg1").withResourceType(AWSResourceType.ASG); resource.setAdditionalField(ASGJanitorCrawler.ASG_FIELD_LC_NAME, "launchConfig"); resource.setAdditionalField(ASGJanitorCrawler.ASG_FIELD_MAX_SIZE, "0"); int launchConfiguAgeThreshold = 60; MonkeyCalendar calendar = new TestMonkeyCalendar(); DateTime now = new DateTime(calendar.now().getTimeInMillis()); resource.setAdditionalField(ASGJanitorCrawler.ASG_FIELD_LC_CREATION_TIME, String.valueOf(now.minusDays(launchConfiguAgeThreshold - 1).getMillis())); int retentionDays = 3; OldEmptyASGRule rule = new OldEmptyASGRule(calendar, launchConfiguAgeThreshold, retentionDays, new DummyASGInstanceValidator()); Assert.assertTrue(rule.isValid(resource)); Assert.assertNull(resource.getExpectedTerminationTime()); } @Test public void testASGWithInstances() { Resource resource = new AWSResource().withId("asg1").withResourceType(AWSResourceType.ASG); resource.setAdditionalField(ASGJanitorCrawler.ASG_FIELD_LC_NAME, "launchConfig"); resource.setAdditionalField(ASGJanitorCrawler.ASG_FIELD_MAX_SIZE, "2"); resource.setAdditionalField(ASGJanitorCrawler.ASG_FIELD_INSTANCES, "123456789012345671,i-123456789012345672"); int launchConfiguAgeThreshold = 60; MonkeyCalendar calendar = new TestMonkeyCalendar(); DateTime now = new DateTime(calendar.now().getTimeInMillis()); resource.setAdditionalField(ASGJanitorCrawler.ASG_FIELD_LC_CREATION_TIME, String.valueOf(now.minusDays(launchConfiguAgeThreshold + 1).getMillis())); int retentionDays = 3; OldEmptyASGRule rule = new OldEmptyASGRule(calendar, launchConfiguAgeThreshold, retentionDays, new DummyASGInstanceValidator()); Assert.assertTrue(rule.isValid(resource)); Assert.assertNull(resource.getExpectedTerminationTime()); } @Test public void testASGWithoutInstanceAndNonZeroSize() { Resource resource = new AWSResource().withId("asg1").withResourceType(AWSResourceType.ASG); resource.setAdditionalField(ASGJanitorCrawler.ASG_FIELD_LC_NAME, "launchConfig"); resource.setAdditionalField(ASGJanitorCrawler.ASG_FIELD_MAX_SIZE, "2"); int launchConfiguAgeThreshold = 60; MonkeyCalendar calendar = new TestMonkeyCalendar(); DateTime now = new DateTime(calendar.now().getTimeInMillis()); resource.setAdditionalField(ASGJanitorCrawler.ASG_FIELD_LC_CREATION_TIME, String.valueOf(now.minusDays(launchConfiguAgeThreshold + 1).getMillis())); int retentionDays = 3; OldEmptyASGRule rule = new OldEmptyASGRule(calendar, launchConfiguAgeThreshold, retentionDays, new DummyASGInstanceValidator()); Assert.assertTrue(rule.isValid(resource)); Assert.assertNull(resource.getExpectedTerminationTime()); } @Test public void testEmptyASGWithoutLaunchConfig() { Resource resource = new AWSResource().withId("asg1").withResourceType(AWSResourceType.ASG); resource.setAdditionalField(ASGJanitorCrawler.ASG_FIELD_MAX_SIZE, "0"); int launchConfiguAgeThreshold = 60; MonkeyCalendar calendar = new TestMonkeyCalendar(); DateTime now = new DateTime(calendar.now().getTimeInMillis()); int retentionDays = 3; OldEmptyASGRule rule = new OldEmptyASGRule(calendar, launchConfiguAgeThreshold, retentionDays, new DummyASGInstanceValidator()); Assert.assertFalse(rule.isValid(resource)); TestUtils.verifyTerminationTimeRough(resource, retentionDays, now); } @Test public void testEmptyASGWithLaunchConfigWithoutCreateTime() { Resource resource = new AWSResource().withId("asg1").withResourceType(AWSResourceType.ASG); resource.setAdditionalField(ASGJanitorCrawler.ASG_FIELD_LC_NAME, "launchConfig"); resource.setAdditionalField(ASGJanitorCrawler.ASG_FIELD_MAX_SIZE, "0"); int launchConfiguAgeThreshold = 60; MonkeyCalendar calendar = new TestMonkeyCalendar(); int retentionDays = 3; OldEmptyASGRule rule = new OldEmptyASGRule(calendar, launchConfiguAgeThreshold, retentionDays, new DummyASGInstanceValidator()); Assert.assertTrue(rule.isValid(resource)); Assert.assertNull(resource.getExpectedTerminationTime()); } @Test public void testResourceWithExpectedTerminationTimeSet() { Resource resource = new AWSResource().withId("asg1").withResourceType(AWSResourceType.ASG); resource.setAdditionalField(ASGJanitorCrawler.ASG_FIELD_MAX_SIZE, "0"); int launchConfiguAgeThreshold = 60; MonkeyCalendar calendar = new TestMonkeyCalendar(); DateTime now = new DateTime(calendar.now().getTimeInMillis()); int retentionDays = 3; OldEmptyASGRule rule = new OldEmptyASGRule(calendar, launchConfiguAgeThreshold, retentionDays, new DummyASGInstanceValidator()); Date oldTermDate = new Date(now.plusDays(10).getMillis()); String oldTermReason = "Foo"; resource.setExpectedTerminationTime(oldTermDate); resource.setTerminationReason(oldTermReason); Assert.assertFalse(rule.isValid(resource)); Assert.assertEquals(oldTermDate, resource.getExpectedTerminationTime()); Assert.assertEquals(oldTermReason, resource.getTerminationReason()); } @Test(expectedExceptions = IllegalArgumentException.class) public void testNullValidator() { new OldEmptyASGRule(new TestMonkeyCalendar(), 3, 60, null); } @Test(expectedExceptions = IllegalArgumentException.class) public void testNullResource() { OldEmptyASGRule rule = new OldEmptyASGRule(new TestMonkeyCalendar(), 3, 60, new DummyASGInstanceValidator()); rule.isValid(null); } @Test(expectedExceptions = IllegalArgumentException.class) public void testNgativeRetentionDays() { new OldEmptyASGRule(new TestMonkeyCalendar(), -1, 60, new DummyASGInstanceValidator()); } @Test(expectedExceptions = IllegalArgumentException.class) public void testNgativeLaunchConfigAgeThreshold() { new OldEmptyASGRule(new TestMonkeyCalendar(), 3, -1, new DummyASGInstanceValidator()); } @Test(expectedExceptions = IllegalArgumentException.class) public void testNullCalendar() { new OldEmptyASGRule(null, 3, 60, new DummyASGInstanceValidator()); } @Test public void testNonASGResource() { Resource resource = new AWSResource().withId("i-12345678901234567").withResourceType(AWSResourceType.INSTANCE); OldEmptyASGRule rule = new OldEmptyASGRule(new TestMonkeyCalendar(), 3, 60, new DummyASGInstanceValidator()); Assert.assertTrue(rule.isValid(resource)); Assert.assertNull(resource.getExpectedTerminationTime()); } }
4,740
0
Create_ds/SimianArmy/src/test/java/com/netflix/simianarmy/aws/janitor/rule
Create_ds/SimianArmy/src/test/java/com/netflix/simianarmy/aws/janitor/rule/instance/TestOrphanedInstanceRule.java
/* * * Copyright 2012 Netflix, Inc. * * Licensed 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. * */ // CHECKSTYLE IGNORE Javadoc // CHECKSTYLE IGNORE MagicNumberCheck package com.netflix.simianarmy.aws.janitor.rule.instance; import java.util.Date; import org.joda.time.DateTime; import org.testng.Assert; import org.testng.annotations.Test; import com.netflix.simianarmy.Resource; import com.netflix.simianarmy.TestUtils; import com.netflix.simianarmy.aws.AWSResource; import com.netflix.simianarmy.aws.AWSResourceType; import com.netflix.simianarmy.aws.janitor.crawler.InstanceJanitorCrawler; import com.netflix.simianarmy.aws.janitor.rule.TestMonkeyCalendar; public class TestOrphanedInstanceRule { @Test public void testOrphanedInstancesWithOwner() { int ageThreshold = 5; DateTime now = DateTime.now(); Resource resource = new AWSResource().withId("i-12345678901234567").withResourceType(AWSResourceType.INSTANCE) .withLaunchTime(new Date(now.minusDays(ageThreshold + 1).getMillis())) .withOwnerEmail("owner@foo.com"); ((AWSResource) resource).setAWSResourceState("running"); int retentionDaysWithOwner = 4; int retentionDaysWithoutOwner = 8; OrphanedInstanceRule rule = new OrphanedInstanceRule(new TestMonkeyCalendar(), ageThreshold, retentionDaysWithOwner, retentionDaysWithoutOwner); Assert.assertFalse(rule.isValid(resource)); TestUtils.verifyTerminationTimeRough(resource, retentionDaysWithOwner, now); } @Test public void testOrphanedInstancesWithoutOwner() { int ageThreshold = 5; DateTime now = DateTime.now(); Resource resource = new AWSResource().withId("i-12345678901234567").withResourceType(AWSResourceType.INSTANCE) .withLaunchTime(new Date(now.minusDays(ageThreshold + 1).getMillis())); ((AWSResource) resource).setAWSResourceState("running"); int retentionDaysWithOwner = 4; int retentionDaysWithoutOwner = 8; OrphanedInstanceRule rule = new OrphanedInstanceRule(new TestMonkeyCalendar(), ageThreshold, retentionDaysWithOwner, retentionDaysWithoutOwner); Assert.assertFalse(rule.isValid(resource)); TestUtils.verifyTerminationTimeRough(resource, retentionDaysWithoutOwner, now); } @Test public void testOrphanedInstancesWithoutLaunchTime() { int ageThreshold = 5; Resource resource = new AWSResource().withId("i-12345678901234567").withResourceType(AWSResourceType.INSTANCE); ((AWSResource) resource).setAWSResourceState("running"); int retentionDaysWithOwner = 4; int retentionDaysWithoutOwner = 8; OrphanedInstanceRule rule = new OrphanedInstanceRule(new TestMonkeyCalendar(), ageThreshold, retentionDaysWithOwner, retentionDaysWithoutOwner); Assert.assertTrue(rule.isValid(resource)); Assert.assertNull(resource.getExpectedTerminationTime()); } @Test public void testOrphanedInstancesWithLaunchTimeNotExpires() { int ageThreshold = 5; DateTime now = DateTime.now(); Resource resource = new AWSResource().withId("i-12345678901234567").withResourceType(AWSResourceType.INSTANCE) .withLaunchTime(new Date(now.minusDays(ageThreshold - 1).getMillis())); ((AWSResource) resource).setAWSResourceState("running"); int retentionDaysWithOwner = 4; int retentionDaysWithoutOwner = 8; OrphanedInstanceRule rule = new OrphanedInstanceRule(new TestMonkeyCalendar(), ageThreshold, retentionDaysWithOwner, retentionDaysWithoutOwner); Assert.assertTrue(rule.isValid(resource)); Assert.assertNull(resource.getExpectedTerminationTime()); } @Test public void testNonOrphanedInstances() { int ageThreshold = 5; Resource resource = new AWSResource().withId("i-12345678901234567").withResourceType(AWSResourceType.INSTANCE) .setAdditionalField(InstanceJanitorCrawler.INSTANCE_FIELD_ASG_NAME, "asg1"); ((AWSResource) resource).setAWSResourceState("running"); int retentionDaysWithOwner = 4; int retentionDaysWithoutOwner = 8; OrphanedInstanceRule rule = new OrphanedInstanceRule(new TestMonkeyCalendar(), ageThreshold, retentionDaysWithOwner, retentionDaysWithoutOwner); Assert.assertTrue(rule.isValid(resource)); Assert.assertNull(resource.getExpectedTerminationTime()); } @Test public void testResourceWithExpectedTerminationTimeSet() { DateTime now = DateTime.now(); Date oldTermDate = new Date(now.plusDays(10).getMillis()); String oldTermReason = "Foo"; int ageThreshold = 5; Resource resource = new AWSResource().withId("i-12345678901234567").withResourceType(AWSResourceType.INSTANCE) .withLaunchTime(new Date(now.minusDays(ageThreshold + 1).getMillis())) .withExpectedTerminationTime(oldTermDate) .withTerminationReason(oldTermReason); ((AWSResource) resource).setAWSResourceState("running"); int retentionDaysWithOwner = 4; int retentionDaysWithoutOwner = 8; OrphanedInstanceRule rule = new OrphanedInstanceRule(new TestMonkeyCalendar(), ageThreshold, retentionDaysWithOwner, retentionDaysWithoutOwner); Assert.assertFalse(rule.isValid(resource)); Assert.assertEquals(oldTermDate, resource.getExpectedTerminationTime()); Assert.assertEquals(oldTermReason, resource.getTerminationReason()); } @Test(expectedExceptions = IllegalArgumentException.class) public void testNullResource() { OrphanedInstanceRule rule = new OrphanedInstanceRule(new TestMonkeyCalendar(), 5, 4, 8); rule.isValid(null); } @Test(expectedExceptions = IllegalArgumentException.class) public void testNgativeAgeThreshold() { new OrphanedInstanceRule(new TestMonkeyCalendar(), -1, 4, 8); } @Test(expectedExceptions = IllegalArgumentException.class) public void testNgativeRetentionDaysWithOwner() { new OrphanedInstanceRule(new TestMonkeyCalendar(), 5, -4, 8); } @Test(expectedExceptions = IllegalArgumentException.class) public void testNgativeRetentionDaysWithoutOwner() { new OrphanedInstanceRule(new TestMonkeyCalendar(), 5, 4, -8); } @Test(expectedExceptions = IllegalArgumentException.class) public void testNullCalendar() { new OrphanedInstanceRule(null, 5, 4, 8); } @Test public void testNonInstanceResource() { Resource resource = new AWSResource().withId("asg1").withResourceType(AWSResourceType.ASG); ((AWSResource) resource).setAWSResourceState("running"); OrphanedInstanceRule rule = new OrphanedInstanceRule(new TestMonkeyCalendar(), 0, 0, 0); Assert.assertTrue(rule.isValid(resource)); Assert.assertNull(resource.getExpectedTerminationTime()); } @Test public void testNonRunningInstance() { Resource resource = new AWSResource().withId("i-12345678901234567").withResourceType(AWSResourceType.INSTANCE); ((AWSResource) resource).setAWSResourceState("stopping"); OrphanedInstanceRule rule = new OrphanedInstanceRule(new TestMonkeyCalendar(), 0, 0, 0); Assert.assertTrue(rule.isValid(resource)); Assert.assertNull(resource.getExpectedTerminationTime()); } }
4,741
0
Create_ds/SimianArmy/src/test/java/com/netflix/simianarmy/aws/janitor/rule
Create_ds/SimianArmy/src/test/java/com/netflix/simianarmy/aws/janitor/rule/generic/TestUntaggedRule.java
/* * * Copyright 2012 Netflix, Inc. * * Licensed 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. * */ // CHECKSTYLE IGNORE Javadoc // CHECKSTYLE IGNORE MagicNumberCheck package com.netflix.simianarmy.aws.janitor.rule.generic; import java.util.Date; import java.util.HashSet; import java.util.Set; import org.joda.time.DateTime; import org.testng.Assert; import org.testng.annotations.Test; import com.netflix.simianarmy.Resource; import com.netflix.simianarmy.TestUtils; import com.netflix.simianarmy.aws.AWSResource; import com.netflix.simianarmy.aws.AWSResourceType; import com.netflix.simianarmy.aws.janitor.crawler.InstanceJanitorCrawler; import com.netflix.simianarmy.aws.janitor.rule.TestMonkeyCalendar; public class TestUntaggedRule { @Test public void testUntaggedInstanceWithOwner() { DateTime now = DateTime.now(); Resource resource = new AWSResource().withId("i-12345678901234567").withResourceType(AWSResourceType.INSTANCE) .withOwnerEmail("owner@foo.com"); resource.setTag("tag1", "value1"); ((AWSResource) resource).setAWSResourceState("running"); Set<String> tags = new HashSet<String>(); tags.add("tag1"); tags.add("tag2"); int retentionDaysWithOwner = 4; int retentionDaysWithoutOwner = 8; UntaggedRule rule = new UntaggedRule(new TestMonkeyCalendar(), tags, retentionDaysWithOwner, retentionDaysWithoutOwner); Assert.assertFalse(rule.isValid(resource)); TestUtils.verifyTerminationTimeRough(resource, retentionDaysWithOwner, now); } @Test public void testUntaggedInstanceWithoutOwner() { DateTime now = DateTime.now(); Resource resource = new AWSResource().withId("i-12345678901234567").withResourceType(AWSResourceType.INSTANCE); resource.setTag("tag1", "value1"); ((AWSResource) resource).setAWSResourceState("running"); Set<String> tags = new HashSet<String>(); tags.add("tag1"); tags.add("tag2"); int retentionDaysWithOwner = 4; int retentionDaysWithoutOwner = 8; UntaggedRule rule = new UntaggedRule(new TestMonkeyCalendar(), tags, retentionDaysWithOwner, retentionDaysWithoutOwner); Assert.assertFalse(rule.isValid(resource)); TestUtils.verifyTerminationTimeRough(resource, retentionDaysWithoutOwner, now); } @Test public void testTaggedInstance() { Resource resource = new AWSResource().withId("i-12345678901234567").withResourceType(AWSResourceType.INSTANCE); resource.setTag("tag1", "value1"); resource.setTag("tag2", "value2"); ((AWSResource) resource).setAWSResourceState("running"); Set<String> tags = new HashSet<String>(); tags.add("tag1"); tags.add("tag2"); int retentionDaysWithOwner = 4; int retentionDaysWithoutOwner = 8; UntaggedRule rule = new UntaggedRule(new TestMonkeyCalendar(), tags, retentionDaysWithOwner, retentionDaysWithoutOwner); Assert.assertTrue(rule.isValid(resource)); } @Test public void testUntaggedResource() { DateTime now = DateTime.now(); Resource imageResource = new AWSResource().withId("ami-123123").withResourceType(AWSResourceType.IMAGE); Resource asgResource = new AWSResource().withId("my-cool-asg").withResourceType(AWSResourceType.ASG); Resource ebsSnapshotResource = new AWSResource().withId("snap-12345678901234567").withResourceType(AWSResourceType.EBS_SNAPSHOT); Resource lauchConfigurationResource = new AWSResource().withId("my-cool-launch-configuration").withResourceType(AWSResourceType.LAUNCH_CONFIG); Set<String> tags = new HashSet<String>(); tags.add("tag1"); tags.add("tag2"); int retentionDaysWithOwner = 4; int retentionDaysWithoutOwner = 8; UntaggedRule rule = new UntaggedRule(new TestMonkeyCalendar(), tags, retentionDaysWithOwner, retentionDaysWithoutOwner); Assert.assertFalse(rule.isValid(imageResource)); Assert.assertFalse(rule.isValid(asgResource)); Assert.assertFalse(rule.isValid(ebsSnapshotResource)); Assert.assertFalse(rule.isValid(lauchConfigurationResource)); TestUtils.verifyTerminationTimeRough(imageResource, retentionDaysWithoutOwner, now); TestUtils.verifyTerminationTimeRough(asgResource, retentionDaysWithoutOwner, now); TestUtils.verifyTerminationTimeRough(ebsSnapshotResource, retentionDaysWithoutOwner, now); TestUtils.verifyTerminationTimeRough(lauchConfigurationResource, retentionDaysWithoutOwner, now); } @Test public void testResourceWithExpectedTerminationTimeSet() { DateTime now = DateTime.now(); Date oldTermDate = new Date(now.plusDays(10).getMillis()); String oldTermReason = "Foo"; Resource resource = new AWSResource().withId("i-12345678901234567").withResourceType(AWSResourceType.INSTANCE) .withExpectedTerminationTime(oldTermDate) .withTerminationReason(oldTermReason); ((AWSResource) resource).setAWSResourceState("running"); Set<String> tags = new HashSet<String>(); tags.add("tag1"); tags.add("tag2"); int retentionDaysWithOwner = 4; int retentionDaysWithoutOwner = 8; UntaggedRule rule = new UntaggedRule(new TestMonkeyCalendar(), tags, retentionDaysWithOwner, retentionDaysWithoutOwner); Assert.assertFalse(rule.isValid(resource)); Assert.assertEquals(oldTermDate, resource.getExpectedTerminationTime()); Assert.assertEquals(oldTermReason, resource.getTerminationReason()); } }
4,742
0
Create_ds/SimianArmy/src/test/java/com/netflix/simianarmy/aws/janitor/rule
Create_ds/SimianArmy/src/test/java/com/netflix/simianarmy/aws/janitor/rule/generic/TestTagValueExclusionRule.java
/* * * Copyright 2012 Netflix, Inc. * * Licensed 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. * */ // CHECKSTYLE IGNORE Javadoc // CHECKSTYLE IGNORE MagicNumberCheck package com.netflix.simianarmy.aws.janitor.rule.generic; import com.netflix.simianarmy.Resource; import com.netflix.simianarmy.aws.AWSResource; import com.netflix.simianarmy.aws.AWSResourceType; import org.testng.Assert; import org.testng.annotations.BeforeTest; import org.testng.annotations.Test; import java.util.HashMap; public class TestTagValueExclusionRule { HashMap<String,String> exclusionTags = null; @BeforeTest public void beforeTest() { exclusionTags = new HashMap<>(); exclusionTags.put("tag1", "excludeme"); exclusionTags.put("tag2", "excludeme2"); } @Test public void testExcludeTaggedResourceWithTagAndValueMatch1() { Resource r1 = new AWSResource().withId("i-12345678901234567").withResourceType(AWSResourceType.INSTANCE).withOwnerEmail("owner@foo.com"); r1.setTag("tag", null); r1.setTag("tag1", "excludeme"); r1.setTag("tag2", "somethingelse"); TagValueExclusionRule rule = new TagValueExclusionRule(exclusionTags); Assert.assertTrue(rule.isValid(r1)); } @Test public void testExcludeTaggedResourceWithTagAndValueMatch2() { Resource r1 = new AWSResource().withId("i-12345678901234567").withResourceType(AWSResourceType.INSTANCE).withOwnerEmail("owner@foo.com"); r1.setTag("tag", null); r1.setTag("tag1", "somethingelse"); r1.setTag("tag2", "excludeme2"); TagValueExclusionRule rule = new TagValueExclusionRule(exclusionTags); Assert.assertTrue(rule.isValid(r1)); } @Test public void testExcludeTaggedResourceWithTagAndValueMatchBoth() { Resource r1 = new AWSResource().withId("i-12345678901234567").withResourceType(AWSResourceType.INSTANCE).withOwnerEmail("owner@foo.com"); r1.setTag("tag", null); r1.setTag("tag1", "excludeme"); r1.setTag("tag2", "excludeme2"); TagValueExclusionRule rule = new TagValueExclusionRule(exclusionTags); Assert.assertTrue(rule.isValid(r1)); } @Test public void testExcludeTaggedResourceTagMatchOnly() { Resource r1 = new AWSResource().withId("i-12345678901234567").withResourceType(AWSResourceType.INSTANCE).withOwnerEmail("owner@foo.com"); r1.setTag("tag", null); r1.setTag("tag1", "somethingelse"); r1.setTag("tag2", "somethingelse2"); TagValueExclusionRule rule = new TagValueExclusionRule(exclusionTags); Assert.assertFalse(rule.isValid(r1)); } @Test public void testExcludeTaggedResourceAllNullTags() { Resource r1 = new AWSResource().withId("i-12345678901234567").withResourceType(AWSResourceType.INSTANCE).withOwnerEmail("owner@foo.com"); r1.setTag("tag", null); r1.setTag("tag1", null); r1.setTag("tag2", null); TagValueExclusionRule rule = new TagValueExclusionRule(exclusionTags); Assert.assertFalse(rule.isValid(r1)); } @Test public void testExcludeTaggedResourceValueMatchOnly() { Resource r1 = new AWSResource().withId("i-12345678901234567").withResourceType(AWSResourceType.INSTANCE).withOwnerEmail("owner@foo.com"); r1.setTag("tag", null); r1.setTag("tagA", "excludeme"); r1.setTag("tagB", "excludeme2"); TagValueExclusionRule rule = new TagValueExclusionRule(exclusionTags); Assert.assertFalse(rule.isValid(r1)); } @Test public void testExcludeUntaggedResource() { Resource r1 = new AWSResource().withId("i-12345678901234567").withResourceType(AWSResourceType.INSTANCE).withOwnerEmail("owner@foo.com"); TagValueExclusionRule rule = new TagValueExclusionRule(exclusionTags); Assert.assertFalse(rule.isValid(r1)); } @Test public void testNameValueConstructor() { Resource r1 = new AWSResource().withId("i-12345678901234567").withResourceType(AWSResourceType.INSTANCE).withOwnerEmail("owner@foo.com"); r1.setTag("tag1", "excludeme"); String names = "tag1"; String vals = "excludeme"; TagValueExclusionRule rule = new TagValueExclusionRule(names.split(","), vals.split(",")); Assert.assertTrue(rule.isValid(r1)); } @Test public void testNameValueConstructor2() { Resource r1 = new AWSResource().withId("i-12345678901234567").withResourceType(AWSResourceType.INSTANCE).withOwnerEmail("owner@foo.com"); r1.setTag("tag1", "excludeme"); String names = "tag1,tag2"; String vals = "excludeme,excludeme2"; TagValueExclusionRule rule = new TagValueExclusionRule(names.split(","), vals.split(",")); Assert.assertTrue(rule.isValid(r1)); } }
4,743
0
Create_ds/SimianArmy/src/test/java/com/netflix/simianarmy/aws/janitor/rule
Create_ds/SimianArmy/src/test/java/com/netflix/simianarmy/aws/janitor/rule/volume/TestOldDetachedVolumeRule.java
/* * * Copyright 2012 Netflix, Inc. * * Licensed 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. * */ //CHECKSTYLE IGNORE Javadoc //CHECKSTYLE IGNORE MagicNumberCheck package com.netflix.simianarmy.aws.janitor.rule.volume; import java.util.Calendar; import java.util.Date; import java.util.TimeZone; import org.joda.time.DateTime; import org.joda.time.DateTimeZone; import org.testng.Assert; import org.testng.annotations.Test; import com.netflix.simianarmy.MonkeyCalendar; import com.netflix.simianarmy.Resource; import com.netflix.simianarmy.TestUtils; import com.netflix.simianarmy.aws.AWSResource; import com.netflix.simianarmy.aws.AWSResourceType; import com.netflix.simianarmy.aws.janitor.VolumeTaggingMonkey; import com.netflix.simianarmy.aws.janitor.rule.TestMonkeyCalendar; import com.netflix.simianarmy.janitor.JanitorMonkey; import static org.joda.time.DateTimeConstants.MILLIS_PER_DAY; import static org.mockito.Mockito.spy; import static org.mockito.Mockito.when; public class TestOldDetachedVolumeRule { @Test public void testNonVolumeResource() { Resource resource = new AWSResource().withId("asg1").withResourceType(AWSResourceType.ASG); ((AWSResource) resource).setAWSResourceState("available"); OldDetachedVolumeRule rule = new OldDetachedVolumeRule(new TestMonkeyCalendar(), 0, 0); Assert.assertTrue(rule.isValid(resource)); Assert.assertNull(resource.getExpectedTerminationTime()); } @Test public void testUnavailableVolume() { Resource resource = new AWSResource().withId("vol-12345678901234567").withResourceType(AWSResourceType.EBS_VOLUME); ((AWSResource) resource).setAWSResourceState("stopped"); OldDetachedVolumeRule rule = new OldDetachedVolumeRule(new TestMonkeyCalendar(), 0, 0); Assert.assertTrue(rule.isValid(resource)); Assert.assertNull(resource.getExpectedTerminationTime()); } @Test public void testTaggedAsNotMark() { int ageThreshold = 5; DateTime now = DateTime.now(); Resource resource = new AWSResource().withId("vol-12345678901234567").withResourceType(AWSResourceType.EBS_VOLUME) .withLaunchTime(new Date(now.minusDays(ageThreshold + 1).getMillis())); ((AWSResource) resource).setAWSResourceState("available"); Date lastDetachTime = new Date(now.minusDays(ageThreshold + 1).getMillis()); String metaTag = VolumeTaggingMonkey.makeMetaTag(null, null, lastDetachTime); resource.setTag(JanitorMonkey.JANITOR_META_TAG, metaTag); int retentionDays = 4; OldDetachedVolumeRule rule = new OldDetachedVolumeRule(new TestMonkeyCalendar(), ageThreshold, retentionDays); resource.setTag(JanitorMonkey.JANITOR_TAG, "donotmark"); Assert.assertTrue(rule.isValid(resource)); Assert.assertNull(resource.getExpectedTerminationTime()); } @Test public void testNoMetaTag() { int ageThreshold = 5; DateTime now = DateTime.now(); Resource resource = new AWSResource().withId("vol-12345678901234567").withResourceType(AWSResourceType.EBS_VOLUME) .withLaunchTime(new Date(now.minusDays(ageThreshold + 1).getMillis())); ((AWSResource) resource).setAWSResourceState("available"); int retentionDays = 4; OldDetachedVolumeRule rule = new OldDetachedVolumeRule(new TestMonkeyCalendar(), ageThreshold, retentionDays); resource.setTag(JanitorMonkey.JANITOR_TAG, "donotmark"); Assert.assertTrue(rule.isValid(resource)); Assert.assertNull(resource.getExpectedTerminationTime()); } @Test public void testUserSpecifiedTerminationDate() { int ageThreshold = 5; DateTime now = DateTime.now(); Resource resource = new AWSResource().withId("vol-12345678901234567").withResourceType(AWSResourceType.EBS_VOLUME) .withLaunchTime(new Date(now.minusDays(ageThreshold + 1).getMillis())); ((AWSResource) resource).setAWSResourceState("available"); int retentionDays = 4; DateTime userDate = new DateTime(now.plusDays(3).withTimeAtStartOfDay()); resource.setTag(JanitorMonkey.JANITOR_TAG, OldDetachedVolumeRule.TERMINATION_DATE_FORMATTER.print(userDate)); OldDetachedVolumeRule rule = new OldDetachedVolumeRule(new TestMonkeyCalendar(), ageThreshold, retentionDays); Assert.assertFalse(rule.isValid(resource)); Assert.assertEquals(resource.getExpectedTerminationTime().getTime(), userDate.getMillis()); } @Test public void testOldDetachedVolume() { int ageThreshold = 5; DateTime now = DateTime.now(); Resource resource = new AWSResource().withId("vol-12345678901234567").withResourceType(AWSResourceType.EBS_VOLUME) .withLaunchTime(new Date(now.minusDays(ageThreshold + 1).getMillis())); ((AWSResource) resource).setAWSResourceState("available"); Date lastDetachTime = new Date(now.minusDays(ageThreshold + 1).getMillis()); String metaTag = VolumeTaggingMonkey.makeMetaTag(null, null, lastDetachTime); resource.setTag(JanitorMonkey.JANITOR_META_TAG, metaTag); int retentionDays = 4; OldDetachedVolumeRule rule = new OldDetachedVolumeRule(new TestMonkeyCalendar(), ageThreshold, retentionDays); Assert.assertFalse(rule.isValid(resource)); TestUtils.verifyTerminationTimeRough(resource, retentionDays, now); } /** This test exists to check logic on a utility method. * The tagging rule for resource expiry uses a variable nubmer of days. * However, JodaTime date arithmetic for DAYS uses calendar days. It does NOT * treat a day as 24 hours in this case (HOUR arithmetic, however, does). * Therefore, a termination policy of 4 days (96 hours) will actually occur in * 95 hours if the resource is tagged with that rule within 4 days of the DST * cutover. * * We experienced test case failures around the 2014 spring DST cutover that * prevented us from getting green builds. So, the assertion logic was loosened * to check that we were within a day of the expected date. For the test case, * all but 4 days of the year this problem never shows up. To verify that our * fix was correct, this test case explicitly sets the date. The other tests * that use a DateTime of "DateTime.now()" are not true unit tests, because the * test does not isolate the date. They are actually a partial integration test, * as they leave the date up to the system where the test executes. * * We have to mock the call to MonkeyCalendar.now() because the constructor * for that class uses Calendar.getInstance() internally. * */ @Test public void testOldDetachedVolumeBeforeDaylightSavingsCutover() { int ageThreshold = 5; //here we set the create date to a few days before a known DST cutover, where //we observed DST failures DateTime closeToSpringAheadDst = new DateTime(2014, 3, 7, 0, 0, DateTimeZone.forID("America/Los_Angeles")); Resource resource = new AWSResource().withId("vol-12345678901234567").withResourceType(AWSResourceType.EBS_VOLUME) .withLaunchTime(new Date(closeToSpringAheadDst.minusDays(ageThreshold + 1).getMillis())); ((AWSResource) resource).setAWSResourceState("available"); Date lastDetachTime = new Date(closeToSpringAheadDst.minusDays(ageThreshold + 1).getMillis()); String metaTag = VolumeTaggingMonkey.makeMetaTag(null, null, lastDetachTime); resource.setTag(JanitorMonkey.JANITOR_META_TAG, metaTag); int retentionDays = 4; //set the "now" to the fixed execution date for this rule and create a partial mock Calendar fixed = Calendar.getInstance(TimeZone.getTimeZone("America/Los_Angeles")); fixed.setTimeInMillis(closeToSpringAheadDst.getMillis()); MonkeyCalendar monkeyCalendar = new TestMonkeyCalendar(); MonkeyCalendar spyCalendar = spy(monkeyCalendar); when(spyCalendar.now()).thenReturn(fixed); //use the partial mock for the OldDetachedVolumeRule OldDetachedVolumeRule rule = new OldDetachedVolumeRule(spyCalendar, ageThreshold, retentionDays); Assert.assertFalse(rule.isValid(resource)); //this volume should be seen as invalid //3.26.2014. Commenting out DST cutover verification. A line in //OldDetachedVolumeRule.isValid actually creates a new date from the Tag value. //while this unit test tries its best to use invariants, the tag does not contain timezone //information, so a time set in the Los Angeles timezone and tagged, then parsed as //UTC (if that's how the VM running the test is set) will fail. ///////////////////////////// //Leaving the code in place to be uncommnented later if that class is refactored //to support a design that promotes more complete testing. //now verify that the difference between "now" and the cutoff is slightly under the intended //retention limit, as the DST cutover makes us lose one hour //verifyDSTCutoverHappened(resource, retentionDays, closeToSpringAheadDst); ///////////////////////////// //now verify that our projected termination time is within one day of what was asked for TestUtils.verifyTerminationTimeRough(resource, retentionDays, closeToSpringAheadDst); } @Test public void testDetachedVolumeNotOld() { int ageThreshold = 5; DateTime now = DateTime.now(); Resource resource = new AWSResource().withId("vol-12345678901234567").withResourceType(AWSResourceType.EBS_VOLUME) .withLaunchTime(new Date(now.minusDays(ageThreshold + 1).getMillis())); ((AWSResource) resource).setAWSResourceState("available"); Date lastDetachTime = new Date(now.minusDays(ageThreshold - 1).getMillis()); String metaTag = VolumeTaggingMonkey.makeMetaTag(null, null, lastDetachTime); resource.setTag(JanitorMonkey.JANITOR_META_TAG, metaTag); int retentionDays = 4; OldDetachedVolumeRule rule = new OldDetachedVolumeRule(new TestMonkeyCalendar(), ageThreshold, retentionDays); Assert.assertTrue(rule.isValid(resource)); Assert.assertNull(resource.getExpectedTerminationTime()); } @Test public void testAttachedVolume() { int ageThreshold = 5; DateTime now = DateTime.now(); Resource resource = new AWSResource().withId("vol-12345678901234567").withResourceType(AWSResourceType.EBS_VOLUME) .withLaunchTime(new Date(now.minusDays(ageThreshold + 1).getMillis())); ((AWSResource) resource).setAWSResourceState("available"); String metaTag = VolumeTaggingMonkey.makeMetaTag("i-12345678901234567", "owner", null); resource.setTag(JanitorMonkey.JANITOR_META_TAG, metaTag); int retentionDays = 4; OldDetachedVolumeRule rule = new OldDetachedVolumeRule(new TestMonkeyCalendar(), ageThreshold, retentionDays); Assert.assertTrue(rule.isValid(resource)); Assert.assertNull(resource.getExpectedTerminationTime()); } @Test public void testResourceWithExpectedTerminationTimeSet() { DateTime now = DateTime.now(); Date oldTermDate = new Date(now.plusDays(10).getMillis()); String oldTermReason = "Foo"; int ageThreshold = 5; Resource resource = new AWSResource().withId("vol-12345678901234567").withResourceType(AWSResourceType.EBS_VOLUME) .withLaunchTime(new Date(now.minusDays(ageThreshold + 1).getMillis())); ((AWSResource) resource).setAWSResourceState("available"); Date lastDetachTime = new Date(now.minusDays(ageThreshold + 1).getMillis()); String metaTag = VolumeTaggingMonkey.makeMetaTag(null, null, lastDetachTime); resource.setTag(JanitorMonkey.JANITOR_META_TAG, metaTag); int retentionDays = 4; OldDetachedVolumeRule rule = new OldDetachedVolumeRule(new TestMonkeyCalendar(), ageThreshold, retentionDays); resource.setExpectedTerminationTime(oldTermDate); resource.setTerminationReason(oldTermReason); Assert.assertFalse(rule.isValid(resource)); Assert.assertEquals(oldTermDate, resource.getExpectedTerminationTime()); Assert.assertEquals(oldTermReason, resource.getTerminationReason()); } @Test(expectedExceptions = IllegalArgumentException.class) public void testNullResource() { OldDetachedVolumeRule rule = new OldDetachedVolumeRule(new TestMonkeyCalendar(), 5, 4); rule.isValid(null); } @Test(expectedExceptions = IllegalArgumentException.class) public void testNgativeAgeThreshold() { new OldDetachedVolumeRule(new TestMonkeyCalendar(), -1, 4); } @Test(expectedExceptions = IllegalArgumentException.class) public void testNgativeRetentionDaysWithOwner() { new OldDetachedVolumeRule(new TestMonkeyCalendar(), 5, -4); } @Test(expectedExceptions = IllegalArgumentException.class) public void testNullCalendar() { new OldDetachedVolumeRule(null, 5, 4); } /** Verify that a test conditioned to run across the spring DST cutover actually did * cross that threshold. The real difference will be about 0.05 days less than * the retentionDays parameter. * @param resource The AWS resource being tested * @param retentionDays Number of days the resource should be kept around * @param timeOfCheck When the check is executed */ private void verifyDSTCutoverHappened(Resource resource, int retentionDays, DateTime timeOfCheck) { double realDays = (double) (resource.getExpectedTerminationTime().getTime() - timeOfCheck.getMillis()) / (double) MILLIS_PER_DAY; long days = (resource.getExpectedTerminationTime().getTime() - timeOfCheck.getMillis()) / MILLIS_PER_DAY; Assert.assertTrue(realDays < (double) retentionDays); Assert.assertNotEquals(days, retentionDays); } }
4,744
0
Create_ds/SimianArmy/src/test/java/com/netflix/simianarmy
Create_ds/SimianArmy/src/test/java/com/netflix/simianarmy/chaos/TestChaosMonkeyArmy.java
/* * * Copyright 2012 Netflix, Inc. * * Licensed 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. * */ // CHECKSTYLE IGNORE Javadoc package com.netflix.simianarmy.chaos; import java.io.File; import java.io.IOException; import java.util.List; import java.util.Properties; import org.testng.Assert; import org.testng.annotations.BeforeTest; import org.testng.annotations.Test; import com.google.common.base.Charsets; import com.google.common.io.Files; import com.netflix.simianarmy.basic.chaos.BasicChaosMonkey; import com.netflix.simianarmy.chaos.ChaosCrawler.InstanceGroup; import com.netflix.simianarmy.chaos.TestChaosMonkeyContext.Notification; import com.netflix.simianarmy.chaos.TestChaosMonkeyContext.SshAction; // CHECKSTYLE IGNORE MagicNumberCheck public class TestChaosMonkeyArmy { private File sshKey; @BeforeTest public void createSshKey() throws IOException { sshKey = File.createTempFile("tmp", "key"); Files.write("fakekey", sshKey, Charsets.UTF_8); sshKey.deleteOnExit(); } private TestChaosMonkeyContext runChaosMonkey(String key) { return runChaosMonkey(key, true); } private TestChaosMonkeyContext runChaosMonkey(String key, boolean burnMoney) { Properties properties = new Properties(); properties.setProperty("simianarmy.chaos.enabled", "true"); properties.setProperty("simianarmy.chaos.leashed", "false"); properties.setProperty("simianarmy.chaos.TYPE_A.enabled", "true"); properties.setProperty("simianarmy.chaos.notification.global.enabled", "true"); properties.setProperty("simianarmy.chaos.burnmoney", Boolean.toString(burnMoney)); properties.setProperty("simianarmy.chaos.shutdowninstance.enabled", "false"); properties.setProperty("simianarmy.chaos." + key.toLowerCase() + ".enabled", "true"); properties.setProperty("simianarmy.chaos.ssh.key", sshKey.getAbsolutePath()); TestChaosMonkeyContext ctx = new TestChaosMonkeyContext(properties); ChaosMonkey chaos = new BasicChaosMonkey(ctx); chaos.start(); chaos.stop(); return ctx; } private void checkSelected(TestChaosMonkeyContext ctx) { List<InstanceGroup> selectedOn = ctx.selectedOn(); Assert.assertEquals(selectedOn.size(), 2); Assert.assertEquals(selectedOn.get(0).type(), TestChaosMonkeyContext.CrawlerTypes.TYPE_A); Assert.assertEquals(selectedOn.get(0).name(), "name0"); Assert.assertEquals(selectedOn.get(1).type(), TestChaosMonkeyContext.CrawlerTypes.TYPE_A); Assert.assertEquals(selectedOn.get(1).name(), "name1"); } private void checkNotifications(TestChaosMonkeyContext ctx, String key) { List<Notification> notifications = ctx.getGloballyNotifiedList(); Assert.assertEquals(notifications.size(), 2); Assert.assertEquals(notifications.get(0).getInstance(), "0:i-123456789012345670"); Assert.assertEquals(notifications.get(0).getChaosType().getKey(), key); Assert.assertEquals(notifications.get(1).getInstance(), "1:i-123456789012345671"); Assert.assertEquals(notifications.get(1).getChaosType().getKey(), key); } private void checkSshActions(TestChaosMonkeyContext ctx, String key) { List<SshAction> sshActions = ctx.getSshActions(); Assert.assertEquals(sshActions.size(), 4); Assert.assertEquals(sshActions.get(0).getMethod(), "put"); Assert.assertEquals(sshActions.get(0).getInstanceId(), "0:i-123456789012345670"); // We require that each script include the name of the chaos type // This makes testing easier, and also means the scripts show where they came from Assert.assertTrue(sshActions.get(0).getContents().toLowerCase().contains(key.toLowerCase())); Assert.assertEquals(sshActions.get(1).getMethod(), "exec"); Assert.assertEquals(sshActions.get(1).getInstanceId(), "0:i-123456789012345670"); Assert.assertEquals(sshActions.get(2).getMethod(), "put"); Assert.assertEquals(sshActions.get(2).getInstanceId(), "1:i-123456789012345671"); Assert.assertTrue(sshActions.get(2).getContents().contains(key)); Assert.assertEquals(sshActions.get(3).getMethod(), "exec"); Assert.assertEquals(sshActions.get(3).getInstanceId(), "1:i-123456789012345671"); } @Test public void testShutdownInstance() { String key = "ShutdownInstance"; TestChaosMonkeyContext ctx = runChaosMonkey(key); checkSelected(ctx); checkNotifications(ctx, key); List<String> terminated = ctx.terminated(); Assert.assertEquals(terminated.size(), 2); Assert.assertEquals(terminated.get(0), "0:i-123456789012345670"); Assert.assertEquals(terminated.get(1), "1:i-123456789012345671"); } @Test public void testBlockAllNetworkTraffic() { String key = "BlockAllNetworkTraffic"; TestChaosMonkeyContext ctx = runChaosMonkey(key); checkSelected(ctx); checkNotifications(ctx, key); List<String> cloudActions = ctx.getCloudActions(); Assert.assertEquals(cloudActions.size(), 3); Assert.assertEquals(cloudActions.get(0), "createSecurityGroup:0:i-123456789012345670:blocked-network"); Assert.assertEquals(cloudActions.get(1), "setInstanceSecurityGroups:0:i-123456789012345670:sg-1"); Assert.assertEquals(cloudActions.get(2), "setInstanceSecurityGroups:1:i-123456789012345671:sg-1"); } @Test public void testDetachVolumes() { String key = "DetachVolumes"; TestChaosMonkeyContext ctx = runChaosMonkey(key); checkSelected(ctx); checkNotifications(ctx, key); List<String> cloudActions = ctx.getCloudActions(); Assert.assertEquals(cloudActions.size(), 4); Assert.assertEquals(cloudActions.get(0), "detach:0:i-123456789012345670:volume-1"); Assert.assertEquals(cloudActions.get(1), "detach:0:i-123456789012345670:volume-2"); Assert.assertEquals(cloudActions.get(2), "detach:1:i-123456789012345671:volume-1"); Assert.assertEquals(cloudActions.get(3), "detach:1:i-123456789012345671:volume-2"); } @Test public void testBurnCpu() { String key = "BurnCpu"; TestChaosMonkeyContext ctx = runChaosMonkey(key); checkSelected(ctx); checkNotifications(ctx, key); checkSshActions(ctx, key); } @Test public void testBurnIo() { String key = "BurnIO"; TestChaosMonkeyContext ctx = runChaosMonkey(key); checkSelected(ctx); checkNotifications(ctx, key); checkSshActions(ctx, key); } @Test public void testBurnIoWithoutBurnMoney() { String key = "BurnIO"; TestChaosMonkeyContext ctx = runChaosMonkey(key, false); checkSelected(ctx); List<Notification> notifications = ctx.getGloballyNotifiedList(); Assert.assertEquals(notifications.size(), 0); List<SshAction> sshActions = ctx.getSshActions(); Assert.assertEquals(sshActions.size(), 0); } @Test public void testFillDisk() { String key = "FillDisk"; TestChaosMonkeyContext ctx = runChaosMonkey(key); checkSelected(ctx); checkNotifications(ctx, key); checkSshActions(ctx, key); } @Test public void testFillDiskWithoutBurnMoney() { String key = "FillDisk"; TestChaosMonkeyContext ctx = runChaosMonkey(key, false); checkSelected(ctx); List<Notification> notifications = ctx.getGloballyNotifiedList(); Assert.assertEquals(notifications.size(), 0); List<SshAction> sshActions = ctx.getSshActions(); Assert.assertEquals(sshActions.size(), 0); } @Test public void testFailDns() { String key = "FailDns"; TestChaosMonkeyContext ctx = runChaosMonkey(key); checkSelected(ctx); checkNotifications(ctx, key); checkSshActions(ctx, key); } @Test public void testFailDynamoDb() { String key = "FailDynamoDb"; TestChaosMonkeyContext ctx = runChaosMonkey(key); checkSelected(ctx); checkNotifications(ctx, key); checkSshActions(ctx, key); } @Test public void testFailEc2() { String key = "FailEc2"; TestChaosMonkeyContext ctx = runChaosMonkey(key); checkSelected(ctx); checkNotifications(ctx, key); checkSshActions(ctx, key); } @Test public void testFailS3() { String key = "FailS3"; TestChaosMonkeyContext ctx = runChaosMonkey(key); checkSelected(ctx); checkNotifications(ctx, key); checkSshActions(ctx, key); } @Test public void testKillProcess() { String key = "KillProcesses"; TestChaosMonkeyContext ctx = runChaosMonkey(key); checkSelected(ctx); checkNotifications(ctx, key); checkSshActions(ctx, key); } @Test public void testNetworkCorruption() { String key = "NetworkCorruption"; TestChaosMonkeyContext ctx = runChaosMonkey(key); checkSelected(ctx); checkNotifications(ctx, key); checkSshActions(ctx, key); } @Test public void testNetworkLatency() { String key = "NetworkLatency"; TestChaosMonkeyContext ctx = runChaosMonkey(key); checkSelected(ctx); checkNotifications(ctx, key); checkSshActions(ctx, key); } @Test public void testNetworkLoss() { String key = "NetworkLoss"; TestChaosMonkeyContext ctx = runChaosMonkey(key); checkSelected(ctx); checkNotifications(ctx, key); checkSshActions(ctx, key); } @Test public void testNullRoute() { String key = "NullRoute"; TestChaosMonkeyContext ctx = runChaosMonkey(key); checkSelected(ctx); checkNotifications(ctx, key); checkSshActions(ctx, key); } }
4,745
0
Create_ds/SimianArmy/src/test/java/com/netflix/simianarmy
Create_ds/SimianArmy/src/test/java/com/netflix/simianarmy/chaos/TestChaosMonkeyContext.java
/* * * Copyright 2012 Netflix, Inc. * * Licensed 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. * */ // CHECKSTYLE IGNORE Javadoc package com.netflix.simianarmy.chaos; import com.amazonaws.services.autoscaling.model.TagDescription; import com.google.common.base.Joiner; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import com.netflix.simianarmy.CloudClient; import com.netflix.simianarmy.GroupType; import com.netflix.simianarmy.MonkeyConfiguration; import com.netflix.simianarmy.TestMonkeyContext; import com.netflix.simianarmy.basic.BasicConfiguration; import com.netflix.simianarmy.basic.chaos.BasicChaosInstanceSelector; import com.netflix.simianarmy.chaos.ChaosCrawler.InstanceGroup; import org.jclouds.compute.ComputeService; import org.jclouds.compute.domain.ExecChannel; import org.jclouds.compute.domain.ExecResponse; import org.jclouds.domain.LoginCredentials; import org.jclouds.io.Payload; import org.jclouds.ssh.SshClient; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.InputStream; import java.util.*; public class TestChaosMonkeyContext extends TestMonkeyContext implements ChaosMonkey.Context { private static final Logger LOGGER = LoggerFactory.getLogger(TestChaosMonkeyContext.class); private final BasicConfiguration cfg; public TestChaosMonkeyContext() { this(new Properties()); } protected TestChaosMonkeyContext(Properties properties) { super(ChaosMonkey.Type.CHAOS); cfg = new BasicConfiguration(properties); } public TestChaosMonkeyContext(String propFile) { super(ChaosMonkey.Type.CHAOS); Properties props = new Properties(); try { InputStream is = TestChaosMonkeyContext.class.getResourceAsStream(propFile); try { props.load(is); } finally { is.close(); } } catch (Exception e) { LOGGER.error("Unable to load properties file " + propFile, e); } cfg = new BasicConfiguration(props); } @Override public MonkeyConfiguration configuration() { return cfg; } public static class TestInstanceGroup implements InstanceGroup { private final GroupType type; private final String name; private final String region; private final List<String> instances = new ArrayList<String>(); private final List<TagDescription> tags = new ArrayList<TagDescription>(); public TestInstanceGroup(GroupType type, String name, String region, String... instances) { this.type = type; this.name = name; this.region = region; for (String i : instances) { this.instances.add(i); } } @Override public List<TagDescription> tags() { return tags; } @Override public GroupType type() { return type; } @Override public String name() { return name; } @Override public String region() { return region; } @Override public List<String> instances() { return Collections.unmodifiableList(instances); } @Override public void addInstance(String ignored) { } public void deleteInstance(String id) { instances.remove(id); } @Override public InstanceGroup copyAs(String newName) { return new TestInstanceGroup(this.type, newName, this.region, instances().toString()); } } public enum CrawlerTypes implements GroupType { TYPE_A, TYPE_B, TYPE_C, TYPE_D }; @Override public ChaosCrawler chaosCrawler() { return new ChaosCrawler() { @Override public EnumSet<?> groupTypes() { return EnumSet.allOf(CrawlerTypes.class); } @Override public List<InstanceGroup> groups() { InstanceGroup gA0 = new TestInstanceGroup(CrawlerTypes.TYPE_A, "name0", "reg1", "0:i-123456789012345670"); InstanceGroup gA1 = new TestInstanceGroup(CrawlerTypes.TYPE_A, "name1", "reg1", "1:i-123456789012345671"); InstanceGroup gB2 = new TestInstanceGroup(CrawlerTypes.TYPE_B, "name2", "reg1", "2:i-123456789012345672"); InstanceGroup gB3 = new TestInstanceGroup(CrawlerTypes.TYPE_B, "name3", "reg1", "3:i-123456789012345673"); InstanceGroup gC1 = new TestInstanceGroup(CrawlerTypes.TYPE_C, "name4", "reg1", "3:i-123456789012345674", "3:i-123456789012345675"); InstanceGroup gC2 = new TestInstanceGroup(CrawlerTypes.TYPE_C, "name5", "reg1", "3:i-123456789012345676", "3:i-123456789012345677"); InstanceGroup gD0 = new TestInstanceGroup(CrawlerTypes.TYPE_D, "new-group-TestGroup1-XXXXXXXXX", "reg1", "3:i-123456789012345678", "3:i-123456789012345679"); return Arrays.asList(gA0, gA1, gB2, gB3, gC1, gC2, gD0); } @Override public List<InstanceGroup> groups(String... names) { Map<String, InstanceGroup> nameToGroup = new HashMap<String, InstanceGroup>(); for (InstanceGroup ig : groups()) { nameToGroup.put(ig.name(), ig); } List<InstanceGroup> list = new LinkedList<InstanceGroup>(); for (String name : names) { InstanceGroup ig = nameToGroup.get(name); if (ig == null) { continue; } for (String instanceId : selected) { // Remove selected instances from crawler list TestInstanceGroup testIg = (TestInstanceGroup) ig; testIg.deleteInstance(instanceId); } list.add(ig); } return list; } }; } private final List<InstanceGroup> selectedOn = new LinkedList<InstanceGroup>(); public List<InstanceGroup> selectedOn() { return selectedOn; } @Override public ChaosInstanceSelector chaosInstanceSelector() { return new BasicChaosInstanceSelector() { @Override public Collection<String> select(InstanceGroup group, double probability) { selectedOn.add(group); Collection<String> instances = super.select(group, probability); selected.addAll(instances); return instances; } }; } private final List<String> terminated = new LinkedList<String>(); private final List<String> selected = Lists.newArrayList(); private final List<String> cloudActions = Lists.newArrayList(); public List<String> terminated() { return terminated; } private final Map<String, String> securityGroupNames = Maps.newHashMap(); @Override public CloudClient cloudClient() { return new CloudClient() { @Override public void terminateInstance(String instanceId) { terminated.add(instanceId); } @Override public void createTagsForResources(Map<String, String> keyValueMap, String... resourceIds) { } @Override public void deleteAutoScalingGroup(String asgName) { } @Override public void deleteVolume(String volumeId) { } @Override public void deleteSnapshot(String snapshotId) { } @Override public void deleteImage(String imageId) { } @Override public void deleteLaunchConfiguration(String launchConfigName) { } @Override public void deleteElasticLoadBalancer(String elbId) { } @Override public void deleteDNSRecord(String dnsname, String dnstype, String hostedzoneid) { } @Override public List<String> listAttachedVolumes(String instanceId, boolean includeRoot) { List<String> volumes = Lists.newArrayList(); if (includeRoot) { volumes.add("volume-0"); } volumes.add("volume-1"); volumes.add("volume-2"); return volumes; } @Override public void detachVolume(String instanceId, String volumeId, boolean force) { cloudActions.add("detach:" + instanceId + ":" + volumeId); } @Override public ComputeService getJcloudsComputeService() { throw new UnsupportedOperationException(); } @Override public String getJcloudsId(String instanceId) { throw new UnsupportedOperationException(); } @Override public SshClient connectSsh(String instanceId, LoginCredentials credentials) { return new MockSshClient(instanceId, credentials); } @Override public String findSecurityGroup(String instanceId, String groupName) { return securityGroupNames.get(groupName); } @Override public String createSecurityGroup(String instanceId, String groupName, String description) { String id = "sg-" + (securityGroupNames.size() + 1); securityGroupNames.put(groupName, id); cloudActions.add("createSecurityGroup:" + instanceId + ":" + groupName); return id; } @Override public boolean canChangeInstanceSecurityGroups(String instanceId) { return true; } @Override public void setInstanceSecurityGroups(String instanceId, List<String> groupIds) { cloudActions.add("setInstanceSecurityGroups:" + instanceId + ":" + Joiner.on(',').join(groupIds)); } }; } private final List<SshAction> sshActions = Lists.newArrayList(); public static class SshAction { private String instanceId; private String method; private String path; private String contents; private String command; public String getInstanceId() { return instanceId; } public String getMethod() { return method; } public String getPath() { return path; } public String getContents() { return contents; } public String getCommand() { return command; } } private class MockSshClient implements SshClient { private final String instanceId; private final LoginCredentials credentials; public MockSshClient(String instanceId, LoginCredentials credentials) { this.instanceId = instanceId; this.credentials = credentials; } @Override public String getUsername() { return credentials.getUser(); } @Override public String getHostAddress() { throw new UnsupportedOperationException(); } @Override public void put(String path, Payload contents) { throw new UnsupportedOperationException(); } @Override public Payload get(String path) { throw new UnsupportedOperationException(); } @Override public ExecResponse exec(String command) { SshAction action = new SshAction(); action.method = "exec"; action.instanceId = instanceId; action.command = command; sshActions.add(action); String output = ""; String error = ""; int exitStatus = 0; return new ExecResponse(output, error, exitStatus); } @Override public ExecChannel execChannel(String command) { throw new UnsupportedOperationException(); } @Override public void connect() { } @Override public void disconnect() { } @Override public void put(String path, String contents) { SshAction action = new SshAction(); action.method = "put"; action.instanceId = instanceId; action.path = path; action.contents = contents; sshActions.add(action); } } private List<Notification> groupNotified = Lists.newArrayList(); private List<Notification> globallyNotified = Lists.newArrayList(); static class Notification { private final String instance; private final ChaosType chaosType; public Notification(String instance, ChaosType chaosType) { this.instance = instance; this.chaosType = chaosType; } public String getInstance() { return instance; } public ChaosType getChaosType() { return chaosType; } } @Override public ChaosEmailNotifier chaosEmailNotifier() { return new ChaosEmailNotifier(null) { @Override public String getSourceAddress(String to) { return "source@chaosMonkey.foo"; } @Override public String[] getCcAddresses(String to) { return new String[] {}; } @Override public String buildEmailSubject(String to) { return String.format("Testing Chaos termination notification for %s", to); } @Override public void sendTerminationNotification(InstanceGroup group, String instance, ChaosType chaosType) { groupNotified.add(new Notification(instance, chaosType)); } @Override public void sendTerminationGlobalNotification(InstanceGroup group, String instance, ChaosType chaosType) { globallyNotified.add(new Notification(instance, chaosType)); } }; } public int getNotified() { return groupNotified.size(); } public int getGloballyNotified() { return globallyNotified.size(); } public List<Notification> getNotifiedList() { return groupNotified; } public List<Notification> getGloballyNotifiedList() { return globallyNotified; } public List<SshAction> getSshActions() { return sshActions; } public List<String> getCloudActions() { return cloudActions; } }
4,746
0
Create_ds/SimianArmy/src/test/java/com/netflix/simianarmy/client
Create_ds/SimianArmy/src/test/java/com/netflix/simianarmy/client/vsphere/TestVSphereContext.java
/* * Copyright 2012 Immobilien Scout GmbH * * Licensed 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. */ // CHECKSTYLE IGNORE Javadoc package com.netflix.simianarmy.client.vsphere; import static org.testng.Assert.assertNotNull; import static org.testng.Assert.assertTrue; import org.testng.annotations.Test; import com.netflix.simianarmy.client.aws.AWSClient; /** * @author ingmar.krusch@immobilienscout24.de */ public class TestVSphereContext { @Test public void shouldSetClientOfCorrectType() { VSphereContext context = new VSphereContext(); AWSClient awsClient = context.awsClient(); assertNotNull(awsClient); assertTrue(awsClient instanceof VSphereClient); } }
4,747
0
Create_ds/SimianArmy/src/test/java/com/netflix/simianarmy/client
Create_ds/SimianArmy/src/test/java/com/netflix/simianarmy/client/vsphere/TestPropertyBasedTerminationStrategy.java
/* * Copyright 2012 Immobilien Scout GmbH * * Licensed 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. */ //CHECKSTYLE IGNORE Javadoc package com.netflix.simianarmy.client.vsphere; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import static org.testng.Assert.assertEquals; import static org.testng.Assert.fail; import java.rmi.RemoteException; import org.testng.annotations.Test; import com.netflix.simianarmy.basic.BasicConfiguration; import com.vmware.vim25.mo.VirtualMachine; /** * @author ingmar.krusch@immobilienscout24.de */ public class TestPropertyBasedTerminationStrategy { private BasicConfiguration configMock = mock(BasicConfiguration.class); private VirtualMachine virtualMachineMock = mock(VirtualMachine.class); @Test public void shouldReturnConfiguredPropertyNameAndValueAfterConstructedFromConfig() { when(configMock.getStrOrElse("simianarmy.client.vsphere.terminationStrategy.property.name", "Force Boot")) .thenReturn("configured name"); when(configMock.getStrOrElse("simianarmy.client.vsphere.terminationStrategy.property.value", "server")) .thenReturn("configured value"); PropertyBasedTerminationStrategy strategy = new PropertyBasedTerminationStrategy(configMock); assertEquals(strategy.getPropertyName(), "configured name"); assertEquals(strategy.getPropertyValue(), "configured value"); } @Test public void shouldSetPropertyAndResetVirtualMachineAfterTermination() { when(configMock.getStrOrElse("simianarmy.client.vsphere.terminationStrategy.property.name", "Force Boot")) .thenReturn("configured name"); when(configMock.getStrOrElse("simianarmy.client.vsphere.terminationStrategy.property.value", "server")) .thenReturn("configured value"); PropertyBasedTerminationStrategy strategy = new PropertyBasedTerminationStrategy(configMock); try { strategy.terminate(virtualMachineMock); verify(virtualMachineMock, times(1)).setCustomValue("configured name", "configured value"); verify(virtualMachineMock, times(1)).resetVM_Task(); } catch (RemoteException e) { fail("termination should not fail", e); } } }
4,748
0
Create_ds/SimianArmy/src/test/java/com/netflix/simianarmy/client
Create_ds/SimianArmy/src/test/java/com/netflix/simianarmy/client/vsphere/TestVSpehereClient.java
/* * Copyright 2012 Immobilien Scout GmbH * * Licensed 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. */ // CHECKSTYLE IGNORE Javadoc package com.netflix.simianarmy.client.vsphere; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import static org.testng.Assert.assertTrue; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import java.rmi.RemoteException; import java.util.List; import org.testng.annotations.Test; import com.amazonaws.services.autoscaling.model.AutoScalingGroup; import com.amazonaws.services.autoscaling.model.Instance; import com.vmware.vim25.mo.ManagedEntity; import com.vmware.vim25.mo.VirtualMachine; /** * @author ingmar.krusch@immobilienscout24.de */ public class TestVSpehereClient { @Test public void shouldTerminateCorrectly() throws RemoteException { VSphereServiceConnection connection = mock(VSphereServiceConnection.class); VirtualMachine vm1 = createVMMock("vm1"); when(connection.getVirtualMachineById("vm1")).thenReturn(vm1); TerminationStrategy strategy = mock(PropertyBasedTerminationStrategy.class); VSphereClient client = new VSphereClient(strategy, connection); client.terminateInstance("vm1"); verify(strategy, times(1)).terminate(vm1); } @Test public void shouldDescribeGroupsCorrectly() { VSphereServiceConnection connection = mock(VSphereServiceConnection.class); TerminationStrategy strategy = mock(PropertyBasedTerminationStrategy.class); VirtualMachine[] virtualMachines = {createVMMock("vm1"), createVMMock("vm2")}; when(connection.describeVirtualMachines()).thenReturn(virtualMachines); VSphereClient client = new VSphereClient(strategy, connection); List<AutoScalingGroup> groups = client.describeAutoScalingGroups(); String str = flattenGroups(groups); assertTrue(groups.size() == 2, "did not desribes the 2 vm's that were given"); assertTrue(str.indexOf("group:vm1.parent.name:id:vm1.name:") >= 0, "did not describe vm1 correctly"); assertTrue(str.indexOf("group:vm2.parent.name:id:vm2.name:") >= 0, "did not describe vm2 correctly"); } private String flattenGroups(List<AutoScalingGroup> groups) { StringBuilder buf = new StringBuilder(); for (AutoScalingGroup asg : groups) { List<Instance> instances = asg.getInstances(); buf.append("group:").append(asg.getAutoScalingGroupName()).append(":"); for (Instance instance : instances) { buf.append("id:").append(instance.getInstanceId()).append(":"); } } return buf.toString(); } private VirtualMachine createVMMock(String id) { VirtualMachine vm1 = mock(VirtualMachine.class); ManagedEntity me1 = mock(ManagedEntity.class); when(vm1.getName()).thenReturn(id + ".name"); when(vm1.getParent()).thenReturn(me1); when(me1.getName()).thenReturn(id + ".parent.name"); return vm1; } }
4,749
0
Create_ds/SimianArmy/src/test/java/com/netflix/simianarmy/client
Create_ds/SimianArmy/src/test/java/com/netflix/simianarmy/client/vsphere/TestVSphereGroups.java
/* * Copyright 2012 Immobilien Scout GmbH * * Licensed 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. */ // CHECKSTYLE IGNORE Javadoc package com.netflix.simianarmy.client.vsphere; import static org.testng.Assert.assertEquals; import java.util.List; import org.testng.annotations.Test; import com.amazonaws.services.autoscaling.model.AutoScalingGroup; import com.amazonaws.services.autoscaling.model.Instance; /** * @author ingmar.krusch@immobilienscout24.de */ public class TestVSphereGroups { @Test public void shouldReturnListContainigSingleASGWhenAddInstanceIsCalledOnce() { VSphereGroups groups = new VSphereGroups(); groups.addInstance("anyInstanceId", "anyGroupName"); List<AutoScalingGroup> list = groups.asList(); assertEquals(1, list.size()); AutoScalingGroup firstItem = list.get(0); assertEquals("anyGroupName", firstItem.getAutoScalingGroupName()); List<Instance> instances = firstItem.getInstances(); assertEquals(1, instances.size()); assertEquals("anyInstanceId", instances.get(0).getInstanceId()); } @Test public void shouldReturnListContainingSingleASGWithTwoInstancesWhenAddInstanceIsCaledTwiceForSameGroup() { VSphereGroups groups = new VSphereGroups(); groups.addInstance("anyInstanceId", "anyGroupName"); groups.addInstance("anyOtherInstanceId", "anyGroupName"); List<AutoScalingGroup> list = groups.asList(); assertEquals(1, list.size()); List<Instance> instances = list.get(0).getInstances(); assertEquals(2, instances.size()); assertEquals("anyInstanceId", instances.get(0).getInstanceId()); assertEquals("anyOtherInstanceId", instances.get(1).getInstanceId()); } @Test public void shouldReturnListContainigTwoASGWhenAddInstanceIsCalledTwice() { VSphereGroups groups = new VSphereGroups(); groups.addInstance("anyInstanceId", "anyGroupName"); groups.addInstance("anyOtherInstanceId", "anyOtherGroupName"); List<AutoScalingGroup> list = groups.asList(); assertEquals(2, list.size()); AutoScalingGroup firstGroup = list.get(0); assertEquals("anyGroupName", firstGroup.getAutoScalingGroupName()); List<Instance> firstGroupInstances = firstGroup.getInstances(); assertEquals(1, firstGroupInstances.size()); assertEquals("anyInstanceId", firstGroupInstances.get(0).getInstanceId()); AutoScalingGroup secondGroup = list.get(1); assertEquals("anyOtherGroupName", secondGroup.getAutoScalingGroupName()); List<Instance> secondGroupInstances = secondGroup.getInstances(); assertEquals(1, secondGroupInstances.size()); assertEquals("anyOtherInstanceId", secondGroupInstances.get(0).getInstanceId()); } }
4,750
0
Create_ds/SimianArmy/src/test/java/com/netflix/simianarmy/client
Create_ds/SimianArmy/src/test/java/com/netflix/simianarmy/client/vsphere/TestVSphereServiceConnection.java
/* * Copyright 2012 Immobilien Scout GmbH * * Licensed 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. */ // CHECKSTYLE IGNORE Javadoc package com.netflix.simianarmy.client.vsphere; import static com.netflix.simianarmy.client.vsphere.VSphereServiceConnection.VIRTUAL_MACHINE_TYPE_NAME; import static junit.framework.Assert.assertSame; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import static org.testng.Assert.assertEquals; import java.rmi.RemoteException; import org.testng.Assert; import org.testng.annotations.Test; import com.amazonaws.AmazonServiceException; import com.netflix.simianarmy.basic.BasicConfiguration; import com.vmware.vim25.InvalidProperty; import com.vmware.vim25.RuntimeFault; import com.vmware.vim25.mo.InventoryNavigator; import com.vmware.vim25.mo.ManagedEntity; import com.vmware.vim25.mo.VirtualMachine; /** * @author ingmar.krusch@immobilienscout24.de */ public class TestVSphereServiceConnection { // private ServiceInstance serviceMock = mock(ServiceInstance.class); private BasicConfiguration configMock = mock(BasicConfiguration.class); @Test public void shouldReturnConfiguredPropertiesAfterConstructedFromConfig() { when(configMock.getStr("simianarmy.client.vsphere.username")).thenReturn("configured username"); when(configMock.getStr("simianarmy.client.vsphere.password")).thenReturn("configured password"); when(configMock.getStr("simianarmy.client.vsphere.url")).thenReturn("configured url"); VSphereServiceConnection service = new VSphereServiceConnection(configMock); assertEquals(service.getUsername(), "configured username"); assertEquals(service.getPassword(), "configured password"); assertEquals(service.getUrl(), "configured url"); } @Test public void shouldCallSearchManagedEntityAndReturnVMForDoItGetVirtualMachineById() throws RemoteException { VSphereServiceConnectionWithMockedInventoryNavigator service = new VSphereServiceConnectionWithMockedInventoryNavigator(); InventoryNavigator inventoryNavigatorMock = service.getInventoryNavigatorMock(); VirtualMachine vmMock = mock(VirtualMachine.class); when(inventoryNavigatorMock.searchManagedEntity(VIRTUAL_MACHINE_TYPE_NAME, "instanceId")).thenReturn(vmMock); VirtualMachine actualVM = service.getVirtualMachineById("instanceId"); verify(inventoryNavigatorMock).searchManagedEntity(VIRTUAL_MACHINE_TYPE_NAME, "instanceId"); assertSame(vmMock, actualVM); } @Test //(expectedExceptions = AmazonServiceException.class) public void shouldThrowExceptionWhenCallingSearchManagedEntitiesOnDescribeWhenNoVMsAreReturned() throws RemoteException { VSphereServiceConnectionWithMockedInventoryNavigator service = new VSphereServiceConnectionWithMockedInventoryNavigator(); try { service.describeVirtualMachines(); } catch (AmazonServiceException e) { Assert.assertTrue(e != null); } } @Test public void shouldCallSearchManagedEntitiesOnDescribeWhenAtLeastOneVMIsReturned() throws RemoteException { VSphereServiceConnectionWithMockedInventoryNavigator service = new VSphereServiceConnectionWithMockedInventoryNavigator(); InventoryNavigator inventoryNavigatorMock = service.getInventoryNavigatorMock(); ManagedEntity[] meMocks = new ManagedEntity[] {mock(VirtualMachine.class)}; when(inventoryNavigatorMock.searchManagedEntities(VIRTUAL_MACHINE_TYPE_NAME)).thenReturn(meMocks); VirtualMachine[] actualVMs = service.describeVirtualMachines(); verify(inventoryNavigatorMock).searchManagedEntities(VIRTUAL_MACHINE_TYPE_NAME); assertSame(meMocks[0], actualVMs[0]); } @Test(expectedExceptions = AmazonServiceException.class) public void shouldEncapsulateInvalidPropertyException() throws RemoteException { VSphereServiceConnectionWithMockedInventoryNavigator service = new VSphereServiceConnectionWithMockedInventoryNavigator(); InventoryNavigator inventoryNavigatorMock = service.getInventoryNavigatorMock(); when(inventoryNavigatorMock.searchManagedEntities(VIRTUAL_MACHINE_TYPE_NAME)).thenThrow(new InvalidProperty()); service.describeVirtualMachines(); } @Test(expectedExceptions = AmazonServiceException.class) public void shouldEncapsulateRuntimeFaultException() throws RemoteException { VSphereServiceConnectionWithMockedInventoryNavigator service = new VSphereServiceConnectionWithMockedInventoryNavigator(); InventoryNavigator inventoryNavigatorMock = service.getInventoryNavigatorMock(); when(inventoryNavigatorMock.searchManagedEntities(VIRTUAL_MACHINE_TYPE_NAME)).thenThrow(new RuntimeFault()); service.describeVirtualMachines(); } @Test(expectedExceptions = AmazonServiceException.class) public void shouldEncapsulateRemoteExceptionException() throws RemoteException { VSphereServiceConnectionWithMockedInventoryNavigator service = new VSphereServiceConnectionWithMockedInventoryNavigator(); InventoryNavigator inventoryNavigatorMock = service.getInventoryNavigatorMock(); when(inventoryNavigatorMock.searchManagedEntities(VIRTUAL_MACHINE_TYPE_NAME)).thenThrow(new RemoteException()); service.describeVirtualMachines(); } // The API class ServerConnection is final and can therefore not be mocked. // It's possible to work around this using a wrapper, but this is a lot of // fake code that needs to be written and tested again just to test that // this code really calls the interface method. This is something that rather // should be tested in a system test. //@Test // public void shouldDisconnectSeviceByLogoutOverConnection() { // VSphereServiceConnectionWithMockedConnection connection = // new VSphereServiceConnectionWithMockedConnection(); // // ServiceInstance serviceMock = connection.getService(); // ServerConnection serverConnectionMock = mock(ServerConnection.class); // when(serviceMock.getServerConnection()).thenReturn(serverConnectionMock); // // connection.disconnect(); // // verify(serviceMock).getServerConnection(); // verify(serverConnectionMock).logout(); // assertNull(connection.getService()); // } } //class VSphereServiceConnectionWithMockedConnection extends VSphereServiceConnection { // public VSphereServiceConnectionWithMockedConnection() { // super(mock(BasicConfiguration.class)); // this.setService(mock(ServiceInstance.class)); // } //} class VSphereServiceConnectionWithMockedInventoryNavigator extends VSphereServiceConnection { private InventoryNavigator inventoryNavigatorMock = mock(InventoryNavigator.class); public VSphereServiceConnectionWithMockedInventoryNavigator() { super(mock(BasicConfiguration.class)); } @Override protected InventoryNavigator getInventoryNavigator() { return inventoryNavigatorMock; } public InventoryNavigator getInventoryNavigatorMock() { return inventoryNavigatorMock; } }
4,751
0
Create_ds/SimianArmy/src/test/java/com/netflix/simianarmy/client
Create_ds/SimianArmy/src/test/java/com/netflix/simianarmy/client/aws/TestAWSClient.java
/* * * Copyright 2012 Netflix, Inc. * * Licensed 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. * */ // CHECKSTYLE IGNORE Javadoc package com.netflix.simianarmy.client.aws; import com.amazonaws.services.autoscaling.AmazonAutoScalingClient; import com.amazonaws.services.autoscaling.model.AutoScalingGroup; import com.amazonaws.services.autoscaling.model.DescribeAutoScalingGroupsRequest; import com.amazonaws.services.autoscaling.model.DescribeAutoScalingGroupsResult; import com.amazonaws.services.autoscaling.model.Instance; import com.amazonaws.services.ec2.AmazonEC2; import com.amazonaws.services.ec2.model.TerminateInstancesRequest; import org.mockito.ArgumentCaptor; import org.testng.Assert; import org.testng.annotations.Test; import java.util.Arrays; import java.util.List; import static org.mockito.Matchers.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; public class TestAWSClient extends AWSClient { public TestAWSClient() { super("us-east-1"); } private AmazonEC2 ec2Mock = mock(AmazonEC2.class); protected AmazonEC2 ec2Client() { return ec2Mock; } private AmazonAutoScalingClient asgMock = mock(AmazonAutoScalingClient.class); protected AmazonAutoScalingClient asgClient() { return asgMock; } protected AmazonEC2 superEc2Client() { return super.ec2Client(); } protected AmazonAutoScalingClient superAsgClient() { return super.asgClient(); } @Test public void testClients() { TestAWSClient client1 = new TestAWSClient(); Assert.assertNotNull(client1.superEc2Client(), "non null super ec2Client"); Assert.assertNotNull(client1.superAsgClient(), "non null super asgClient"); } @Test public void testTerminateInstance() { ArgumentCaptor<TerminateInstancesRequest> arg = ArgumentCaptor.forClass(TerminateInstancesRequest.class); this.terminateInstance("fake:i-12345678901234567"); verify(ec2Mock).terminateInstances(arg.capture()); List<String> instances = arg.getValue().getInstanceIds(); Assert.assertEquals(instances.size(), 1); Assert.assertEquals(instances.get(0), "fake:i-12345678901234567"); } private DescribeAutoScalingGroupsResult mkAsgResult(String asgName, String instanceId) { DescribeAutoScalingGroupsResult result = new DescribeAutoScalingGroupsResult(); AutoScalingGroup asg = new AutoScalingGroup(); asg.setAutoScalingGroupName(asgName); Instance inst = new Instance(); inst.setInstanceId(instanceId); asg.setInstances(Arrays.asList(inst)); result.setAutoScalingGroups(Arrays.asList(asg)); return result; } @Test public void testDescribeAutoScalingGroups() { DescribeAutoScalingGroupsResult result1 = mkAsgResult("asg1", "i-123456789012345670"); result1.setNextToken("nextToken"); DescribeAutoScalingGroupsResult result2 = mkAsgResult("asg2", "i-123456789012345671"); when(asgMock.describeAutoScalingGroups(any(DescribeAutoScalingGroupsRequest.class))).thenReturn(result1) .thenReturn(result2); List<AutoScalingGroup> asgs = this.describeAutoScalingGroups(); verify(asgMock, times(2)).describeAutoScalingGroups(any(DescribeAutoScalingGroupsRequest.class)); Assert.assertEquals(asgs.size(), 2); // 2 asgs with 1 instance each Assert.assertEquals(asgs.get(0).getAutoScalingGroupName(), "asg1"); Assert.assertEquals(asgs.get(0).getInstances().size(), 1); Assert.assertEquals(asgs.get(0).getInstances().get(0).getInstanceId(), "i-123456789012345670"); Assert.assertEquals(asgs.get(1).getAutoScalingGroupName(), "asg2"); Assert.assertEquals(asgs.get(1).getInstances().size(), 1); Assert.assertEquals(asgs.get(1).getInstances().get(0).getInstanceId(), "i-123456789012345671"); } }
4,752
0
Create_ds/SimianArmy/src/test/java/com/netflix/simianarmy/client/aws
Create_ds/SimianArmy/src/test/java/com/netflix/simianarmy/client/aws/chaos/TestASGChaosCrawler.java
/* * * Copyright 2012 Netflix, Inc. * * Licensed 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. * */ // CHECKSTYLE IGNORE Javadoc package com.netflix.simianarmy.client.aws.chaos; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import java.util.Arrays; import java.util.EnumSet; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.Set; import org.testng.Assert; import org.testng.annotations.Test; import com.amazonaws.services.autoscaling.model.AutoScalingGroup; import com.amazonaws.services.autoscaling.model.Instance; import com.amazonaws.services.autoscaling.model.TagDescription; import com.netflix.simianarmy.basic.chaos.BasicInstanceGroup; import com.netflix.simianarmy.chaos.ChaosCrawler.InstanceGroup; import com.netflix.simianarmy.client.aws.AWSClient; import com.netflix.simianarmy.tunable.TunableInstanceGroup; public class TestASGChaosCrawler { private final ASGChaosCrawler crawler; private AutoScalingGroup mkAsg(String asgName, String instanceId) { AutoScalingGroup asg = new AutoScalingGroup(); asg.setAutoScalingGroupName(asgName); Instance inst = new Instance(); inst.setInstanceId(instanceId); asg.setInstances(Arrays.asList(inst)); return asg; } private final AWSClient awsMock; public TestASGChaosCrawler() { awsMock = mock(AWSClient.class); crawler = new ASGChaosCrawler(awsMock); } @Test public void testGroupTypes() { EnumSet<?> types = crawler.groupTypes(); Assert.assertEquals(types.size(), 1); Assert.assertEquals(types.iterator().next().name(), "ASG"); } @Test public void testGroups() { List<AutoScalingGroup> asgList = new LinkedList<AutoScalingGroup>(); asgList.add(mkAsg("asg1", "i-123456789012345670")); asgList.add(mkAsg("asg2", "i-123456789012345671")); when(awsMock.describeAutoScalingGroups((String[]) null)).thenReturn(asgList); List<InstanceGroup> groups = crawler.groups(); verify(awsMock, times(1)).describeAutoScalingGroups((String[]) null); Assert.assertEquals(groups.size(), 2); Assert.assertEquals(groups.get(0).type(), ASGChaosCrawler.Types.ASG); Assert.assertEquals(groups.get(0).name(), "asg1"); Assert.assertEquals(groups.get(0).instances().size(), 1); Assert.assertEquals(groups.get(0).instances().get(0), "i-123456789012345670"); Assert.assertEquals(groups.get(1).type(), ASGChaosCrawler.Types.ASG); Assert.assertEquals(groups.get(1).name(), "asg2"); Assert.assertEquals(groups.get(1).instances().size(), 1); Assert.assertEquals(groups.get(1).instances().get(0), "i-123456789012345671"); } @Test public void testFindAggressionCoefficient() { AutoScalingGroup asg1 = mkAsg("asg1", "i-123456789012345670"); Set<TagDescription> tagDescriptions = new HashSet<>(); tagDescriptions.add(makeTunableTag("1.0")); asg1.setTags(tagDescriptions); double aggression = crawler.findAggressionCoefficient(asg1); Assert.assertEquals(aggression, 1.0); } @Test public void testFindAggressionCoefficient_two() { AutoScalingGroup asg1 = mkAsg("asg1", "i-123456789012345670"); Set<TagDescription> tagDescriptions = new HashSet<>(); tagDescriptions.add(makeTunableTag("2.0")); asg1.setTags(tagDescriptions); double aggression = crawler.findAggressionCoefficient(asg1); Assert.assertEquals(aggression, 2.0); } @Test public void testFindAggressionCoefficient_null() { AutoScalingGroup asg1 = mkAsg("asg1", "i-123456789012345670"); Set<TagDescription> tagDescriptions = new HashSet<>(); tagDescriptions.add(makeTunableTag(null)); asg1.setTags(tagDescriptions); double aggression = crawler.findAggressionCoefficient(asg1); Assert.assertEquals(aggression, 1.0); } @Test public void testFindAggressionCoefficient_unparsable() { AutoScalingGroup asg1 = mkAsg("asg1", "i-123456789012345670"); Set<TagDescription> tagDescriptions = new HashSet<>(); tagDescriptions.add(makeTunableTag("not a number")); asg1.setTags(tagDescriptions); double aggression = crawler.findAggressionCoefficient(asg1); Assert.assertEquals(aggression, 1.0); } private TagDescription makeTunableTag(String value) { TagDescription desc = new TagDescription(); desc.setKey("chaosMonkey.aggressionCoefficient"); desc.setValue(value); return desc; } @Test public void testGetInstanceGroup_basic() { AutoScalingGroup asg = mkAsg("asg1", "i-123456789012345670"); InstanceGroup group = crawler.getInstanceGroup(asg, 1.0); Assert.assertTrue( (group instanceof BasicInstanceGroup) ); Assert.assertFalse( (group instanceof TunableInstanceGroup) ); } @Test public void testGetInstanceGroup_tunable() { AutoScalingGroup asg = mkAsg("asg1", "i-123456789012345670"); InstanceGroup group = crawler.getInstanceGroup(asg, 2.0); Assert.assertTrue( (group instanceof TunableInstanceGroup) ); } }
4,753
0
Create_ds/SimianArmy/src/test/java/com/netflix/simianarmy/client/aws
Create_ds/SimianArmy/src/test/java/com/netflix/simianarmy/client/aws/chaos/TestFilterASGChaosCrawler.java
/* * * Copyright 2012 Netflix, Inc. * * Licensed 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. * */ // CHECKSTYLE IGNORE Javadoc package com.netflix.simianarmy.client.aws.chaos; import com.amazonaws.services.autoscaling.model.TagDescription; import com.netflix.simianarmy.GroupType; import com.netflix.simianarmy.basic.chaos.BasicInstanceGroup; import com.netflix.simianarmy.chaos.ChaosCrawler; import com.netflix.simianarmy.chaos.ChaosCrawler.InstanceGroup; import org.testng.annotations.BeforeTest; import org.testng.annotations.Test; import java.util.*; import static org.mockito.Mockito.*; import static org.testng.Assert.assertEquals; public class TestFilterASGChaosCrawler { private ChaosCrawler crawlerMock; private ChaosCrawler crawler; private String tagKey, tagValue; public enum Types implements GroupType { /** only crawls AutoScalingGroups. */ ASG; } @BeforeTest public void beforeTest() { crawlerMock = mock(ChaosCrawler.class); tagKey = "key-" + UUID.randomUUID().toString(); tagValue = "tagValue-" + UUID.randomUUID().toString(); crawler = new FilteringChaosCrawler(crawlerMock, new TagPredicate(tagKey, tagValue)); } @Test public void testFilterGroups() { List<TagDescription> tagList = new ArrayList<TagDescription>(); TagDescription td = new TagDescription(); td.setKey(tagKey); td.setValue(tagValue); tagList.add(td); List<InstanceGroup> listGroup = new LinkedList<InstanceGroup>(); listGroup.add(new BasicInstanceGroup("asg1", Types.ASG, "region1", tagList) ); listGroup.add(new BasicInstanceGroup("asg2", Types.ASG, "region2", Collections.<TagDescription>emptyList()) ); listGroup.add(new BasicInstanceGroup("asg3", Types.ASG, "region3", tagList) ); listGroup.add(new BasicInstanceGroup("asg4", Types.ASG, "region4", Collections.<TagDescription>emptyList()) ); when(crawlerMock.groups()).thenReturn(listGroup); List<InstanceGroup> groups = crawlerMock.groups(); assertEquals(groups.size(), 4); groups = crawler.groups(); assertEquals(groups.size(), 2); assertEquals(groups.get(0).name(), "asg1"); assertEquals(groups.get(1).name(), "asg3"); } }
4,754
0
Create_ds/SimianArmy/src/test/java/com/netflix/simianarmy
Create_ds/SimianArmy/src/test/java/com/netflix/simianarmy/tunable/TestTunablyAggressiveChaosMonkey.java
/* * * Copyright 2012 Netflix, Inc. * * Licensed 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 com.netflix.simianarmy.tunable; import com.amazonaws.services.autoscaling.model.TagDescription; import org.testng.Assert; import org.testng.annotations.Test; import com.netflix.simianarmy.GroupType; import com.netflix.simianarmy.basic.chaos.BasicInstanceGroup; import com.netflix.simianarmy.chaos.ChaosCrawler.InstanceGroup; import com.netflix.simianarmy.chaos.TestChaosMonkeyContext; import java.util.Collections; public class TestTunablyAggressiveChaosMonkey { private enum GroupTypes implements GroupType { TYPE_A, TYPE_B }; @Test public void testFullProbability_basic() { TestChaosMonkeyContext ctx = new TestChaosMonkeyContext("fullProbability.properties"); TunablyAggressiveChaosMonkey chaos = new TunablyAggressiveChaosMonkey(ctx); InstanceGroup basic = new BasicInstanceGroup("basic", GroupTypes.TYPE_A, "region", Collections.<TagDescription>emptyList()); double probability = chaos.getEffectiveProbability(basic); Assert.assertEquals(probability, 1.0); } @Test public void testFullProbability_tuned() { TestChaosMonkeyContext ctx = new TestChaosMonkeyContext("fullProbability.properties"); TunablyAggressiveChaosMonkey chaos = new TunablyAggressiveChaosMonkey(ctx); TunableInstanceGroup tuned = new TunableInstanceGroup("basic", GroupTypes.TYPE_A, "region", Collections.<TagDescription>emptyList()); tuned.setAggressionCoefficient(0.5); double probability = chaos.getEffectiveProbability(tuned); Assert.assertEquals(probability, 0.5); } }
4,755
0
Create_ds/SimianArmy/src/main/java/com/netflix
Create_ds/SimianArmy/src/main/java/com/netflix/simianarmy/AbstractEmailBuilder.java
/* * * Copyright 2012 Netflix, Inc. * * Licensed 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 com.netflix.simianarmy; /** The abstract email builder. */ public abstract class AbstractEmailBuilder implements EmailBuilder { @Override public String buildEmailBody(String emailAddress) { StringBuilder body = new StringBuilder(); String header = getHeader(); if (header != null) { body.append(header); } String entryTable = getEntryTable(emailAddress); if (entryTable != null) { body.append(entryTable); } String footer = getFooter(); if (footer != null) { body.append(footer); } return body.toString(); } /** * Gets the header to the email body. */ protected abstract String getHeader(); /** * Gets the table of entries in the email body. * @param emailAddress the email address to notify * @return the HTML string representing the table for the resources to send to the * email address */ protected abstract String getEntryTable(String emailAddress); /** * Gets the footer of the email body. */ protected abstract String getFooter(); /** * Gets the HTML cell in the table of a string value. * @param value the string to put in the table * @return the HTML text */ protected String getHtmlCell(String value) { return "<td style=\"padding: 4px\">" + value + "</td>"; } /** * Gets the HTML string displaying the table header with the specified column names. * @param columns the column names for the table */ protected String getHtmlTableHeader(String[] columns) { StringBuilder tableHeader = new StringBuilder(); tableHeader.append( "<table border=\"1\" style=\"border-width:1px; border-spacing: 0px; border-collapse: seperate;\">"); tableHeader.append("<tr style=\"background-color: #E8E8E8;\" >"); for (String col : columns) { tableHeader.append(getHtmlCell(col)); } tableHeader.append("</tr>"); return tableHeader.toString(); } }
4,756
0
Create_ds/SimianArmy/src/main/java/com/netflix
Create_ds/SimianArmy/src/main/java/com/netflix/simianarmy/MonkeyType.java
/* * * Copyright 2013 Netflix, Inc. * * Licensed 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 com.netflix.simianarmy; /** * Marker interface for all monkey type enumerations. */ public interface MonkeyType extends NamedType { }
4,757
0
Create_ds/SimianArmy/src/main/java/com/netflix
Create_ds/SimianArmy/src/main/java/com/netflix/simianarmy/EmailBuilder.java
/* * * Copyright 2012 Netflix, Inc. * * Licensed 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 com.netflix.simianarmy; /** Interface for build the email body. */ public interface EmailBuilder { /** * Builds an email body for an email address. * @param emailAddress the email address to send notification to * @return the email body */ String buildEmailBody(String emailAddress); }
4,758
0
Create_ds/SimianArmy/src/main/java/com/netflix
Create_ds/SimianArmy/src/main/java/com/netflix/simianarmy/MonkeyEmailNotifier.java
/* * * Copyright 2012 Netflix, Inc. * * Licensed 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 com.netflix.simianarmy; /** The interface for the email notifier used by monkeys. */ public interface MonkeyEmailNotifier { /** * Determines if a email address is valid. * @param email the email * @return true if the email address is valid, false otherwise. */ boolean isValidEmail(String email); /** * Builds an email subject for an email address. * @param to the destination email address * @return the email subject */ String buildEmailSubject(String to); /** * Gets the cc email addresses for a to address. * @param to the to address * @return the cc email addresses */ String[] getCcAddresses(String to); /** * Gets the source email addresses for a to address. * @param to the to address * @return the source email addresses */ String getSourceAddress(String to); /** * Sends an email. * @param to the address sent to * @param subject the email subject * @param body the email body */ void sendEmail(String to, String subject, String body); }
4,759
0
Create_ds/SimianArmy/src/main/java/com/netflix
Create_ds/SimianArmy/src/main/java/com/netflix/simianarmy/Resource.java
/* * * Copyright 2012 Netflix, Inc. * * Licensed 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 com.netflix.simianarmy; import java.util.Collection; import java.util.Date; import java.util.Map; /** * The interface of Resource. It defines the interfaces for getting the common properties of a resource, as well as * the methods to add and retrieve the additional properties of a resource. Instead of defining a new subclass of * the Resource interface, new resources that have additional fields other than the common ones can be represented, * by adding field-value pairs. This approach makes serialization and deserialization of resources much easier with * the cost of type safety. */ public interface Resource { /** The enum representing the cleanup state of a resource. **/ public enum CleanupState { /** The resource is marked as a cleanup candidate but has not been cleaned up yet. **/ MARKED, /** The resource is terminated by janitor monkey. **/ JANITOR_TERMINATED, /** The resource is terminated by user before janitor monkey performs the termination. **/ USER_TERMINATED, /** The resource is unmarked and not for cleanup anymore due to some change of situations. **/ UNMARKED } /** * Gets the resource id. * * @return the resource id */ String getId(); /** * Sets the resource id. * * @param id the resource id */ void setId(String id); /** * Sets the resource id and returns the resource. * * @param id the resource id * @return the resource object */ Resource withId(String id); /** * Gets the resource type. * * @return the resource type enum */ ResourceType getResourceType(); /** * Sets the resource type. * * @param type the resource type enum */ void setResourceType(ResourceType type); /** * Sets the resource type and returns the resource. * * @param type resource type enum * @return the resource object */ Resource withResourceType(ResourceType type); /** * Gets the region the resource is in. * * @return the region of the resource */ String getRegion(); /** * Sets the region the resource is in. * * @param region the region the resource is in */ void setRegion(String region); /** * Sets the resource region and returns the resource. * * @param region the region the resource is in * @return the resource object */ Resource withRegion(String region); /** * Gets the owner email of the resource. * * @return the owner email of the resource */ String getOwnerEmail(); /** * Sets the owner email of the resource. * * @param ownerEmail the owner email of the resource */ void setOwnerEmail(String ownerEmail); /** * Sets the resource owner email and returns the resource. * * @param ownerEmail the owner email of the resource * @return the resource object */ Resource withOwnerEmail(String ownerEmail); /** * Gets the description of the resource. * * @return the description of the resource */ String getDescription(); /** * Sets the description of the resource. * * @param description the description of the resource */ void setDescription(String description); /** * Sets the resource description and returns the resource. * * @param description the description of the resource * @return the resource object */ Resource withDescription(String description); /** * Gets the launch time of the resource. * * @return the launch time of the resource */ Date getLaunchTime(); /** * Sets the launch time of the resource. * * @param launchTime the launch time of the resource */ void setLaunchTime(Date launchTime); /** * Sets the resource launch time and returns the resource. * * @param launchTime the launch time of the resource * @return the resource object */ Resource withLaunchTime(Date launchTime); /** * Gets the time that when the resource is marked as a cleanup candidate. * * @return the time that when the resource is marked as a cleanup candidate */ Date getMarkTime(); /** * Sets the time that when the resource is marked as a cleanup candidate. * * @param markTime the time that when the resource is marked as a cleanup candidate */ void setMarkTime(Date markTime); /** * Sets the resource mark time and returns the resource. * * @param markTime the time that when the resource is marked as a cleanup candidate * @return the resource object */ Resource withMarkTime(Date markTime); /** * Gets the the time that when the resource is expected to be terminated. * * @return the time that when the resource is expected to be terminated */ Date getExpectedTerminationTime(); /** * Sets the time that when the resource is expected to be terminated. * * @param expectedTerminationTime the time that when the resource is expected to be terminated */ void setExpectedTerminationTime(Date expectedTerminationTime); /** * Sets the time that when the resource is expected to be terminated and returns the resource. * * @param expectedTerminationTime the time that when the resource is expected to be terminated * @return the resource object */ Resource withExpectedTerminationTime(Date expectedTerminationTime); /** * Gets the time that when the resource is actually terminated. * * @return the time that when the resource is actually terminated */ Date getActualTerminationTime(); /** * Sets the time that when the resource is actually terminated. * * @param actualTerminationTime the time that when the resource is actually terminated */ void setActualTerminationTime(Date actualTerminationTime); /** * Sets the resource actual termination time and returns the resource. * * @param actualTerminationTime the time that when the resource is actually terminated * @return the resource object */ Resource withActualTerminationTime(Date actualTerminationTime); /** * Gets the time that when the owner is notified about the cleanup of the resource. * * @return the time that when the owner is notified about the cleanup of the resource */ Date getNotificationTime(); /** * Sets the time that when the owner is notified about the cleanup of the resource. * * @param notificationTime the time that when the owner is notified about the cleanup of the resource */ void setNotificationTime(Date notificationTime); /** * Sets the time that when the owner is notified about the cleanup of the resource and returns the resource. * * @param notificationTime the time that when the owner is notified about the cleanup of the resource * @return the resource object */ Resource withNnotificationTime(Date notificationTime); /** * Gets the resource state. * * @return the resource state enum */ CleanupState getState(); /** * Sets the resource state. * * @param state the resource state */ void setState(CleanupState state); /** * Sets the resource state and returns the resource. * * @param state resource state enum * @return the resource object */ Resource withState(CleanupState state); /** * Gets the termination reason of the resource. * * @return the termination reason of the resource */ String getTerminationReason(); /** * Sets the termination reason of the resource. * * @param terminationReason the termination reason of the resource */ void setTerminationReason(String terminationReason); /** * Sets the resource termination reason and returns the resource. * * @param terminationReason the termination reason of the resource * @return the resource object */ Resource withTerminationReason(String terminationReason); /** * Gets the boolean to indicate whether or not the resource is opted out of Janitor monkey * so it will not be cleaned. * @return true if the resource is opted out of Janitor monkey, otherwise false */ boolean isOptOutOfJanitor(); /** * Sets the flag to indicate whether or not the resource is opted out of Janitor monkey * so it will not be cleaned. * @param optOutOfJanitor true if the resource is opted out of Janitor monkey, otherwise false */ void setOptOutOfJanitor(boolean optOutOfJanitor); /** * Sets the flag to indicate whether or not the resource is opted out of Janitor monkey * so it will not be cleaned and returns the resource object. * @param optOutOfJanitor true if the resource is opted out of Janitor monkey, otherwise false * @return the resource object */ Resource withOptOutOfJanitor(boolean optOutOfJanitor); /** * Gets a map from fields of resources to corresponding values. Values are represented * as Strings so they can be displayed or stored in databases like SimpleDB. * @return a map from field name to field value */ Map<String, String> getFieldToValueMap(); /** Adds or sets an additional field with the specified name and value to the resource. * * @param fieldName the field name * @param fieldValue the field value * @return the resource itself for chaining */ Resource setAdditionalField(String fieldName, String fieldValue); /** Gets the value of an additional field with the specified name of the resource. * * @param fieldName the field name * @return the field value */ String getAdditionalField(String fieldName); /** * Gets all additional field names in the resource. * @return a collection of names of all additional fields */ Collection<String> getAdditionalFieldNames(); /** * Adds a tag with the specified key and value to the resource. * @param key the key of the tag * @param value the value of the tag */ void setTag(String key, String value); /** * Gets the tag value for a specific key of the resource. * @param key the key of the tag * @return the value of the tag */ String getTag(String key); /** * Gets all the keys of tags. * @return collection of keys of all tags */ Collection<String> getAllTagKeys(); /** Clone a resource with the exact field values of the current object. * * @return the clone of the resource */ Resource cloneResource(); }
4,760
0
Create_ds/SimianArmy/src/main/java/com/netflix
Create_ds/SimianArmy/src/main/java/com/netflix/simianarmy/MonkeyCalendar.java
/* * * Copyright 2012 Netflix, Inc. * * Licensed 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 com.netflix.simianarmy; import java.util.Calendar; import java.util.Date; /** * The Interface MonkeyCalendar used to tell if a monkey should be running or now. We only want monkeys to run during * business hours, so that engineers will be on-hand if something goes wrong. */ public interface MonkeyCalendar { /** * Checks if is monkey time. * * @param monkey * the monkey * @return true, if is monkey time */ boolean isMonkeyTime(Monkey monkey); /** * Open hour. This is the "open" hour for then the monkey should start working. * * @return the int */ int openHour(); /** * Close hour. This is the "close" hour for when the monkey should stop working. * * @return the int */ int closeHour(); /** * Get the current time using whatever timezone is used for monkey date calculations. * * @return the calendar */ Calendar now(); /** Gets the next business day from the start date after n business days. * * @param date the start date * @param n the number of business days from now * @return the business day after n business days */ Date getBusinessDay(Date date, int n); }
4,761
0
Create_ds/SimianArmy/src/main/java/com/netflix
Create_ds/SimianArmy/src/main/java/com/netflix/simianarmy/Monkey.java
/* * * Copyright 2012 Netflix, Inc. * * Licensed 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 com.netflix.simianarmy; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.netflix.simianarmy.MonkeyRecorder.Event; /** * The abstract Monkey class, it provides a minimal interface from which all monkeys must be derived. */ public abstract class Monkey { /** The Constant LOGGER. */ private static final Logger LOGGER = LoggerFactory.getLogger(Monkey.class); /** * The Interface Context. */ public interface Context { /** * Scheduler. * * @return the monkey scheduler */ MonkeyScheduler scheduler(); /** * Calendar. * * @return the monkey calendar */ MonkeyCalendar calendar(); /** * Cloud client. * * @return the cloud client */ CloudClient cloudClient(); /** * Recorder. * * @return the monkey recorder */ MonkeyRecorder recorder(); /** * Add a event to the summary report. The ChaosMonkey uses this to print a summary after the chaos run is * complete. * * @param evt * The Event to be reported */ void reportEvent(Event evt); /** * Used to clear the event summary on the start of a chaos run. */ void resetEventReport(); /** * Returns a summary of what the chaos run did. */ String getEventReport(); /** * Configuration. * * @return the monkey configuration */ MonkeyConfiguration configuration(); } /** The context. */ private final Context ctx; /** * Instantiates a new monkey. * * @param ctx * the context */ public Monkey(Context ctx) { this.ctx = ctx; } /** * Type. * * @return the monkey type enum */ public abstract MonkeyType type(); /** * Do monkey business. */ public abstract void doMonkeyBusiness(); /** * Context. * * @return the context */ public Context context() { return ctx; } /** * Run. This is run on the schedule set by the MonkeyScheduler */ public void run() { if (ctx.calendar().isMonkeyTime(this)) { LOGGER.info(this.type().name() + " Monkey Running ..."); try { this.doMonkeyBusiness(); } finally { String eventReport = context().getEventReport(); if (eventReport != null) { LOGGER.info("Reporting what I did...\n" + eventReport); } } } else { LOGGER.info("Not Time for " + this.type().name() + " Monkey"); } } /** * Start. Sets up the schedule for the monkey to run on. */ public void start() { final Monkey me = this; ctx.scheduler().start(this, new Runnable() { @Override public void run() { try { me.run(); } catch (Exception e) { LOGGER.error(me.type().name() + " Monkey Error: ", e); } } }); } /** * Stop. Removes the monkey from the schedule. */ public void stop() { ctx.scheduler().stop(this); } }
4,762
0
Create_ds/SimianArmy/src/main/java/com/netflix
Create_ds/SimianArmy/src/main/java/com/netflix/simianarmy/ResourceType.java
/* * * Copyright 2013 Netflix, Inc. * * Licensed 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 com.netflix.simianarmy; /** * Marker interface for all resource type enumerations. */ public interface ResourceType extends NamedType { }
4,763
0
Create_ds/SimianArmy/src/main/java/com/netflix
Create_ds/SimianArmy/src/main/java/com/netflix/simianarmy/MonkeyRunner.java
/* * * Copyright 2012 Netflix, Inc. * * Licensed 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 com.netflix.simianarmy; import java.lang.reflect.Constructor; import java.util.Collections; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.ListIterator; import java.util.Map; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * The MonkeyRunner Singleton. */ public enum MonkeyRunner { /** The instance. */ INSTANCE; /** The Constant LOGGER. */ private static final Logger LOGGER = LoggerFactory.getLogger(MonkeyRunner.class); /** * Gets the single instance of MonkeyRunner. * * @return single instance of MonkeyRunner */ public static MonkeyRunner getInstance() { return INSTANCE; } /** * Start all the monkeys registered with addMonkey or replaceMonkey. */ public void start() { for (Monkey monkey : monkeys) { LOGGER.info("Starting " + monkey.type().name() + " Monkey"); monkey.start(); } } /** * Stop all of the registered monkeys. */ public void stop() { for (Monkey monkey : monkeys) { LOGGER.info("Stopping " + monkey.type().name() + " Monkey"); monkey.stop(); } } /** * The monkey map. Maps the monkey class to the context class that is registered. This is so we can create new * monkeys in factory() that have the same context types as the registered ones. */ private final Map<Class<? extends Monkey>, Class<? extends Monkey.Context>> monkeyMap = new HashMap<Class<? extends Monkey>, Class<? extends Monkey.Context>>(); /** The monkeys. */ private final List<Monkey> monkeys = new LinkedList<Monkey>(); /** * Gets the registered monkeys. * * @return the monkeys */ public List<Monkey> getMonkeys() { return Collections.unmodifiableList(monkeys); } /** * Adds a simple monkey void constructor. * * @param monkeyClass * the monkey class */ public void addMonkey(Class<? extends Monkey> monkeyClass) { addMonkey(monkeyClass, null); } /** * Replace a simple monkey that has void constructor. * * @param monkeyClass * the monkey class */ public void replaceMonkey(Class<? extends Monkey> monkeyClass) { replaceMonkey(monkeyClass, null); } /** * Adds the monkey. * * @param monkeyClass * the monkey class * @param ctxClass * the context class that is passed to the monkey class constructor. */ public void addMonkey(Class<? extends Monkey> monkeyClass, Class<? extends Monkey.Context> ctxClass) { if (monkeyMap.containsKey(monkeyClass)) { throw new RuntimeException(monkeyClass.getName() + " already registered, use replaceMonkey instead of addMonkey"); } monkeyMap.put(monkeyClass, ctxClass); monkeys.add(factory(monkeyClass, ctxClass)); } /** * Replace monkey. If a monkey is already registered this will replace that registered monkey. * * @param monkeyClass * the monkey class * @param ctxClass * the context class that is passed to the monkey class constructor. */ public void replaceMonkey(Class<? extends Monkey> monkeyClass, Class<? extends Monkey.Context> ctxClass) { monkeyMap.put(monkeyClass, ctxClass); ListIterator<Monkey> li = monkeys.listIterator(); while (li.hasNext()) { Monkey monkey = li.next(); if (monkey.getClass() == monkeyClass) { li.set(factory(monkeyClass, ctxClass)); return; } } Monkey monkey = factory(monkeyClass, ctxClass); monkeys.add(monkey); } /** * Removes the monkey. factory() will no longer be able to construct monkeys of the specified monkey class. * * @param monkeyClass * the monkey class */ public void removeMonkey(Class<? extends Monkey> monkeyClass) { ListIterator<Monkey> li = monkeys.listIterator(); while (li.hasNext()) { Monkey monkey = li.next(); if (monkey.getClass() == monkeyClass) { monkey.stop(); li.remove(); break; } } monkeyMap.remove(monkeyClass); } /** * Monkey factory. This will generate a new monkey object of the monkeyClass type. If a monkey of monkeyClass has * not been registered then this will attempt to find a registered subclass and create an object of that type. * Example: * * <pre> * {@code * MonkeyRunner.getInstance().addMonkey(BasicChaosMonkey.class, BasicMonkeyContext.class); * // This will actually return a BasicChaosMonkey since that is the only subclass that was registered * ChaosMonkey monkey = MonkeyRunner.getInstance().factory(ChaosMonkey.class); *} * </pre> * * @param <T> * the generic type, must be a subclass of Monkey * @param monkeyClass * the monkey class * @return the monkey */ public <T extends Monkey> T factory(Class<T> monkeyClass) { Class<? extends Monkey.Context> ctxClass = getContextClass(monkeyClass); if (ctxClass == null) { // look for derived class already in our map for (Map.Entry<Class<? extends Monkey>, Class<? extends Monkey.Context>> pair : monkeyMap.entrySet()) { if (monkeyClass.isAssignableFrom(pair.getKey())) { @SuppressWarnings("unchecked") T monkey = (T) factory(pair.getKey(), pair.getValue()); return monkey; } } } return factory(monkeyClass, ctxClass); } /** * Monkey Factory. Given a monkey class and a monkey context class it will generate a new monkey. If the * contextClass is null it will try to generate a new monkeyClass with a void constructor; * * @param <T> * the generic type, must be a subclass of Monkey * @param monkeyClass * the monkey class * @param contextClass * the context class * @return the monkey */ public <T extends Monkey> T factory(Class<T> monkeyClass, Class<? extends Monkey.Context> contextClass) { try { if (contextClass == null) { // assume Monkey class has has void ctor return monkeyClass.newInstance(); } // then find corresponding ctor for (Constructor<?> ctor : monkeyClass.getDeclaredConstructors()) { Class<?>[] paramTypes = ctor.getParameterTypes(); if (paramTypes.length != 1) { continue; } if (paramTypes[0].getName().endsWith("$Context")) { @SuppressWarnings("unchecked") T monkey = (T) ctor.newInstance(contextClass.newInstance()); return monkey; } } } catch (Exception e) { LOGGER.error("monkeyFactory error, cannot make monkey from " + monkeyClass.getName() + " with " + (contextClass == null ? null : contextClass.getName()), e); } return null; } /** * Gets the context class. You should not need this. * * @param monkeyClass * the monkey class * @return the context class or null if a monkeyClass has not been registered */ public Class<? extends Monkey.Context> getContextClass(Class<? extends Monkey> monkeyClass) { return monkeyMap.get(monkeyClass); } }
4,764
0
Create_ds/SimianArmy/src/main/java/com/netflix
Create_ds/SimianArmy/src/main/java/com/netflix/simianarmy/CloudClient.java
/* * * Copyright 2012 Netflix, Inc. * * Licensed 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 com.netflix.simianarmy; import org.jclouds.compute.ComputeService; import org.jclouds.domain.LoginCredentials; import org.jclouds.ssh.SshClient; import java.util.List; import java.util.Map; /** * The CloudClient interface. This abstractions provides the interface that the monkeys need to interact with * "the cloud". */ public interface CloudClient { /** * Terminates instance. * * @param instanceId * the instance id * * @throws NotFoundException * if the instance no longer exists or was already terminated after the crawler discovered it then you * should get a NotFoundException */ void terminateInstance(String instanceId); /** * Deletes an auto scaling group. * * @param asgName * the auto scaling group name */ void deleteAutoScalingGroup(String asgName); /** * Deletes a launch configuration. * * @param launchConfigName * the launch configuration name */ void deleteLaunchConfiguration(String launchConfigName); /** * Deletes a volume. * * @param volumeId * the volume id */ void deleteVolume(String volumeId); /** * Deletes a snapshot. * * @param snapshotId * the snapshot id. */ void deleteSnapshot(String snapshotId); /** Deletes an image. * * @param imageId * the image id. */ void deleteImage(String imageId); /** * Deletes an elastic load balancer. * * @param elbId * the elastic load balancer id */ void deleteElasticLoadBalancer(String elbId); /** * Deletes a DNS record. * * @param dnsName * the DNS record to delete * @param dnsType * the DNS type (CNAME, A, or AAAA) * @param hostedZoneID * the ID of the hosted zone (required for AWS Route53 records) */ public void deleteDNSRecord(String dnsName, String dnsType, String hostedZoneID); /** * Adds or overwrites tags for the specified resources. * * @param keyValueMap * the new tags in the form of map from key to value * * @param resourceIds * the list of resource ids */ void createTagsForResources(Map<String, String> keyValueMap, String... resourceIds); /** * Lists all EBS volumes attached to the specified instance. * * @param instanceId * the instance id * @param includeRoot * if the root volume is on EBS, should we include it? * * @throws NotFoundException * if the instance no longer exists or was already terminated after the crawler discovered it then you * should get a NotFoundException */ List<String> listAttachedVolumes(String instanceId, boolean includeRoot); /** * Detaches an EBS volumes from the specified instance. * * @param instanceId * the instance id * @param volumeId * the volume id * @param force * if we should force-detach the volume. Probably best not to use on high-value volumes. * * @throws NotFoundException * if the instance no longer exists or was already terminated after the crawler discovered it then you * should get a NotFoundException */ void detachVolume(String instanceId, String volumeId, boolean force); /** * Returns the jClouds compute service. */ ComputeService getJcloudsComputeService(); /** * Returns the jClouds node id for an instance id on this CloudClient. */ String getJcloudsId(String instanceId); /** * Opens an SSH connection to an instance. * * @param instanceId * instance id to connect to * @param credentials * SSH credentials to use * @return {@link SshClient}, in connected state */ SshClient connectSsh(String instanceId, LoginCredentials credentials); /** * Finds a security group with the given name, that can be applied to the given instance. * * For example, if it is a VPC instance, it makes sure that it is in the same VPC group. * * @param instanceId * the instance that the group must be applied to * @param groupName * the name of the group to find * * @return The group id, or null if not found */ String findSecurityGroup(String instanceId, String groupName); /** * Creates an (empty) security group, that can be applied to the given instance. * * @param instanceId * instance that group should be applicable to * @param groupName * name for new group * @param description * description for new group * * @return the id of the security group */ String createSecurityGroup(String instanceId, String groupName, String description); /** * Checks if we can change the security groups of an instance. * * @param instanceId * instance to check * * @return true iff we can change security groups. */ boolean canChangeInstanceSecurityGroups(String instanceId); /** * Sets the security groups for an instance. * * Note this is only valid for VPC instances. * * @param instanceId * the instance id * @param groupIds * ids of desired new groups * * @throws NotFoundException * if the instance no longer exists or was already terminated after the crawler discovered it then you * should get a NotFoundException */ void setInstanceSecurityGroups(String instanceId, List<String> groupIds); }
4,765
0
Create_ds/SimianArmy/src/main/java/com/netflix
Create_ds/SimianArmy/src/main/java/com/netflix/simianarmy/FeatureNotEnabledException.java
/* * * Copyright 2012 Netflix, Inc. * * Licensed 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 com.netflix.simianarmy; /** * The Class FeatureNotEnabledException. * * These exceptions will be thrown when a feature is not enabled when being accessed. */ public class FeatureNotEnabledException extends Exception { private static final long serialVersionUID = 8392434473284901306L; /** * Instantiates a FeatureNotEnabledException with a message. * @param msg the error message */ public FeatureNotEnabledException(String msg) { super(msg); } }
4,766
0
Create_ds/SimianArmy/src/main/java/com/netflix
Create_ds/SimianArmy/src/main/java/com/netflix/simianarmy/MonkeyConfiguration.java
/* * * Copyright 2012 Netflix, Inc. * * Licensed 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 com.netflix.simianarmy; /** * The Interface MonkeyConfiguration. */ public interface MonkeyConfiguration { /** * Gets the boolean associated with property string. If not found it will return false. * * @param property * the property name * @return the boolean value */ boolean getBool(String property); /** * Gets the boolean associated with property string. If not found it will return dflt. * * @param property * the property name * @param dflt * the default value * @return the bool property value, or dflt if none set */ boolean getBoolOrElse(String property, boolean dflt); /** * Gets the number (double) associated with property string. If not found it will return dflt. * * @param property * the property name * @param dflt * the default value * @return the numeric property value, or dflt if none set */ double getNumOrElse(String property, double dflt); /** * Gets the string associated with property string. If not found it will return null. * * @param property * the property name * @return the string property value */ String getStr(String property); /** * Gets the string associated with property string. If not found it will return dflt. * * @param property * the property name * @param dflt * the default value * @return the string property value, or dflt if none set */ String getStrOrElse(String property, String dflt); /** * If the configuration has dynamic elements then they should be reloaded with this. */ void reload(); /** * Reloads the properties of specific group. * @param groupName * the instance group's name */ void reload(String groupName); }
4,767
0
Create_ds/SimianArmy/src/main/java/com/netflix
Create_ds/SimianArmy/src/main/java/com/netflix/simianarmy/MonkeyRecorder.java
/* * * Copyright 2012 Netflix, Inc. * * Licensed 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 com.netflix.simianarmy; import java.util.Date; import java.util.List; import java.util.Map; /** * The Interface MonkeyRecorder. This is use to store and find events in some datastore. */ public interface MonkeyRecorder { /** * The Interface Event. */ public interface Event { /** * Event Id. * * @return the string */ String id(); /** * Event time. * * @return the date */ Date eventTime(); /** * Monkey type. * * @return the monkey type enum */ MonkeyType monkeyType(); /** * Event type. * * @return the event type enum */ EventType eventType(); /** * Region. * * @return the region for the event */ String region(); /** * Fields. * * * @return the map of strings that may have been provided when the event was created */ Map<String, String> fields(); /** * Field. * * @param name * the name * @return the string associated with that field */ String field(String name); /** * Adds the field. * * @param name * the name * @param value * the value * @return <b>this</b> so you can chain multiple addField calls together */ Event addField(String name, String value); } /** * New event. * * @param monkeyType * the monkey type * @param eventType * the event type * @param region * the region the event occurred * @param id * the id * @return the event */ Event newEvent(MonkeyType monkeyType, EventType eventType, String region, String id); default Event newEvent(MonkeyType monkeyType, EventType eventType, Resource resource, String id) { if (resource == null) throw new IllegalArgumentException("resource must not be null"); Event event = newEvent(monkeyType, eventType, resource.getRegion(), id); if (resource.getAllTagKeys() != null) { for(String key : resource.getAllTagKeys()) { event.addField(key, resource.getTag(key)); } } event.addField("ResourceDescription", resource.getDescription()); event.addField("ResourceType", resource.getResourceType().toString()); event.addField("ResourceId", resource.getId()); return event; } /** * Record event. * * @param evt * the evt */ void recordEvent(Event evt); /** * Find events. * * @param query * arbitrary map of strings to used to filter the results * @param after * the after * @return the list of events */ List<Event> findEvents(Map<String, String> query, Date after); /** * Find events. * * @param monkeyType * the monkey type * @param query * arbitrary map of strings to used to filter the results * @param after * the after * @return the list of events */ List<Event> findEvents(MonkeyType monkeyType, Map<String, String> query, Date after); /** * Find events. * * @param monkeyType * the monkey type * @param eventType * the event type * @param query * arbitrary map of strings to used to filter the results * @param after * the after * @return the list */ List<Event> findEvents(MonkeyType monkeyType, EventType eventType, Map<String, String> query, Date after); }
4,768
0
Create_ds/SimianArmy/src/main/java/com/netflix
Create_ds/SimianArmy/src/main/java/com/netflix/simianarmy/EventType.java
/* * * Copyright 2013 Netflix, Inc. * * Licensed 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 com.netflix.simianarmy; /** * Marker interface for all event type enumerations. */ public interface EventType extends NamedType { }
4,769
0
Create_ds/SimianArmy/src/main/java/com/netflix
Create_ds/SimianArmy/src/main/java/com/netflix/simianarmy/GroupType.java
/* * * Copyright 2013 Netflix, Inc. * * Licensed 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 com.netflix.simianarmy; /** * Marker interface for all group type enumerations. */ public interface GroupType extends NamedType { }
4,770
0
Create_ds/SimianArmy/src/main/java/com/netflix
Create_ds/SimianArmy/src/main/java/com/netflix/simianarmy/NamedType.java
/* * * Copyright 2013 Netflix, Inc. * * Licensed 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 com.netflix.simianarmy; /** * Interface requiring a name() method. */ public interface NamedType { /** * Name of this instance. */ String name(); }
4,771
0
Create_ds/SimianArmy/src/main/java/com/netflix
Create_ds/SimianArmy/src/main/java/com/netflix/simianarmy/NotFoundException.java
/* * * Copyright 2012 Netflix, Inc. * * Licensed 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 com.netflix.simianarmy; /** * The Class NotFoundException. * * These exceptions will be thrown when a Monkey is trying to interact with a remote resource but it no longer exists * (or never existed). It is used as an adapter to translate a cloud provider exception into something common that the * monkeys can easily handle. */ @SuppressWarnings("serial") public class NotFoundException extends RuntimeException { /** * Instantiates a new NotFound exception. * * @param message * the exception message */ public NotFoundException(String message) { super(message); } /** * Instantiates a new NotFound exception. * * @param message * the exception message * @param cause * the exception cause. This should be the raw exception from the cloud provider. */ public NotFoundException(String message, Throwable cause) { super(message, cause); } /** * Instantiates a new NotFound exception. * * @param cause * the exception cause. This should be the raw exception from the cloud provider. */ public NotFoundException(Throwable cause) { super(cause); } }
4,772
0
Create_ds/SimianArmy/src/main/java/com/netflix
Create_ds/SimianArmy/src/main/java/com/netflix/simianarmy/InstanceGroupNotFoundException.java
/* * * Copyright 2012 Netflix, Inc. * * Licensed 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 com.netflix.simianarmy; /** * The Class InstanceGroupNotFoundException. * * These exceptions will be thrown when an instance group cannot be found with the * given name and type. */ public class InstanceGroupNotFoundException extends Exception { private static final long serialVersionUID = -5492120875166280476L; private final String groupType; private final String groupName; /** * Instantiates an InstanceGroupNotFoundException with the group type and name. * @param groupType the group type * @param groupName the gruop name */ public InstanceGroupNotFoundException(String groupType, String groupName) { super(errorMessage(groupType, groupName)); this.groupType = groupType; this.groupName = groupName; } @Override public String toString() { return errorMessage(groupType, groupName); } private static String errorMessage(String groupType, String groupName) { return String.format("Instance group named '%s' [type %s] cannot be found.", groupName, groupType); } }
4,773
0
Create_ds/SimianArmy/src/main/java/com/netflix
Create_ds/SimianArmy/src/main/java/com/netflix/simianarmy/MonkeyScheduler.java
/* * * Copyright 2012 Netflix, Inc. * * Licensed 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 com.netflix.simianarmy; import java.util.concurrent.TimeUnit; /** * The Interface MonkeyScheduler. */ public interface MonkeyScheduler { /** * Frequency. How often the monkey should run, works in conjunction with frequencyUnit(). If frequency is 2 and * frequencyUnit is TimeUnit.HOUR then the monkey will run once ever 2 hours. * * @return the frequency interval */ int frequency(); /** * Frequency unit. This is the time unit that corresponds with frequency(). * * @return time unit */ TimeUnit frequencyUnit(); /** * Start the scheduler to cause the monkey run at a specified interval. * * @param monkey * the monkey being scheduled * @param run * the Runnable to start, generally calls doMonkeyBusiness */ void start(Monkey monkey, Runnable run); /** * Stop the scheduler for a given monkey. After this the monkey will no longer run on the fixed schedule. * * @param monkey * the monkey being scheduled */ void stop(Monkey monkey); }
4,774
0
Create_ds/SimianArmy/src/main/java/com/netflix/simianarmy
Create_ds/SimianArmy/src/main/java/com/netflix/simianarmy/conformity/ConformityMonkey.java
/* * * Copyright 2013 Netflix, Inc. * * Licensed 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 com.netflix.simianarmy.conformity; import com.netflix.simianarmy.Monkey; import com.netflix.simianarmy.MonkeyConfiguration; import com.netflix.simianarmy.MonkeyType; import java.util.Collection; /** * The abstract class for Conformity Monkey. */ public abstract class ConformityMonkey extends Monkey { /** * The Interface Context. */ public interface Context extends Monkey.Context { /** * Configuration. * * @return the monkey configuration */ MonkeyConfiguration configuration(); /** * Crawler that gets information of all clusters for conformity check. * @return all clusters for conformity check */ ClusterCrawler clusterCrawler(); /** * Conformity rule engine. * @return the Conformity rule engine */ ConformityRuleEngine ruleEngine(); /** * Email notifier used to send notifications by the Conformity monkey. * @return the email notifier */ ConformityEmailNotifier emailNotifier(); /** * The regions the monkey is running in. * @return the regions the monkey is running in. */ Collection<String> regions(); /** * The tracker of the clusters for conformity monkey to check. * @return the tracker of the clusters for conformity monkey to check. */ ConformityClusterTracker clusterTracker(); /** * Gets the flag to indicate whether the monkey is leashed. * @return true if the monkey is leashed and does not make real change or send notifications to * cluster owners, false otherwise. */ boolean isLeashed(); } /** The context. */ private final Context ctx; /** * Instantiates a new Conformity monkey. * * @param ctx * the context. */ public ConformityMonkey(Context ctx) { super(ctx); this.ctx = ctx; } /** * The monkey Type. */ public enum Type implements MonkeyType { /** Conformity monkey. */ CONFORMITY } /** {@inheritDoc} */ @Override public final Type type() { return Type.CONFORMITY; } /** {@inheritDoc} */ @Override public Context context() { return ctx; } /** {@inheritDoc} */ @Override public abstract void doMonkeyBusiness(); }
4,775
0
Create_ds/SimianArmy/src/main/java/com/netflix/simianarmy
Create_ds/SimianArmy/src/main/java/com/netflix/simianarmy/conformity/Conformity.java
/* * * Copyright 2013 Netflix, Inc. * * Licensed 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 com.netflix.simianarmy.conformity; import com.google.common.collect.Lists; import org.apache.commons.lang.Validate; import java.util.Collection; import java.util.Collections; /** * The class defining the result of a conformity check. */ public class Conformity { private final String ruleId; private final Collection<String> failedComponents = Lists.newArrayList(); /** * Constructor. * @param ruleId * the conformity rule id * @param failedComponents * the components that cause the conformity check to fail, if there is * no failed components, it means the conformity check passes. */ public Conformity(String ruleId, Collection<String> failedComponents) { Validate.notNull(ruleId); Validate.notNull(failedComponents); this.ruleId = ruleId; for (String failedComponent : failedComponents) { this.failedComponents.add(failedComponent); } } /** * Gets the conformity rule id. * @return * the conformity rule id */ public String getRuleId() { return ruleId; } /** * Gets the components that cause the conformity check to fail. * @return * the components that cause the conformity check to fail */ public Collection<String> getFailedComponents() { return Collections.unmodifiableCollection(failedComponents); } }
4,776
0
Create_ds/SimianArmy/src/main/java/com/netflix/simianarmy
Create_ds/SimianArmy/src/main/java/com/netflix/simianarmy/conformity/ConformityEmailBuilder.java
/* * * Copyright 2013 Netflix, Inc. * * Licensed 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 com.netflix.simianarmy.conformity; import com.netflix.simianarmy.AbstractEmailBuilder; import java.util.Collection; import java.util.Map; /** The abstract class for building Conformity monkey email notifications. */ public abstract class ConformityEmailBuilder extends AbstractEmailBuilder { /** * Sets the map from an owner email to the clusters that belong to the owner * and need to send notifications for. * @param emailToClusters the map from owner email to the owned clusters * @param rules all conformity rules that are used to find the description of each rule to display */ public abstract void setEmailToClusters(Map<String, Collection<Cluster>> emailToClusters, Collection<ConformityRule> rules); }
4,777
0
Create_ds/SimianArmy/src/main/java/com/netflix/simianarmy
Create_ds/SimianArmy/src/main/java/com/netflix/simianarmy/conformity/ConformityRule.java
/* * * Copyright 2013 Netflix, Inc. * * Licensed 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 com.netflix.simianarmy.conformity; /** * Interface for a conformity check rule. */ public interface ConformityRule { /** * Performs the conformity check against the rule. * @param cluster * the cluster to check for conformity * @return * the conformity check result */ Conformity check(Cluster cluster); /** * Gets the name/id of the rule. * @return * the name of the rule */ String getName(); /** * Gets the human-readable reason to explain why the cluster is not conforming. * @return the human-readable reason to explain why the cluster is not conforming */ String getNonconformingReason(); }
4,778
0
Create_ds/SimianArmy/src/main/java/com/netflix/simianarmy
Create_ds/SimianArmy/src/main/java/com/netflix/simianarmy/conformity/ConformityClusterTracker.java
/* * * Copyright 2013 Netflix, Inc. * * Licensed 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 com.netflix.simianarmy.conformity; import java.util.List; /** * The interface that defines the tracker to manage clusters for Conformity monkey to use. */ public interface ConformityClusterTracker { /** * Adds a cluster to the tracker. If the cluster with the same name already exists, * the method updates the record with the cluster parameter. * @param cluster * the cluster to add or update */ void addOrUpdate(Cluster cluster); /** * Gets the list of clusters in a list of regions. * @param regions * the regions of the clusters, when the parameter is null or empty, the method returns * clusters from all regions * @return list of clusters in the given regions */ List<Cluster> getAllClusters(String... regions); /** * Gets the list of non-conforming clusters in a list of regions. * @param regions the regions of the clusters, when the parameter is null or empty, the method returns * clusters from all regions * @return list of clusters in the given regions */ List<Cluster> getNonconformingClusters(String... regions); /** * Gets the cluster with a specific name from . * @param name the cluster name * @param region the region of the cluster * @return the cluster with the name */ Cluster getCluster(String name, String region); /** * Deletes a list of clusters from the tracker. * @param clusters the list of clusters to delete. The parameter cannot be null. If it is empty, * no cluster is deleted. */ void deleteClusters(Cluster... clusters); }
4,779
0
Create_ds/SimianArmy/src/main/java/com/netflix/simianarmy
Create_ds/SimianArmy/src/main/java/com/netflix/simianarmy/conformity/Cluster.java
/* * * Copyright 2013 Netflix, Inc. * * Licensed 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 com.netflix.simianarmy.conformity; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import com.google.common.collect.Sets; import org.apache.commons.lang.StringUtils; import org.apache.commons.lang.Validate; import org.joda.time.format.DateTimeFormat; import org.joda.time.format.DateTimeFormatter; import java.util.Collection; import java.util.Collections; import java.util.Date; import java.util.List; import java.util.Map; import java.util.Set; /** * The class implementing clusters. Cluster is the basic unit of conformity check. It can be a single ASG or * a group of ASGs that belong to the same application, for example, a cluster in the Asgard deployment system. */ public class Cluster { public static final String OWNER_EMAIL = "ownerEmail"; public static final String CLUSTER = "cluster"; public static final String REGION = "region"; public static final String IS_CONFORMING = "isConforming"; public static final String IS_OPTEDOUT = "isOptedOut"; public static final String UPDATE_TIMESTAMP = "updateTimestamp"; public static final String EXCLUDED_RULES = "excludedRules"; public static final String CONFORMITY_RULES = "conformityRules"; public static final DateTimeFormatter DATE_FORMATTER = DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:ss"); private final String name; private final Collection<AutoScalingGroup> autoScalingGroups = Lists.newArrayList(); private final String region; private String ownerEmail; private Date updateTime; private final Map<String, Conformity> conformities = Maps.newHashMap(); private final Collection<String> excludedConformityRules = Sets.newHashSet(); private boolean isConforming; private boolean isOptOutOfConformity; private final Set<String> soloInstances = Sets.newHashSet(); /** * Constructor. * @param name * the name of the cluster * @param autoScalingGroups * the auto scaling groups in the cluster */ public Cluster(String name, String region, AutoScalingGroup... autoScalingGroups) { Validate.notNull(name); Validate.notNull(region); Validate.notNull(autoScalingGroups); this.name = name; this.region = region; for (AutoScalingGroup asg : autoScalingGroups) { this.autoScalingGroups.add(asg); } } /** * Constructor. * @param name * the name of the cluster * @param soloInstances * the list of all instances */ public Cluster(String name, String region, Set<String> soloInstances) { Validate.notNull(name); Validate.notNull(region); Validate.notNull(soloInstances); this.name = name; this.region = region; for (String soleInstance : soloInstances) { this.soloInstances.add(soleInstance); } } /** * Gets the name of the cluster. * @return * the name of the cluster */ public String getName() { return name; } /** * Gets the region of the cluster. * @return * the region of the cluster */ public String getRegion() { return region; } /** * * Gets the auto scaling groups of the auto scaling group. * @return * the auto scaling groups in the cluster */ public Collection<AutoScalingGroup> getAutoScalingGroups() { return Collections.unmodifiableCollection(autoScalingGroups); } /** * Gets the owner email of the cluster. * @return * the owner email of the cluster */ public String getOwnerEmail() { return ownerEmail; } /** * Sets the owner email of the cluster. * @param ownerEmail * the owner email of the cluster */ public void setOwnerEmail(String ownerEmail) { this.ownerEmail = ownerEmail; } /** * Gets the update time of the cluster. * @return * the update time of the cluster */ public Date getUpdateTime() { return new Date(updateTime.getTime()); } /** * Sets the update time of the cluster. * @param updateTime * the update time of the cluster */ public void setUpdateTime(Date updateTime) { this.updateTime = new Date(updateTime.getTime()); } /** * Gets all conformity check information of the cluster. * @return * all conformity check information of the cluster */ public Collection<Conformity> getConformties() { return conformities.values(); } /** * Gets the conformity information for a conformity rule. * @param rule * the conformity rule * @return * the conformity for the rule */ public Conformity getConformity(ConformityRule rule) { Validate.notNull(rule); return conformities.get(rule.getName()); } /** * Updates the cluster with a new conformity check result. * @param conformity * the conformity to update * @return * the cluster itself * */ public Cluster updateConformity(Conformity conformity) { Validate.notNull(conformity); conformities.put(conformity.getRuleId(), conformity); return this; } /** * Clears the conformity check results. */ public void clearConformities() { conformities.clear(); } /** * Gets the boolean flag to indicate whether the cluster is conforming to * all non-excluded conformity rules. * @return * true if the cluster is conforming against all non-excluded rules, * false otherwise */ public boolean isConforming() { return isConforming; } /** * Sets the boolean flag to indicate whether the cluster is conforming to * all non-excluded conformity rules. * @param conforming * true if the cluster is conforming against all non-excluded rules, * false otherwise */ public void setConforming(boolean conforming) { isConforming = conforming; } /** * Gets names of all excluded conformity rules for this cluster. * @return * names of all excluded conformity rules for this cluster */ public Collection<String> getExcludedRules() { return Collections.unmodifiableCollection(excludedConformityRules); } /** * Excludes rules for the cluster. * @param ruleIds * the rule ids to exclude * @return * the cluster itself */ public Cluster excludeRules(String... ruleIds) { Validate.notNull(ruleIds); for (String ruleId : ruleIds) { Validate.notNull(ruleId); excludedConformityRules.add(ruleId.trim()); } return this; } /** * Gets the flag to indicate whether the cluster is opted out of Conformity monkey. * @return true if the cluster is not handled by Conformity monkey, false otherwise */ public boolean isOptOutOfConformity() { return isOptOutOfConformity; } /** * Sets the flag to indicate whether the cluster is opted out of Conformity monkey. * @param optOutOfConformity * true if the cluster is not handled by Conformity monkey, false otherwise */ public void setOptOutOfConformity(boolean optOutOfConformity) { isOptOutOfConformity = optOutOfConformity; } /** * Gets a map from fields of resources to corresponding values. Values are represented * as Strings so they can be displayed or stored in databases like SimpleDB. * @return a map from field name to field value */ public Map<String, String> getFieldToValueMap() { Map<String, String> map = Maps.newHashMap(); putToMapIfNotNull(map, CLUSTER, name); putToMapIfNotNull(map, REGION, region); putToMapIfNotNull(map, OWNER_EMAIL, ownerEmail); putToMapIfNotNull(map, UPDATE_TIMESTAMP, String.valueOf(DATE_FORMATTER.print(updateTime.getTime()))); putToMapIfNotNull(map, IS_CONFORMING, String.valueOf(isConforming)); putToMapIfNotNull(map, IS_OPTEDOUT, String.valueOf(isOptOutOfConformity)); putToMapIfNotNull(map, EXCLUDED_RULES, StringUtils.join(excludedConformityRules, ",")); List<String> ruleIds = Lists.newArrayList(); for (Conformity conformity : conformities.values()) { map.put(conformity.getRuleId(), StringUtils.join(conformity.getFailedComponents(), ",")); ruleIds.add(conformity.getRuleId()); } putToMapIfNotNull(map, CONFORMITY_RULES, StringUtils.join(ruleIds, ",")); return map; } /** * Parse a map from field name to value to a cluster. * @param fieldToValue the map from field name to value * @return the cluster that is de-serialized from the map */ public static Cluster parseFieldToValueMap(Map<String, String> fieldToValue) { Validate.notNull(fieldToValue); Cluster cluster = new Cluster(fieldToValue.get(CLUSTER), fieldToValue.get(REGION)); cluster.setOwnerEmail(fieldToValue.get(OWNER_EMAIL)); cluster.setConforming(Boolean.parseBoolean(fieldToValue.get(IS_CONFORMING))); cluster.setOptOutOfConformity(Boolean.parseBoolean(fieldToValue.get(IS_OPTEDOUT))); cluster.excludeRules(StringUtils.split(fieldToValue.get(EXCLUDED_RULES), ",")); cluster.setUpdateTime(new Date(DATE_FORMATTER.parseDateTime(fieldToValue.get(UPDATE_TIMESTAMP)).getMillis())); for (String ruleId : StringUtils.split(fieldToValue.get(CONFORMITY_RULES), ",")) { cluster.updateConformity(new Conformity(ruleId, Lists.newArrayList(StringUtils.split(fieldToValue.get(ruleId), ",")))); } return cluster; } private static void putToMapIfNotNull(Map<String, String> map, String key, String value) { Validate.notNull(map); Validate.notNull(key); if (value != null) { map.put(key, value); } } public Set<String> getSoloInstances() { return Collections.unmodifiableSet(soloInstances); } }
4,780
0
Create_ds/SimianArmy/src/main/java/com/netflix/simianarmy
Create_ds/SimianArmy/src/main/java/com/netflix/simianarmy/conformity/ConformityEmailNotifier.java
/* * * Copyright 2013 Netflix, Inc. * * Licensed 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 com.netflix.simianarmy.conformity; import com.amazonaws.services.simpleemail.AmazonSimpleEmailServiceClient; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import com.netflix.simianarmy.aws.AWSEmailNotifier; import org.apache.commons.lang.Validate; import org.joda.time.DateTime; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.Collection; import java.util.List; import java.util.Map; /** * The email notifier implemented for Janitor Monkey. */ public class ConformityEmailNotifier extends AWSEmailNotifier { /** The Constant LOGGER. */ private static final Logger LOGGER = LoggerFactory.getLogger(ConformityEmailNotifier.class); private static final String UNKNOWN_EMAIL = "UNKNOWN"; private final Collection<String> regions = Lists.newArrayList(); private final String defaultEmail; private final List<String> ccEmails = Lists.newArrayList(); private final ConformityClusterTracker clusterTracker; private final ConformityEmailBuilder emailBuilder; private final String sourceEmail; private final Map<String, Collection<Cluster>> invalidEmailToClusters = Maps.newHashMap(); private final Collection<ConformityRule> rules = Lists.newArrayList(); private final int openHour; private final int closeHour; /** * The Interface Context. */ public interface Context { /** * Gets the Amazon Simple Email Service client. * @return the Amazon Simple Email Service client */ AmazonSimpleEmailServiceClient sesClient(); /** * Gets the open hour the email notifications are sent. * @return * the open hour the email notifications are sent */ int openHour(); /** * Gets the close hour the email notifications are sent. * @return * the close hour the email notifications are sent */ int closeHour(); /** * Gets the source email the notifier uses to send email. * @return the source email */ String sourceEmail(); /** * Gets the default email the notifier sends to when there is no owner specified for a cluster. * @return the default email */ String defaultEmail(); /** * Gets the regions the notifier is running in. * @return the regions the notifier is running in. */ Collection<String> regions(); /** Gets the Conformity Monkey's cluster tracker. * @return the Conformity Monkey's cluster tracker */ ConformityClusterTracker clusterTracker(); /** Gets the Conformity email builder. * @return the Conformity email builder */ ConformityEmailBuilder emailBuilder(); /** Gets the cc email addresses. * @return the cc email addresses */ String[] ccEmails(); /** * Gets all the conformity rules. * @return all conformity rules. */ Collection<ConformityRule> rules(); } /** * Constructor. * @param ctx the context. */ public ConformityEmailNotifier(Context ctx) { super(ctx.sesClient()); this.openHour = ctx.openHour(); this.closeHour = ctx.closeHour(); for (String region : ctx.regions()) { this.regions.add(region); } this.defaultEmail = ctx.defaultEmail(); this.clusterTracker = ctx.clusterTracker(); this.emailBuilder = ctx.emailBuilder(); String[] ctxCCs = ctx.ccEmails(); if (ctxCCs != null) { for (String ccEmail : ctxCCs) { this.ccEmails.add(ccEmail); } } this.sourceEmail = ctx.sourceEmail(); Validate.notNull(ctx.rules()); for (ConformityRule rule : ctx.rules()) { rules.add(rule); } } /** * Gets all the clusters that are not conforming and sends email notifications to the owners. */ public void sendNotifications() { int currentHour = DateTime.now().getHourOfDay(); if (currentHour < openHour || currentHour > closeHour) { LOGGER.info("It is not the time for Conformity Monkey to send notifications. You can change " + "simianarmy.conformity.notification.openHour and simianarmy.conformity.notification.openHour" + " to make it work at this hour."); return; } validateEmails(); Map<String, Collection<Cluster>> emailToClusters = Maps.newHashMap(); for (Cluster cluster : clusterTracker.getNonconformingClusters(regions.toArray(new String[regions.size()]))) { if (cluster.isOptOutOfConformity()) { LOGGER.info(String.format("Cluster %s is opted out of Conformity Monkey so no notification is sent.", cluster.getName())); continue; } if (!cluster.isConforming()) { String email = cluster.getOwnerEmail(); if (!isValidEmail(email)) { if (defaultEmail != null) { LOGGER.info(String.format("Email %s is not valid, send to the default email address %s", email, defaultEmail)); putEmailAndCluster(emailToClusters, defaultEmail, cluster); } else { if (email == null) { email = UNKNOWN_EMAIL; } LOGGER.info(String.format("Email %s is not valid and default email is not set for cluster %s", email, cluster.getName())); putEmailAndCluster(invalidEmailToClusters, email, cluster); } } else { putEmailAndCluster(emailToClusters, email, cluster); } } else { LOGGER.debug(String.format("Cluster %s is conforming so no notification needs to be sent.", cluster.getName())); } } emailBuilder.setEmailToClusters(emailToClusters, rules); for (Map.Entry<String, Collection<Cluster>> entry : emailToClusters.entrySet()) { String email = entry.getKey(); String emailBody = emailBuilder.buildEmailBody(email); String subject = buildEmailSubject(email); sendEmail(email, subject, emailBody); for (Cluster cluster : entry.getValue()) { LOGGER.debug(String.format("Notification is sent for cluster %s to %s", cluster.getName(), email)); } LOGGER.info(String.format("Email notification has been sent to %s for %d clusters.", email, entry.getValue().size())); } } @Override public String buildEmailSubject(String to) { return String.format("Conformity Monkey Notification for %s", to); } @Override public String[] getCcAddresses(String to) { return ccEmails.toArray(new String[ccEmails.size()]); } @Override public String getSourceAddress(String to) { return sourceEmail; } private void validateEmails() { if (defaultEmail != null) { Validate.isTrue(isValidEmail(defaultEmail), String.format("Default email %s is invalid", defaultEmail)); } if (ccEmails != null) { for (String ccEmail : ccEmails) { Validate.isTrue(isValidEmail(ccEmail), String.format("CC email %s is invalid", ccEmail)); } } } private void putEmailAndCluster(Map<String, Collection<Cluster>> map, String email, Cluster cluster) { Collection<Cluster> clusters = map.get(email); if (clusters == null) { clusters = Lists.newArrayList(); map.put(email, clusters); } clusters.add(cluster); } }
4,781
0
Create_ds/SimianArmy/src/main/java/com/netflix/simianarmy
Create_ds/SimianArmy/src/main/java/com/netflix/simianarmy/conformity/ConformityRuleEngine.java
/* * * Copyright 2013 Netflix, Inc. * * Licensed 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 com.netflix.simianarmy.conformity; import com.google.common.collect.Lists; import org.apache.commons.lang.Validate; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.Collection; import java.util.Collections; /** * The class implementing the conformity rule engine. */ public class ConformityRuleEngine { private static final Logger LOGGER = LoggerFactory.getLogger(ConformityRuleEngine.class); private final Collection<ConformityRule> rules = Lists.newArrayList(); /** * Checks whether a cluster is conforming or not against the rules in the engine. This * method runs the checks the cluster against all the rules. * * @param cluster * the cluster * @return true if the cluster is conforming, false otherwise. */ public boolean check(Cluster cluster) { Validate.notNull(cluster); cluster.clearConformities(); for (ConformityRule rule : rules) { if (!cluster.getExcludedRules().contains(rule.getName())) { LOGGER.info(String.format("Running conformity rule %s on cluster %s", rule.getName(), cluster.getName())); cluster.updateConformity(rule.check(cluster)); } else { LOGGER.info(String.format("Conformity rule %s is excluded on cluster %s", rule.getName(), cluster.getName())); } } boolean isConforming = true; for (Conformity conformity : cluster.getConformties()) { if (!conformity.getFailedComponents().isEmpty()) { isConforming = false; } } cluster.setConforming(isConforming); return isConforming; } /** * Add a conformity rule. * * @param rule * The conformity rule to add. * @return The Conformity rule engine object. */ public ConformityRuleEngine addRule(ConformityRule rule) { Validate.notNull(rule); rules.add(rule); return this; } /** * Gets all conformity rules in the rule engine. * @return all conformity rules in the rule engine */ public Collection<ConformityRule> rules() { return Collections.unmodifiableCollection(rules); } }
4,782
0
Create_ds/SimianArmy/src/main/java/com/netflix/simianarmy
Create_ds/SimianArmy/src/main/java/com/netflix/simianarmy/conformity/AutoScalingGroup.java
/* * * Copyright 2013 Netflix, Inc. * * Licensed 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 com.netflix.simianarmy.conformity; import com.google.common.collect.Lists; import org.apache.commons.lang.Validate; import java.util.Collection; import java.util.Collections; /** * The class implementing the auto scaling groups. */ public class AutoScalingGroup { private final String name; private final Collection<String> instances = Lists.newArrayList(); private boolean isSuspended; /** * Constructor. * @param name * the name of the auto scaling group * @param instances * the instance ids in the auto scaling group */ public AutoScalingGroup(String name, String... instances) { Validate.notNull(instances); this.name = name; for (String instance : instances) { this.instances.add(instance); } this.isSuspended = false; } /** * Gets the name of the auto scaling group. * @return * the name of the auto scaling group */ public String getName() { return name; } /** * * Gets the instances of the auto scaling group. * @return * the instances of the auto scaling group */ public Collection<String> getInstances() { return Collections.unmodifiableCollection(instances); } /** * Gets the flag to indicate whether the ASG is suspended. * @return true if the ASG is suspended, false otherwise */ public boolean isSuspended() { return isSuspended; } /** * Sets the flag to indicate whether the ASG is suspended. * @param suspended true if the ASG is suspended, false otherwise */ public void setSuspended(boolean suspended) { isSuspended = suspended; } }
4,783
0
Create_ds/SimianArmy/src/main/java/com/netflix/simianarmy
Create_ds/SimianArmy/src/main/java/com/netflix/simianarmy/conformity/ClusterCrawler.java
/* * * Copyright 2013 Netflix, Inc. * * Licensed 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 com.netflix.simianarmy.conformity; import java.util.List; /** * The interface of the crawler for Conformity Monkey to get the cluster information. */ public interface ClusterCrawler { /** * Gets the up to date information for a collection of clusters. When the input argument is null * or empty, the method returns all clusters. * * @param clusterNames * the cluster names * @return the list of clusters */ List<Cluster> clusters(String... clusterNames); /** * Gets the owner email for a cluster to set the ownerEmail field when crawl. * @param cluster * the cluster * @return the owner email of the cluster */ String getOwnerEmailForCluster(Cluster cluster); /** * Updates the excluded conformity rules for the given cluster. * @param cluster */ void updateExcludedConformityRules(Cluster cluster); }
4,784
0
Create_ds/SimianArmy/src/main/java/com/netflix/simianarmy/resources
Create_ds/SimianArmy/src/main/java/com/netflix/simianarmy/resources/janitor/JanitorMonkeyResource.java
/* * * Copyright 2012 Netflix, Inc. * * Licensed 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 com.netflix.simianarmy.resources.janitor; import com.netflix.simianarmy.MonkeyRecorder.Event; import com.netflix.simianarmy.MonkeyRunner; import com.netflix.simianarmy.janitor.JanitorMonkey; import org.apache.commons.lang.StringUtils; import org.codehaus.jackson.JsonEncoding; import org.codehaus.jackson.JsonGenerator; import org.codehaus.jackson.JsonNode; import org.codehaus.jackson.map.MappingJsonFactory; import org.codehaus.jackson.map.ObjectMapper; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.ws.rs.GET; import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.QueryParam; import javax.ws.rs.core.Context; import javax.ws.rs.core.Response; import javax.ws.rs.core.UriInfo; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.util.Map; /** * The Class JanitorMonkeyResource for json REST apis. */ @Path("/v1/janitor") public class JanitorMonkeyResource { /** The Constant JSON_FACTORY. */ private static final MappingJsonFactory JSON_FACTORY = new MappingJsonFactory(); /** The monkey. */ private static JanitorMonkey monkey; /** The Constant LOGGER. */ private static final Logger LOGGER = LoggerFactory.getLogger(JanitorMonkeyResource.class); /** * Instantiates a janitor monkey resource with a specific janitor monkey. * * @param monkey * the janitor monkey */ public JanitorMonkeyResource(JanitorMonkey monkey) { JanitorMonkeyResource.monkey = monkey; } public JanitorMonkeyResource() { } public JanitorMonkey getJanitorMonkey() { if (JanitorMonkeyResource.monkey == null ) { JanitorMonkeyResource.monkey = MonkeyRunner.getInstance().factory(JanitorMonkey.class); } return monkey; } /** * GET /api/v1/janitor/addEvent will try to a add a new event with the information in the url query string. * This is the same as the regular POST addEvent except through a query string. This technically isn't * very REST-ful as it is a GET call that creates an Opt-out/in event, but is a convenience method * for exposing opt-in/opt-out functionality more directly, for example in an email notification. * * @param eventType eventType from the query string * @param resourceId resourceId from the query string * @return the response * @throws IOException */ @GET @Path("addEvent") public Response addEventThroughHttpGet( @QueryParam("eventType") String eventType, @QueryParam("resourceId") String resourceId, @QueryParam("region") String region) throws IOException { Response.Status responseStatus; ByteArrayOutputStream baos = new ByteArrayOutputStream(); baos.write("<html><body style=\"text-align:center\">".getBytes()); if (StringUtils.isEmpty(eventType) || StringUtils.isEmpty(resourceId)) { responseStatus = Response.Status.BAD_REQUEST; baos.write("<p>NOPE!<br/><br/>Janitor didn't get that: eventType and resourceId parameters are both required</p>".getBytes()); } else { ByteArrayOutputStream baos2 = new ByteArrayOutputStream(); JsonGenerator gen = JSON_FACTORY.createJsonGenerator(baos2, JsonEncoding.UTF8); gen.writeStartObject(); gen.writeStringField("eventType", eventType); gen.writeStringField("resourceId", resourceId); if (eventType.equals("OPTIN")) { responseStatus = optInResource(resourceId, true, region, gen); } else if (eventType.equals("OPTOUT")) { responseStatus = optInResource(resourceId, false, region, gen); } else { responseStatus = Response.Status.BAD_REQUEST; gen.writeStringField("message", String.format("Unrecognized event type: %s", eventType)); } gen.writeEndObject(); gen.close(); if(responseStatus == Response.Status.OK) { baos.write(("<p>SUCCESS!<br/><br/>Resource <strong>" + resourceId + "</strong> has been " + eventType + " of Janitor Monkey!</p>").getBytes()); } else { baos.write(("<p>NOPE!<br/><br/>Janitor is Confused! Error processing Resource <strong>" + resourceId + "</strong></p>").getBytes()); } String jsonout = String.format("<p><em>Monkey JSON Response:</em><br/><br/><textarea cols=40 rows=20>%s</textarea></p>", baos2.toString()); baos.write(jsonout.getBytes()); } baos.write("</body></html>".getBytes()); return Response.status(responseStatus).entity(baos.toString("UTF-8")).build(); } /** * POST /api/v1/janitor will try a add a new event with the information in the url context. * * @param content * the Json content passed to the http POST request * @return the response * @throws IOException */ @POST public Response addEvent(String content) throws IOException { ObjectMapper mapper = new ObjectMapper(); LOGGER.info(String.format("JSON content: '%s'", content)); JsonNode input = mapper.readTree(content); String eventType = getStringField(input, "eventType"); String resourceId = getStringField(input, "resourceId"); String region = getStringField(input, "region"); Response.Status responseStatus; ByteArrayOutputStream baos = new ByteArrayOutputStream(); JsonGenerator gen = JSON_FACTORY.createJsonGenerator(baos, JsonEncoding.UTF8); gen.writeStartObject(); gen.writeStringField("eventType", eventType); gen.writeStringField("resourceId", resourceId); if (StringUtils.isEmpty(eventType) || StringUtils.isEmpty(resourceId)) { responseStatus = Response.Status.BAD_REQUEST; gen.writeStringField("message", "eventType and resourceId parameters are all required"); } else { if (eventType.equals("OPTIN")) { responseStatus = optInResource(resourceId, true, region, gen); } else if (eventType.equals("OPTOUT")) { responseStatus = optInResource(resourceId, false, region, gen); } else { responseStatus = Response.Status.BAD_REQUEST; gen.writeStringField("message", String.format("Unrecognized event type: %s", eventType)); } } gen.writeEndObject(); gen.close(); LOGGER.info("entity content is '{}'", baos.toString("UTF-8")); return Response.status(responseStatus).entity(baos.toString("UTF-8")).build(); } /** * Gets the janitor status (e.g. to support an AWS ELB Healthcheck on an instance running JanitorMonkey). * Creates GET /api/v1/janitor api which responds 200 OK if JanitorMonkey is running. * * @param uriInfo * the uri info * @return the chaos events json response * @throws IOException * Signals that an I/O exception has occurred. */ @GET public Response getJanitorStatus(@Context UriInfo uriInfo) throws IOException { ByteArrayOutputStream baos = new ByteArrayOutputStream(); JsonGenerator gen = JSON_FACTORY.createJsonGenerator(baos, JsonEncoding.UTF8); gen.writeStartArray(); gen.writeStartObject(); gen.writeStringField("JanitorMonkeyStatus", "OnLikeDonkeyKong"); gen.writeEndObject(); gen.writeEndArray(); gen.close(); return Response.status(Response.Status.OK).entity(baos.toString("UTF-8")).build(); } private Response.Status optInResource(String resourceId, boolean optIn, String region, JsonGenerator gen) throws IOException { String op = optIn ? "in" : "out"; LOGGER.info(String.format("Opt %s resource %s for Janitor Monkey.", op, resourceId)); Response.Status responseStatus; Event evt; if (optIn) { evt = getJanitorMonkey().optInResource(resourceId, region); } else { evt = getJanitorMonkey().optOutResource(resourceId, region); } if (evt != null) { responseStatus = Response.Status.OK; gen.writeStringField("monkeyType", evt.monkeyType().name()); gen.writeStringField("eventId", evt.id()); gen.writeNumberField("eventTime", evt.eventTime().getTime()); gen.writeStringField("region", evt.region()); for (Map.Entry<String, String> pair : evt.fields().entrySet()) { gen.writeStringField(pair.getKey(), pair.getValue()); } } else { responseStatus = Response.Status.INTERNAL_SERVER_ERROR; gen.writeStringField("message", String.format("Failed to opt %s resource %s", op, resourceId)); } LOGGER.info(String.format("Opt %s operation completed.", op)); return responseStatus; } private String getStringField(JsonNode input, String field) { JsonNode node = input.get(field); if (node == null) { return null; } return node.getTextValue(); } }
4,785
0
Create_ds/SimianArmy/src/main/java/com/netflix/simianarmy/resources
Create_ds/SimianArmy/src/main/java/com/netflix/simianarmy/resources/chaos/ChaosMonkeyResource.java
/* * * Copyright 2012 Netflix, Inc. * * Licensed 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 com.netflix.simianarmy.resources.chaos; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.util.Calendar; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.ws.rs.GET; import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.core.Context; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import javax.ws.rs.core.UriInfo; import com.google.common.base.Strings; import com.netflix.simianarmy.Monkey; import com.sun.jersey.spi.resource.Singleton; import org.apache.commons.lang.StringUtils; import org.codehaus.jackson.JsonEncoding; import org.codehaus.jackson.JsonGenerator; import org.codehaus.jackson.JsonNode; import org.codehaus.jackson.map.MappingJsonFactory; import org.codehaus.jackson.map.ObjectMapper; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.netflix.simianarmy.FeatureNotEnabledException; import com.netflix.simianarmy.InstanceGroupNotFoundException; import com.netflix.simianarmy.MonkeyRecorder.Event; import com.netflix.simianarmy.MonkeyRunner; import com.netflix.simianarmy.NotFoundException; import com.netflix.simianarmy.chaos.ChaosMonkey; import com.netflix.simianarmy.chaos.ChaosType; import com.netflix.simianarmy.chaos.ShutdownInstanceChaosType; /** * The Class ChaosMonkeyResource for json REST apis. */ @Path("/v1/chaos") @Produces(MediaType.APPLICATION_JSON) @Singleton public class ChaosMonkeyResource { /** The Constant JSON_FACTORY. */ private static final MappingJsonFactory JSON_FACTORY = new MappingJsonFactory(); /** The monkey. */ private ChaosMonkey monkey = null; /** The Constant LOGGER. */ private static final Logger LOGGER = LoggerFactory.getLogger(ChaosMonkeyResource.class); /** * Instantiates a chaos monkey resource with a specific chaos monkey. * * @param monkey * the chaos monkey */ public ChaosMonkeyResource(ChaosMonkey monkey) { this.monkey = monkey; } /** * Instantiates a chaos monkey resource using a registered chaos monkey from factory. */ public ChaosMonkeyResource() { for (Monkey runningMonkey : MonkeyRunner.getInstance().getMonkeys()) { if (runningMonkey instanceof ChaosMonkey) { this.monkey = (ChaosMonkey) runningMonkey; break; } } if (this.monkey == null) { LOGGER.info("Creating a new Chaos monkey instance for the resource."); this.monkey = MonkeyRunner.getInstance().factory(ChaosMonkey.class); } } /** * Gets the chaos events. Creates GET /api/v1/chaos api which outputs the chaos events in json. Users can specify * cgi query params to filter the results and use "since" query param to set the start of a timerange. "since" should * be specified in milliseconds since the epoch. * * @param uriInfo * the uri info * @return the chaos events json response * @throws IOException * Signals that an I/O exception has occurred. */ @GET public Response getChaosEvents(@Context UriInfo uriInfo) throws IOException { Map<String, String> query = new HashMap<String, String>(); Date date = null; for (Map.Entry<String, List<String>> pair : uriInfo.getQueryParameters().entrySet()) { if (pair.getValue().isEmpty()) { continue; } if (pair.getKey().equals("since")) { date = new Date(Long.parseLong(pair.getValue().get(0))); } else { query.put(pair.getKey(), pair.getValue().get(0)); } } // if "since" not set, default to 24 hours ago if (date == null) { Calendar now = monkey.context().calendar().now(); now.add(Calendar.DAY_OF_YEAR, -1); date = now.getTime(); } List<Event> evts = monkey.context().recorder() .findEvents(ChaosMonkey.Type.CHAOS, ChaosMonkey.EventTypes.CHAOS_TERMINATION, query, date); ByteArrayOutputStream baos = new ByteArrayOutputStream(); JsonGenerator gen = JSON_FACTORY.createJsonGenerator(baos, JsonEncoding.UTF8); gen.writeStartArray(); for (Event evt : evts) { gen.writeStartObject(); gen.writeStringField("monkeyType", evt.monkeyType().name()); gen.writeStringField("eventId", evt.id()); gen.writeStringField("eventType", evt.eventType().name()); gen.writeNumberField("eventTime", evt.eventTime().getTime()); gen.writeStringField("region", evt.region()); for (Map.Entry<String, String> pair : evt.fields().entrySet()) { gen.writeStringField(pair.getKey(), pair.getValue()); } gen.writeEndObject(); } gen.writeEndArray(); gen.close(); return Response.status(Response.Status.OK).entity(baos.toString("UTF-8")).build(); } /** * POST /api/v1/chaos will try a add a new event with the information in the url context, * ignoring the monkey probability and max termination configurations, for a specific instance group. * * @param content * the Json content passed to the http POST request * @return the response * @throws IOException */ @POST public Response addEvent(String content) throws IOException { ObjectMapper mapper = new ObjectMapper(); LOGGER.info(String.format("JSON content: '%s'", content)); JsonNode input = mapper.readTree(content); String eventType = getStringField(input, "eventType"); String groupType = getStringField(input, "groupType"); String groupName = getStringField(input, "groupName"); String chaosTypeName = getStringField(input, "chaosType"); ChaosType chaosType; if (!Strings.isNullOrEmpty(chaosTypeName)) { chaosType = ChaosType.parse(this.monkey.getChaosTypes(), chaosTypeName); } else { chaosType = new ShutdownInstanceChaosType(monkey.context().configuration()); } Response.Status responseStatus; ByteArrayOutputStream baos = new ByteArrayOutputStream(); JsonGenerator gen = JSON_FACTORY.createJsonGenerator(baos, JsonEncoding.UTF8); gen.writeStartObject(); gen.writeStringField("eventType", eventType); gen.writeStringField("groupType", groupType); gen.writeStringField("groupName", groupName); gen.writeStringField("chaosType", chaosType.getKey()); if (StringUtils.isEmpty(eventType) || StringUtils.isEmpty(groupType) || StringUtils.isEmpty(groupName)) { responseStatus = Response.Status.BAD_REQUEST; gen.writeStringField("message", "eventType, groupType, and groupName parameters are all required"); } else { if (eventType.equals("CHAOS_TERMINATION")) { responseStatus = addTerminationEvent(groupType, groupName, chaosType, gen); } else { responseStatus = Response.Status.BAD_REQUEST; gen.writeStringField("message", String.format("Unrecognized event type: %s", eventType)); } } gen.writeEndObject(); gen.close(); LOGGER.info("entity content is '{}'", baos.toString("UTF-8")); return Response.status(responseStatus).entity(baos.toString("UTF-8")).build(); } private Response.Status addTerminationEvent(String groupType, String groupName, ChaosType chaosType, JsonGenerator gen) throws IOException { LOGGER.info("Running on-demand termination for instance group type '{}' and name '{}'", groupType, groupName); Response.Status responseStatus; try { Event evt = monkey.terminateNow(groupType, groupName, chaosType); if (evt != null) { responseStatus = Response.Status.OK; gen.writeStringField("monkeyType", evt.monkeyType().name()); gen.writeStringField("eventId", evt.id()); gen.writeNumberField("eventTime", evt.eventTime().getTime()); gen.writeStringField("region", evt.region()); for (Map.Entry<String, String> pair : evt.fields().entrySet()) { gen.writeStringField(pair.getKey(), pair.getValue()); } } else { responseStatus = Response.Status.INTERNAL_SERVER_ERROR; gen.writeStringField("message", String.format("Failed to terminate instance in group %s [type %s]", groupName, groupType)); } } catch (FeatureNotEnabledException e) { responseStatus = Response.Status.FORBIDDEN; gen.writeStringField("message", e.getMessage()); } catch (InstanceGroupNotFoundException e) { responseStatus = Response.Status.NOT_FOUND; gen.writeStringField("message", e.getMessage()); } catch (NotFoundException e) { // Available instance cannot be found to terminate, maybe the instance is already gone responseStatus = Response.Status.GONE; gen.writeStringField("message", e.getMessage()); } LOGGER.info("On-demand termination completed."); return responseStatus; } private String getStringField(JsonNode input, String field) { JsonNode node = input.get(field); if (node == null) { return null; } return node.getTextValue(); } }
4,786
0
Create_ds/SimianArmy/src/main/java/com/netflix/simianarmy
Create_ds/SimianArmy/src/main/java/com/netflix/simianarmy/basic/BasicMonkeyServer.java
/* * * Copyright 2012 Netflix, Inc. * * Licensed 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 com.netflix.simianarmy.basic; import java.io.IOException; import java.io.InputStream; import java.util.Properties; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import com.netflix.simianarmy.basic.conformity.BasicConformityMonkey; import com.netflix.simianarmy.basic.conformity.BasicConformityMonkeyContext; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.netflix.simianarmy.MonkeyRunner; import com.netflix.simianarmy.aws.janitor.VolumeTaggingMonkey; import com.netflix.simianarmy.basic.janitor.BasicJanitorMonkey; import com.netflix.simianarmy.basic.janitor.BasicJanitorMonkeyContext; import com.netflix.simianarmy.basic.janitor.BasicVolumeTaggingMonkeyContext; /** * Will periodically run the configured monkeys. */ @SuppressWarnings("serial") public class BasicMonkeyServer extends HttpServlet { private static final Logger LOGGER = LoggerFactory.getLogger(BasicMonkeyServer.class); private static final MonkeyRunner RUNNER = MonkeyRunner.getInstance(); /** * Add the monkeys that will be run. */ @SuppressWarnings("unchecked") public void addMonkeysToRun() { LOGGER.info("Adding Chaos Monkey."); RUNNER.replaceMonkey(this.chaosClass, this.chaosContextClass); LOGGER.info("Adding Volume Tagging Monkey."); RUNNER.replaceMonkey(VolumeTaggingMonkey.class, BasicVolumeTaggingMonkeyContext.class); LOGGER.info("Adding Janitor Monkey."); RUNNER.replaceMonkey(BasicJanitorMonkey.class, BasicJanitorMonkeyContext.class); LOGGER.info("Adding Conformity Monkey."); RUNNER.replaceMonkey(BasicConformityMonkey.class, BasicConformityMonkeyContext.class); } /** * make the class of the client object configurable. */ @SuppressWarnings("rawtypes") private Class chaosContextClass = com.netflix.simianarmy.basic.BasicChaosMonkeyContext.class; /** * make the class of the chaos object configurable. */ @SuppressWarnings("rawtypes") private Class chaosClass = com.netflix.simianarmy.basic.chaos.BasicChaosMonkey.class; @Override public void init() throws ServletException { super.init(); configureClient(); addMonkeysToRun(); RUNNER.start(); } /** * Loads the client that is configured. * @throws ServletException * if the configured client cannot be loaded properly */ @SuppressWarnings("rawtypes") private void configureClient() throws ServletException { Properties clientConfig = loadClientConfigProperties(); Class newContextClass = loadClientClass(clientConfig, "simianarmy.client.context.class"); this.chaosContextClass = (newContextClass == null ? this.chaosContextClass : newContextClass); Class newChaosClass = loadClientClass(clientConfig, "simianarmy.client.chaos.class"); this.chaosClass = (newChaosClass == null ? this.chaosClass : newChaosClass); } @SuppressWarnings("rawtypes") private Class loadClientClass(Properties clientConfig, String key) throws ServletException { ClassLoader classLoader = BasicMonkeyServer.class.getClassLoader(); try { String clientClassName = clientConfig.getProperty(key); if (clientClassName == null || clientClassName.isEmpty()) { LOGGER.info("using standard client for " + key); return null; } Class newClass = classLoader.loadClass(clientClassName); LOGGER.info("using " + key + " loaded " + newClass.getCanonicalName()); return newClass; } catch (ClassNotFoundException e) { throw new ServletException("Could not load " + key, e); } } /** * Load the client config properties file. * * @return Properties The contents of the client config file * @throws ServletException * if the file cannot be read */ private Properties loadClientConfigProperties() throws ServletException { String propertyFileName = "client.properties"; String clientConfigFileName = System.getProperty(propertyFileName, "/" + propertyFileName); LOGGER.info("using client properties " + clientConfigFileName); InputStream input = null; Properties p = new Properties(); try { try { input = BasicMonkeyServer.class.getResourceAsStream(clientConfigFileName); p.load(input); return p; } finally { if (input != null) { input.close(); } } } catch (IOException e) { throw new ServletException("Could not load " + clientConfigFileName, e); } } @SuppressWarnings("unchecked") @Override public void destroy() { RUNNER.stop(); LOGGER.info("Stopping Chaos Monkey."); RUNNER.removeMonkey(this.chaosClass); LOGGER.info("Stopping Volume Tagging Monkey."); RUNNER.removeMonkey(VolumeTaggingMonkey.class); LOGGER.info("Stopping Janitor Monkey."); RUNNER.removeMonkey(BasicJanitorMonkey.class); LOGGER.info("Stopping Conformity Monkey."); RUNNER.removeMonkey(BasicConformityMonkey.class); super.destroy(); } }
4,787
0
Create_ds/SimianArmy/src/main/java/com/netflix/simianarmy
Create_ds/SimianArmy/src/main/java/com/netflix/simianarmy/basic/BasicCalendar.java
/* * * Copyright 2012 Netflix, Inc. * * Licensed 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 com.netflix.simianarmy.basic; import java.util.Calendar; import java.util.Date; import java.util.Set; import java.util.TimeZone; import java.util.TreeSet; import org.apache.commons.lang.Validate; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.netflix.simianarmy.Monkey; import com.netflix.simianarmy.MonkeyCalendar; import com.netflix.simianarmy.MonkeyConfiguration; // CHECKSTYLE IGNORE MagicNumberCheck /** * The Class BasicCalendar. */ public class BasicCalendar implements MonkeyCalendar { /** The Constant LOGGER. */ private static final Logger LOGGER = LoggerFactory.getLogger(BasicCalendar.class); /** The open hour. */ private final int openHour; /** The close hour. */ private final int closeHour; /** The tz. */ private final TimeZone tz; /** The holidays. */ protected final Set<Integer> holidays = new TreeSet<Integer>(); /** The cfg. */ private MonkeyConfiguration cfg; /** * Instantiates a new basic calendar. * * @param cfg * the monkey configuration */ public BasicCalendar(MonkeyConfiguration cfg) { this.cfg = cfg; openHour = (int) cfg.getNumOrElse("simianarmy.calendar.openHour", 9); closeHour = (int) cfg.getNumOrElse("simianarmy.calendar.closeHour", 15); tz = TimeZone.getTimeZone(cfg.getStrOrElse("simianarmy.calendar.timezone", "America/Los_Angeles")); } /** * Instantiates a new basic calendar. * * @param open * the open hour * @param close * the close hour * @param timezone * the timezone */ public BasicCalendar(int open, int close, TimeZone timezone) { openHour = open; closeHour = close; tz = timezone; } /** * Instantiates a new basic calendar. * * @param open * the open hour * @param close * the close hour * @param timezone * the timezone */ public BasicCalendar(MonkeyConfiguration cfg, int open, int close, TimeZone timezone) { this.cfg = cfg; openHour = open; closeHour = close; tz = timezone; } /** {@inheritDoc} */ @Override public int openHour() { return openHour; } /** {@inheritDoc} */ @Override public int closeHour() { return closeHour; } /** {@inheritDoc} */ @Override public Calendar now() { return Calendar.getInstance(tz); } /** {@inheritDoc} */ @Override public boolean isMonkeyTime(Monkey monkey) { if (cfg != null && cfg.getStr("simianarmy.calendar.isMonkeyTime") != null) { boolean monkeyTime = cfg.getBool("simianarmy.calendar.isMonkeyTime"); if (monkeyTime) { LOGGER.debug("isMonkeyTime: Found property 'simianarmy.calendar.isMonkeyTime': " + monkeyTime + ". Time for monkey."); return monkeyTime; } else { LOGGER.debug("isMonkeyTime: Found property 'simianarmy.calendar.isMonkeyTime': " + monkeyTime + ". Continuing regular calendar check for monkey time."); } } Calendar now = now(); int dow = now.get(Calendar.DAY_OF_WEEK); if (dow == Calendar.SATURDAY || dow == Calendar.SUNDAY) { LOGGER.debug("isMonkeyTime: Happy Weekend! Not time for monkey."); return false; } int hour = now.get(Calendar.HOUR_OF_DAY); if (hour < openHour || hour > closeHour) { LOGGER.debug("isMonkeyTime: Not inside open hours. Not time for monkey."); return false; } if (isHoliday(now)) { LOGGER.debug("isMonkeyTime: Happy Holiday! Not time for monkey."); return false; } LOGGER.debug("isMonkeyTime: Time for monkey."); return true; } /** * Checks if is holiday. * * @param now * the current time * @return true, if is holiday */ protected boolean isHoliday(Calendar now) { if (!holidays.contains(now.get(Calendar.YEAR))) { loadHolidays(now.get(Calendar.YEAR)); } return holidays.contains(now.get(Calendar.DAY_OF_YEAR)); } /** * Load holidays. * * @param year * the year */ protected void loadHolidays(int year) { holidays.clear(); // these aren't all strictly holidays, but days when engineers will likely // not be in the office to respond to rampaging monkeys // new years, or closest work day holidays.add(workDayInYear(year, Calendar.JANUARY, 1)); // 3rd monday == MLK Day holidays.add(dayOfYear(year, Calendar.JANUARY, Calendar.MONDAY, 3)); // 3rd monday == Presidents Day holidays.add(dayOfYear(year, Calendar.FEBRUARY, Calendar.MONDAY, 3)); // last monday == Memorial Day holidays.add(dayOfYear(year, Calendar.MAY, Calendar.MONDAY, -1)); // 4th of July, or closest work day holidays.add(workDayInYear(year, Calendar.JULY, 4)); // first monday == Labor Day holidays.add(dayOfYear(year, Calendar.SEPTEMBER, Calendar.MONDAY, 1)); // second monday == Columbus Day holidays.add(dayOfYear(year, Calendar.OCTOBER, Calendar.MONDAY, 2)); // veterans day, Nov 11th, or closest work day holidays.add(workDayInYear(year, Calendar.NOVEMBER, 11)); // 4th thursday == Thanksgiving holidays.add(dayOfYear(year, Calendar.NOVEMBER, Calendar.THURSDAY, 4)); // 4th friday == "black friday", monkey goes shopping! holidays.add(dayOfYear(year, Calendar.NOVEMBER, Calendar.FRIDAY, 4)); // christmas eve holidays.add(dayOfYear(year, Calendar.DECEMBER, 24)); // christmas day holidays.add(dayOfYear(year, Calendar.DECEMBER, 25)); // day after christmas holidays.add(dayOfYear(year, Calendar.DECEMBER, 26)); // new years eve holidays.add(dayOfYear(year, Calendar.DECEMBER, 31)); // mark the holiday set with the year, so on Jan 1 it will automatically // recalculate the holidays for next year holidays.add(year); } /** * Day of year. * * @param year * the year * @param month * the month * @param day * the day * @return the day of the year */ protected int dayOfYear(int year, int month, int day) { Calendar holiday = now(); holiday.set(Calendar.YEAR, year); holiday.set(Calendar.MONTH, month); holiday.set(Calendar.DAY_OF_MONTH, day); return holiday.get(Calendar.DAY_OF_YEAR); } /** * Day of year. * * @param year * the year * @param month * the month * @param dayOfWeek * the day of week * @param weekInMonth * the week in month * @return the day of the year */ protected int dayOfYear(int year, int month, int dayOfWeek, int weekInMonth) { Calendar holiday = now(); holiday.set(Calendar.YEAR, year); holiday.set(Calendar.MONTH, month); holiday.set(Calendar.DAY_OF_WEEK, dayOfWeek); holiday.set(Calendar.DAY_OF_WEEK_IN_MONTH, weekInMonth); return holiday.get(Calendar.DAY_OF_YEAR); } /** * Work day in year. * * @param year * the year * @param month * the month * @param day * the day * @return the day of the year adjusted to the closest workday */ protected int workDayInYear(int year, int month, int day) { Calendar holiday = now(); holiday.set(Calendar.YEAR, year); holiday.set(Calendar.MONTH, month); holiday.set(Calendar.DAY_OF_MONTH, day); int doy = holiday.get(Calendar.DAY_OF_YEAR); int dow = holiday.get(Calendar.DAY_OF_WEEK); if (dow == Calendar.SATURDAY) { return doy - 1; // FRIDAY } if (dow == Calendar.SUNDAY) { return doy + 1; // MONDAY } return doy; } @Override public Date getBusinessDay(Date date, int n) { Validate.isTrue(n >= 0); Calendar calendar = now(); calendar.setTime(date); while (isHoliday(calendar) || isWeekend(calendar) || n-- > 0) { calendar.add(Calendar.DATE, 1); } return calendar.getTime(); } private boolean isWeekend(Calendar calendar) { int dow = calendar.get(Calendar.DAY_OF_WEEK); return dow == Calendar.SATURDAY || dow == Calendar.SUNDAY; } }
4,788
0
Create_ds/SimianArmy/src/main/java/com/netflix/simianarmy
Create_ds/SimianArmy/src/main/java/com/netflix/simianarmy/basic/LocalDbRecorder.java
/* * * Copyright 2012 Netflix, Inc. * * Licensed 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 com.netflix.simianarmy.basic; import java.io.File; import java.io.IOException; import java.io.Serializable; import java.util.ArrayList; import java.util.Collections; import java.util.Date; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentNavigableMap; import org.mapdb.Atomic; import org.mapdb.DB; import org.mapdb.DBMaker; import org.mapdb.Fun; import com.netflix.simianarmy.EventType; import com.netflix.simianarmy.MonkeyConfiguration; import com.netflix.simianarmy.MonkeyRecorder; import com.netflix.simianarmy.MonkeyType; import com.netflix.simianarmy.chaos.ChaosMonkey; /** * Replacement for SimpleDB on non-AWS: use an embedded db. * * @author jgardner * */ public class LocalDbRecorder implements MonkeyRecorder { private static DB db = null; private static Atomic.Long nextId = null; private static ConcurrentNavigableMap<Fun.Tuple2<Long, Long>, Event> eventMap = null; // Upper bound, so we don't fill the disk with monkey events private static final double MAX_EVENTS = 10000; private double maxEvents = MAX_EVENTS; private String dbFilename = "simianarmy_events"; private String dbpassword = null; /** Constructor. * */ public LocalDbRecorder(MonkeyConfiguration configuration) { if (configuration != null) { dbFilename = configuration.getStrOrElse("simianarmy.recorder.localdb.file", null); maxEvents = configuration.getNumOrElse("simianarmy.recorder.localdb.max_events", MAX_EVENTS); dbpassword = configuration.getStrOrElse("simianarmy.recorder.localdb.password", null); } } private synchronized void init() { if (nextId != null) { return; } File dbFile = null; dbFile = (dbFilename == null) ? tempDbFile() : new File(dbFilename); if (dbpassword != null) { db = DBMaker.newFileDB(dbFile) .closeOnJvmShutdown() .encryptionEnable(dbpassword) .make(); } else { db = DBMaker.newFileDB(dbFile) .closeOnJvmShutdown() .make(); } eventMap = db.getTreeMap("eventMap"); nextId = db.createAtomicLong("next", 1); } private static File tempDbFile() { try { final File tmpFile = File.createTempFile("mapdb", "db"); tmpFile.deleteOnExit(); return tmpFile; } catch (IOException e) { throw new RuntimeException("Temporary DB file could not be created", e); } } /* (non-Javadoc) * @see com.netflix.simianarmy.MonkeyRecorder#newEvent(MonkeyType, EventType, String, String) */ @Override public Event newEvent(MonkeyType monkeyType, EventType eventType, String region, String id) { init(); return new MapDbRecorderEvent(monkeyType, eventType, region, id); } /* (non-Javadoc) * @see com.netflix.simianarmy.MonkeyRecorder#recordEvent(com.netflix.simianarmy.MonkeyRecorder.Event) */ @Override public void recordEvent(Event evt) { init(); Fun.Tuple2<Long, Long> id = Fun.t2(evt.eventTime().getTime(), nextId.incrementAndGet()); if (eventMap.size() + 1 > maxEvents) { eventMap.remove(eventMap.firstKey()); } eventMap.put(id, evt); db.commit(); } /* (non-Javadoc) * @see com.netflix.simianarmy.MonkeyRecorder#findEvents(java.util.Map, java.util.Date) */ @Override public List<Event> findEvents(Map<String, String> query, Date after) { init(); List<Event> foundEvents = new ArrayList<Event>(); for (Event evt : eventMap.tailMap(toKey(after)).values()) { boolean matched = true; for (Map.Entry<String, String> pair : query.entrySet()) { if (pair.getKey().equals("id") && !evt.id().equals(pair.getValue())) { matched = false; } if (pair.getKey().equals("monkeyType") && !evt.monkeyType().toString().equals(pair.getValue())) { matched = false; } if (pair.getKey().equals("eventType") && !evt.eventType().toString().equals(pair.getValue())) { matched = false; } } if (matched) { foundEvents.add(evt); } } return foundEvents; } /* (non-Javadoc) * @see com.netflix.simianarmy.MonkeyRecorder#findEvents(MonkeyType, Map, Date) */ @Override public List<Event> findEvents(MonkeyType monkeyType, Map<String, String> query, Date after) { Map<String, String> copy = new LinkedHashMap<String, String>(query); copy.put("monkeyType", monkeyType.name()); return findEvents(copy, after); } /* (non-Javadoc) * @see com.netflix.simianarmy.MonkeyRecorder#findEvents(MonkeyType, EventType, Map, Date) */ @Override public List<Event> findEvents(MonkeyType monkeyType, EventType eventType, Map<String, String> query, Date after) { Map<String, String> copy = new LinkedHashMap<String, String>(query); copy.put("monkeyType", monkeyType.name()); copy.put("eventType", eventType.name()); return findEvents(copy, after); } private Fun.Tuple2<Long, Long> toKey(Date date) { return Fun.t2(date.getTime(), 0L); } /** Loggable event for LocalDbRecorder. * */ public static class MapDbRecorderEvent implements MonkeyRecorder.Event, Serializable { /** The monkey type. */ private MonkeyType monkeyType; /** The event type. */ private EventType eventType; /** The event id. */ private String id; /** The event region. */ private String region; /** The fields. */ private Map<String, String> fields = new HashMap<String, String>(); /** The event time. */ private Date date; private static final long serialVersionUID = 1L; /** Constructor. * @param monkeyType * @param eventType * @param region * @param id */ public MapDbRecorderEvent(MonkeyType monkeyType, EventType eventType, String region, String id) { this.monkeyType = monkeyType; this.eventType = eventType; this.id = id; this.region = region; this.date = new Date(); } /** Constructor. * @param monkeyType * @param eventType * @param region * @param id * @param time */ public MapDbRecorderEvent(MonkeyType monkeyType, EventType eventType, String region, String id, long time) { this.monkeyType = monkeyType; this.eventType = eventType; this.id = id; this.region = region; this.date = new Date(time); } /* (non-Javadoc) * @see com.netflix.simianarmy.MonkeyRecorder.Event#id() */ @Override public String id() { return id; } /* (non-Javadoc) * @see com.netflix.simianarmy.MonkeyRecorder.Event#eventTime() */ @Override public Date eventTime() { return new Date(date.getTime()); } /* (non-Javadoc) * @see com.netflix.simianarmy.MonkeyRecorder.Event#monkeyType() */ @Override public MonkeyType monkeyType() { return monkeyType; } /* (non-Javadoc) * @see com.netflix.simianarmy.MonkeyRecorder.Event#eventType() */ @Override public EventType eventType() { return eventType; } /* (non-Javadoc) * @see com.netflix.simianarmy.MonkeyRecorder.Event#region() */ @Override public String region() { return region; } /* (non-Javadoc) * @see com.netflix.simianarmy.MonkeyRecorder.Event#fields() */ @Override public Map<String, String> fields() { return Collections.unmodifiableMap(fields); } /* (non-Javadoc) * @see com.netflix.simianarmy.MonkeyRecorder.Event#field(java.lang.String) */ @Override public String field(String name) { return fields.get(name); } /* (non-Javadoc) * @see com.netflix.simianarmy.MonkeyRecorder.Event#addField(java.lang.String, java.lang.String) */ @Override public Event addField(String name, String value) { fields.put(name, value); return this; } } /** Appears to be used for testing, if so should be moved to a unit test. (2/16/2014, mgeis) * @param args */ public static void main(String[] args) { LocalDbRecorder r = new LocalDbRecorder(null); r.init(); List<Event> events2 = r.findEvents(new HashMap<String, String>(), new Date(0)); for (Event event : events2) { System.out.println("Got:" + event + ": " + event.eventTime().getTime()); } for (int i = 0; i < 10; i++) { Event event = r.newEvent(ChaosMonkey.Type.CHAOS, ChaosMonkey.EventTypes.CHAOS_TERMINATION, "1", "1"); r.recordEvent(event); System.out.println("Added:" + event + ": " + event.eventTime().getTime()); } List<Event> events = r.findEvents(new HashMap<String, String>(), new Date(0)); for (Event event : events) { System.out.println("Got:" + event + ": " + event.eventTime().getTime()); } } }
4,789
0
Create_ds/SimianArmy/src/main/java/com/netflix/simianarmy
Create_ds/SimianArmy/src/main/java/com/netflix/simianarmy/basic/BasicConfiguration.java
/* * * Copyright 2012 Netflix, Inc. * * Licensed 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 com.netflix.simianarmy.basic; import com.netflix.simianarmy.MonkeyConfiguration; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.Properties; /** * The Class BasicConfiguration. */ public class BasicConfiguration implements MonkeyConfiguration { /** The Constant LOGGER. */ private static final Logger LOGGER = LoggerFactory.getLogger(BasicConfiguration.class); /** The properties. */ private Properties props; /** * Instantiates a new basic configuration. * @param props * the properties */ public BasicConfiguration(Properties props) { this.props = props; } /** {@inheritDoc} */ @Override public boolean getBool(String property) { return getBoolOrElse(property, false); } /** {@inheritDoc} */ @Override public boolean getBoolOrElse(String property, boolean dflt) { String val = props.getProperty(property); if (val == null) { return dflt; } val = val.trim(); return Boolean.parseBoolean(val); } /** {@inheritDoc} */ @Override public double getNumOrElse(String property, double dflt) { String val = props.getProperty(property); double result = dflt; if (val != null && !val.isEmpty()) { try { result = Double.parseDouble(val); } catch (NumberFormatException e) { LOGGER.error("failed to parse property: " + property + "; returning default value: " + dflt, e); } } return result; } /** {@inheritDoc} */ @Override public String getStr(String property) { return getStrOrElse(property, null); } /** {@inheritDoc} */ @Override public String getStrOrElse(String property, String dflt) { String val = props.getProperty(property); return val == null ? dflt : val; } /** {@inheritDoc} */ @Override public void reload() { // BasicConfiguration is based on static properties, so reload is a no-op } @Override public void reload(String groupName) { // BasicConfiguration is based on static properties, so reload is a no-op } }
4,790
0
Create_ds/SimianArmy/src/main/java/com/netflix/simianarmy
Create_ds/SimianArmy/src/main/java/com/netflix/simianarmy/basic/BasicSimianArmyContext.java
/* * * Copyright 2012 Netflix, Inc. * * Licensed 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 com.netflix.simianarmy.basic; import com.amazonaws.ClientConfiguration; import com.amazonaws.auth.AWSCredentialsProvider; import com.amazonaws.auth.DefaultAWSCredentialsProviderChain; import com.amazonaws.regions.Region; import com.amazonaws.regions.Regions; import com.netflix.simianarmy.CloudClient; import com.netflix.simianarmy.Monkey; import com.netflix.simianarmy.MonkeyCalendar; import com.netflix.simianarmy.MonkeyConfiguration; import com.netflix.simianarmy.MonkeyRecorder; import com.netflix.simianarmy.MonkeyRecorder.Event; import com.netflix.simianarmy.MonkeyScheduler; import com.netflix.simianarmy.aws.RDSRecorder; import com.netflix.simianarmy.aws.STSAssumeRoleSessionCredentialsProvider; import com.netflix.simianarmy.aws.SimpleDBRecorder; import com.netflix.simianarmy.client.aws.AWSClient; import org.apache.commons.lang.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.InputStream; import java.lang.reflect.Constructor; import java.util.LinkedList; import java.util.Map.Entry; import java.util.Properties; import java.util.concurrent.TimeUnit; /** * The Class BasicSimianArmyContext. */ public class BasicSimianArmyContext implements Monkey.Context { /** The Constant LOGGER. */ private static final Logger LOGGER = LoggerFactory.getLogger(BasicSimianArmyContext.class); /** The configuration properties. */ private final Properties properties = new Properties(); /** The Constant MONKEY_THREADS. */ private static final int MONKEY_THREADS = 1; /** The scheduler. */ private MonkeyScheduler scheduler; /** The calendar. */ private MonkeyCalendar calendar; /** The config. */ private BasicConfiguration config; /** The client. */ private AWSClient client; /** The recorder. */ private MonkeyRecorder recorder; /** The reported events. */ private final LinkedList<Event> eventReport; /** The AWS credentials provider to be used. */ private AWSCredentialsProvider awsCredentialsProvider = new DefaultAWSCredentialsProviderChain(); /** If configured, the ARN of Role to be assumed. */ private final String assumeRoleArn; private final String accountName; private final String account; private final String secret; private final String region; protected ClientConfiguration awsClientConfig = new ClientConfiguration(); /* If configured, the proxy to be used when making AWS API requests */ private final String proxyHost; private final String proxyPort; private final String proxyUsername; private final String proxyPassword; /** The key name of the tag owner used to tag resources - across all Monkeys */ public static String GLOBAL_OWNER_TAGKEY; /** protected constructor as the Shell is meant to be subclassed. */ protected BasicSimianArmyContext(String... configFiles) { eventReport = new LinkedList<Event>(); // Load the config files into props following the provided order. for (String configFile : configFiles) { loadConfigurationFileIntoProperties(configFile); } LOGGER.info("The following are properties in the context."); for (Entry<Object, Object> prop : properties.entrySet()) { Object propertyKey = prop.getKey(); if (isSafeToLog(propertyKey)) { LOGGER.info(String.format("%s = %s", propertyKey, prop.getValue())); } else { LOGGER.info(String.format("%s = (not shown here)", propertyKey)); } } config = new BasicConfiguration(properties); account = config.getStr("simianarmy.client.aws.accountKey"); secret = config.getStr("simianarmy.client.aws.secretKey"); accountName = config.getStrOrElse("simianarmy.client.aws.accountName", "Default"); String defaultRegion = "us-east-1"; Region currentRegion = Regions.getCurrentRegion(); if (currentRegion != null) { defaultRegion = currentRegion.getName(); } region = config.getStrOrElse("simianarmy.client.aws.region", defaultRegion); GLOBAL_OWNER_TAGKEY = config.getStrOrElse("simianarmy.tags.owner", "owner"); // Check for and configure optional proxy configuration proxyHost = config.getStr("simianarmy.client.aws.proxyHost"); proxyPort = config.getStr("simianarmy.client.aws.proxyPort"); proxyUsername = config.getStr("simianarmy.client.aws.proxyUser"); proxyPassword = config.getStr("simianarmy.client.aws.proxyPassword"); if ((proxyHost != null) && (proxyPort != null)) { awsClientConfig.setProxyHost(proxyHost); awsClientConfig.setProxyPort(Integer.parseInt(proxyPort)); if ((proxyUsername != null) && (proxyPassword != null)) { awsClientConfig.setProxyUsername(proxyUsername); awsClientConfig.setProxyPassword(proxyPassword); } } assumeRoleArn = config.getStr("simianarmy.client.aws.assumeRoleArn"); if (assumeRoleArn != null) { this.awsCredentialsProvider = new STSAssumeRoleSessionCredentialsProvider(assumeRoleArn, awsClientConfig); LOGGER.info("Using STSAssumeRoleSessionCredentialsProvider with assume role " + assumeRoleArn); } // if credentials are set explicitly make them available to the AWS SDK if (StringUtils.isNotBlank(account) && StringUtils.isNotBlank(secret)) { this.exportCredentials(account, secret); } createClient(); createCalendar(); createScheduler(); createRecorder(); } /** * Checks whether it is safe to log the property based on the given * property key. * @param propertyKey The key for the property, expected to be resolvable to a String * @return A boolean indicating whether it is safe to log the corresponding property */ protected boolean isSafeToLog(Object propertyKey) { String propertyKeyName = propertyKey.toString(); return !propertyKeyName.contains("secretKey") && !propertyKeyName.contains("vsphere.password"); } /** loads the given config on top of the config read by previous calls. */ protected void loadConfigurationFileIntoProperties(String propertyFileName) { String propFile = System.getProperty(propertyFileName, "/" + propertyFileName); try { LOGGER.info("loading properties file: " + propFile); InputStream is = BasicSimianArmyContext.class.getResourceAsStream(propFile); try { properties.load(is); } finally { is.close(); } } catch (Exception e) { String msg = "Unable to load properties file " + propFile + " set System property \"" + propertyFileName + "\" to valid file"; LOGGER.error(msg); throw new RuntimeException(msg, e); } } private void createScheduler() { int freq = (int) config.getNumOrElse("simianarmy.scheduler.frequency", 1); TimeUnit freqUnit = TimeUnit.valueOf(config.getStrOrElse("simianarmy.scheduler.frequencyUnit", "HOURS")); int threads = (int) config.getNumOrElse("simianarmy.scheduler.threads", MONKEY_THREADS); setScheduler(new BasicScheduler(freq, freqUnit, threads)); } @SuppressWarnings("unchecked") private void createRecorder() { @SuppressWarnings("rawtypes") Class recorderClass = loadClientClass("simianarmy.client.recorder.class"); if (recorderClass != null && recorderClass.equals(RDSRecorder.class)) { String dbDriver = configuration().getStr("simianarmy.recorder.db.driver"); String dbUser = configuration().getStr("simianarmy.recorder.db.user"); String dbPass = configuration().getStr("simianarmy.recorder.db.pass"); String dbUrl = configuration().getStr("simianarmy.recorder.db.url"); String dbTable = configuration().getStr("simianarmy.recorder.db.table"); RDSRecorder rdsRecorder = new RDSRecorder(dbDriver, dbUser, dbPass, dbUrl, dbTable, client.region()); rdsRecorder.init(); setRecorder(rdsRecorder); } else if (recorderClass == null || recorderClass.equals(SimpleDBRecorder.class)) { String domain = config.getStrOrElse("simianarmy.recorder.sdb.domain", "SIMIAN_ARMY"); if (client != null) { SimpleDBRecorder simpleDbRecorder = new SimpleDBRecorder(client, domain); simpleDbRecorder.init(); setRecorder(simpleDbRecorder); } } else { setRecorder((MonkeyRecorder) factory(recorderClass)); } } @SuppressWarnings("unchecked") private void createCalendar() { @SuppressWarnings("rawtypes") Class calendarClass = loadClientClass("simianarmy.calendar.class"); if (calendarClass == null || calendarClass.equals(BasicCalendar.class)) { setCalendar(new BasicCalendar(config)); } else { setCalendar((MonkeyCalendar) factory(calendarClass)); } } /** * Create the specific client with region taken from properties. * Override to provide your own client. */ protected void createClient() { createClient(region); } /** * Create the specific client within passed region, using the appropriate AWS credentials provider * and client configuration. * @param clientRegion */ protected void createClient(String clientRegion) { this.client = new AWSClient(clientRegion, awsCredentialsProvider, awsClientConfig); setCloudClient(this.client); } /** * Gets the AWS client. * @return the AWS client */ public AWSClient awsClient() { return client; } /** * Gets the region. * @return the region */ public String region() { return region; } /** * Gets the accountName * @return the accountName */ public String accountName() { return accountName; } @Override public void reportEvent(Event evt) { this.eventReport.add(evt); } @Override public void resetEventReport() { eventReport.clear(); } @Override public String getEventReport() { StringBuilder report = new StringBuilder(); for (Event event : this.eventReport) { report.append(String.format("%s %s (", event.eventType(), event.id())); boolean isFirst = true; for (Entry<String, String> field : event.fields().entrySet()) { if (!isFirst) { report.append(", "); } else { isFirst = false; } report.append(String.format("%s:%s", field.getKey(), field.getValue())); } report.append(")\n"); } return report.toString(); } /** * Exports credentials as Java system properties * to be picked up by AWS SDK clients. * @param accountKey * @param secretKey */ public void exportCredentials(String accountKey, String secretKey) { System.setProperty("aws.accessKeyId", accountKey); System.setProperty("aws.secretKey", secretKey); } /** {@inheritDoc} */ @Override public MonkeyScheduler scheduler() { return scheduler; } /** * Sets the scheduler. * * @param scheduler * the new scheduler */ protected void setScheduler(MonkeyScheduler scheduler) { this.scheduler = scheduler; } /** {@inheritDoc} */ @Override public MonkeyCalendar calendar() { return calendar; } /** * Sets the calendar. * * @param calendar * the new calendar */ protected void setCalendar(MonkeyCalendar calendar) { this.calendar = calendar; } /** {@inheritDoc} */ @Override public MonkeyConfiguration configuration() { return config; } /** * Sets the configuration. * * @param configuration * the new configuration */ protected void setConfiguration(MonkeyConfiguration configuration) { this.config = (BasicConfiguration) configuration; } /** {@inheritDoc} */ @Override public CloudClient cloudClient() { return client; } /** * Sets the cloud client. * * @param cloudClient * the new cloud client */ protected void setCloudClient(CloudClient cloudClient) { this.client = (AWSClient) cloudClient; } /** {@inheritDoc} */ @Override public MonkeyRecorder recorder() { return recorder; } /** * Sets the recorder. * * @param recorder * the new recorder */ protected void setRecorder(MonkeyRecorder recorder) { this.recorder = recorder; } /** * Gets the configuration properties. * @return the configuration properties */ protected Properties getProperties() { return this.properties; } /** * Gets the AWS credentials provider. * @return the AWS credentials provider */ public AWSCredentialsProvider getAwsCredentialsProvider() { return awsCredentialsProvider; } /** * Gets the AWS client configuration. * @return the AWS client configuration */ public ClientConfiguration getAwsClientConfig() { return awsClientConfig; } /** * Load a class specified by the config; for drop-in replacements. * (Duplicates a method in MonkeyServer; refactor to util?). * * @param key * @return the loaded class or null if the class is not found */ @SuppressWarnings("rawtypes") private Class loadClientClass(String key) { ClassLoader classLoader = getClass().getClassLoader(); try { String clientClassName = config.getStrOrElse(key, null); if (clientClassName == null || clientClassName.isEmpty()) { LOGGER.info("using standard class for " + key); return null; } Class newClass = classLoader.loadClass(clientClassName); LOGGER.info("using " + key + " loaded " + newClass.getCanonicalName()); return newClass; } catch (ClassNotFoundException e) { throw new RuntimeException("Could not load " + key, e); } } /** * Generic factory to create monkey collateral types. * * @param <T> * the generic type to create * @param implClass * the actual concrete type to instantiate. * @return an object of the requested type */ private <T> T factory(Class<T> implClass) { try { // then find corresponding ctor for (Constructor<?> ctor : implClass.getDeclaredConstructors()) { Class<?>[] paramTypes = ctor.getParameterTypes(); if (paramTypes.length != 1) { continue; } if (paramTypes[0].getName().endsWith("Configuration")) { @SuppressWarnings("unchecked") T impl = (T) ctor.newInstance(config); return impl; } } // Last ditch; try no-arg. return implClass.newInstance(); } catch (Exception e) { LOGGER.error("context config error, cannot make an instance of " + implClass.getName(), e); } return null; } }
4,791
0
Create_ds/SimianArmy/src/main/java/com/netflix/simianarmy
Create_ds/SimianArmy/src/main/java/com/netflix/simianarmy/basic/BasicRecorderEvent.java
/* * * Copyright 2012 Netflix, Inc. * * Licensed 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 com.netflix.simianarmy.basic; import java.util.Collections; import java.util.Date; import java.util.HashMap; import java.util.Map; import com.netflix.simianarmy.EventType; import com.netflix.simianarmy.MonkeyRecorder; import com.netflix.simianarmy.MonkeyType; /** * The Class BasicRecorderEvent. */ public class BasicRecorderEvent implements MonkeyRecorder.Event { /** The monkey type. */ private MonkeyType monkeyType; /** The event type. */ private EventType eventType; /** The event id. */ private String id; /** The event region. */ private String region; /** The fields. */ private Map<String, String> fields = new HashMap<String, String>(); /** The event time. */ private Date date; /** * Instantiates a new basic recorder event. * * @param monkeyType * the monkey type * @param eventType * the event type * @param region * the region event occurred in * @param id * the event id */ public BasicRecorderEvent(MonkeyType monkeyType, EventType eventType, String region, String id) { this.monkeyType = monkeyType; this.eventType = eventType; this.id = id; this.region = region; this.date = new Date(); } /** * Instantiates a new basic recorder event. * * @param monkeyType * the monkey type * @param eventType * the event type * @param region * the region event occurred in * @param id * the event id * @param time * the event time */ public BasicRecorderEvent(MonkeyType monkeyType, EventType eventType, String region, String id, long time) { this.monkeyType = monkeyType; this.eventType = eventType; this.id = id; this.region = region; this.date = new Date(time); } /** {@inheritDoc} */ public String id() { return id; } /** {@inheritDoc} */ public String region() { return region; } /** {@inheritDoc} */ public Date eventTime() { return new Date(date.getTime()); } /** {@inheritDoc} */ public MonkeyType monkeyType() { return monkeyType; } /** {@inheritDoc} */ public EventType eventType() { return eventType; } /** {@inheritDoc} */ public Map<String, String> fields() { return Collections.unmodifiableMap(fields); } /** {@inheritDoc} */ public String field(String name) { return fields.get(name); } /** * Adds the fields. * * @param toAdd * the fields to set * @return <b>this</b> so you can chain many addFields calls together */ public MonkeyRecorder.Event addFields(Map<String, String> toAdd) { fields.putAll(toAdd); return this; } /** {@inheritDoc} */ public MonkeyRecorder.Event addField(String name, String value) { fields.put(name, value); return this; } }
4,792
0
Create_ds/SimianArmy/src/main/java/com/netflix/simianarmy
Create_ds/SimianArmy/src/main/java/com/netflix/simianarmy/basic/BasicScheduler.java
/* * * Copyright 2012 Netflix, Inc. * * Licensed 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 com.netflix.simianarmy.basic; import java.util.Calendar; import java.util.Collections; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.TimeUnit; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.netflix.simianarmy.Monkey; import com.netflix.simianarmy.MonkeyRecorder.Event; import com.netflix.simianarmy.MonkeyScheduler; /** * The Class BasicScheduler. */ public class BasicScheduler implements MonkeyScheduler { /** The Constant LOGGER. */ private static final Logger LOGGER = LoggerFactory.getLogger(BasicScheduler.class); /** The futures. */ private HashMap<String, ScheduledFuture<?>> futures = new HashMap<String, ScheduledFuture<?>>(); /** The scheduler. */ private final ScheduledExecutorService scheduler; /** the frequency. */ private int frequency = 1; /** the frequencyUnit. */ private TimeUnit frequencyUnit = TimeUnit.HOURS; /** * Instantiates a new basic scheduler. */ public BasicScheduler() { scheduler = Executors.newScheduledThreadPool(1); } /** * Instantiates a new basic scheduler. * * @param freq * the frequency to run on * @param freqUnit * the unit for the freq argument * @param concurrent * the concurrent number of threads */ public BasicScheduler(int freq, TimeUnit freqUnit, int concurrent) { frequency = freq; frequencyUnit = freqUnit; scheduler = Executors.newScheduledThreadPool(concurrent); } /** {@inheritDoc} */ @Override public int frequency() { return frequency; } /** {@inheritDoc} */ @Override public TimeUnit frequencyUnit() { return frequencyUnit; } /** {@inheritDoc} */ @Override public void start(Monkey monkey, Runnable command) { long cycle = TimeUnit.MILLISECONDS.convert(frequency(), frequencyUnit()); // go back 1 cycle to see if we have any events Calendar cal = Calendar.getInstance(); cal.add(Calendar.MILLISECOND, (int) (-1 * cycle)); Date then = cal.getTime(); List<Event> events = monkey.context().recorder() .findEvents(monkey.type(), Collections.<String, String>emptyMap(), then); if (events.isEmpty()) { // no events so just run now futures.put(monkey.type().name(), scheduler.scheduleWithFixedDelay(command, 0, frequency(), frequencyUnit())); } else { // we have events, so set the start time to the time left in what would have been the last cycle Date eventTime = events.get(0).eventTime(); Date now = new Date(); long init = cycle - (now.getTime() - eventTime.getTime()); LOGGER.info("Detected previous events within cycle, setting " + monkey.type().name() + " start to " + new Date(now.getTime() + init)); futures.put(monkey.type().name(), scheduler.scheduleWithFixedDelay(command, init, cycle, TimeUnit.MILLISECONDS)); } } /** {@inheritDoc} */ @Override public void stop(Monkey monkey) { if (futures.containsKey(monkey.type().name())) { futures.remove(monkey.type().name()).cancel(true); } } }
4,793
0
Create_ds/SimianArmy/src/main/java/com/netflix/simianarmy
Create_ds/SimianArmy/src/main/java/com/netflix/simianarmy/basic/BasicChaosMonkeyContext.java
/* * * Copyright 2012 Netflix, Inc. * * Licensed 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 com.netflix.simianarmy.basic; import com.amazonaws.regions.Region; import com.amazonaws.regions.Regions; import com.amazonaws.services.simpleemail.AmazonSimpleEmailServiceClient; import com.netflix.simianarmy.MonkeyConfiguration; import com.netflix.simianarmy.basic.chaos.BasicChaosEmailNotifier; import com.netflix.simianarmy.basic.chaos.BasicChaosInstanceSelector; import com.netflix.simianarmy.chaos.ChaosCrawler; import com.netflix.simianarmy.chaos.ChaosEmailNotifier; import com.netflix.simianarmy.chaos.ChaosInstanceSelector; import com.netflix.simianarmy.chaos.ChaosMonkey; import com.netflix.simianarmy.client.aws.chaos.ASGChaosCrawler; import com.netflix.simianarmy.client.aws.chaos.FilteringChaosCrawler; import com.netflix.simianarmy.client.aws.chaos.TagPredicate; /** * The Class BasicContext. This provide the basic context needed for the Chaos Monkey to run. It will configure * the Chaos Monkey based on a simianarmy.properties file and chaos.properties. The properties file can be * overridden with -Dsimianarmy.properties=/path/to/my.properties */ public class BasicChaosMonkeyContext extends BasicSimianArmyContext implements ChaosMonkey.Context { /** The crawler. */ private ChaosCrawler crawler; /** The selector. */ private ChaosInstanceSelector selector; /** The chaos email notifier. */ private ChaosEmailNotifier chaosEmailNotifier; /** * Instantiates a new basic context. */ public BasicChaosMonkeyContext() { super("simianarmy.properties", "client.properties", "chaos.properties"); MonkeyConfiguration cfg = configuration(); String tagKey = cfg.getStrOrElse("simianarmy.chaos.ASGtag.key", ""); String tagValue = cfg.getStrOrElse("simianarmy.chaos.ASGtag.value", ""); ASGChaosCrawler chaosCrawler = new ASGChaosCrawler(awsClient()); setChaosCrawler(tagKey.isEmpty() ? chaosCrawler : new FilteringChaosCrawler(chaosCrawler, new TagPredicate(tagKey, tagValue))); setChaosInstanceSelector(new BasicChaosInstanceSelector()); AmazonSimpleEmailServiceClient sesClient = new AmazonSimpleEmailServiceClient(awsClientConfig); if (configuration().getStr("simianarmy.aws.email.region") != null) { sesClient.setRegion(Region.getRegion(Regions.fromName(configuration().getStr("simianarmy.aws.email.region")))); } setChaosEmailNotifier(new BasicChaosEmailNotifier(cfg, sesClient, null)); } /** {@inheritDoc} */ @Override public ChaosCrawler chaosCrawler() { return crawler; } /** * Sets the chaos crawler. * * @param chaosCrawler * the new chaos crawler */ protected void setChaosCrawler(ChaosCrawler chaosCrawler) { this.crawler = chaosCrawler; } /** {@inheritDoc} */ @Override public ChaosInstanceSelector chaosInstanceSelector() { return selector; } /** * Sets the chaos instance selector. * * @param chaosInstanceSelector * the new chaos instance selector */ protected void setChaosInstanceSelector(ChaosInstanceSelector chaosInstanceSelector) { this.selector = chaosInstanceSelector; } @Override public ChaosEmailNotifier chaosEmailNotifier() { return chaosEmailNotifier; } /** * Sets the chaos email notifier. * * @param notifier * the chaos email notifier */ protected void setChaosEmailNotifier(ChaosEmailNotifier notifier) { this.chaosEmailNotifier = notifier; } }
4,794
0
Create_ds/SimianArmy/src/main/java/com/netflix/simianarmy/basic
Create_ds/SimianArmy/src/main/java/com/netflix/simianarmy/basic/calendars/BavarianCalendar.java
/* * * Copyright 2012 Netflix, Inc. * * Licensed 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 com.netflix.simianarmy.basic.calendars; import com.netflix.simianarmy.MonkeyConfiguration; import com.netflix.simianarmy.basic.BasicCalendar; import java.util.Arrays; import java.util.Calendar; import java.util.Collection; // CHECKSTYLE IGNORE MagicNumberCheck /** * The Class BavarianCalendar. */ public class BavarianCalendar extends BasicCalendar { /** * Instantiates a new basic calendar. * * @param cfg the monkey configuration */ public BavarianCalendar(MonkeyConfiguration cfg) { super(cfg); } /** {@inheritDoc} */ @Override protected void loadHolidays(int year) { holidays.clear(); // these aren't all strictly holidays, but days when engineers will likely // not be in the office to respond to rampaging monkeys // first of all, we need easter sunday doy, // because ome other holidays calculated from it int easter = westernEasterDayOfYear(year); // new year holidays.addAll(getHolidayWithBridgeDays(year, dayOfYear(year, Calendar.JANUARY, 1))); // epiphanie holidays.addAll(getHolidayWithBridgeDays(year, dayOfYear(year, Calendar.JANUARY, 6))); // good friday, always friday, don't need to check if it's bridge day holidays.add(easter - 2); // easter monday, always monday, don't need to check if it's bridge day holidays.add(easter + 1); // labor day holidays.addAll(getHolidayWithBridgeDays(year, dayOfYear(year, Calendar.MAY, 1))); // ascension day holidays.addAll(getHolidayWithBridgeDays(year, easter + 39)); // whit monday, always monday, don't need to check if it's bridge day holidays.add(easter + 50); // corpus christi holidays.add(westernEasterDayOfYear(year) + 60); // assumption day holidays.addAll(getHolidayWithBridgeDays(year, dayOfYear(year, Calendar.AUGUST, 15))); // german unity day holidays.addAll(getHolidayWithBridgeDays(year, dayOfYear(year, Calendar.OCTOBER, 3))); // all saints holidays.addAll(getHolidayWithBridgeDays(year, dayOfYear(year, Calendar.NOVEMBER, 1))); // monkey goes on christmas vacations between christmas and new year! holidays.addAll(getHolidayWithBridgeDays(year, dayOfYear(year, Calendar.DECEMBER, 24))); holidays.add(dayOfYear(year, Calendar.DECEMBER, 25)); holidays.add(dayOfYear(year, Calendar.DECEMBER, 26)); holidays.add(dayOfYear(year, Calendar.DECEMBER, 27)); holidays.add(dayOfYear(year, Calendar.DECEMBER, 28)); holidays.add(dayOfYear(year, Calendar.DECEMBER, 29)); holidays.add(dayOfYear(year, Calendar.DECEMBER, 30)); holidays.add(dayOfYear(year, Calendar.DECEMBER, 31)); // mark the holiday set with the year, so on Jan 1 it will automatically // recalculate the holidays for next year holidays.add(year); } /** * Returns collection of holidays, including Monday or Friday * if given holiday is Thuesday or Thursday. * * The behaviour to take Monday as day off if official holiday is Thuesday * and to take Friday as day off if official holiday is Thursday * is specific to [at least] Germany. * We call it, literally, "bridge day". * * @param dayOfYear holiday day of year */ private Collection<Integer> getHolidayWithBridgeDays(int year, int dayOfYear) { Calendar holiday = now(); holiday.set(Calendar.YEAR, year); holiday.set(Calendar.DAY_OF_YEAR, dayOfYear); int dow = holiday.get(Calendar.DAY_OF_WEEK); int mon = holiday.get(Calendar.MONTH); int dom = holiday.get(Calendar.DAY_OF_MONTH); // We don't want to include Monday if Thuesday is January 1. if (dow == Calendar.TUESDAY && dayOfYear != 1) return Arrays.asList(dayOfYear, dayOfYear - 1); // We don't want to include Friday if Thursday is December 31. if (dow == Calendar.THURSDAY && (mon != Calendar.DECEMBER || dom != 31)) return Arrays.asList(dayOfYear, dayOfYear + 1); return Arrays.asList(dayOfYear); } /** * Western easter sunday in year. * * @param year * the year * @return the day of the year of western easter sunday */ protected int westernEasterDayOfYear(int year) { int a = year % 19, b = year / 100, c = year % 100, d = b / 4, e = b % 4, g = (8 * b + 13) / 25, h = (19 * a + b - d - g + 15) % 30, j = c / 4, k = c % 4, m = (a + 11 * h) / 319, r = (2 * e + 2 * j - k - h + m + 32) % 7; int oneBasedMonth = (h - m + r + 90) / 25; int dayOfYear = (h - m + r + oneBasedMonth + 19) % 32; return dayOfYear(year, oneBasedMonth - 1, dayOfYear); } }
4,795
0
Create_ds/SimianArmy/src/main/java/com/netflix/simianarmy/basic
Create_ds/SimianArmy/src/main/java/com/netflix/simianarmy/basic/conformity/BasicConformityMonkey.java
/* * * Copyright 2013 Netflix, Inc. * * Licensed 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 com.netflix.simianarmy.basic.conformity; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import com.netflix.simianarmy.MonkeyCalendar; import com.netflix.simianarmy.MonkeyConfiguration; import com.netflix.simianarmy.conformity.Cluster; import com.netflix.simianarmy.conformity.ClusterCrawler; import com.netflix.simianarmy.conformity.ConformityClusterTracker; import com.netflix.simianarmy.conformity.ConformityEmailNotifier; import com.netflix.simianarmy.conformity.ConformityMonkey; import com.netflix.simianarmy.conformity.ConformityRuleEngine; import org.apache.commons.lang.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.Collection; import java.util.Date; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; /** The basic implementation of Conformity Monkey. */ public class BasicConformityMonkey extends ConformityMonkey { /** The Constant LOGGER. */ private static final Logger LOGGER = LoggerFactory.getLogger(BasicConformityMonkey.class); /** The Constant NS. */ private static final String NS = "simianarmy.conformity."; /** The cfg. */ private final MonkeyConfiguration cfg; private final ClusterCrawler crawler; private final ConformityEmailNotifier emailNotifier; private final Collection<String> regions = Lists.newArrayList(); private final ConformityClusterTracker clusterTracker; private final MonkeyCalendar calendar; private final ConformityRuleEngine ruleEngine; /** Flag to indicate whether the monkey is leashed. */ private boolean leashed; /** * Clusters that are not conforming in the last check. */ private final Map<String, Collection<Cluster>> nonconformingClusters = Maps.newHashMap(); /** * Clusters that are conforming in the last check. */ private final Map<String, Collection<Cluster>> conformingClusters = Maps.newHashMap(); /** * Clusters that the monkey failed to check for some reason. */ private final Map<String, Collection<Cluster>> failedClusters = Maps.newHashMap(); /** * Clusters that do not exist in the cloud anymore. */ private final Map<String, Collection<Cluster>> nonexistentClusters = Maps.newHashMap(); /** * Instantiates a new basic conformity monkey. * * @param ctx * the ctx */ public BasicConformityMonkey(Context ctx) { super(ctx); cfg = ctx.configuration(); crawler = ctx.clusterCrawler(); ruleEngine = ctx.ruleEngine(); emailNotifier = ctx.emailNotifier(); for (String region : ctx.regions()) { regions.add(region); } clusterTracker = ctx.clusterTracker(); calendar = ctx.calendar(); leashed = ctx.isLeashed(); } /** {@inheritDoc} */ @Override public void doMonkeyBusiness() { cfg.reload(); context().resetEventReport(); if (isConformityMonkeyEnabled()) { nonconformingClusters.clear(); conformingClusters.clear(); failedClusters.clear(); nonexistentClusters.clear(); List<Cluster> clusters = crawler.clusters(); Map<String, Set<String>> existingClusterNamesByRegion = Maps.newHashMap(); for (String region : regions) { existingClusterNamesByRegion.put(region, new HashSet<String>()); } for (Cluster cluster : clusters) { existingClusterNamesByRegion.get(cluster.getRegion()).add(cluster.getName()); } List<Cluster> trackedClusters = clusterTracker.getAllClusters(regions.toArray(new String[regions.size()])); for (Cluster trackedCluster : trackedClusters) { if (!existingClusterNamesByRegion.get(trackedCluster.getRegion()).contains(trackedCluster.getName())) { addCluster(nonexistentClusters, trackedCluster); } } for (String region : regions) { Collection<Cluster> toDelete = nonexistentClusters.get(region); if (toDelete != null) { clusterTracker.deleteClusters(toDelete.toArray(new Cluster[toDelete.size()])); } } LOGGER.info(String.format("Performing conformity check for %d crawled clusters.", clusters.size())); Date now = calendar.now().getTime(); for (Cluster cluster : clusters) { boolean conforming; try { conforming = ruleEngine.check(cluster); } catch (Exception e) { LOGGER.error(String.format("Failed to perform conformity check for cluster %s", cluster.getName()), e); addCluster(failedClusters, cluster); continue; } cluster.setUpdateTime(now); cluster.setConforming(conforming); if (conforming) { LOGGER.info(String.format("Cluster %s is conforming", cluster.getName())); addCluster(conformingClusters, cluster); } else { LOGGER.info(String.format("Cluster %s is not conforming", cluster.getName())); addCluster(nonconformingClusters, cluster); } if (!leashed) { LOGGER.info(String.format("Saving cluster %s", cluster.getName())); clusterTracker.addOrUpdate(cluster); } else { LOGGER.info(String.format( "The conformity monkey is leashed, no data change is made for cluster %s.", cluster.getName())); } } if (!leashed) { emailNotifier.sendNotifications(); } else { LOGGER.info("Conformity monkey is leashed, no notification is sent."); } if (cfg.getBoolOrElse(NS + "summaryEmail.enabled", true)) { sendConformitySummaryEmail(); } } } private static void addCluster(Map<String, Collection<Cluster>> map, Cluster cluster) { Collection<Cluster> clusters = map.get(cluster.getRegion()); if (clusters == null) { clusters = Lists.newArrayList(); map.put(cluster.getRegion(), clusters); } clusters.add(cluster); } /** * Send a summary email with about the last run of the conformity monkey. */ protected void sendConformitySummaryEmail() { String summaryEmailTarget = cfg.getStr(NS + "summaryEmail.to"); if (!StringUtils.isEmpty(summaryEmailTarget)) { if (!emailNotifier.isValidEmail(summaryEmailTarget)) { LOGGER.error(String.format("The email target address '%s' for Conformity summary email is invalid", summaryEmailTarget)); return; } StringBuilder message = new StringBuilder(); for (String region : regions) { appendSummary(message, "nonconforming", nonconformingClusters, region, true); appendSummary(message, "failed to check", failedClusters, region, true); appendSummary(message, "nonexistent", nonexistentClusters, region, true); appendSummary(message, "conforming", conformingClusters, region, false); } String subject = getSummaryEmailSubject(); emailNotifier.sendEmail(summaryEmailTarget, subject, message.toString()); } } private void appendSummary(StringBuilder message, String summaryName, Map<String, Collection<Cluster>> regionToClusters, String region, boolean showDetails) { Collection<Cluster> clusters = regionToClusters.get(region); if (clusters == null) { clusters = Lists.newArrayList(); } message.append(String.format("Total %s clusters = %d in region %s<br/>", summaryName, clusters.size(), region)); if (showDetails) { List<String> clusterNames = Lists.newArrayList(); for (Cluster cluster : clusters) { clusterNames.add(cluster.getName()); } message.append(String.format("List: %s<br/><br/>", StringUtils.join(clusterNames, ","))); } } /** * Gets the summary email subject for the last run of conformity monkey. * @return the subject of the summary email */ protected String getSummaryEmailSubject() { return String.format("Conformity monkey execution summary (%s)", StringUtils.join(regions, ",")); } private boolean isConformityMonkeyEnabled() { String prop = NS + "enabled"; if (cfg.getBoolOrElse(prop, true)) { return true; } LOGGER.info("Conformity Monkey is disabled, set {}=true", prop); return false; } }
4,796
0
Create_ds/SimianArmy/src/main/java/com/netflix/simianarmy/basic
Create_ds/SimianArmy/src/main/java/com/netflix/simianarmy/basic/conformity/BasicConformityMonkeyContext.java
/* * Copyright 2013 Netflix, Inc. * * Licensed 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. * */ // CHECKSTYLE IGNORE MagicNumberCheck package com.netflix.simianarmy.basic.conformity; import java.util.Collection; import java.util.Map; import org.apache.commons.lang.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.amazonaws.regions.Region; import com.amazonaws.regions.Regions; import com.amazonaws.services.simpleemail.AmazonSimpleEmailServiceClient; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import com.google.inject.Guice; import com.google.inject.Injector; import com.netflix.discovery.DiscoveryClient; import com.netflix.discovery.guice.EurekaModule; import com.netflix.simianarmy.aws.conformity.RDSConformityClusterTracker; import com.netflix.simianarmy.aws.conformity.SimpleDBConformityClusterTracker; import com.netflix.simianarmy.aws.conformity.crawler.AWSClusterCrawler; import com.netflix.simianarmy.aws.conformity.rule.BasicConformityEurekaClient; import com.netflix.simianarmy.aws.conformity.rule.ConformityEurekaClient; import com.netflix.simianarmy.aws.conformity.rule.CrossZoneLoadBalancing; import com.netflix.simianarmy.aws.conformity.rule.InstanceHasHealthCheckUrl; import com.netflix.simianarmy.aws.conformity.rule.InstanceHasStatusUrl; import com.netflix.simianarmy.aws.conformity.rule.InstanceInSecurityGroup; import com.netflix.simianarmy.aws.conformity.rule.InstanceInVPC; import com.netflix.simianarmy.aws.conformity.rule.InstanceIsHealthyInEureka; import com.netflix.simianarmy.aws.conformity.rule.InstanceTooOld; import com.netflix.simianarmy.aws.conformity.rule.SameZonesInElbAndAsg; import com.netflix.simianarmy.basic.BasicSimianArmyContext; import com.netflix.simianarmy.client.aws.AWSClient; import com.netflix.simianarmy.conformity.ClusterCrawler; import com.netflix.simianarmy.conformity.ConformityClusterTracker; import com.netflix.simianarmy.conformity.ConformityEmailBuilder; import com.netflix.simianarmy.conformity.ConformityEmailNotifier; import com.netflix.simianarmy.conformity.ConformityMonkey; import com.netflix.simianarmy.conformity.ConformityRule; import com.netflix.simianarmy.conformity.ConformityRuleEngine; /** * The basic implementation of the context class for Conformity monkey. */ public class BasicConformityMonkeyContext extends BasicSimianArmyContext implements ConformityMonkey.Context { /** The Constant LOGGER. */ private static final Logger LOGGER = LoggerFactory.getLogger(BasicConformityMonkeyContext.class); /** The email notifier. */ private final ConformityEmailNotifier emailNotifier; private final ConformityClusterTracker clusterTracker; private final Collection<String> regions; private final ClusterCrawler clusterCrawler; private final AmazonSimpleEmailServiceClient sesClient; private final ConformityEmailBuilder conformityEmailBuilder; private final String defaultEmail; private final String[] ccEmails; private final String sourceEmail; private final ConformityRuleEngine ruleEngine; private final boolean leashed; private final Map<String, AWSClient> regionToAwsClient = Maps.newHashMap(); /** * The constructor. */ public BasicConformityMonkeyContext() { super("simianarmy.properties", "client.properties", "conformity.properties"); regions = Lists.newArrayList(region()); // By default, the monkey is leashed leashed = configuration().getBoolOrElse("simianarmy.conformity.leashed", true); LOGGER.info(String.format("Conformity Monkey is running in: %s", regions)); String sdbDomain = configuration().getStrOrElse("simianarmy.conformity.sdb.domain", "SIMIAN_ARMY"); String dbDriver = configuration().getStr("simianarmy.recorder.db.driver"); String dbUser = configuration().getStr("simianarmy.recorder.db.user"); String dbPass = configuration().getStr("simianarmy.recorder.db.pass"); String dbUrl = configuration().getStr("simianarmy.recorder.db.url"); String dbTable = configuration().getStr("simianarmy.conformity.resources.db.table"); if (dbDriver == null) { clusterTracker = new SimpleDBConformityClusterTracker(awsClient(), sdbDomain); } else { RDSConformityClusterTracker rdsClusterTracker = new RDSConformityClusterTracker(dbDriver, dbUser, dbPass, dbUrl, dbTable); rdsClusterTracker.init(); clusterTracker = rdsClusterTracker; } ruleEngine = new ConformityRuleEngine(); boolean eurekaEnabled = configuration().getBoolOrElse("simianarmy.conformity.Eureka.enabled", false); if (eurekaEnabled) { LOGGER.info("Initializing Discovery client."); Injector injector = Guice.createInjector(new EurekaModule()); DiscoveryClient discoveryClient = injector.getInstance(DiscoveryClient.class); ConformityEurekaClient conformityEurekaClient = new BasicConformityEurekaClient(discoveryClient); if (configuration().getBoolOrElse( "simianarmy.conformity.rule.InstanceIsHealthyInEureka.enabled", false)) { ruleEngine.addRule(new InstanceIsHealthyInEureka(conformityEurekaClient)); } if (configuration().getBoolOrElse( "simianarmy.conformity.rule.InstanceHasHealthCheckUrl.enabled", false)) { ruleEngine.addRule(new InstanceHasHealthCheckUrl(conformityEurekaClient)); } if (configuration().getBoolOrElse( "simianarmy.conformity.rule.InstanceHasStatusUrl.enabled", false)) { ruleEngine.addRule(new InstanceHasStatusUrl(conformityEurekaClient)); } } else { LOGGER.info("Discovery/Eureka is not enabled, the conformity rules that need Eureka are not added."); } if (configuration().getBoolOrElse( "simianarmy.conformity.rule.InstanceInSecurityGroup.enabled", false)) { String requiredSecurityGroups = configuration().getStr( "simianarmy.conformity.rule.InstanceInSecurityGroup.requiredSecurityGroups"); if (!StringUtils.isBlank(requiredSecurityGroups)) { ruleEngine.addRule(new InstanceInSecurityGroup(getAwsCredentialsProvider(), StringUtils.split(requiredSecurityGroups, ","))); } else { LOGGER.info("No required security groups is specified, " + "the conformity rule InstanceInSecurityGroup is ignored."); } } if (configuration().getBoolOrElse( "simianarmy.conformity.rule.InstanceTooOld.enabled", false)) { ruleEngine.addRule(new InstanceTooOld(getAwsCredentialsProvider(), (int) configuration().getNumOrElse( "simianarmy.conformity.rule.InstanceTooOld.instanceAgeThreshold", 180))); } if (configuration().getBoolOrElse( "simianarmy.conformity.rule.SameZonesInElbAndAsg.enabled", false)) { ruleEngine().addRule(new SameZonesInElbAndAsg(getAwsCredentialsProvider())); } if (configuration().getBoolOrElse( "simianarmy.conformity.rule.InstanceInVPC.enabled", false)) { ruleEngine.addRule(new InstanceInVPC(getAwsCredentialsProvider())); } if (configuration().getBoolOrElse( "simianarmy.conformity.rule.CrossZoneLoadBalancing.enabled", false)) { ruleEngine().addRule(new CrossZoneLoadBalancing(getAwsCredentialsProvider())); } createClient(region()); regionToAwsClient.put(region(), awsClient()); clusterCrawler = new AWSClusterCrawler(regionToAwsClient, configuration()); sesClient = new AmazonSimpleEmailServiceClient(); if (configuration().getStr("simianarmy.aws.email.region") != null) { sesClient.setRegion(Region.getRegion(Regions.fromName(configuration().getStr("simianarmy.aws.email.region")))); } defaultEmail = configuration().getStrOrElse("simianarmy.conformity.notification.defaultEmail", null); ccEmails = StringUtils.split( configuration().getStrOrElse("simianarmy.conformity.notification.ccEmails", ""), ","); sourceEmail = configuration().getStrOrElse("simianarmy.conformity.notification.sourceEmail", null); conformityEmailBuilder = new BasicConformityEmailBuilder(); emailNotifier = new ConformityEmailNotifier(getConformityEmailNotifierContext()); } public ConformityEmailNotifier.Context getConformityEmailNotifierContext() { return new ConformityEmailNotifier.Context() { @Override public AmazonSimpleEmailServiceClient sesClient() { return sesClient; } @Override public int openHour() { return (int) configuration().getNumOrElse("simianarmy.conformity.notification.openHour", 0); } @Override public int closeHour() { return (int) configuration().getNumOrElse("simianarmy.conformity.notification.closeHour", 24); } @Override public String defaultEmail() { return defaultEmail; } @Override public Collection<String> regions() { return regions; } @Override public ConformityClusterTracker clusterTracker() { return clusterTracker; } @Override public ConformityEmailBuilder emailBuilder() { return conformityEmailBuilder; } @Override public String[] ccEmails() { return ccEmails; } @Override public Collection<ConformityRule> rules() { return ruleEngine.rules(); } @Override public String sourceEmail() { return sourceEmail; } }; } @Override public ClusterCrawler clusterCrawler() { return clusterCrawler; } @Override public ConformityRuleEngine ruleEngine() { return ruleEngine; } /** {@inheritDoc} */ @Override public ConformityEmailNotifier emailNotifier() { return emailNotifier; } @Override public Collection<String> regions() { return regions; } @Override public boolean isLeashed() { return leashed; } @Override public ConformityClusterTracker clusterTracker() { return clusterTracker; } }
4,797
0
Create_ds/SimianArmy/src/main/java/com/netflix/simianarmy/basic
Create_ds/SimianArmy/src/main/java/com/netflix/simianarmy/basic/conformity/BasicConformityEmailBuilder.java
/* * * Copyright 2013 Netflix, Inc. * * Licensed 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 com.netflix.simianarmy.basic.conformity; import com.google.common.collect.Maps; import com.netflix.simianarmy.conformity.Cluster; import com.netflix.simianarmy.conformity.Conformity; import com.netflix.simianarmy.conformity.ConformityEmailBuilder; import com.netflix.simianarmy.conformity.ConformityRule; import org.apache.commons.lang.StringUtils; import org.apache.commons.lang.Validate; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.Collection; import java.util.Map; /** The basic implementation of the email builder for Conformity monkey. */ public class BasicConformityEmailBuilder extends ConformityEmailBuilder { private static final String[] TABLE_COLUMNS = {"Cluster", "Region", "Rule", "Failed Components"}; private static final String AHREF_TEMPLATE = "<a href=\"%s\">%s</a>"; private static final Logger LOGGER = LoggerFactory.getLogger(BasicConformityEmailBuilder.class); private Map<String, Collection<Cluster>> emailToClusters; private final Map<String, ConformityRule> idToRule = Maps.newHashMap(); @Override public void setEmailToClusters(Map<String, Collection<Cluster>> clustersByEmail, Collection<ConformityRule> rules) { Validate.notNull(clustersByEmail); Validate.notNull(rules); this.emailToClusters = clustersByEmail; idToRule.clear(); for (ConformityRule rule : rules) { idToRule.put(rule.getName(), rule); } } @Override protected String getHeader() { StringBuilder header = new StringBuilder(); header.append("<b><h2>Conformity Report</h2></b>"); header.append("The following is a list of failed conformity rules for your cluster(s).<br/>"); return header.toString(); } @Override protected String getEntryTable(String emailAddress) { StringBuilder table = new StringBuilder(); table.append(getHtmlTableHeader(getTableColumns())); for (Cluster cluster : emailToClusters.get(emailAddress)) { for (Conformity conformity : cluster.getConformties()) { if (!conformity.getFailedComponents().isEmpty()) { table.append(getClusterRow(cluster, conformity)); } } } table.append("</table>"); return table.toString(); } @Override protected String getFooter() { return "<br/>Conformity Monkey wiki: https://github.com/Netflix/SimianArmy/wiki<br/>"; } /** * Gets the url to view the details of the cluster. * @param cluster the cluster * @return the url to view/edit the cluster. */ protected String getClusterUrl(Cluster cluster) { return null; } /** * Gets the string when displaying the cluster, e.g. the id. * @param cluster the cluster to display * @return the string to represent the cluster */ protected String getClusterDisplay(Cluster cluster) { return cluster.getName(); } /** Gets the table columns for the table in the email. * * @return the array of column names */ protected String[] getTableColumns() { return TABLE_COLUMNS; } /** * Gets the row for a cluster and a failed conformity check in the table in the email body. * @param cluster the cluster to display * @param conformity the failed conformity check * @return the table row in the email body */ protected String getClusterRow(Cluster cluster, Conformity conformity) { StringBuilder message = new StringBuilder(); message.append("<tr>"); String clusterUrl = getClusterUrl(cluster); if (!StringUtils.isEmpty(clusterUrl)) { message.append(getHtmlCell(String.format(AHREF_TEMPLATE, clusterUrl, getClusterDisplay(cluster)))); } else { message.append(getHtmlCell(getClusterDisplay(cluster))); } message.append(getHtmlCell(cluster.getRegion())); ConformityRule rule = idToRule.get(conformity.getRuleId()); String ruleDesc; if (rule == null) { LOGGER.warn(String.format("Not found rule with name %s", conformity.getRuleId())); ruleDesc = conformity.getRuleId(); } else { ruleDesc = rule.getNonconformingReason(); } message.append(getHtmlCell(ruleDesc)); message.append(getHtmlCell(StringUtils.join(conformity.getFailedComponents(), ","))); message.append("</tr>"); return message.toString(); } }
4,798
0
Create_ds/SimianArmy/src/main/java/com/netflix/simianarmy/basic
Create_ds/SimianArmy/src/main/java/com/netflix/simianarmy/basic/janitor/BasicJanitorMonkey.java
/* * * Copyright 2012 Netflix, Inc. * * Licensed 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 com.netflix.simianarmy.basic.janitor; import java.util.Collection; import java.util.List; import java.util.concurrent.atomic.AtomicLong; import com.netflix.servo.annotations.DataSourceType; import com.netflix.servo.annotations.Monitor; import com.netflix.servo.monitor.Monitors; import com.netflix.simianarmy.*; import com.netflix.simianarmy.MonkeyRecorder.Event; import com.netflix.simianarmy.janitor.AbstractJanitor; import com.netflix.simianarmy.janitor.JanitorEmailNotifier; import com.netflix.simianarmy.janitor.JanitorMonkey; import com.netflix.simianarmy.janitor.JanitorResourceTracker; import org.apache.commons.lang.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** The basic implementation of Janitor Monkey. */ public class BasicJanitorMonkey extends JanitorMonkey { /** The Constant LOGGER. */ private static final Logger LOGGER = LoggerFactory.getLogger(BasicJanitorMonkey.class); /** The Constant NS. */ private static final String NS = "simianarmy.janitor."; /** The cfg. */ private final MonkeyConfiguration cfg; private final List<AbstractJanitor> janitors; private final JanitorEmailNotifier emailNotifier; private final String region; private final String accountName; private final JanitorResourceTracker resourceTracker; private final MonkeyRecorder recorder; private final MonkeyCalendar calendar; /** Keep track of the number of monkey runs */ protected final AtomicLong monkeyRuns = new AtomicLong(0); /** Keep track of the number of monkey errors */ protected final AtomicLong monkeyErrors = new AtomicLong(0); /** Emit a servor signal to track the running monkey */ protected final AtomicLong monkeyRunning = new AtomicLong(0); /** * Instantiates a new basic janitor monkey. * * @param ctx * the ctx */ public BasicJanitorMonkey(Context ctx) { super(ctx); this.cfg = ctx.configuration(); janitors = ctx.janitors(); emailNotifier = ctx.emailNotifier(); region = ctx.region(); accountName = ctx.accountName(); resourceTracker = ctx.resourceTracker(); recorder = ctx.recorder(); calendar = ctx.calendar(); // register this janitor with servo Monitors.registerObject("simianarmy.janitor", this); } /** {@inheritDoc} */ @Override public void doMonkeyBusiness() { cfg.reload(); context().resetEventReport(); if (!isJanitorMonkeyEnabled()) { return; } else { LOGGER.info(String.format("Marking resources with %d janitors.", janitors.size())); monkeyRuns.incrementAndGet(); monkeyRunning.set(1); // prepare to run, this just resets the counts so monitoring is sane for (AbstractJanitor janitor : janitors) { janitor.prepareToRun(); } for (AbstractJanitor janitor : janitors) { LOGGER.info(String.format("Running %s janitor for region %s", janitor.getResourceType(), janitor.getRegion())); try { janitor.markResources(); } catch (Exception e) { monkeyErrors.incrementAndGet(); LOGGER.error(String.format("Got an exception while %s janitor was marking for region %s", janitor.getResourceType(), janitor.getRegion()), e); } LOGGER.info(String.format("Marked %d resources of type %s in the last run.", janitor.getMarkedResources().size(), janitor.getResourceType().name())); LOGGER.info(String.format("Unmarked %d resources of type %s in the last run.", janitor.getUnmarkedResources().size(), janitor.getResourceType())); } if (!cfg.getBoolOrElse("simianarmy.janitor.leashed", true)) { emailNotifier.sendNotifications(); } else { LOGGER.info("Janitor Monkey is leashed, no notification is sent."); } LOGGER.info(String.format("Cleaning resources with %d janitors.", janitors.size())); for (AbstractJanitor janitor : janitors) { try { janitor.cleanupResources(); } catch (Exception e) { monkeyErrors.incrementAndGet(); LOGGER.error(String.format("Got an exception while %s janitor was cleaning for region %s", janitor.getResourceType(), janitor.getRegion()), e); } LOGGER.info(String.format("Cleaned %d resources of type %s in the last run.", janitor.getCleanedResources().size(), janitor.getResourceType())); LOGGER.info(String.format("Failed to clean %d resources of type %s in the last run.", janitor.getFailedToCleanResources().size(), janitor.getResourceType())); } if (cfg.getBoolOrElse(NS + "summaryEmail.enabled", true)) { sendJanitorSummaryEmail(); } monkeyRunning.set(0); } } @Override public Event optInResource(String resourceId) { return optInOrOutResource(resourceId, true, region); } @Override public Event optOutResource(String resourceId) { return optInOrOutResource(resourceId, false, region); } @Override public Event optInResource(String resourceId, String resourceRegion) { return optInOrOutResource(resourceId, true, resourceRegion); } @Override public Event optOutResource(String resourceId, String resourceRegion) { return optInOrOutResource(resourceId, false, resourceRegion); } private Event optInOrOutResource(String resourceId, boolean optIn, String resourceRegion) { if (resourceRegion == null) { resourceRegion = region; } Resource resource = resourceTracker.getResource(resourceId, resourceRegion); if (resource == null) { return null; } EventTypes eventType = optIn ? EventTypes.OPT_IN_RESOURCE : EventTypes.OPT_OUT_RESOURCE; long timestamp = calendar.now().getTimeInMillis(); // The same resource can have multiple events, so we add the timestamp to the id. Event evt = recorder.newEvent(Type.JANITOR, eventType, resource, resourceId + "@" + timestamp); recorder.recordEvent(evt); resource.setOptOutOfJanitor(!optIn); resourceTracker.addOrUpdate(resource); return evt; } /** * Send a summary email with about the last run of the janitor monkey. */ protected void sendJanitorSummaryEmail() { String summaryEmailTarget = cfg.getStr(NS + "summaryEmail.to"); if (!StringUtils.isEmpty(summaryEmailTarget)) { if (!emailNotifier.isValidEmail(summaryEmailTarget)) { LOGGER.error(String.format("The email target address '%s' for Janitor summary email is invalid", summaryEmailTarget)); return; } StringBuilder message = new StringBuilder(); for (AbstractJanitor janitor : janitors) { ResourceType resourceType = janitor.getResourceType(); appendSummary(message, "markings", resourceType, janitor.getMarkedResources(), janitor.getRegion()); appendSummary(message, "unmarkings", resourceType, janitor.getUnmarkedResources(), janitor.getRegion()); appendSummary(message, "cleanups", resourceType, janitor.getCleanedResources(), janitor.getRegion()); appendSummary(message, "cleanup failures", resourceType, janitor.getFailedToCleanResources(), janitor.getRegion()); } String subject = getSummaryEmailSubject(); emailNotifier.sendEmail(summaryEmailTarget, subject, message.toString()); } } private void appendSummary(StringBuilder message, String summaryName, ResourceType resourceType, Collection<Resource> resources, String janitorRegion) { message.append(String.format("Total %s for %s = %d in region %s<br/>", summaryName, resourceType.name(), resources.size(), janitorRegion)); message.append(String.format("List: %s<br/>", printResources(resources))); } private String printResources(Collection<Resource> resources) { StringBuilder sb = new StringBuilder(); boolean isFirst = true; for (Resource r : resources) { if (!isFirst) { sb.append(","); } else { isFirst = false; } sb.append(r.getId()); } return sb.toString(); } /** * Gets the summary email subject for the last run of janitor monkey. * @return the subject of the summary email */ protected String getSummaryEmailSubject() { return String.format("Janitor monkey execution summary (%s, %s)", accountName, region); } /** * Handle cleanup error. This has been abstracted so subclasses can decide to continue causing chaos if desired. * * @param resource * the instance * @param e * the exception */ protected void handleCleanupError(Resource resource, Throwable e) { String msg = String.format("Failed to clean up %s resource %s with error %s", resource.getResourceType(), resource.getId(), e.getMessage()); LOGGER.error(msg); throw new RuntimeException(msg, e); } private boolean isJanitorMonkeyEnabled() { String prop = NS + "enabled"; if (cfg.getBoolOrElse(prop, true)) { return true; } LOGGER.info("JanitorMonkey disabled, set {}=true", prop); return false; } @Monitor(name="runs", type=DataSourceType.COUNTER) public long getMonkeyRuns() { return monkeyRuns.get(); } @Monitor(name="errors", type=DataSourceType.GAUGE) public long getMonkeyErrors() { return monkeyErrors.get(); } @Monitor(name="running", type=DataSourceType.GAUGE) public long getMonkeyRunning() { return monkeyRunning.get(); } }
4,799