repo
stringlengths 1
191
⌀ | file
stringlengths 23
351
| code
stringlengths 0
5.32M
| file_length
int64 0
5.32M
| avg_line_length
float64 0
2.9k
| max_line_length
int64 0
288k
| extension_type
stringclasses 1
value |
|---|---|---|---|---|---|---|
SimianArmy
|
SimianArmy-master/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();
}
}
| 1,249
| 23.509804
| 79
|
java
|
SimianArmy
|
SimianArmy-master/src/test/java/com/netflix/simianarmy/TestUtils.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 static org.joda.time.DateTimeConstants.MILLIS_PER_DAY;
import org.joda.time.DateTime;
import org.testng.Assert;
/** Utility class for test cases.
* @author mgeis
*
*/
public final class TestUtils {
private TestUtils() {
//this should never be called
//if called internally, throw an error
throw new InstantiationError("Instantiation of TestUtils utility class prohibited.");
}
/** Verify that the termination date is roughly retentionDays from now
* By 'roughly' we mean within one day. There are times (twice per year)
* when certain tests execute and the Daylight Savings cutover makes it not
* a precisely rounded day amount (for example, a termination policy of 4 days
* will really be about 3.95 days, or 95 hours, because one hour is lost as
* the clocks "spring ahead").
*
* A more precise, but complicated logic could be written to make sure that "roughly"
* means not more than an hour before and not more than an hour after the anticipated
* cutoff, but that makes the test much less readable.
*
* By just making sure that the difference between the actual and proposed dates
* is less than one day, we get a rough idea of whether the termination time was correct.
* @param resource The AWS Resource to be checked
* @param retentionDays number of days it should be kept around
* @param timeOfCheck The time the check is run
*/
public static void verifyTerminationTimeRough(Resource resource, int retentionDays, DateTime timeOfCheck) {
long days = (resource.getExpectedTerminationTime().getTime() - timeOfCheck.getMillis()) / MILLIS_PER_DAY;
Assert.assertTrue(Math.abs(days - retentionDays) <= 1);
}
}
| 2,440
| 39.683333
| 113
|
java
|
SimianArmy
|
SimianArmy-master/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();
}
}
| 8,258
| 29.588889
| 120
|
java
|
SimianArmy
|
SimianArmy-master/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);
}
}
| 3,317
| 27.358974
| 94
|
java
|
SimianArmy
|
SimianArmy-master/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,582
| 36.260163
| 113
|
java
|
SimianArmy
|
SimianArmy-master/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) );
}
}
| 5,926
| 34.071006
| 86
|
java
|
SimianArmy
|
SimianArmy-master/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");
}
}
| 2,859
| 30.777778
| 118
|
java
|
SimianArmy
|
SimianArmy-master/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);
}
}
}
| 2,875
| 39.507042
| 114
|
java
|
SimianArmy
|
SimianArmy-master/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;
}
}
| 7,999
| 43.94382
| 119
|
java
|
SimianArmy
|
SimianArmy-master/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());
}
}
| 3,341
| 36.133333
| 110
|
java
|
SimianArmy
|
SimianArmy-master/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;
}
}
| 3,581
| 38.362637
| 109
|
java
|
SimianArmy
|
SimianArmy-master/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);
}
}
| 1,216
| 31.026316
| 75
|
java
|
SimianArmy
|
SimianArmy-master/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);
}
}
| 2,190
| 33.777778
| 137
|
java
|
SimianArmy
|
SimianArmy-master/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;
}
}
| 30,267
| 43.122449
| 145
|
java
|
SimianArmy
|
SimianArmy-master/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;
}
}
| 3,998
| 38.205882
| 147
|
java
|
SimianArmy
|
SimianArmy-master/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");
}
}
| 1,436
| 27.74
| 116
|
java
|
SimianArmy
|
SimianArmy-master/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);
}
}
| 9,072
| 40.240909
| 119
|
java
|
SimianArmy
|
SimianArmy-master/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);
}
}
| 7,612
| 39.71123
| 228
|
java
|
SimianArmy
|
SimianArmy-master/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;
}
}
| 5,910
| 36.891026
| 120
|
java
|
SimianArmy
|
SimianArmy-master/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;
}
}
| 11,354
| 50.38009
| 112
|
java
|
SimianArmy
|
SimianArmy-master/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);
}
}
| 19,453
| 53.954802
| 463
|
java
|
SimianArmy
|
SimianArmy-master/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());
}
}
| 1,644
| 25.532258
| 79
|
java
|
SimianArmy
|
SimianArmy-master/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());
}
}
| 8,054
| 44.767045
| 119
|
java
|
SimianArmy
|
SimianArmy-master/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));
}
}
| 5,383
| 37.733813
| 145
|
java
|
SimianArmy
|
SimianArmy-master/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());
}
}
| 6,208
| 46.037879
| 151
|
java
|
SimianArmy
|
SimianArmy-master/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);
}
}
| 14,789
| 49.650685
| 123
|
java
|
SimianArmy
|
SimianArmy-master/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());
}
}
| 9,357
| 48.252632
| 119
|
java
|
SimianArmy
|
SimianArmy-master/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);
}
}
| 9,367
| 47.791667
| 119
|
java
|
SimianArmy
|
SimianArmy-master/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());
}
}
| 7,354
| 46.451613
| 119
|
java
|
SimianArmy
|
SimianArmy-master/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,557
| 40.816514
| 102
|
java
|
SimianArmy
|
SimianArmy-master/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);
}
}
| 10,081
| 45.460829
| 161
|
java
|
SimianArmy
|
SimianArmy-master/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"));
}
}
| 6,647
| 43.32
| 114
|
java
|
SimianArmy
|
SimianArmy-master/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,865
| 37.928
| 96
|
java
|
SimianArmy
|
SimianArmy-master/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,746
| 38.558333
| 108
|
java
|
SimianArmy
|
SimianArmy-master/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);
}
}
| 5,786
| 38.910345
| 108
|
java
|
SimianArmy
|
SimianArmy-master/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;
}
}
| 7,751
| 38.55102
| 111
|
java
|
SimianArmy
|
SimianArmy-master/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,883
| 39.7
| 114
|
java
|
SimianArmy
|
SimianArmy-master/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;
}
}
| 3,439
| 38.54023
| 120
|
java
|
SimianArmy
|
SimianArmy-master/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);
}
}
| 9,165
| 46.739583
| 325
|
java
|
SimianArmy
|
SimianArmy-master/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);
}
}
| 3,819
| 40.521739
| 96
|
java
|
SimianArmy
|
SimianArmy-master/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;
}
}
| 2,974
| 34.416667
| 93
|
java
|
SimianArmy
|
SimianArmy-master/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), ","));
}
}
| 3,363
| 36.797753
| 94
|
java
|
SimianArmy
|
SimianArmy-master/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");
}
}
| 2,448
| 32.094595
| 100
|
java
|
SimianArmy
|
SimianArmy-master/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,378
| 36.110169
| 108
|
java
|
SimianArmy
|
SimianArmy-master/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"), "");
}
}
| 2,846
| 30.285714
| 79
|
java
|
SimianArmy
|
SimianArmy-master/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);
}
}
| 7,579
| 34.924171
| 98
|
java
|
SimianArmy
|
SimianArmy-master/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);
}
}
| 2,334
| 31.430556
| 103
|
java
|
SimianArmy
|
SimianArmy-master/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");
}
}
| 3,380
| 38.313953
| 108
|
java
|
SimianArmy
|
SimianArmy-master/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?");
}
}
| 6,256
| 39.62987
| 94
|
java
|
SimianArmy
|
SimianArmy-master/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;
}
}
| 5,118
| 35.304965
| 97
|
java
|
SimianArmy
|
SimianArmy-master/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);
}
}
| 8,985
| 46.04712
| 116
|
java
|
SimianArmy
|
SimianArmy-master/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");
}
}
}
| 23,675
| 44.706564
| 138
|
java
|
SimianArmy
|
SimianArmy-master/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,519
| 45.597938
| 111
|
java
|
SimianArmy
|
SimianArmy-master/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());
}
}
}
| 5,831
| 35.911392
| 152
|
java
|
SimianArmy
|
SimianArmy-master/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);
}
}
| 10,598
| 31.215805
| 111
|
java
|
SimianArmy
|
SimianArmy-master/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;
}
}
| 15,512
| 31.251559
| 122
|
java
|
SimianArmy
|
SimianArmy-master/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");
}
}
}
| 9,654
| 40.796537
| 120
|
java
|
SimianArmy
|
SimianArmy-master/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();
}
| 819
| 25.451613
| 79
|
java
|
SimianArmy
|
SimianArmy-master/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);
}
| 2,595
| 28.5
| 98
|
java
|
SimianArmy
|
SimianArmy-master/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,104
| 23.005848
| 113
|
java
|
SimianArmy
|
SimianArmy-master/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,565
| 25.241379
| 110
|
java
|
SimianArmy
|
SimianArmy-master/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 {
}
| 784
| 29.192308
| 79
|
java
|
SimianArmy
|
SimianArmy-master/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 {
}
| 790
| 29.423077
| 79
|
java
|
SimianArmy
|
SimianArmy-master/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);
}
| 1,764
| 28.416667
| 115
|
java
|
SimianArmy
|
SimianArmy-master/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 {
}
| 784
| 29.192308
| 79
|
java
|
SimianArmy
|
SimianArmy-master/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);
}
}
| 1,748
| 30.8
| 84
|
java
|
SimianArmy
|
SimianArmy-master/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);
}
| 963
| 32.241379
| 79
|
java
|
SimianArmy
|
SimianArmy-master/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);
}
| 6,586
| 28.940909
| 118
|
java
|
SimianArmy
|
SimianArmy-master/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 {
}
| 786
| 29.269231
| 79
|
java
|
SimianArmy
|
SimianArmy-master/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);
}
}
| 1,893
| 29.548387
| 118
|
java
|
SimianArmy
|
SimianArmy-master/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);
}
| 1,748
| 28.15
| 79
|
java
|
SimianArmy
|
SimianArmy-master/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);
}
}
| 1,142
| 29.078947
| 85
|
java
|
SimianArmy
|
SimianArmy-master/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);
}
| 1,895
| 27.298507
| 117
|
java
|
SimianArmy
|
SimianArmy-master/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();
}
}
| 2,746
| 31.702381
| 116
|
java
|
SimianArmy
|
SimianArmy-master/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();
}
| 11,589
| 29.025907
| 115
|
java
|
SimianArmy
|
SimianArmy-master/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);
}
}
| 8,516
| 32.797619
| 117
|
java
|
SimianArmy
|
SimianArmy-master/src/main/java/com/netflix/simianarmy/client/MonkeyRestClient.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.client;
import org.apache.commons.lang.Validate;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultServiceUnavailableRetryStrategy;
import org.apache.http.impl.client.HttpClientBuilder;
import org.codehaus.jackson.JsonNode;
import org.codehaus.jackson.map.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.io.InputStream;
import java.util.Scanner;
/**
* A REST client used by monkeys.
*/
public abstract class MonkeyRestClient {
private static final Logger LOGGER = LoggerFactory.getLogger(MonkeyRestClient.class);
private final HttpClient httpClient;
/**
* Constructor.
* @param timeout the timeout in milliseconds
* @param maxRetries the max number of retries
* @param retryInterval the interval in milliseconds between retries
*/
public MonkeyRestClient(int timeout, int maxRetries, int retryInterval) {
Validate.isTrue(timeout >= 0);
Validate.isTrue(maxRetries >= 0);
Validate.isTrue(retryInterval > 0);
RequestConfig config = RequestConfig.custom()
.setConnectTimeout(timeout)
.build();
httpClient = HttpClientBuilder.create()
.setDefaultRequestConfig(config)
.setServiceUnavailableRetryStrategy(new DefaultServiceUnavailableRetryStrategy(maxRetries, retryInterval))
.build();
}
/**
* Gets the response in JSON from a url.
* @param url the url
* @return the JSON node for the response
*/
// CHECKSTYLE IGNORE MagicNumberCheck
public JsonNode getJsonNodeFromUrl(String url) throws IOException {
LOGGER.info(String.format("Getting Json response from url: %s", url));
HttpGet request = new HttpGet(url);
request.setHeader("Accept", "application/json");
HttpResponse response = httpClient.execute(request);
InputStream is = response.getEntity().getContent();
String jsonContent;
if (is != null) {
Scanner s = new Scanner(is, "UTF-8").useDelimiter("\\A");
jsonContent = s.hasNext() ? s.next() : "";
is.close();
} else {
return null;
}
int code = response.getStatusLine().getStatusCode();
if (code == 404) {
return null;
} else if (code >= 300 || code < 200) {
throw new DataReadException(code, url, jsonContent);
}
JsonNode result;
try {
ObjectMapper mapper = new ObjectMapper();
result = mapper.readTree(jsonContent);
} catch (Exception e) {
throw new RuntimeException(String.format("Error trying to parse json response from url %s, got: %s",
url, jsonContent), e);
}
return result;
}
/**
* Gets the base url of the service for a specific region.
* @param region the region
* @return the base url in the region
*/
public abstract String getBaseUrl(String region);
public static class DataReadException extends RuntimeException {
public DataReadException(int code, String url, String jsonContent) {
super(String.format("Response code %d from url %s: %s", code, url, jsonContent));
}
}
}
| 4,120
| 34.222222
| 118
|
java
|
SimianArmy
|
SimianArmy-master/src/main/java/com/netflix/simianarmy/client/aws/AWSClient.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.client.aws;
import com.amazonaws.AmazonServiceException;
import com.amazonaws.ClientConfiguration;
import com.amazonaws.auth.AWSCredentials;
import com.amazonaws.auth.AWSCredentialsProvider;
import com.amazonaws.auth.AWSSessionCredentials;
import com.amazonaws.services.autoscaling.AmazonAutoScalingClient;
import com.amazonaws.services.autoscaling.model.*;
import com.amazonaws.services.ec2.AmazonEC2;
import com.amazonaws.services.ec2.AmazonEC2Client;
import com.amazonaws.services.ec2.model.*;
import com.amazonaws.services.ec2.model.Instance;
import com.amazonaws.services.ec2.model.Tag;
import com.amazonaws.services.elasticloadbalancing.AmazonElasticLoadBalancingClient;
import com.amazonaws.services.elasticloadbalancing.model.*;
import com.amazonaws.services.elasticloadbalancing.model.DescribeLoadBalancersRequest;
import com.amazonaws.services.elasticloadbalancing.model.DescribeLoadBalancersResult;
import com.amazonaws.services.elasticloadbalancing.model.DescribeTagsRequest;
import com.amazonaws.services.elasticloadbalancing.model.DescribeTagsResult;
import com.amazonaws.services.elasticloadbalancing.model.TagDescription;
import com.amazonaws.services.route53.AmazonRoute53Client;
import com.amazonaws.services.route53.model.*;
import com.amazonaws.services.simpledb.AmazonSimpleDB;
import com.amazonaws.services.simpledb.AmazonSimpleDBClient;
import com.google.common.base.Objects;
import com.google.common.base.Strings;
import com.google.common.base.Suppliers;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Iterables;
import com.google.common.collect.Sets;
import com.google.inject.Module;
import com.netflix.simianarmy.CloudClient;
import com.netflix.simianarmy.NotFoundException;
import org.apache.commons.lang.Validate;
import org.jclouds.ContextBuilder;
import org.jclouds.aws.domain.SessionCredentials;
import org.jclouds.compute.ComputeService;
import org.jclouds.compute.ComputeServiceContext;
import org.jclouds.compute.Utils;
import org.jclouds.compute.domain.ComputeMetadata;
import org.jclouds.compute.domain.NodeMetadata;
import org.jclouds.compute.domain.NodeMetadataBuilder;
import org.jclouds.domain.Credentials;
import org.jclouds.domain.LoginCredentials;
import org.jclouds.logging.slf4j.config.SLF4JLoggingModule;
import org.jclouds.ssh.SshClient;
import org.jclouds.ssh.jsch.config.JschSshClientModule;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.*;
/**
* The Class AWSClient. Simple Amazon EC2 and Amazon ASG client interface.
*/
public class AWSClient implements CloudClient {
/** The Constant LOGGER. */
private static final Logger LOGGER = LoggerFactory.getLogger(AWSClient.class);
/** The region. */
private final String region;
/** The plain name for AWS account */
private final String accountName;
/** Maximum retry count for Simple DB */
private static final int SIMPLE_DB_MAX_RETRY = 11;
private final AWSCredentialsProvider awsCredentialsProvider;
private final ClientConfiguration awsClientConfig;
private ComputeService jcloudsComputeService;
/**
* This constructor will let the AWS SDK obtain the credentials, which will
* choose such in the following order:
*
* <ul>
* <li>Environment Variables: {@code AWS_ACCESS_KEY_ID} and
* {@code AWS_SECRET_KEY}</li>
* <li>Java System Properties: {@code aws.accessKeyId} and
* {@code aws.secretKey}</li>
* <li>Instance Metadata Service, which provides the credentials associated
* with the IAM role for the EC2 instance</li>
* </ul>
*
* <p>
* If credentials are provided explicitly, use
* {@link com.netflix.simianarmy.basic.BasicSimianArmyContext#exportCredentials(String, String)}
* which will set them as System properties used by each AWS SDK call.
* </p>
*
* <p>
* <b>Note:</b> Avoid storing credentials received dynamically via the
* {@link com.amazonaws.auth.InstanceProfileCredentialsProvider} as these will be rotated and
* their renewal is handled by its
* {@link com.amazonaws.auth.InstanceProfileCredentialsProvider#getCredentials()} method.
* </p>
*
* @param region
* the region
* @see com.amazonaws.auth.DefaultAWSCredentialsProviderChain
* @see com.amazonaws.auth.InstanceProfileCredentialsProvider
* @see com.netflix.simianarmy.basic.BasicSimianArmyContext#exportCredentials(String, String)
*/
public AWSClient(String region) {
this.region = region;
this.accountName = "Default";
this.awsCredentialsProvider = null;
this.awsClientConfig = null;
}
/**
* The constructor allows you to provide your own AWS credentials provider.
* @param region
* the region
* @param awsCredentialsProvider
* the AWS credentials provider
*/
public AWSClient(String region, AWSCredentialsProvider awsCredentialsProvider) {
this.region = region;
this.accountName = "Default";
this.awsCredentialsProvider = awsCredentialsProvider;
this.awsClientConfig = null;
}
/**
* The constructor allows you to provide your own AWS client configuration.
* @param region
* the region
* @param awsClientConfig
* the AWS client configuration
*/
public AWSClient(String region, ClientConfiguration awsClientConfig) {
this.region = region;
this.accountName = "Default";
this.awsCredentialsProvider = null;
this.awsClientConfig = awsClientConfig;
}
/**
* The constructor allows you to provide your own AWS credentials provider and client config.
* @param region
* the region
* @param awsCredentialsProvider
* the AWS credentials provider
* @param awsClientConfig
* the AWS client configuration
*/
public AWSClient(String region, AWSCredentialsProvider awsCredentialsProvider, ClientConfiguration awsClientConfig) {
this.region = region;
this.accountName = "Default";
this.awsCredentialsProvider = awsCredentialsProvider;
this.awsClientConfig = awsClientConfig;
}
/**
* The Region.
*
* @return the region the client is configured to communicate with
*/
public String region() {
return region;
}
/**
* The accountName.
*
* @return the plain name for the aws account easier to identify which account
* monkey is running in
*/
public String accountName() {
return accountName;
}
/**
* Amazon EC2 client. Abstracted to aid testing.
*
* @return the Amazon EC2 client
*/
protected AmazonEC2 ec2Client() {
AmazonEC2 client;
if (awsClientConfig == null) {
if (awsCredentialsProvider == null) {
client = new AmazonEC2Client();
} else {
client = new AmazonEC2Client(awsCredentialsProvider);
}
} else {
if (awsCredentialsProvider == null) {
client = new AmazonEC2Client(awsClientConfig);
} else {
client = new AmazonEC2Client(awsCredentialsProvider, awsClientConfig);
}
}
client.setEndpoint("ec2." + region + ".amazonaws.com");
return client;
}
/**
* Amazon ASG client. Abstracted to aid testing.
*
* @return the Amazon Auto Scaling client
*/
protected AmazonAutoScalingClient asgClient() {
AmazonAutoScalingClient client;
if (awsClientConfig == null) {
if (awsCredentialsProvider == null) {
client = new AmazonAutoScalingClient();
} else {
client = new AmazonAutoScalingClient(awsCredentialsProvider);
}
} else {
if (awsCredentialsProvider == null) {
client = new AmazonAutoScalingClient(awsClientConfig);
} else {
client = new AmazonAutoScalingClient(awsCredentialsProvider, awsClientConfig);
}
}
client.setEndpoint("autoscaling." + region + ".amazonaws.com");
return client;
}
/**
* Amazon ELB client. Abstracted to aid testing.
*
* @return the Amazon ELB client
*/
protected AmazonElasticLoadBalancingClient elbClient() {
AmazonElasticLoadBalancingClient client;
if (awsClientConfig == null) {
if (awsCredentialsProvider == null) {
client = new AmazonElasticLoadBalancingClient();
} else {
client = new AmazonElasticLoadBalancingClient(awsCredentialsProvider);
}
} else {
if (awsCredentialsProvider == null) {
client = new AmazonElasticLoadBalancingClient(awsClientConfig);
} else {
client = new AmazonElasticLoadBalancingClient(awsCredentialsProvider, awsClientConfig);
}
}
client.setEndpoint("elasticloadbalancing." + region + ".amazonaws.com");
return client;
}
/**
* Amazon Route53 client. Abstracted to aid testing.
*
* @return the Amazon Route53 client
*/
protected AmazonRoute53Client route53Client() {
AmazonRoute53Client client;
if (awsClientConfig == null) {
if (awsCredentialsProvider == null) {
client = new AmazonRoute53Client();
} else {
client = new AmazonRoute53Client(awsCredentialsProvider);
}
} else {
if (awsCredentialsProvider == null) {
client = new AmazonRoute53Client(awsClientConfig);
} else {
client = new AmazonRoute53Client(awsCredentialsProvider, awsClientConfig);
}
}
client.setEndpoint("route53.amazonaws.com");
return client;
}
/**
* Amazon SimpleDB client.
*
* @return the Amazon SimpleDB client
*/
public AmazonSimpleDB sdbClient() {
AmazonSimpleDB client;
ClientConfiguration cc = awsClientConfig;
if (cc == null) {
cc = new ClientConfiguration();
cc.setMaxErrorRetry(SIMPLE_DB_MAX_RETRY);
}
if (awsCredentialsProvider == null) {
client = new AmazonSimpleDBClient(cc);
} else {
client = new AmazonSimpleDBClient(awsCredentialsProvider, cc);
}
// us-east-1 has special naming
// http://docs.amazonwebservices.com/general/latest/gr/rande.html#sdb_region
if (region == null || region.equals("us-east-1")) {
client.setEndpoint("sdb.amazonaws.com");
} else {
client.setEndpoint("sdb." + region + ".amazonaws.com");
}
return client;
}
/**
* Describe auto scaling groups.
*
* @return the list
*/
public List<AutoScalingGroup> describeAutoScalingGroups() {
return describeAutoScalingGroups((String[]) null);
}
/**
* Describe a set of specific auto scaling groups.
*
* @param names the ASG names
* @return the auto scaling groups
*/
public List<AutoScalingGroup> describeAutoScalingGroups(String... names) {
if (names == null || names.length == 0) {
LOGGER.info(String.format("Getting all auto-scaling groups in region %s.", region));
} else {
LOGGER.info(String.format("Getting auto-scaling groups for %d names in region %s.", names.length, region));
}
List<AutoScalingGroup> asgs = new LinkedList<AutoScalingGroup>();
AmazonAutoScalingClient asgClient = asgClient();
DescribeAutoScalingGroupsRequest request = new DescribeAutoScalingGroupsRequest();
if (names != null) {
request.setAutoScalingGroupNames(Arrays.asList(names));
}
DescribeAutoScalingGroupsResult result = asgClient.describeAutoScalingGroups(request);
asgs.addAll(result.getAutoScalingGroups());
while (result.getNextToken() != null) {
request.setNextToken(result.getNextToken());
result = asgClient.describeAutoScalingGroups(request);
asgs.addAll(result.getAutoScalingGroups());
}
LOGGER.info(String.format("Got %d auto-scaling groups in region %s.", asgs.size(), region));
return asgs;
}
/**
* Describe a set of specific ELBs.
*
* @param names the ELB names
* @return the ELBs
*/
public List<LoadBalancerDescription> describeElasticLoadBalancers(String... names) {
if (names == null || names.length == 0) {
LOGGER.info(String.format("Getting all ELBs in region %s.", region));
} else {
LOGGER.info(String.format("Getting ELBs for %d names in region %s.", names.length, region));
}
AmazonElasticLoadBalancingClient elbClient = elbClient();
DescribeLoadBalancersRequest request = new DescribeLoadBalancersRequest().withLoadBalancerNames(names);
DescribeLoadBalancersResult result = elbClient.describeLoadBalancers(request);
List<LoadBalancerDescription> elbs = result.getLoadBalancerDescriptions();
LOGGER.info(String.format("Got %d ELBs in region %s.", elbs.size(), region));
return elbs;
}
/**
* Describe a specific ELB.
*
* @param name the ELB names
* @return the ELBs
*/
public LoadBalancerAttributes describeElasticLoadBalancerAttributes(String name) {
LOGGER.info(String.format("Getting attributes for ELB with name '%s' in region %s.", name, region));
AmazonElasticLoadBalancingClient elbClient = elbClient();
DescribeLoadBalancerAttributesRequest request = new DescribeLoadBalancerAttributesRequest().withLoadBalancerName(name);
DescribeLoadBalancerAttributesResult result = elbClient.describeLoadBalancerAttributes(request);
LoadBalancerAttributes attrs = result.getLoadBalancerAttributes();
LOGGER.info(String.format("Got attributes for ELB with name '%s' in region %s.", name, region));
return attrs;
}
/**
* Retreive the tags for a specific ELB.
*
* @param name the ELB names
* @return the ELBs
*/
public List<TagDescription> describeElasticLoadBalancerTags(String name) {
LOGGER.info(String.format("Getting tags for ELB with name '%s' in region %s.", name, region));
AmazonElasticLoadBalancingClient elbClient = elbClient();
DescribeTagsRequest request = new DescribeTagsRequest().withLoadBalancerNames(name);
DescribeTagsResult result = elbClient.describeTags(request);
LOGGER.info(String.format("Got tags for ELB with name '%s' in region %s.", name, region));
return result.getTagDescriptions();
}
/**
* Describe a set of specific auto-scaling instances.
*
* @param instanceIds the instance ids
* @return the instances
*/
public List<AutoScalingInstanceDetails> describeAutoScalingInstances(String... instanceIds) {
if (instanceIds == null || instanceIds.length == 0) {
LOGGER.info(String.format("Getting all auto-scaling instances in region %s.", region));
} else {
LOGGER.info(String.format("Getting auto-scaling instances for %d ids in region %s.",
instanceIds.length, region));
}
List<AutoScalingInstanceDetails> instances = new LinkedList<AutoScalingInstanceDetails>();
AmazonAutoScalingClient asgClient = asgClient();
DescribeAutoScalingInstancesRequest request = new DescribeAutoScalingInstancesRequest();
if (instanceIds != null) {
request.setInstanceIds(Arrays.asList(instanceIds));
}
DescribeAutoScalingInstancesResult result = asgClient.describeAutoScalingInstances(request);
instances.addAll(result.getAutoScalingInstances());
while (result.getNextToken() != null) {
request = request.withNextToken(result.getNextToken());
result = asgClient.describeAutoScalingInstances(request);
instances.addAll(result.getAutoScalingInstances());
}
LOGGER.info(String.format("Got %d auto-scaling instances.", instances.size()));
return instances;
}
/**
* Describe a set of specific instances.
*
* @param instanceIds the instance ids
* @return the instances
*/
public List<Instance> describeInstances(String... instanceIds) {
if (instanceIds == null || instanceIds.length == 0) {
LOGGER.info(String.format("Getting all EC2 instances in region %s.", region));
} else {
LOGGER.info(String.format("Getting EC2 instances for %d ids in region %s.", instanceIds.length, region));
}
List<Instance> instances = new LinkedList<Instance>();
AmazonEC2 ec2Client = ec2Client();
DescribeInstancesRequest request = new DescribeInstancesRequest();
if (instanceIds != null) {
request.withInstanceIds(Arrays.asList(instanceIds));
}
DescribeInstancesResult result = ec2Client.describeInstances(request);
for (Reservation reservation : result.getReservations()) {
instances.addAll(reservation.getInstances());
}
LOGGER.info(String.format("Got %d EC2 instances in region %s.", instances.size(), region));
return instances;
}
/**
* Describe a set of specific launch configurations.
*
* @param names the launch configuration names
* @return the launch configurations
*/
public List<LaunchConfiguration> describeLaunchConfigurations(String... names) {
if (names == null || names.length == 0) {
LOGGER.info(String.format("Getting all launch configurations in region %s.", region));
} else {
LOGGER.info(String.format("Getting launch configurations for %d names in region %s.",
names.length, region));
}
List<LaunchConfiguration> lcs = new LinkedList<LaunchConfiguration>();
AmazonAutoScalingClient asgClient = asgClient();
DescribeLaunchConfigurationsRequest request = new DescribeLaunchConfigurationsRequest()
.withLaunchConfigurationNames(names);
DescribeLaunchConfigurationsResult result = asgClient.describeLaunchConfigurations(request);
lcs.addAll(result.getLaunchConfigurations());
while (result.getNextToken() != null) {
request.setNextToken(result.getNextToken());
result = asgClient.describeLaunchConfigurations(request);
lcs.addAll(result.getLaunchConfigurations());
}
LOGGER.info(String.format("Got %d launch configurations in region %s.", lcs.size(), region));
return lcs;
}
/** {@inheritDoc} */
@Override
public void deleteAutoScalingGroup(String asgName) {
Validate.notEmpty(asgName);
LOGGER.info(String.format("Deleting auto-scaling group with name %s in region %s.", asgName, region));
AmazonAutoScalingClient asgClient = asgClient();
DeleteAutoScalingGroupRequest request = new DeleteAutoScalingGroupRequest()
.withAutoScalingGroupName(asgName).withForceDelete(true);
try {
asgClient.deleteAutoScalingGroup(request);
LOGGER.info(String.format("Deleted auto-scaling group with name %s in region %s.", asgName, region));
}catch(Exception e) {
LOGGER.error("Got an exception deleting ASG " + asgName, e);
}
}
/** {@inheritDoc} */
@Override
public void deleteLaunchConfiguration(String launchConfigName) {
Validate.notEmpty(launchConfigName);
LOGGER.info(String.format("Deleting launch configuration with name %s in region %s.",
launchConfigName, region));
AmazonAutoScalingClient asgClient = asgClient();
DeleteLaunchConfigurationRequest request = new DeleteLaunchConfigurationRequest()
.withLaunchConfigurationName(launchConfigName);
asgClient.deleteLaunchConfiguration(request);
}
/** {@inheritDoc} */
@Override
public void deleteImage(String imageId) {
Validate.notEmpty(imageId);
LOGGER.info(String.format("Deleting image %s in region %s.",
imageId, region));
AmazonEC2 ec2Client = ec2Client();
DeregisterImageRequest request = new DeregisterImageRequest(imageId);
ec2Client.deregisterImage(request);
}
/** {@inheritDoc} */
@Override
public void deleteVolume(String volumeId) {
Validate.notEmpty(volumeId);
LOGGER.info(String.format("Deleting volume %s in region %s.", volumeId, region));
AmazonEC2 ec2Client = ec2Client();
DeleteVolumeRequest request = new DeleteVolumeRequest().withVolumeId(volumeId);
ec2Client.deleteVolume(request);
}
/** {@inheritDoc} */
@Override
public void deleteSnapshot(String snapshotId) {
Validate.notEmpty(snapshotId);
LOGGER.info(String.format("Deleting snapshot %s in region %s.", snapshotId, region));
AmazonEC2 ec2Client = ec2Client();
DeleteSnapshotRequest request = new DeleteSnapshotRequest().withSnapshotId(snapshotId);
ec2Client.deleteSnapshot(request);
}
/** {@inheritDoc} */
@Override
public void deleteElasticLoadBalancer(String elbId) {
Validate.notEmpty(elbId);
LOGGER.info(String.format("Deleting ELB %s in region %s.", elbId, region));
AmazonElasticLoadBalancingClient elbClient = elbClient();
DeleteLoadBalancerRequest request = new DeleteLoadBalancerRequest(elbId);
elbClient.deleteLoadBalancer(request);
}
/** {@inheritDoc} */
@Override
public void deleteDNSRecord(String dnsName, String dnsType, String hostedZoneID) {
Validate.notEmpty(dnsName);
Validate.notEmpty(dnsType);
if(dnsType.equals("A") || dnsType.equals("AAAA") || dnsType.equals("CNAME")) {
LOGGER.info(String.format("Deleting DNS Route 53 record %s", dnsName));
AmazonRoute53Client route53Client = route53Client();
// AWS API requires us to query for the record first
ListResourceRecordSetsRequest listRequest = new ListResourceRecordSetsRequest(hostedZoneID);
listRequest.setMaxItems("1");
listRequest.setStartRecordType(dnsType);
listRequest.setStartRecordName(dnsName);
ListResourceRecordSetsResult listResult = route53Client.listResourceRecordSets(listRequest);
if (listResult.getResourceRecordSets().size() < 1) {
throw new NotFoundException("Could not find Route53 record for " + dnsName + " (" + dnsType + ") in zone " + hostedZoneID);
} else {
ResourceRecordSet resourceRecord = listResult.getResourceRecordSets().get(0);
ArrayList<Change> changeList = new ArrayList<>();
Change recordChange = new Change(ChangeAction.DELETE, resourceRecord);
changeList.add(recordChange);
ChangeBatch recordChangeBatch = new ChangeBatch(changeList);
ChangeResourceRecordSetsRequest request = new ChangeResourceRecordSetsRequest(hostedZoneID, recordChangeBatch);
ChangeResourceRecordSetsResult result = route53Client.changeResourceRecordSets(request);
}
} else {
LOGGER.error("dnsType must be one of 'A', 'AAAA', or 'CNAME'");
}
}
/** {@inheritDoc} */
@Override
public void terminateInstance(String instanceId) {
Validate.notEmpty(instanceId);
LOGGER.info(String.format("Terminating instance %s in region %s.", instanceId, region));
try {
ec2Client().terminateInstances(new TerminateInstancesRequest(Arrays.asList(instanceId)));
} catch (AmazonServiceException e) {
if (e.getErrorCode().equals("InvalidInstanceID.NotFound")) {
throw new NotFoundException("AWS instance " + instanceId + " not found", e);
}
throw e;
}
}
/** {@inheritDoc} */
public void setInstanceSecurityGroups(String instanceId, List<String> groupIds) {
Validate.notEmpty(instanceId);
LOGGER.info(String.format("Removing all security groups from instance %s in region %s.", instanceId, region));
try {
ModifyInstanceAttributeRequest request = new ModifyInstanceAttributeRequest();
request.setInstanceId(instanceId);
request.setGroups(groupIds);
ec2Client().modifyInstanceAttribute(request);
} catch (AmazonServiceException e) {
if (e.getErrorCode().equals("InvalidInstanceID.NotFound")) {
throw new NotFoundException("AWS instance " + instanceId + " not found", e);
}
throw e;
}
}
/**
* Describe a set of specific EBS volumes.
*
* @param volumeIds the volume ids
* @return the volumes
*/
public List<Volume> describeVolumes(String... volumeIds) {
if (volumeIds == null || volumeIds.length == 0) {
LOGGER.info(String.format("Getting all EBS volumes in region %s.", region));
} else {
LOGGER.info(String.format("Getting EBS volumes for %d ids in region %s.", volumeIds.length, region));
}
AmazonEC2 ec2Client = ec2Client();
DescribeVolumesRequest request = new DescribeVolumesRequest();
if (volumeIds != null) {
request.setVolumeIds(Arrays.asList(volumeIds));
}
DescribeVolumesResult result = ec2Client.describeVolumes(request);
List<Volume> volumes = result.getVolumes();
LOGGER.info(String.format("Got %d EBS volumes in region %s.", volumes.size(), region));
return volumes;
}
/**
* Describe a set of specific EBS snapshots.
*
* @param snapshotIds the snapshot ids
* @return the snapshots
*/
public List<Snapshot> describeSnapshots(String... snapshotIds) {
if (snapshotIds == null || snapshotIds.length == 0) {
LOGGER.info(String.format("Getting all EBS snapshots in region %s.", region));
} else {
LOGGER.info(String.format("Getting EBS snapshotIds for %d ids in region %s.", snapshotIds.length, region));
}
AmazonEC2 ec2Client = ec2Client();
DescribeSnapshotsRequest request = new DescribeSnapshotsRequest();
// Set the owner id to self to avoid getting snapshots from other accounts.
request.withOwnerIds(Arrays.<String>asList("self"));
if (snapshotIds != null) {
request.setSnapshotIds(Arrays.asList(snapshotIds));
}
DescribeSnapshotsResult result = ec2Client.describeSnapshots(request);
List<Snapshot> snapshots = result.getSnapshots();
LOGGER.info(String.format("Got %d EBS snapshots in region %s.", snapshots.size(), region));
return snapshots;
}
@Override
public void createTagsForResources(Map<String, String> keyValueMap, String... resourceIds) {
Validate.notNull(keyValueMap);
Validate.notEmpty(keyValueMap);
Validate.notNull(resourceIds);
Validate.notEmpty(resourceIds);
AmazonEC2 ec2Client = ec2Client();
List<Tag> tags = new ArrayList<Tag>();
for (Map.Entry<String, String> entry : keyValueMap.entrySet()) {
tags.add(new Tag(entry.getKey(), entry.getValue()));
}
CreateTagsRequest req = new CreateTagsRequest(Arrays.asList(resourceIds), tags);
ec2Client.createTags(req);
}
/**
* Describe a set of specific images.
*
* @param imageIds the image ids
* @return the images
*/
public List<Image> describeImages(String... imageIds) {
if (imageIds == null || imageIds.length == 0) {
LOGGER.info(String.format("Getting all AMIs in region %s.", region));
} else {
LOGGER.info(String.format("Getting AMIs for %d ids in region %s.", imageIds.length, region));
}
AmazonEC2 ec2Client = ec2Client();
DescribeImagesRequest request = new DescribeImagesRequest();
if (imageIds != null) {
request.setImageIds(Arrays.asList(imageIds));
}
DescribeImagesResult result = ec2Client.describeImages(request);
List<Image> images = result.getImages();
LOGGER.info(String.format("Got %d AMIs in region %s.", images.size(), region));
return images;
}
@Override
public void detachVolume(String instanceId, String volumeId, boolean force) {
Validate.notEmpty(instanceId);
LOGGER.info(String.format("Detach volumes from instance %s in region %s.", instanceId, region));
try {
DetachVolumeRequest detachVolumeRequest = new DetachVolumeRequest();
detachVolumeRequest.setForce(force);
detachVolumeRequest.setInstanceId(instanceId);
detachVolumeRequest.setVolumeId(volumeId);
ec2Client().detachVolume(detachVolumeRequest);
} catch (AmazonServiceException e) {
if (e.getErrorCode().equals("InvalidInstanceID.NotFound")) {
throw new NotFoundException("AWS instance " + instanceId + " not found", e);
}
throw e;
}
}
@Override
public List<String> listAttachedVolumes(String instanceId, boolean includeRoot) {
Validate.notEmpty(instanceId);
LOGGER.info(String.format("Listing volumes attached to instance %s in region %s.", instanceId, region));
try {
List<String> volumeIds = new ArrayList<String>();
for (Instance instance : describeInstances(instanceId)) {
String rootDeviceName = instance.getRootDeviceName();
for (InstanceBlockDeviceMapping ibdm : instance.getBlockDeviceMappings()) {
EbsInstanceBlockDevice ebs = ibdm.getEbs();
if (ebs == null) {
continue;
}
String volumeId = ebs.getVolumeId();
if (Strings.isNullOrEmpty(volumeId)) {
continue;
}
if (!includeRoot && rootDeviceName != null && rootDeviceName.equals(ibdm.getDeviceName())) {
continue;
}
volumeIds.add(volumeId);
}
}
return volumeIds;
} catch (AmazonServiceException e) {
if (e.getErrorCode().equals("InvalidInstanceID.NotFound")) {
throw new NotFoundException("AWS instance " + instanceId + " not found", e);
}
throw e;
}
}
/**
* Describe a set of security groups.
*
* @param groupNames the names of the groups to find
* @return a list of matching groups
*/
public List<SecurityGroup> describeSecurityGroups(String... groupNames) {
AmazonEC2 ec2Client = ec2Client();
DescribeSecurityGroupsRequest request = new DescribeSecurityGroupsRequest();
if (groupNames == null || groupNames.length == 0) {
LOGGER.info(String.format("Getting all EC2 security groups in region %s.", region));
} else {
LOGGER.info(String.format("Getting EC2 security groups for %d names in region %s.", groupNames.length,
region));
request.withGroupNames(groupNames);
}
DescribeSecurityGroupsResult result;
try {
result = ec2Client.describeSecurityGroups(request);
} catch (AmazonServiceException e) {
if (e.getErrorCode().equals("InvalidGroup.NotFound")) {
LOGGER.info("Got InvalidGroup.NotFound error for security groups; returning empty list");
return Collections.emptyList();
}
throw e;
}
List<SecurityGroup> securityGroups = result.getSecurityGroups();
LOGGER.info(String.format("Got %d EC2 security groups in region %s.", securityGroups.size(), region));
return securityGroups;
}
/** {@inheritDoc} */
public String createSecurityGroup(String instanceId, String name, String description) {
String vpcId = getVpcId(instanceId);
AmazonEC2 ec2Client = ec2Client();
CreateSecurityGroupRequest request = new CreateSecurityGroupRequest();
request.setGroupName(name);
request.setDescription(description);
request.setVpcId(vpcId);
LOGGER.info(String.format("Creating EC2 security group %s.", name));
CreateSecurityGroupResult result = ec2Client.createSecurityGroup(request);
return result.getGroupId();
}
/**
* Convenience wrapper around describeInstances, for a single instance id.
*
* @param instanceId id of instance to find
* @return the instance info, or null if instance not found
*/
public Instance describeInstance(String instanceId) {
Instance instance = null;
for (Instance i : describeInstances(instanceId)) {
if (instance != null) {
throw new IllegalStateException("Duplicate instance: " + instanceId);
}
instance = i;
}
return instance;
}
/** {@inheritDoc} */
@Override
public ComputeService getJcloudsComputeService() {
if (jcloudsComputeService == null) {
synchronized(this) {
if (jcloudsComputeService == null) {
AWSCredentials awsCredentials = awsCredentialsProvider.getCredentials();
String username = awsCredentials.getAWSAccessKeyId();
String password = awsCredentials.getAWSSecretKey();
Credentials credentials;
if (awsCredentials instanceof AWSSessionCredentials) {
AWSSessionCredentials awsSessionCredentials = (AWSSessionCredentials) awsCredentials;
credentials = SessionCredentials.builder().accessKeyId(username).secretAccessKey(password)
.sessionToken(awsSessionCredentials.getSessionToken()).build();
} else {
credentials = new Credentials(username, password);
}
ComputeServiceContext jcloudsContext = ContextBuilder.newBuilder("aws-ec2")
.credentialsSupplier(Suppliers.ofInstance(credentials))
.modules(ImmutableSet.<Module>of(new SLF4JLoggingModule(), new JschSshClientModule()))
.buildView(ComputeServiceContext.class);
this.jcloudsComputeService = jcloudsContext.getComputeService();
}
}
}
return jcloudsComputeService;
}
/** {@inheritDoc} */
@Override
public String getJcloudsId(String instanceId) {
return this.region + "/" + instanceId;
}
@Override
public SshClient connectSsh(String instanceId, LoginCredentials credentials) {
ComputeService computeService = getJcloudsComputeService();
String jcloudsId = getJcloudsId(instanceId);
NodeMetadata node = getJcloudsNode(computeService, jcloudsId);
node = NodeMetadataBuilder.fromNodeMetadata(node).credentials(credentials).build();
Utils utils = computeService.getContext().utils();
SshClient ssh = utils.sshForNode().apply(node);
ssh.connect();
return ssh;
}
private NodeMetadata getJcloudsNode(ComputeService computeService, String jcloudsId) {
// Work around a jclouds bug / documentation issue...
// TODO: Figure out what's broken, and eliminate this function
// This should work (?):
// Set<NodeMetadata> nodes = computeService.listNodesByIds(Collections.singletonList(jcloudsId));
Set<NodeMetadata> nodes = Sets.newHashSet();
for (ComputeMetadata n : computeService.listNodes()) {
if (jcloudsId.equals(n.getId())) {
nodes.add((NodeMetadata) n);
}
}
if (nodes.isEmpty()) {
LOGGER.warn("Unable to find jclouds node: {}", jcloudsId);
for (ComputeMetadata n : computeService.listNodes()) {
LOGGER.info("Did find node: {}", n);
}
throw new IllegalStateException("Unable to find node using jclouds: " + jcloudsId);
}
NodeMetadata node = Iterables.getOnlyElement(nodes);
return node;
}
/** {@inheritDoc} */
@Override
public String findSecurityGroup(String instanceId, String groupName) {
String vpcId = getVpcId(instanceId);
SecurityGroup found = null;
List<SecurityGroup> securityGroups = describeSecurityGroups(vpcId, groupName);
for (SecurityGroup sg : securityGroups) {
if (Objects.equal(vpcId, sg.getVpcId())) {
if (found != null) {
throw new IllegalStateException("Duplicate security groups found");
}
found = sg;
}
}
if (found == null) {
return null;
}
return found.getGroupId();
}
/**
* Gets the VPC id for the given instance.
*
* @param instanceId
* instance we're checking
* @return vpc id, or null if not a vpc instance
*/
String getVpcId(String instanceId) {
Instance awsInstance = describeInstance(instanceId);
String vpcId = awsInstance.getVpcId();
if (Strings.isNullOrEmpty(vpcId)) {
return null;
}
return vpcId;
}
/** {@inheritDoc} */
@Override
public boolean canChangeInstanceSecurityGroups(String instanceId) {
return null != getVpcId(instanceId);
}
}
| 38,651
| 38.121457
| 139
|
java
|
SimianArmy
|
SimianArmy-master/src/main/java/com/netflix/simianarmy/client/aws/chaos/FilteringChaosCrawler.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.client.aws.chaos;
import com.google.common.base.Predicate;
import com.google.common.collect.Iterables;
import com.google.common.collect.Lists;
import com.netflix.simianarmy.chaos.ChaosCrawler;
import java.util.EnumSet;
import java.util.List;
/**
* The Class FilteringChaosCrawler. This will filter the result from ASGChaosCrawler for all available AutoScalingGroups associated with the AWS account based on requested filter.
*/
public class FilteringChaosCrawler implements ChaosCrawler {
private final ChaosCrawler crawler;
private final Predicate<? super InstanceGroup> predicate;
public FilteringChaosCrawler(ChaosCrawler crawler, Predicate<? super InstanceGroup> predicate) {
this.crawler = crawler;
this.predicate = predicate;
}
/** {@inheritDoc} */
@Override
public EnumSet<?> groupTypes() {
return crawler.groupTypes();
}
/** {@inheritDoc} */
@Override
public List<InstanceGroup> groups() {
return filter(crawler.groups());
}
/** {@inheritDoc} */
@Override
public List<InstanceGroup> groups(String... names) {
return filter(crawler.groups(names));
}
/**
* Return the filtered list of InstanceGroups using the requested predicate. The filter is applied on the InstanceGroup retrieved from the ASGChaosCrawler class.
* @param list list of InstanceGroups result of the chaos crawler
* @return The appropriate {@link InstanceGroup}
*/
protected List<InstanceGroup> filter(List<InstanceGroup> list) {
return Lists.newArrayList(Iterables.filter(list, predicate));
}
}
| 2,296
| 32.289855
| 179
|
java
|
SimianArmy
|
SimianArmy-master/src/main/java/com/netflix/simianarmy/client/aws/chaos/TagPredicate.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.client.aws.chaos;
import com.amazonaws.services.autoscaling.model.TagDescription;
import com.google.common.base.Predicate;
import com.google.common.collect.Iterables;
import com.netflix.simianarmy.chaos.ChaosCrawler;
/**
* * The Class TagPredicate. This will apply the tag-key and the tag-value filter on the list of InstanceGroups .
*/
public class TagPredicate implements Predicate<ChaosCrawler.InstanceGroup> {
private final String key, value;
public TagPredicate(String key, String value) {
this.key = key;
this.value = value;
}
@Override
public boolean apply(ChaosCrawler.InstanceGroup instanceGroup) {
return Iterables.any(instanceGroup.tags(), new com.google.common.base.Predicate<TagDescription>() {
@Override
public boolean apply(TagDescription tagDescription) {
return tagDescription.getKey().equals(key) && tagDescription.getValue().equals(value);
}
});
}
}
| 1,656
| 34.255319
| 114
|
java
|
SimianArmy
|
SimianArmy-master/src/main/java/com/netflix/simianarmy/client/aws/chaos/ASGChaosCrawler.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.client.aws.chaos;
import java.util.EnumSet;
import java.util.LinkedList;
import java.util.List;
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.GroupType;
import com.netflix.simianarmy.basic.chaos.BasicChaosMonkey;
import com.netflix.simianarmy.basic.chaos.BasicInstanceGroup;
import com.netflix.simianarmy.chaos.ChaosCrawler;
import com.netflix.simianarmy.client.aws.AWSClient;
import com.netflix.simianarmy.tunable.TunableInstanceGroup;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* The Class ASGChaosCrawler. This will crawl for all available AutoScalingGroups associated with the AWS account.
*/
public class ASGChaosCrawler implements ChaosCrawler {
/** The Constant LOGGER. */
private static final Logger LOGGER = LoggerFactory.getLogger(ASGChaosCrawler.class);
/**
* The key of the tag that set the aggression coefficient
*/
private static final String CHAOS_MONKEY_AGGRESSION_COEFFICIENT_KEY = "chaosMonkey.aggressionCoefficient";
/**
* The group types Types.
*/
public enum Types implements GroupType {
/** only crawls AutoScalingGroups. */
ASG;
}
/** The aws client. */
private final AWSClient awsClient;
/**
* Instantiates a new basic chaos crawler.
*
* @param awsClient
* the aws client
*/
public ASGChaosCrawler(AWSClient awsClient) {
this.awsClient = awsClient;
}
/** {@inheritDoc} */
@Override
public EnumSet<?> groupTypes() {
return EnumSet.allOf(Types.class);
}
/** {@inheritDoc} */
@Override
public List<InstanceGroup> groups() {
return groups((String[]) null);
}
@Override
public List<InstanceGroup> groups(String... names) {
List<InstanceGroup> list = new LinkedList<InstanceGroup>();
for (AutoScalingGroup asg : awsClient.describeAutoScalingGroups(names)) {
InstanceGroup ig = getInstanceGroup(asg, findAggressionCoefficient(asg));
for (Instance inst : asg.getInstances()) {
ig.addInstance(inst.getInstanceId());
}
list.add(ig);
}
return list;
}
/**
* Returns the desired InstanceGroup. If there is no set aggression coefficient, then it
* returns the basic impl, otherwise it returns the tunable impl.
* @param asg The autoscaling group
* @return The appropriate {@link InstanceGroup}
*/
protected InstanceGroup getInstanceGroup(AutoScalingGroup asg, double aggressionCoefficient) {
InstanceGroup instanceGroup;
// if coefficient is 1 then the BasicInstanceGroup is fine, otherwise use Tunable
if (aggressionCoefficient == 1.0) {
instanceGroup = new BasicInstanceGroup(asg.getAutoScalingGroupName(), Types.ASG, awsClient.region(), asg.getTags());
} else {
TunableInstanceGroup tunable = new TunableInstanceGroup(asg.getAutoScalingGroupName(), Types.ASG, awsClient.region(), asg.getTags());
tunable.setAggressionCoefficient(aggressionCoefficient);
instanceGroup = tunable;
}
return instanceGroup;
}
/**
* Reads tags on AutoScalingGroup looking for the tag for the aggression coefficient
* and determines the coefficient value. The default value is 1 if there no tag or
* if the value in the tag is not a parsable number.
*
* @param asg The AutoScalingGroup that might have an aggression coefficient tag
* @return The set or default aggression coefficient.
*/
protected double findAggressionCoefficient(AutoScalingGroup asg) {
List<TagDescription> tagDescriptions = asg.getTags();
double aggression = 1.0;
for (TagDescription tagDescription : tagDescriptions) {
if ( CHAOS_MONKEY_AGGRESSION_COEFFICIENT_KEY.equalsIgnoreCase(tagDescription.getKey()) ) {
String value = tagDescription.getValue();
// prevent NPE on parseDouble
if (value == null) {
break;
}
try {
aggression = Double.parseDouble(value);
LOGGER.info("Aggression coefficient of {} found for ASG {}", value, asg.getAutoScalingGroupName());
} catch (NumberFormatException e) {
LOGGER.warn("Unparsable value of {} found in tag {} for ASG {}", value, CHAOS_MONKEY_AGGRESSION_COEFFICIENT_KEY, asg.getAutoScalingGroupName());
aggression = 1.0;
}
// stop looking
break;
}
}
return aggression;
}
}
| 5,475
| 32.802469
| 156
|
java
|
SimianArmy
|
SimianArmy-master/src/main/java/com/netflix/simianarmy/client/vsphere/PropertyBasedTerminationStrategy.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.
*/
package com.netflix.simianarmy.client.vsphere;
import java.rmi.RemoteException;
import com.netflix.simianarmy.MonkeyConfiguration;
import com.vmware.vim25.mo.VirtualMachine;
/**
* Terminates a VirtualMachine by setting the named property and resetting it.
*
* The following properties can be overridden in the client.properties
* simianarmy.client.vsphere.terminationStrategy.property.name = PROPERTY_NAME
* simianarmy.client.vsphere.terminationStrategy.property.value = PROPERTY_VALUE
*
* @author ingmar.krusch@immobilienscout24.de
*/
public class PropertyBasedTerminationStrategy implements TerminationStrategy {
private final String propertyName;
private final String propertyValue;
/**
* Reads property name <code>simianarmy.client.vsphere.terminationStrategy.property.name</code>
* (default: Force Boot) and value <code>simianarmy.client.vsphere.terminationStrategy.property.value</code>
* (default: server) from config.
*/
public PropertyBasedTerminationStrategy(MonkeyConfiguration config) {
this.propertyName = config.getStrOrElse(
"simianarmy.client.vsphere.terminationStrategy.property.name", "Force Boot");
this.propertyValue = config.getStrOrElse(
"simianarmy.client.vsphere.terminationStrategy.property.value", "server");
}
@Override
public void terminate(VirtualMachine virtualMachine) throws RemoteException {
virtualMachine.setCustomValue(getPropertyName(), getPropertyValue());
virtualMachine.resetVM_Task();
}
public String getPropertyName() {
return propertyName;
}
public String getPropertyValue() {
return propertyValue;
}
}
| 2,316
| 36.370968
| 112
|
java
|
SimianArmy
|
SimianArmy-master/src/main/java/com/netflix/simianarmy/client/vsphere/TerminationStrategy.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.
*/
package com.netflix.simianarmy.client.vsphere;
import java.rmi.RemoteException;
import com.vmware.vim25.mo.VirtualMachine;
/**
* Abstracts the concrete way a VirtualMachine is terminated. Implement this to fit to your infrastructure.
*
* @author ingmar.krusch@immobilienscout24.de
*/
public interface TerminationStrategy {
/**
* Terminate the given VirtualMachine.
*/
void terminate(VirtualMachine virtualMachine) throws RemoteException;
}
| 1,071
| 31.484848
| 107
|
java
|
SimianArmy
|
SimianArmy-master/src/main/java/com/netflix/simianarmy/client/vsphere/VSphereGroups.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.
*/
package com.netflix.simianarmy.client.vsphere;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.amazonaws.services.autoscaling.model.AutoScalingGroup;
import com.amazonaws.services.autoscaling.model.Instance;
/**
* Wraps the creation and grouping of Instance's in AutoScalingGroup's.
*
* @author ingmar.krusch@immobilienscout24.de
*/
class VSphereGroups {
private final Map<String, AutoScalingGroup> map = new HashMap<String, AutoScalingGroup>();
/**
* Get all AutoScalingGroup's that have been added.
*/
public List<AutoScalingGroup> asList() {
ArrayList<AutoScalingGroup> list = new ArrayList<AutoScalingGroup>(map.values());
Collections.sort(list, new Comparator<AutoScalingGroup>() {
@Override
public int compare(AutoScalingGroup o1, AutoScalingGroup o2) {
return o1.getAutoScalingGroupName().compareTo(o2.getAutoScalingGroupName());
}
});
return list;
}
/**
* Add the given instance to the named group.
*/
public void addInstance(final String instanceId, final String groupName) {
if (!map.containsKey(groupName)) {
final AutoScalingGroup asg = new AutoScalingGroup();
asg.setAutoScalingGroupName(groupName);
map.put(groupName, asg);
}
final AutoScalingGroup asg = map.get(groupName);
Instance instance = new Instance();
instance.setInstanceId(instanceId);
asg.getInstances().add(instance);
}
}
| 2,253
| 32.641791
| 94
|
java
|
SimianArmy
|
SimianArmy-master/src/main/java/com/netflix/simianarmy/client/vsphere/VSphereContext.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.
*/
package com.netflix.simianarmy.client.vsphere;
import com.netflix.simianarmy.MonkeyConfiguration;
import com.netflix.simianarmy.basic.BasicChaosMonkeyContext;
/**
* This Context extends the BasicContext in order to provide a different client: the VSphereClient.
*
* @author ingmar.krusch@immobilienscout24.de
*/
public class VSphereContext extends BasicChaosMonkeyContext {
@Override
protected void createClient() {
MonkeyConfiguration config = configuration();
final PropertyBasedTerminationStrategy terminationStrategy = new PropertyBasedTerminationStrategy(config);
final VSphereServiceConnection connection = new VSphereServiceConnection(config);
final VSphereClient client = new VSphereClient(terminationStrategy, connection);
setCloudClient(client);
}
}
| 1,424
| 38.583333
| 114
|
java
|
SimianArmy
|
SimianArmy-master/src/main/java/com/netflix/simianarmy/client/vsphere/VSphereServiceConnection.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.
*/
package com.netflix.simianarmy.client.vsphere;
import java.net.MalformedURLException;
import java.net.URL;
import java.rmi.RemoteException;
import java.util.Arrays;
import com.amazonaws.AmazonServiceException;
import com.netflix.simianarmy.MonkeyConfiguration;
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.ServiceInstance;
import com.vmware.vim25.mo.VirtualMachine;
/**
* Wraps the connection to VSphere and handles the raw service calls.
*
* The following properties can be overridden in the client.properties
* simianarmy.client.vsphere.url = https://YOUR_VSPHERE_SERVER/sdk
* simianarmy.client.vsphere.username = YOUR_SERVICE_ACCOUNT_USERNAME
* simianarmy.client.vsphere.password = YOUR_SERVICE_ACCOUNT_PASSWORD
*
* @author ingmar.krusch@immobilienscout24.de
*/
public class VSphereServiceConnection {
/** The type of managedEntity we operate on are virtual machines. */
public static final String VIRTUAL_MACHINE_TYPE_NAME = "VirtualMachine";
/** The username that is used to connect to VSpehere Center. */
private String username = null;
/** The password that is used to connect to VSpehere Center. */
private String password = null;
/** The url that is used to connect to VSpehere Center. */
private String url = null;
/** The ServiceInstance that is used to issue multiple requests to VSpehere Center. */
private ServiceInstance service = null;
/**
* Constructor.
*/
public VSphereServiceConnection(MonkeyConfiguration config) {
this.url = config.getStr("simianarmy.client.vsphere.url");
this.username = config.getStr("simianarmy.client.vsphere.username");
this.password = config.getStr("simianarmy.client.vsphere.password");
}
/** disconnect from the service if not already disconnected. */
public void disconnect() {
if (service != null) {
service.getServerConnection().logout();
service = null;
}
}
/** connect to the service if not already connected. */
public void connect() throws AmazonServiceException {
try {
if (service == null) {
service = new ServiceInstance(new URL(url), username, password, true);
}
} catch (RemoteException e) {
throw new AmazonServiceException("cannot connect to VSphere", e);
} catch (MalformedURLException e) {
throw new AmazonServiceException("cannot connect to VSphere", e);
}
}
/**
* Gets the named VirtualMachine.
*/
public VirtualMachine getVirtualMachineById(String instanceId) throws RemoteException {
InventoryNavigator inventoryNavigator = getInventoryNavigator();
VirtualMachine virtualMachine = (VirtualMachine) inventoryNavigator.searchManagedEntity(
VIRTUAL_MACHINE_TYPE_NAME, instanceId);
return virtualMachine;
}
/**
* Return all VirtualMachines from VSpehere Center.
*
* @throws AmazonServiceException
* If there is any communication error or if no VirtualMachine's are found. */
public VirtualMachine[] describeVirtualMachines() throws AmazonServiceException {
ManagedEntity[] mes = null;
try {
mes = getInventoryNavigator().searchManagedEntities(VIRTUAL_MACHINE_TYPE_NAME);
} catch (InvalidProperty e) {
throw new AmazonServiceException("cannot query VSphere", e);
} catch (RuntimeFault e) {
throw new AmazonServiceException("cannot query VSphere", e);
} catch (RemoteException e) {
throw new AmazonServiceException("cannot query VSphere", e);
}
if (mes == null || mes.length == 0) {
throw new AmazonServiceException(
"vsphere returned zero entities of type \""
+ VIRTUAL_MACHINE_TYPE_NAME + "\""
);
} else {
return Arrays.copyOf(mes, mes.length, VirtualMachine[].class);
}
}
protected InventoryNavigator getInventoryNavigator() {
return new InventoryNavigator(service.getRootFolder());
}
public String getUsername() {
return username;
}
public String getPassword() {
return password;
}
public String getUrl() {
return url;
}
}
| 5,181
| 35.751773
| 97
|
java
|
SimianArmy
|
SimianArmy-master/src/main/java/com/netflix/simianarmy/client/vsphere/VSphereClient.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.
*/
package com.netflix.simianarmy.client.vsphere;
import java.rmi.RemoteException;
import java.util.List;
import com.amazonaws.AmazonServiceException;
import com.amazonaws.services.autoscaling.model.AutoScalingGroup;
import com.netflix.simianarmy.client.aws.AWSClient;
import com.vmware.vim25.mo.VirtualMachine;
/**
* This client describes the VSphere folders as AutoScalingGroup's containing the virtual machines that are directly in
* that folder. The hierarchy is flattened this way. And it can terminate these VMs with the configured
* TerminationStrategy.
*
* @author ingmar.krusch@immobilienscout24.de
*/
public class VSphereClient extends AWSClient {
// private static final Logger LOGGER = LoggerFactory.getLogger(VSphereClient.class);
private final TerminationStrategy terminationStrategy;
private final VSphereServiceConnection connection;
/**
* Create the specific Client from the given strategy and connection.
*/
public VSphereClient(TerminationStrategy terminationStrategy, VSphereServiceConnection connection) {
super("region-" + connection.getUrl());
this.terminationStrategy = terminationStrategy;
this.connection = connection;
}
@Override
public List<AutoScalingGroup> describeAutoScalingGroups(String... names) {
final VSphereGroups groups = new VSphereGroups();
try {
connection.connect();
for (VirtualMachine virtualMachine : connection.describeVirtualMachines()) {
String instanceId = virtualMachine.getName();
String groupName = virtualMachine.getParent().getName();
boolean shouldAddNamedGroup = true;
if (names != null) {
// TODO need to implement this feature!!!
throw new RuntimeException("This feature (selecting groups by name) is not implemented yet");
}
if (shouldAddNamedGroup) {
groups.addInstance(instanceId, groupName);
}
}
} finally {
connection.disconnect();
}
return groups.asList();
}
@Override
/**
* reinstall the given instance. If it is powered down this will be ignored and the
* reinstall occurs the next time the machine is powered up.
*/
public void terminateInstance(String instanceId) {
try {
connection.connect();
VirtualMachine virtualMachine = connection.getVirtualMachineById(instanceId);
this.terminationStrategy.terminate(virtualMachine);
} catch (RemoteException e) {
throw new AmazonServiceException("cannot destroy & recreate " + instanceId, e);
} finally {
connection.disconnect();
}
}
}
| 3,420
| 35.393617
| 119
|
java
|
SimianArmy
|
SimianArmy-master/src/main/java/com/netflix/simianarmy/client/edda/EddaClient.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.client.edda;
import com.netflix.simianarmy.MonkeyConfiguration;
import com.netflix.simianarmy.client.MonkeyRestClient;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.Validate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* The REST client to access Edda to get the history of a cloud resource.
*/
public class EddaClient extends MonkeyRestClient {
private static final Logger LOGGER = LoggerFactory.getLogger(EddaClient.class);
private final MonkeyConfiguration config;
/**
* Constructor.
* @param timeout the timeout in milliseconds
* @param maxRetries the max number of retries
* @param retryInterval the interval in milliseconds between retries
* @param config the monkey configuration
*/
public EddaClient(int timeout, int maxRetries, int retryInterval, MonkeyConfiguration config) {
super(timeout, maxRetries, retryInterval);
this.config = config;
}
@Override
public String getBaseUrl(String region) {
Validate.notEmpty(region);
String baseUrl = config.getStr("simianarmy.janitor.edda.endpoint." + region);
if (StringUtils.isBlank(baseUrl)) {
LOGGER.error(String.format("No endpoint of Edda is found for region %s.", region));
}
return baseUrl;
}
}
| 2,005
| 34.821429
| 99
|
java
|
SimianArmy
|
SimianArmy-master/src/main/java/com/netflix/simianarmy/tunable/TunableInstanceGroup.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 com.netflix.simianarmy.GroupType;
import com.netflix.simianarmy.basic.chaos.BasicInstanceGroup;
import java.util.List;
/**
* Allows for individual InstanceGroups to alter the aggressiveness
* of ChaosMonkey.
*
* @author jeffggardner
*
*/
public class TunableInstanceGroup extends BasicInstanceGroup {
public TunableInstanceGroup(String name, GroupType type, String region, List<TagDescription> tags) {
super(name, type, region, tags);
}
private double aggressionCoefficient = 1.0;
/**
* @return the aggressionCoefficient
*/
public final double getAggressionCoefficient() {
return aggressionCoefficient;
}
/**
* @param aggressionCoefficient the aggressionCoefficient to set
*/
public final void setAggressionCoefficient(double aggressionCoefficient) {
this.aggressionCoefficient = aggressionCoefficient;
}
}
| 1,620
| 27.438596
| 102
|
java
|
SimianArmy
|
SimianArmy-master/src/main/java/com/netflix/simianarmy/tunable/TunablyAggressiveChaosMonkey.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.netflix.simianarmy.basic.chaos.BasicChaosMonkey;
import com.netflix.simianarmy.chaos.ChaosCrawler.InstanceGroup;
/**
* This class modifies the probability by multiplying the configured
* probability by the aggression coefficient tag on the instance group.
*
* @author jeffggardner
*/
public class TunablyAggressiveChaosMonkey extends BasicChaosMonkey {
public TunablyAggressiveChaosMonkey(Context ctx) {
super(ctx);
}
/**
* Gets the tuned probability value, returns 0 if the group is not
* enabled. Calls getEffectiveProbability and modifies that value if
* the instance group is a TunableInstanceGroup.
*
* @param group The instance group
* @return the effective probability value for the instance group
*/
@Override
protected double getEffectiveProbability(InstanceGroup group) {
if (!isGroupEnabled(group)) {
return 0;
}
double probability = getEffectiveProbabilityFromCfg(group);
// if this instance group is tunable, then factor in the aggression coefficient
if (group instanceof TunableInstanceGroup ) {
TunableInstanceGroup tunable = (TunableInstanceGroup) group;
probability *= tunable.getAggressionCoefficient();
}
return probability;
}
}
| 1,947
| 30.934426
| 83
|
java
|
SimianArmy
|
SimianArmy-master/src/main/java/com/netflix/simianarmy/janitor/Rule.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.Resource;
/**
* The rule implementing a logic to decide if a resource should be considered as a candidate of cleanup.
*/
public interface Rule {
/**
* Decides whether the resource should be a candidate of cleanup based on the underlying rule. When
* the rule considers the resource as a candidate of cleanup, it sets the expected termination time
* and termination reason of the resource.
*
* @param resource
* The resource
* @return true if the resource is valid and is not for cleanup, false otherwise
*/
boolean isValid(Resource resource);
}
| 1,319
| 33.736842
| 104
|
java
|
SimianArmy
|
SimianArmy-master/src/main/java/com/netflix/simianarmy/janitor/JanitorMonkey.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.EventType;
import com.netflix.simianarmy.Monkey;
import com.netflix.simianarmy.MonkeyConfiguration;
import com.netflix.simianarmy.MonkeyRecorder.Event;
import com.netflix.simianarmy.MonkeyType;
import java.util.List;
/**
* The abstract class for a Janitor Monkey.
*/
public abstract class JanitorMonkey extends Monkey {
/** The key name of the Janitor tag used to tag resources. */
public static final String JANITOR_TAG = "janitor";
/** The key name of the Janitor meta tag used to tag resources. */
public static final String JANITOR_META_TAG = "JANITOR_META";
/** The key name of the tag instance used to tag resources. */
public static final String INSTANCE_TAG_KEY = "instance";
/** The key name of the tag detach time used to tag resources. */
public static final String DETACH_TIME_TAG_KEY = "detachTime";
/**
* The Interface Context.
*/
public interface Context extends Monkey.Context {
/**
* Configuration.
*
* @return the monkey configuration
*/
MonkeyConfiguration configuration();
/**
* Janitors run by this monkey.
* @return the janitors
*/
List<AbstractJanitor> janitors();
/**
* Email notifier used to send notifications by the janitor monkey.
* @return the email notifier
*/
JanitorEmailNotifier emailNotifier();
/**
* The region the monkey is running in.
* @return the region the monkey is running in.
*/
String region();
/**
* The accountName the monkey is running in.
* @return the accountName the monkey is running in.
*/
String accountName();
/**
* The Janitor resource tracker.
* @return the Janitor resource tracker.
*/
JanitorResourceTracker resourceTracker();
}
/** The context. */
private final Context ctx;
/**
* Instantiates a new janitor monkey.
*
* @param ctx
* the context.
*/
public JanitorMonkey(Context ctx) {
super(ctx);
this.ctx = ctx;
}
/**
* The monkey Type.
*/
public static enum Type implements MonkeyType {
/** janitor monkey. */
JANITOR
}
/**
* The event types that this monkey causes.
*/
public enum EventTypes implements EventType {
/** Marking a resource as a cleanup candidate. */
MARK_RESOURCE,
/** Un-Marking a resource. */
UNMARK_RESOURCE,
/** Clean up a resource. */
CLEANUP_RESOURCE,
/** Opt in a resource. */
OPT_IN_RESOURCE,
/** Opt out a resource. */
OPT_OUT_RESOURCE
}
/** {@inheritDoc} */
@Override
public final Type type() {
return Type.JANITOR;
}
/** {@inheritDoc} */
@Override
public Context context() {
return ctx;
}
/** {@inheritDoc} */
@Override
public abstract void doMonkeyBusiness();
/**
* Opt in a resource for Janitor Monkey.
* @param resourceId the resource id
* @return the opt-in event
*/
public abstract Event optInResource(String resourceId);
/**
* Opt out a resource for Janitor Monkey.
* @param resourceId the resource id
* @return the opt-out event
*/
public abstract Event optOutResource(String resourceId);
/**
* Opt in a resource for Janitor Monkey.
* @param resourceId the resource id
* @param region the region of the resource
* @return the opt-in event
*/
public abstract Event optInResource(String resourceId, String region);
/**
* Opt out a resource for Janitor Monkey.
* @param resourceId the resource id
* @param region the region of the resource
* @return the opt-out event
*/
public abstract Event optOutResource(String resourceId, String region);
}
| 4,688
| 26.582353
| 79
|
java
|
SimianArmy
|
SimianArmy-master/src/main/java/com/netflix/simianarmy/janitor/DryRunnableJanitor.java
|
/*
*
* Copyright 2017 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.Resource;
public interface DryRunnableJanitor extends Janitor {
default void cleanupDryRun(Resource markedResource) throws DryRunnableJanitorException {
// NO-OP
}
}
| 895
| 31
| 92
|
java
|
SimianArmy
|
SimianArmy-master/src/main/java/com/netflix/simianarmy/janitor/Janitor.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.ResourceType;
/**
* The interface for a janitor that performs the mark and cleanup operations for
* cloud resources of a resource type.
*/
public interface Janitor {
/**
* Gets the resource type the janitor is cleaning up.
* @return the resource type the janitor is cleaning up.
*/
ResourceType getResourceType();
/**
* Mark cloud resources as cleanup candidates and remove the marks for resources
* that no longer exist or should not be cleanup candidates anymore.
*/
void markResources();
/**
* Clean the resources up that are marked as cleanup candidates when appropriate.
*/
void cleanupResources();
}
| 1,389
| 29.217391
| 85
|
java
|
SimianArmy
|
SimianArmy-master/src/main/java/com/netflix/simianarmy/janitor/JanitorResourceTracker.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.Resource;
import com.netflix.simianarmy.ResourceType;
import java.util.List;
/**
* The interface to track the resources marked/cleaned by the Janitor Monkey.
*
*/
public interface JanitorResourceTracker {
/**
* Adds a resource to the tracker. If the resource with the same id already exists
* in the tracker, the method updates the record with the resource parameter.
* @param resource the resource to add or update
*/
void addOrUpdate(Resource resource);
/** Gets the list of resources of a specific resource type and cleanup state in a region.
*
* @param resourceType the resource type
* @param state the cleanup state of the resources
* @param region the region of the resources, when the parameter is null, the method returns
* resources from all regions
* @return list of resources that match the resource type, state and region
*/
List<Resource> getResources(ResourceType resourceType, Resource.CleanupState state, String region);
/** Gets the resource of a specific id.
*
* @param resourceId the resource id
* @return the resource that matches the resource id
*/
Resource getResource(String resourceId);
/** Gets the resource of a specific id.
*
* @param resourceId the resource id
* @param regionId the region id
* @return the resource that matches the resource id and region
*/
Resource getResource(String resourceId, String regionId);
}
| 2,200
| 33.390625
| 103
|
java
|
SimianArmy
|
SimianArmy-master/src/main/java/com/netflix/simianarmy/janitor/JanitorRuleEngine.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.Resource;
import java.util.List;
/**
* The interface for janitor rule engine that can decide if a resource should be a candidate of cleanup
* based on a collection of rules.
*/
public interface JanitorRuleEngine {
/**
* Decides whether the resource should be a candidate of cleanup based on the underlying rules.
*
* @param resource
* The resource
* @return true if the resource is valid and should not be a candidate of cleanup based on the underlying rules,
* false otherwise.
*/
boolean isValid(Resource resource);
/**
* Add a rule to decide if a resource should be a candidate for cleanup.
*
* @param rule
* The rule to decide if a resource should be a candidate for cleanup.
* @return The JanitorRuleEngine object.
*/
JanitorRuleEngine addRule(Rule rule);
/**
* Add a rule to decide if a resource should be excluded for cleanup.
* Exclusion rules are evaluated before regular rules. If a resource
* matches an exclusion rule, it is excluded from all other cleanup rules.
*
* @param rule
* The rule to decide if a resource should be excluded for cleanup.
* @return The JanitorRuleEngine object.
*/
JanitorRuleEngine addExclusionRule(Rule rule);
/**
* Get rules to find out what's planned for enforcement.
*
* @return An ArrayList of Rules.
*/
List<Rule> getRules();
/**
* Get rules to find out what's excluded for enforcement.
*
* @return An ArrayList of Rules.
*/
List<Rule> getExclusionRules();
}
| 2,351
| 30.783784
| 116
|
java
|
SimianArmy
|
SimianArmy-master/src/main/java/com/netflix/simianarmy/janitor/AbstractJanitor.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 java.util.*;
import com.google.common.collect.Maps;
import com.netflix.servo.annotations.DataSourceType;
import com.netflix.servo.annotations.Monitor;
import com.netflix.servo.annotations.MonitorTags;
import com.netflix.servo.monitor.BasicCounter;
import com.netflix.servo.monitor.Counter;
import com.netflix.servo.monitor.MonitorConfig;
import com.netflix.servo.monitor.Monitors;
import com.netflix.servo.tag.BasicTagList;
import com.netflix.servo.tag.TagList;
import com.netflix.simianarmy.*;
import com.netflix.simianarmy.MonkeyRecorder.Event;
import com.netflix.simianarmy.Resource.CleanupState;
import com.netflix.simianarmy.janitor.JanitorMonkey.EventTypes;
import com.netflix.simianarmy.janitor.JanitorMonkey.Type;
import org.apache.commons.lang.Validate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* An abstract implementation of Janitor. It marks resources that the rule engine considers
* invalid as cleanup candidate and sets the expected termination date. It also removes the
* cleanup candidate flag from resources that no longer exist or the rule engine no longer
* considers invalid due to change of conditions. For resources marked as cleanup candidates
* and the expected termination date is passed, the janitor removes the resources from the
* cloud.
*/
public abstract class AbstractJanitor implements Janitor, DryRunnableJanitor {
/** The Constant LOGGER. */
private static final Logger LOGGER = LoggerFactory.getLogger(AbstractJanitor.class);
/** Tags to attach to servo metrics */
@MonitorTags
protected TagList tags;
private final String region;
/** The region the janitor is running in. */
public String getRegion() {
return region;
}
/**
* The rule engine used to decide if a resource should be a cleanup
* candidate.
*/
private final JanitorRuleEngine ruleEngine;
/** The janitor crawler to get resources from the cloud. */
private final JanitorCrawler crawler;
/** The resource type that the janitor is responsible for to clean up. **/
private final ResourceType resourceType;
/** The janitor resource tracker that is responsible for keeping track of
* resource status.
*/
private final JanitorResourceTracker resourceTracker;
private final Collection<Resource> markedResources = new ArrayList<Resource>();
private final Collection<Resource> cleanedResources = new ArrayList<Resource>();
private final Collection<Resource> unmarkedResources = new ArrayList<Resource>();
private final Collection<Resource> failedToCleanResources = new ArrayList<Resource>();
private final Collection<Resource> skippedVanishedOrValidResources = new ArrayList<>();
private final MonkeyCalendar calendar;
private final MonkeyConfiguration config;
/** Flag to indicate whether the Janitor is leashed. */
private boolean leashed;
private final MonkeyRecorder recorder;
/** The number of resources that have been checked on this run. */
private int checkedResourcesCount;
private Counter cleanupDryRunFailureCount = new BasicCounter(MonitorConfig.builder("dryRunCleanupFailures").build());
/**
* Sets the flag to indicate if the janitor is leashed.
*
* @param isLeashed true if the the janitor is leased, false otherwise.
*/
protected void setLeashed(boolean isLeashed) {
this.leashed = isLeashed;
}
/**
* The Interface Context.
*/
public interface Context {
/** Region.
*
* @return the region
*/
String region();
/**
* Configuration.
*
* @return the monkey configuration
*/
MonkeyConfiguration configuration();
/**
* Calendar.
*
* @return the monkey calendar
*/
MonkeyCalendar calendar();
/**
* Janitor rule engine.
* @return the janitor rule engine
*/
JanitorRuleEngine janitorRuleEngine();
/**
* Janitor crawler.
*
* @return the chaos crawler
*/
JanitorCrawler janitorCrawler();
/**
* Janitor resource tracker.
*
* @return the janitor resource tracker
*/
JanitorResourceTracker janitorResourceTracker();
/**
* Recorder.
*
* @return the recorder to record events
*/
MonkeyRecorder recorder();
}
/**
* Constructor.
* @param ctx the context
* @param resourceType the resource type the janitor is taking care
*/
public AbstractJanitor(Context ctx, ResourceType resourceType) {
Validate.notNull(ctx);
Validate.notNull(resourceType);
this.region = ctx.region();
Validate.notNull(region);
this.ruleEngine = ctx.janitorRuleEngine();
Validate.notNull(ruleEngine);
this.crawler = ctx.janitorCrawler();
Validate.notNull(crawler);
this.resourceTracker = ctx.janitorResourceTracker();
Validate.notNull(resourceTracker);
this.calendar = ctx.calendar();
Validate.notNull(calendar);
this.config = ctx.configuration();
Validate.notNull(config);
// By default the janitor is leashed.
this.leashed = config.getBoolOrElse("simianarmy.janitor.leashed", true);
this.resourceType = resourceType;
Validate.notNull(resourceType);
// recorder could be null and no events are recorded when it is.
this.recorder = ctx.recorder();
// setup servo tags, currently just tag each published metric with the region
this.tags = BasicTagList.of("simianarmy.janitor.region", ctx.region());
// register this janitor with servo
String monitorObjName = String.format("simianarmy.janitor.%s.%s", this.resourceType.name(), this.region);
Monitors.registerObject(monitorObjName, this);
}
@Override
public ResourceType getResourceType() {
return resourceType;
}
/**
* Clears this object's internal resource lists in preparation for a new
* run.
*
* This is an optional method as regular Janitor processing will
* automatically clear resource lists as it runs.
*
* This method offers an explicit clear so that the resources will be
* consistent across the run. For example, when starting a run after a
* previous run has finished, cleanedResources will be holding the cleaned
* resources from the prior run until cleanupResources() is called. By
* calling prepareToRun() first, the resource lists will be consistent
* for the entire run.
*/
public void prepareToRun() {
markedResources.clear();
unmarkedResources.clear();
checkedResourcesCount = 0;
cleanedResources.clear();
failedToCleanResources.clear();
}
/**
* Marks all resources obtained from the crawler as cleanup candidate if
* the janitor rule engine thinks so.
*/
@Override
public void markResources() {
if (config.getBoolOrElse("simianarmy.janitor.skipMark", false)) {
LOGGER.info("*****SKIPPING MARKING {}****", resourceType);
return ;
}
markedResources.clear();
unmarkedResources.clear();
checkedResourcesCount = 0;
Map<String, Resource> trackedMarkedResources = getTrackedMarkedResources();
List<Resource> crawledResources = crawler.resources(resourceType);
LOGGER.info("Looking for cleanup candidate in {} crawled resources. LeashMode={}", crawledResources.size(), leashed);
Date now = calendar.now().getTime();
for (Resource resource : crawledResources) {
checkedResourcesCount++;
Resource trackedResource = trackedMarkedResources.get(resource.getId());
if (!ruleEngine.isValid(resource)) {
// If the resource is already marked, ignore it
if (trackedResource != null) {
LOGGER.debug("Resource {} is already marked. LeashMode={}", resource.getId(), leashed);
continue;
}
LOGGER.info("Marking resource {} of type {} with expected termination time as {} LeashMode={}"
, resource.getId(), resource.getResourceType(), resource.getExpectedTerminationTime(), leashed);
resource.setState(CleanupState.MARKED);
resource.setMarkTime(now);
resourceTracker.addOrUpdate(resource);
if (!leashed && recorder != null) {
Event evt = recorder.newEvent(Type.JANITOR, EventTypes.MARK_RESOURCE, resource, resource.getId());
recorder.recordEvent(evt);
}
postMark(resource);
markedResources.add(resource);
} else if (trackedResource != null) {
// The resource was marked and now the rule engine does not consider it as a cleanup candidate.
// So the janitor needs to unmark the resource.
LOGGER.info("Unmarking resource {} LeashMode={}", resource.getId(), leashed);
resource.setState(CleanupState.UNMARKED);
resourceTracker.addOrUpdate(resource);
if (!leashed && recorder != null) {
Event evt = recorder.newEvent(
Type.JANITOR, EventTypes.UNMARK_RESOURCE, resource, resource.getId());
recorder.recordEvent(evt);
}
unmarkedResources.add(resource);
}
}
// Unmark the resources that are terminated by user so not returned by the crawler.
unmarkUserTerminatedResources(crawledResources, trackedMarkedResources);
}
/**
* Gets the existing resources that are marked as cleanup candidate. Allowing the subclass to override for e.g.
* to handle multi-region.
* @return the map from resource id to marked resource
*/
protected Map<String, Resource> getTrackedMarkedResources() {
Map<String, Resource> trackedMarkedResources = Maps.newHashMap();
for (Resource resource : resourceTracker.getResources(resourceType, Resource.CleanupState.MARKED, region)) {
trackedMarkedResources.put(resource.getId(), resource);
}
return trackedMarkedResources;
}
/**
* Cleans up all cleanup candidates that are OK to remove.
*/
@Override
public void cleanupResources() {
cleanedResources.clear();
failedToCleanResources.clear();
skippedVanishedOrValidResources.clear();
Map<String, Resource> trackedMarkedResources = getTrackedMarkedResources();
LOGGER.info("Checking {} marked resources for cleanup. LeashMode={}", trackedMarkedResources.size(), leashed);
Date now = calendar.now().getTime();
for (Resource markedResource : trackedMarkedResources.values()) {
if (config.getBoolOrElse("simianarmy.janitor.skipVanishedOrValidResources", false)) {
// find matching crawled resource. This ensures we always have the freshest resource.
List<Resource> matchingCrawledResources = Optional.ofNullable(crawler.resources(markedResource.getId()))
.orElse(Collections.emptyList());
LOGGER.info("Rechecking resource {} before deletion {} - matching candidates {}",
markedResource, markedResource.getResourceType(), matchingCrawledResources);
Optional<Resource> crawledResource = matchingCrawledResources.stream()
.filter(r -> r.equals(markedResource))
.findFirst();
if (!crawledResource.isPresent() || ruleEngine.isValid(crawledResource.get())) {
skippedVanishedOrValidResources.add(markedResource);
LOGGER.warn("Skipping resource {} that either no longer exists or is now valid", markedResource);
continue;
}
}
if (canClean(markedResource, now)) {
LOGGER.info("Cleaning up resource {} of type {}. LeashMode={}",
markedResource.getId(), markedResource.getResourceType().name(), leashed);
try {
if (leashed) {
cleanupDryRun(markedResource.cloneResource());
} else {
cleanup(markedResource);
markedResource.setActualTerminationTime(now);
markedResource.setState(Resource.CleanupState.JANITOR_TERMINATED);
resourceTracker.addOrUpdate(markedResource);
if (recorder != null) {
Event evt = recorder.newEvent(Type.JANITOR, EventTypes.CLEANUP_RESOURCE, markedResource,
markedResource.getId());
recorder.recordEvent(evt);
}
postCleanup(markedResource);
cleanedResources.add(markedResource);
}
} catch (Exception e) {
String message;
if (e instanceof DryRunnableJanitorException) {
message = String.format("Failed Dry Run cleanup of resource %s of type %s. LeashMode=%b",
markedResource.getId(), markedResource.getResourceType().name(), leashed);
cleanupDryRunFailureCount.increment();
} else {
message = String.format("Failed to clean up the resource %s of type %s. LeashMode=%b",
markedResource.getId(), markedResource.getResourceType().name(), leashed);
failedToCleanResources.add(markedResource);
}
LOGGER.error(message, e);
}
}
}
}
/** Determines if the input resource can be cleaned. The Janitor calls this method
* before cleaning up a resource and only cleans the resource when the method returns
* true. A resource is considered to be OK to clean if
* 1) it is marked as cleanup candidates
* 2) the expected termination time is already passed
* 3) the owner has already been notified about the cleanup
* 4) the resource is not opted out of Janitor monkey
* The method can be overridden in subclasses.
* @param resource the resource the Janitor considers to clean
* @param now the time that represents the current time
* @return true if the resource is OK to clean, false otherwise
*/
protected boolean canClean(Resource resource, Date now) {
return resource.getState() == Resource.CleanupState.MARKED
&& !resource.isOptOutOfJanitor()
&& resource.getExpectedTerminationTime() != null
&& resource.getExpectedTerminationTime().before(now)
&& resource.getNotificationTime() != null
&& resource.getNotificationTime().before(now);
}
/**
* Implements required operations after a resource is marked.
* @param resource The resource that is marked
*/
protected abstract void postMark(Resource resource);
/**
* Cleans a resource up, e.g. deleting the resource from the cloud.
* @param resource The resource that is cleaned up.
*/
protected abstract void cleanup(Resource resource);
/**
* Implements required operations after a resource is cleaned.
* @param resource The resource that is cleaned up.
*/
protected abstract void postCleanup(Resource resource);
/** gets the resources marked in the last run of the Janitor. */
public Collection<Resource> getMarkedResources() {
return Collections.unmodifiableCollection(markedResources);
}
/** gets the resources unmarked in the last run of the Janitor. */
public Collection<Resource> getUnmarkedResources() {
return Collections.unmodifiableCollection(unmarkedResources);
}
/** gets the resources cleaned in the last run of the Janitor. */
public Collection<Resource> getCleanedResources() {
return Collections.unmodifiableCollection(cleanedResources);
}
/** gets the resources that failed to be cleaned in the last run of the Janitor. */
public Collection<Resource> getFailedToCleanResources() {
return Collections.unmodifiableCollection(failedToCleanResources);
}
private void unmarkUserTerminatedResources(List<Resource> crawledResources, Map<String, Resource> trackedMarkedResources) {
Set<String> crawledResourceIds = new HashSet<String>();
for (Resource crawledResource : crawledResources) {
crawledResourceIds.add(crawledResource.getId());
}
if (config.getBoolOrElse("simianarmy.janitor.unmarkResourceNotReturnedByCrawler", false)) {
for (Resource markedResource : trackedMarkedResources.values()) {
if (!crawledResourceIds.contains(markedResource.getId())) {
// The resource does not exist anymore.
LOGGER.info("Resource {} is not returned by the crawler. It should already be terminated. LeashMode={}",
markedResource.getId(), leashed);
markedResource.setState(Resource.CleanupState.USER_TERMINATED);
resourceTracker.addOrUpdate(markedResource);
unmarkedResources.add(markedResource);
}
}
}
}
@Monitor(name="cleanedResourcesCount", type=DataSourceType.GAUGE)
public int getResourcesCleanedCount() {
return cleanedResources.size();
}
@Monitor(name="markedResourcesCount", type=DataSourceType.GAUGE)
public int getMarkedResourcesCount() {
return markedResources.size();
}
@Monitor(name="failedToCleanResourcesCount", type=DataSourceType.GAUGE)
public int getFailedToCleanResourcesCount() {
return failedToCleanResources.size();
}
@Monitor(name="unmarkedResourcesCount", type=DataSourceType.GAUGE)
public int getUnmarkedResourcesCount() {
return unmarkedResources.size();
}
@Monitor(name="checkedResourcesCount", type=DataSourceType.GAUGE)
public int getCheckedResourcesCount() {
return checkedResourcesCount;
}
@Monitor(name="skippedVanishedOrValidResources", type = DataSourceType.GAUGE)
public int skippedVanishedOrValidResources() {
return skippedVanishedOrValidResources.size();
}
public Counter getCleanupDryRunFailureCount() {
return cleanupDryRunFailureCount;
}
}
| 19,637
| 39.324435
| 127
|
java
|
SimianArmy
|
SimianArmy-master/src/main/java/com/netflix/simianarmy/janitor/DryRunnableJanitorException.java
|
/*
*
* Copyright 2017 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;
public class DryRunnableJanitorException extends Exception {
public DryRunnableJanitorException(String message) {
super(message);
}
public DryRunnableJanitorException(String message, Throwable cause) {
super(message, cause);
}
}
| 944
| 30.5
| 79
|
java
|
SimianArmy
|
SimianArmy-master/src/main/java/com/netflix/simianarmy/janitor/JanitorCrawler.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 java.util.EnumSet;
import java.util.List;
import com.netflix.simianarmy.Resource;
import com.netflix.simianarmy.ResourceType;
/**
* The crawler for janitor monkey.
*/
public interface JanitorCrawler {
/**
* Resource types.
*
* @return the type of resources this crawler crawls
*/
EnumSet<? extends ResourceType> resourceTypes();
/**
* Resources crawled by this crawler for a specific resource type.
*
* @param resourceType the resource type
* @return the list
*/
List<Resource> resources(ResourceType resourceType);
/**
* Gets the up to date information for a collection of resource ids. When the input argument is null
* or empty, the method returns all resources.
*
* @param resourceIds
* the resource ids
* @return the list of resources
*/
List<Resource> resources(String... resourceIds);
/**
* Gets the owner email for a resource to set the ownerEmail field when crawl.
* @param resource the resource
* @return the owner email of the resource
*/
String getOwnerEmailForResource(Resource resource);
}
| 1,842
| 27.796875
| 104
|
java
|
SimianArmy
|
SimianArmy-master/src/main/java/com/netflix/simianarmy/janitor/JanitorEmailBuilder.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 java.util.Collection;
import java.util.Map;
import com.netflix.simianarmy.AbstractEmailBuilder;
import com.netflix.simianarmy.Resource;
/** The abstract class for building Janitor monkey email notifications. */
public abstract class JanitorEmailBuilder extends AbstractEmailBuilder {
/**
* Sets the map from an owner email to the resources that belong to the owner
* and need to send notifications for.
* @param emailToResources the map from owner email to the owned resource
*/
public abstract void setEmailToResources(Map<String, Collection<Resource>> emailToResources);
}
| 1,294
| 34.972222
| 97
|
java
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.