index int64 0 0 | repo_id stringlengths 26 205 | file_path stringlengths 51 246 | content stringlengths 8 433k | __index_level_0__ int64 0 10k |
|---|---|---|---|---|
0 | Create_ds/Fenzo/fenzo-core/src/test/java/com/netflix | Create_ds/Fenzo/fenzo-core/src/test/java/com/netflix/fenzo/ScalarResourceTests.java | /*
* Copyright 2016 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.fenzo;
import com.netflix.fenzo.functions.Action1;
import org.apache.mesos.Protos;
import org.junit.Assert;
import org.junit.Test;
import java.util.*;
public class ScalarResourceTests {
private TaskScheduler getScheduler() {
return getScheduler(false);
}
private TaskScheduler getScheduler(boolean singleLeaseMode) {
return new TaskScheduler.Builder()
.withLeaseOfferExpirySecs(1000000)
.withSingleOfferPerVM(singleLeaseMode)
.withLeaseRejectAction(new Action1<VirtualMachineLease>() {
@Override
public void call(VirtualMachineLease virtualMachineLease) {
System.out.println("Rejecting offer on host " + virtualMachineLease.hostname());
}
})
.build();
}
// Test that asking for a scalar resource gets the task assigned
@Test
public void testScalar1() throws Exception {
final TaskScheduler scheduler = getScheduler();
final Map<String, Double> scalars = new HashMap<>();
scalars.put("gpu", 1.0);
final TaskRequest task = TaskRequestProvider.getTaskRequest(null, 1, 100, 1, 1, 1, null, null, null, scalars);
final VirtualMachineLease host1 = LeaseProvider.getLeaseOffer("host1", 4.0, 4000.0, 100, 1024,
Collections.singletonList(new VirtualMachineLease.Range(1, 10)), null, scalars);
final SchedulingResult result = scheduler.scheduleOnce(Collections.singletonList(task), Collections.singletonList(host1));
Assert.assertEquals(0, result.getFailures().size());
Assert.assertEquals(1, result.getResultMap().size());
Assert.assertEquals(task.getId(), result.getResultMap().values().iterator().next().getTasksAssigned().iterator().next().getRequest().getId());
}
// Test that asking for more than available scalar resources does not get the task assigned
@Test
public void testInsufficientScalarResources() throws Exception {
final TaskScheduler scheduler = getScheduler();
final double scalarsOnHost=4.0;
final TaskRequest task = TaskRequestProvider.getTaskRequest(null, 1, 100, 1, 1, 1, null, null, null, Collections.singletonMap("gpu", scalarsOnHost+1.0));
final VirtualMachineLease host1 = LeaseProvider.getLeaseOffer("host1", 4.0, 4000.0, 100, 1024,
Collections.singletonList(new VirtualMachineLease.Range(1, 10)), null, Collections.singletonMap("gpu", scalarsOnHost));
final SchedulingResult result = scheduler.scheduleOnce(Collections.singletonList(task), Collections.singletonList(host1));
Assert.assertEquals(1, result.getFailures().size());
Assert.assertEquals(0, result.getResultMap().size());
Assert.assertEquals(VMResource.Other, result.getFailures().values().iterator().next().get(0).getFailures().get(0).getResource());
System.out.println(result.getFailures().values().iterator().next().get(0).getFailures().get(0));
}
@Test
public void testMultipleTasksScalarRequests() throws Exception {
final TaskScheduler scheduler = getScheduler();
final double scalarsOnHost = 4.0;
final List<TaskRequest> tasks = new ArrayList<>();
for (int i = 0; i < scalarsOnHost + 1; i++)
tasks.add(TaskRequestProvider.getTaskRequest(null, 1, 100, 1, 1, 1, null, null, null, Collections.singletonMap("gpu", 1.0)));
final VirtualMachineLease host1 = LeaseProvider.getLeaseOffer("host1", scalarsOnHost*2.0, scalarsOnHost*2000.0, 100, 1024,
Collections.singletonList(new VirtualMachineLease.Range(1, 10)), null, Collections.singletonMap("gpu", scalarsOnHost));
final SchedulingResult result = scheduler.scheduleOnce(tasks, Collections.singletonList(host1));
Assert.assertEquals(1, result.getFailures().size());
Assert.assertEquals(1, result.getResultMap().size());
Assert.assertEquals((int)scalarsOnHost, result.getResultMap().values().iterator().next().getTasksAssigned().size());
Assert.assertEquals(VMResource.Other, result.getFailures().values().iterator().next().get(0).getFailures().get(0).getResource());
}
@Test
public void testScalarRequestsAcrossHosts() throws Exception {
final TaskScheduler scheduler = getScheduler();
final double scalarsOnHost = 4.0;
final List<TaskRequest> tasks = new ArrayList<>();
for (int i = 0; i < scalarsOnHost * 2; i++)
tasks.add(TaskRequestProvider.getTaskRequest(null, 1, 100, 1, 1, 1, null, null, null, Collections.singletonMap("gpu", 1.0)));
final VirtualMachineLease host1 = LeaseProvider.getLeaseOffer("host1", scalarsOnHost, scalarsOnHost*1000.0, 100, 1024,
Collections.singletonList(new VirtualMachineLease.Range(1, 10)), null, Collections.singletonMap("gpu", scalarsOnHost));
final VirtualMachineLease host2 = LeaseProvider.getLeaseOffer("host2", scalarsOnHost, scalarsOnHost*1000.0, 100, 1024,
Collections.singletonList(new VirtualMachineLease.Range(1, 10)), null, Collections.singletonMap("gpu", scalarsOnHost));
final SchedulingResult result = scheduler.scheduleOnce(tasks, Arrays.asList(host1, host2));
Assert.assertEquals(0, result.getFailures().size());
Assert.assertEquals(2, result.getResultMap().size());
int tasksAssigned=0;
for(VMAssignmentResult r: result.getResultMap().values()) {
tasksAssigned += r.getTasksAssigned().size();
}
Assert.assertEquals(tasks.size(), tasksAssigned);
}
// test allocation of multiple scalar resources
@Test
public void testMultipleScalarResources() throws Exception {
final TaskScheduler scheduler = getScheduler();
final double scalars1OnHost = 4.0;
final double scalars2OnHost = 2.0;
final Map<String, Double> scalarReqs = new HashMap<>();
scalarReqs.put("gpu", 1.0);
scalarReqs.put("foo", 1.0);
final List<TaskRequest> tasks = new ArrayList<>();
for(int i=0; i<scalars1OnHost*2; i++)
tasks.add(TaskRequestProvider.getTaskRequest(null, 1, 100, 1, 1, 1, null, null, null, scalarReqs));
final Map<String, Double> scalarResources = new HashMap<>();
scalarResources.put("gpu", scalars1OnHost);
scalarResources.put("foo", scalars2OnHost);
final VirtualMachineLease host1 = LeaseProvider.getLeaseOffer("host1", scalars1OnHost*2.0, scalars1OnHost*2000.0, 100, 1024,
Collections.singletonList(new VirtualMachineLease.Range(1, 10)), null, scalarResources);
final VirtualMachineLease host2 = LeaseProvider.getLeaseOffer("host2", scalars1OnHost*2.0, scalars1OnHost*2000.0, 100, 1024,
Collections.singletonList(new VirtualMachineLease.Range(1, 10)), null, scalarResources);
final SchedulingResult result = scheduler.scheduleOnce(tasks, Arrays.asList(host1, host2));
Assert.assertEquals((int)(scalars1OnHost/scalars2OnHost)*2, result.getFailures().size());
Assert.assertEquals(2, result.getResultMap().size());
int tasksAssigned=0;
for(VMAssignmentResult r: result.getResultMap().values()) {
tasksAssigned += r.getTasksAssigned().size();
}
Assert.assertEquals((int)(scalars2OnHost*2.0), tasksAssigned);
}
@Test
public void testInsufficientScalarResourcesWithSingleLeaseMode() {
final TaskScheduler scheduler = getScheduler(true);
final double scalarsOnHost=4.0;
final TaskRequest task = TaskRequestProvider.getTaskRequest(null, 1, 100, 1, 1, 1, null, null, null, Collections.singletonMap("gpu", scalarsOnHost+1.0));
final VirtualMachineLease host1 = LeaseProvider.getLeaseOffer("host1", 4.0, 4000.0, 100, 1024,
Collections.singletonList(new VirtualMachineLease.Range(1, 10)), null, Collections.singletonMap("gpu", scalarsOnHost));
final SchedulingResult result = scheduler.scheduleOnce(Collections.singletonList(task), Collections.singletonList(host1));
Assert.assertEquals(1, result.getFailures().size());
Assert.assertEquals(0, result.getResultMap().size());
Assert.assertEquals(VMResource.Other, result.getFailures().values().iterator().next().get(0).getFailures().get(0).getResource());
System.out.println(result.getFailures().values().iterator().next().get(0).getFailures().get(0));
}
@Test
public void testRemovingLeaseAndAddingBackSameLeaseWithSingleLeaseMode() {
final TaskScheduler scheduler = getScheduler(true);
final TaskRequest task = TaskRequestProvider.getTaskRequest(null, 1, 1, 1,
1, 1, null, null, null, Collections.emptyMap());
final VirtualMachineLease lease1 = LeaseProvider.getLeaseOffer("host1", 1.0, 1.0, 1, 1,
Collections.singletonList(new VirtualMachineLease.Range(1, 10)), null, Collections.emptyMap());
final SchedulingResult result1 = scheduler.scheduleOnce(Collections.singletonList(task), Collections.singletonList(lease1));
Assert.assertEquals(0, result1.getFailures().size());
Assert.assertEquals(1, result1.getResultMap().size());
// Expire the leases and run a scheduling loop to make sure they are gone
scheduler.expireAllLeases();
scheduler.scheduleOnce(Collections.emptyList(), Collections.emptyList());
List<VirtualMachineCurrentState> vmCurrentStates1 = scheduler.getVmCurrentStates();
Collection<Protos.Offer> offers1 = vmCurrentStates1.get(0).getAllCurrentOffers();
Assert.assertEquals(0, offers1.size());
// Run another scheduling iteration with the same lease and make sure it can be added back as an offer
final SchedulingResult result2 = scheduler.scheduleOnce(Collections.singletonList(task), Collections.singletonList(lease1));
Assert.assertEquals(0, result2.getFailures().size());
Assert.assertEquals(1, result2.getResultMap().size());
List<VirtualMachineCurrentState> vmCurrentStates2 = scheduler.getVmCurrentStates();
Collection<Protos.Offer> offers2 = vmCurrentStates2.get(0).getAllCurrentOffers();
Assert.assertEquals(1, offers2.size());
System.out.println(vmCurrentStates2.get(0).getAllCurrentOffers());
}
}
| 9,100 |
0 | Create_ds/Fenzo/fenzo-core/src/test/java/com/netflix | Create_ds/Fenzo/fenzo-core/src/test/java/com/netflix/fenzo/ResourceSetsTests.java | /*
* Copyright 2015 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.fenzo;
import com.netflix.fenzo.functions.Action1;
import com.netflix.fenzo.functions.Func1;
import com.netflix.fenzo.plugins.BinPackingFitnessCalculators;
import org.junit.Assert;
import org.apache.mesos.Protos;
import org.junit.Test;
import java.util.*;
import java.util.concurrent.atomic.AtomicBoolean;
public class ResourceSetsTests {
private static final String resSetsAttrName = "res";
static String hostAttrName = "MachineType";
static final String hostAttrVal1="4coreServers";
static Map<String, Protos.Attribute> getResSetsAttributesMap(String name, int x, int y) {
Map<String, Protos.Attribute> attr = new HashMap<>();
attr.put(
resSetsAttrName,
Protos.Attribute.newBuilder().setName(resSetsAttrName)
.setType(Protos.Value.Type.TEXT)
.setText(Protos.Value.Text.newBuilder().setValue(
PreferentialNamedConsumableResourceSet.attributeName + "-" + name + "-" + x + "-" + y
)).build()
);
attr.put(
hostAttrName,
Protos.Attribute.newBuilder().setName(hostAttrName)
.setType(Protos.Value.Type.TEXT)
.setText(Protos.Value.Text.newBuilder().setValue(hostAttrVal1))
.build()
);
return attr;
}
private TaskScheduler getTaskScheduler() {
return getTaskScheduler(true);
}
private TaskScheduler getTaskScheduler(boolean useBinPacking) {
return getTaskSchedulerWithAutoscale(useBinPacking, null);
}
private TaskScheduler getTaskSchedulerWithAutoscale(boolean useBinPacking, Action1<AutoScaleAction> callback, AutoScaleRule... rules) {
final TaskScheduler.Builder builder = new TaskScheduler.Builder()
.withLeaseOfferExpirySecs(1000000)
.withLeaseRejectAction(new Action1<VirtualMachineLease>() {
@Override
public void call(VirtualMachineLease virtualMachineLease) {
System.out.println("Rejecting offer on host " + virtualMachineLease.hostname());
}
})
.withAutoScaleByAttributeName(hostAttrName)
.withFitnessGoodEnoughFunction(new Func1<Double, Boolean>() {
@Override
public Boolean call(Double aDouble) {
return aDouble > 1.0;
}
});
if(callback!=null && rules!=null) {
builder.withAutoScalerCallback(callback);
for (AutoScaleRule r : rules)
builder.withAutoScaleRule(r);
}
if(useBinPacking)
builder
.withFitnessCalculator(BinPackingFitnessCalculators.cpuMemBinPacker);
return builder.build();
}
// Create 4 tasks to be launched on 1 host which has 3 resource sets. Two tasks ask for one value for the
// resourceSet and the other two tasks ask for another value. Confirm that exactly two of the three resource sets
// are used.
@Test
public void testSimpleResourceSetAllocation() throws Exception {
int numCores=4;
int numENIs=numCores-1;
int numIPsPerEni=8;
List<VirtualMachineLease> leases = new ArrayList<>();
List<VirtualMachineLease.Range> ports = new ArrayList<>();
ports.add(new VirtualMachineLease.Range(1, 10));
leases.add(LeaseProvider.getLeaseOffer(
"hostA", numCores, numCores*1000, ports, getResSetsAttributesMap("ENIs", numENIs, numIPsPerEni)));
TaskRequest.NamedResourceSetRequest sr1 = new TaskRequest.NamedResourceSetRequest("ENIs", "sg1", 1, 1);
TaskRequest.NamedResourceSetRequest sr2 = new TaskRequest.NamedResourceSetRequest("ENIs", "sg2", 1, 1);
List<TaskRequest> tasks = new ArrayList<>();
tasks.add(TaskRequestProvider.getTaskRequest(
"grp", 1, 100, 0, 0, 0, null, null, Collections.singletonMap(sr1.getResName(), sr1)));
tasks.add(TaskRequestProvider.getTaskRequest(
"grp", 1, 100, 0, 0, 0, null, null, Collections.singletonMap(sr2.getResName(), sr2)));
// add two more tasks with similar resource requests
tasks.add(TaskRequestProvider.getTaskRequest(
"grp", 1, 100, 0, 0, 0, null, null, Collections.singletonMap(sr1.getResName(), sr1)));
tasks.add(TaskRequestProvider.getTaskRequest(
"grp", 1, 100, 0, 0, 0, null, null, Collections.singletonMap(sr2.getResName(), sr2)));
final TaskScheduler taskScheduler = getTaskScheduler();
final SchedulingResult result = taskScheduler.scheduleOnce(tasks, leases);
Assert.assertTrue(result.getResultMap().size() == 1);
final VMAssignmentResult assignmentResult = result.getResultMap().values().iterator().next();
Set<Integer> uniqueResSetIndeces = new HashSet<>();
for(TaskAssignmentResult r: assignmentResult.getTasksAssigned()) {
final List<PreferentialNamedConsumableResourceSet.ConsumeResult> consumeResults = r.getrSets();
Assert.assertTrue(consumeResults != null);
System.out.println("Task " + r.getRequest().getId() + ": index=" + consumeResults.get(0).getIndex());
uniqueResSetIndeces.add(consumeResults.get(0).getIndex());
}
Assert.assertTrue(uniqueResSetIndeces.size() == 2);
}
// Create a host that has 3 resource sets. Create three tasks with different resource values so each get assigned
// one of the 3 resource sets - so all 3 resource sets are now assigned. Although, each will have additional
// subResources available. Submit two new tasks - one with a resource value of one of the three already assigned,
// and another task with a new fourth resource value. Confirm that the first of these two tasks succeeds in
// assignment but the second one fails.
@Test
public void testResSetAllocationFailure() throws Exception {
int numCores=4;
int numENIs=numCores-1;
int numIPsPerEni=8;
List<VirtualMachineLease> leases = new ArrayList<>();
List<VirtualMachineLease.Range> ports = new ArrayList<>();
ports.add(new VirtualMachineLease.Range(1, 10));
leases.add(LeaseProvider.getLeaseOffer(
"hostA", numCores, numCores*1000, ports, getResSetsAttributesMap("ENIs", numENIs, numIPsPerEni)));
TaskRequest.NamedResourceSetRequest sr1 = new TaskRequest.NamedResourceSetRequest("ENIs", "sg1", 1, 1);
TaskRequest.NamedResourceSetRequest sr2 = new TaskRequest.NamedResourceSetRequest("ENIs", "sg2", 1, 1);
TaskRequest.NamedResourceSetRequest sr3 = new TaskRequest.NamedResourceSetRequest("ENIs", "sg3", 1, 1);
TaskRequest.NamedResourceSetRequest sr4 = new TaskRequest.NamedResourceSetRequest("ENIs", "sg4", 1, 1);
List<TaskRequest> tasks = new ArrayList<>();
tasks.add(TaskRequestProvider.getTaskRequest(
"grp", 1, 100, 0, 0, 0, null, null, Collections.singletonMap(sr1.getResName(), sr1)));
tasks.add(TaskRequestProvider.getTaskRequest(
"grp", 1, 100, 0, 0, 0, null, null, Collections.singletonMap(sr2.getResName(), sr2)));
tasks.add(TaskRequestProvider.getTaskRequest(
"grp", 1, 100, 0, 0, 0, null, null, Collections.singletonMap(sr3.getResName(), sr3)));
// task 4 same as task 1
tasks.add(TaskRequestProvider.getTaskRequest(
"grp", 0.25, 100, 0, 0, 0, null, null, Collections.singletonMap(sr1.getResName(), sr1)));
// task 5 uses sg4
tasks.add(TaskRequestProvider.getTaskRequest(
"grp", 0.25, 100, 0, 0, 0, null, null, Collections.singletonMap(sr1.getResName(), sr4)));
final TaskScheduler taskScheduler = getTaskScheduler();
final SchedulingResult result = taskScheduler.scheduleOnce(tasks, leases);
Assert.assertTrue(result.getResultMap().size() == 1);
final VMAssignmentResult assignmentResult = result.getResultMap().values().iterator().next();
Set<Integer> uniqueResSetIndeces = new HashSet<>();
int tasksAssigned=0;
for(TaskAssignmentResult r: assignmentResult.getTasksAssigned()) {
tasksAssigned++;
final List<PreferentialNamedConsumableResourceSet.ConsumeResult> consumeResults = r.getrSets();
Assert.assertTrue(consumeResults != null);
//System.out.println("Task " + r.getRequest().getId() + ": index=" + consumeResults.get(0).getIndex());
uniqueResSetIndeces.add(consumeResults.get(0).getIndex());
}
Assert.assertTrue(uniqueResSetIndeces.size() == 3);
Assert.assertTrue(tasksAssigned == 4);
final Map<TaskRequest, List<TaskAssignmentResult>> failures = result.getFailures();
Assert.assertTrue(failures != null && failures.size() == 1);
final List<TaskAssignmentResult> fail = failures.values().iterator().next();
Assert.assertTrue(fail.size() == 1);
final List<AssignmentFailure> failDetails = fail.iterator().next().getFailures();
Assert.assertTrue(failDetails!=null && failDetails.size()==1);
Assert.assertTrue(failDetails.iterator().next().getResource() == VMResource.ResourceSet);
//System.out.println(failDetails.iterator().next());
}
// Create a host that has 3 resource sets, each with 2 sub-resources. Submit a task that uses 1 rSet with
// 2 subResources. Then submit another similar job, confirm that it goes to a different resourceSet. Same again
// with a 3rd job. Then, submit a 4th job and ensure that although its resource requests for cpu/memory would fit,
// it fails since there are no more resource sets available
@Test
public void testResSetAllocFillupSubRes() throws Exception {
int numCores=4;
int numENIs=numCores-1;
int numIPsPerEni=2;
List<VirtualMachineLease> leases = new ArrayList<>();
List<VirtualMachineLease.Range> ports = new ArrayList<>();
ports.add(new VirtualMachineLease.Range(1, 10));
leases.add(LeaseProvider.getLeaseOffer(
"hostA", numCores, numCores*1000, ports, getResSetsAttributesMap("ENIs", numENIs, numIPsPerEni)));
TaskRequest.NamedResourceSetRequest sr1 = new TaskRequest.NamedResourceSetRequest("ENIs", "sg1", 1, 2);
List<TaskRequest> tasks = new ArrayList<>();
tasks.add(TaskRequestProvider.getTaskRequest(
"grp", 1, 100, 0, 0, 0, null, null, Collections.singletonMap(sr1.getResName(), sr1)));
tasks.add(TaskRequestProvider.getTaskRequest(
"grp", 1, 100, 0, 0, 0, null, null, Collections.singletonMap(sr1.getResName(), sr1)));
tasks.add(TaskRequestProvider.getTaskRequest(
"grp", 1, 100, 0, 0, 0, null, null, Collections.singletonMap(sr1.getResName(), sr1)));
tasks.add(TaskRequestProvider.getTaskRequest(
"grp", 1, 100, 0, 0, 0, null, null, Collections.singletonMap(sr1.getResName(), sr1)));
final TaskScheduler taskScheduler = getTaskScheduler();
final SchedulingResult result = taskScheduler.scheduleOnce(tasks, leases);
Assert.assertTrue(result.getResultMap().size() == 1);
final VMAssignmentResult assignmentResult = result.getResultMap().values().iterator().next();
Set<Integer> uniqueResSetIndeces = new HashSet<>();
int tasksAssigned=0;
for(TaskAssignmentResult r: assignmentResult.getTasksAssigned()) {
tasksAssigned++;
final List<PreferentialNamedConsumableResourceSet.ConsumeResult> consumeResults = r.getrSets();
Assert.assertTrue(consumeResults != null);
//System.out.println("Task " + r.getRequest().getId() + ": index=" + consumeResults.get(0).getIndex());
uniqueResSetIndeces.add(consumeResults.get(0).getIndex());
}
Assert.assertTrue(uniqueResSetIndeces.size() == 3);
Assert.assertTrue(tasksAssigned == 3);
final Map<TaskRequest, List<TaskAssignmentResult>> failures = result.getFailures();
Assert.assertTrue(failures != null && failures.size() == 1);
final List<TaskAssignmentResult> fail = failures.values().iterator().next();
Assert.assertTrue(fail.size() == 1);
final List<AssignmentFailure> failDetails = fail.iterator().next().getFailures();
Assert.assertTrue(failDetails!=null && failDetails.size()==1);
Assert.assertTrue(failDetails.iterator().next().getResource() == VMResource.ResourceSet);
}
// Create a host with 3 resource sets, each with 2 sub-resources. Submit two tasks that use up two of the 3 sets.
// That is, two tasks, each with different value for the resource set name, rs1 and rs2. Then, submit multiple tasks
// each with a request for a 3rd value for the resource name, rs3, but, asking for 0 sub-resources. Ensure that we
// are able to launch N of these, where N > 2 (sub-resources), at least until other resources on the host fill up
// (cpu/memory). And that the tasks asking for resource set value rs3 land on a different set than those asking
// for rs1 and rs2.
@Test
public void testResSetAllocFillWith0SubresRequests() throws Exception {
int numCores=4;
int numENIs=numCores-1;
int numIPsPerEni=2;
List<VirtualMachineLease> leases = new ArrayList<>();
List<VirtualMachineLease.Range> ports = new ArrayList<>();
ports.add(new VirtualMachineLease.Range(1, 10));
leases.add(LeaseProvider.getLeaseOffer(
"hostA", numCores, numCores*1000, ports, getResSetsAttributesMap("ENIs", numENIs, numIPsPerEni)));
TaskRequest.NamedResourceSetRequest sr1 = new TaskRequest.NamedResourceSetRequest("ENIs", "sg1", 1, 1);
TaskRequest.NamedResourceSetRequest sr2 = new TaskRequest.NamedResourceSetRequest("ENIs", "sg2", 1, 1);
TaskRequest.NamedResourceSetRequest sr3 = new TaskRequest.NamedResourceSetRequest("ENIs", "sg3", 1, 0);
// create two tasks, one asking for sr1 and another asking sr2
List<TaskRequest> tasks = new ArrayList<>();
tasks.add(TaskRequestProvider.getTaskRequest(
"grp", 0.1, 100, 0, 0, 0, null, null, Collections.singletonMap(sr1.getResName(), sr1)));
tasks.add(TaskRequestProvider.getTaskRequest(
"grp", 0.1, 100, 0, 0, 0, null, null, Collections.singletonMap(sr2.getResName(), sr2)));
// create 10 tasks asking for sr3
final int N=20; // #tasks for sr3
for(int i=0; i<N; i++)
tasks.add(TaskRequestProvider.getTaskRequest(
"grp", 0.1, 100, 0, 0, 0, null, null, Collections.singletonMap(sr3.getResName(), sr3)));
final TaskScheduler taskScheduler = getTaskScheduler();
final SchedulingResult result = taskScheduler.scheduleOnce(tasks, leases);
Assert.assertTrue(result.getResultMap().size() == 1);
Assert.assertEquals(0, result.getFailures().size());
final VMAssignmentResult assignmentResult = result.getResultMap().values().iterator().next();
final Map<String, Integer> counts = new HashMap<>();
for(TaskAssignmentResult r: assignmentResult.getTasksAssigned()) {
final String value = r.getRequest().getCustomNamedResources().get("ENIs").getResValue();
if(counts.get(value) == null)
counts.put(value, 1);
else
counts.put(value, counts.get(value)+1);
}
List<Integer> li = new ArrayList<>(counts.values());
Collections.sort(li);
Assert.assertEquals(1, (int) li.get(0));
Assert.assertEquals(1, (int) li.get(1));
Assert.assertEquals(N, (int) li.get(2));
}
// Create a host with 3 resource sets, each with 2 sub-resources. Submit these types of jobs:
// - Job type 1: asks for resource set sr1 with 1 sub-resource
// - Job type 2: asks for resource set sr2 with 1 sub-resource
// - Job type 3: does not ask for any resource set
// - Job type 4: asks for resource set sr3 with 1 sub-resource
// Submit 1 job each of type 1 and type 2. Then submit 2 jobs of type 3.
// Ensure that all of them get allocated. Even though the type 3 job doesn't ask for a resource set, it is supposed
// to get assigned a "catch-all" resource set.
// Submit another job of type 4 and ensure that it does not get assigned.
@Test
public void testNoResSetReqJob() throws Exception {
int numCores=4;
int numENIs=numCores-1;
int numIPsPerEni=2;
List<VirtualMachineLease> leases = new ArrayList<>();
List<VirtualMachineLease.Range> ports = new ArrayList<>();
ports.add(new VirtualMachineLease.Range(1, 10));
leases.add(LeaseProvider.getLeaseOffer(
"hostA", numCores, numCores*1000, ports, getResSetsAttributesMap("ENIs", numENIs, numIPsPerEni)));
TaskRequest.NamedResourceSetRequest sr1 = new TaskRequest.NamedResourceSetRequest("ENIs", "sg1", 1, 1);
TaskRequest.NamedResourceSetRequest sr2 = new TaskRequest.NamedResourceSetRequest("ENIs", "sg2", 1, 1);
TaskRequest.NamedResourceSetRequest sr3 = new TaskRequest.NamedResourceSetRequest("ENIs", "sg3", 1, 1);
// create two tasks, one asking for sr1 and another asking sr2
List<TaskRequest> tasks = new ArrayList<>();
tasks.add(TaskRequestProvider.getTaskRequest(
"grp", 0.1, 100, 0, 0, 0, null, null, Collections.singletonMap(sr1.getResName(), sr1)));
tasks.add(TaskRequestProvider.getTaskRequest(
"grp", 0.1, 100, 0, 0, 0, null, null, Collections.singletonMap(sr2.getResName(), sr2)));
final TaskScheduler taskScheduler = getTaskScheduler();
SchedulingResult result = taskScheduler.scheduleOnce(tasks, leases);
Assert.assertTrue(result.getResultMap().size() == 1);
Assert.assertEquals(0, result.getFailures().size());
final VMAssignmentResult assignmentResult = result.getResultMap().values().iterator().next();
Set<String> uniqueSRs = new HashSet<>();
for(TaskAssignmentResult r: assignmentResult.getTasksAssigned()) {
uniqueSRs.add(r.getRequest().getCustomNamedResources().values().iterator().next().getResValue());
taskScheduler.getTaskAssigner().call(r.getRequest(), "hostA");
}
Assert.assertEquals(2, uniqueSRs.size());
leases.clear();
leases.add(LeaseProvider.getConsumedLease(result.getResultMap().values().iterator().next()));
tasks.clear();
tasks.add(TaskRequestProvider.getTaskRequest(
"grp", 0.1, 100, 0, 0, 0, null, null, null));
tasks.add(TaskRequestProvider.getTaskRequest(
"grp", 0.1, 100, 0, 0, 0, null, null, Collections.singletonMap(sr3.getResName(), sr3)));
result = taskScheduler.scheduleOnce(tasks, leases);
Assert.assertTrue(result.getResultMap().size() == 1);
Assert.assertEquals(1, result.getResultMap().values().iterator().next().getTasksAssigned().size());
Assert.assertTrue(result.getResultMap().values().iterator().next().getTasksAssigned().iterator().next()
.getRequest().getCustomNamedResources() == null);
Assert.assertEquals(1, result.getFailures().size());
Assert.assertEquals(VMResource.ResourceSet,
result.getFailures().values().iterator().next().get(0).getFailures().get(0).getResource());
}
// Test that an initialization of scheduler with tasks assigned from before does the right thing for next scheduling
// iteration. Create a host with 3 resource sets, each with 2 sub-resources. Initialize scheduler with three tasks
// already assigned from before. Each task asks for 1 sub-resource. Task 1 requests resource set sr1 and was assigned
// on set 0. Task 2 requests resource set sr1 and was assigned on set 1. Task 3 requests resource set sr2 and was
// assigned on set 2.
// Now schedule 2 tasks, one asking for sr1 and another for sr3. The first task should get assigned and the second
// one should not.
// Then schedule another 2 tasks, one asking for sr2 and another asking sr3. The first task should get assigned
// and the second task should not.
@Test
public void testInitingSchedulerWithPreviousTasks() throws Exception {
int numCores=4;
int numENIs=numCores-1;
int numIPsPerEni=2;
List<VirtualMachineLease> leases = new ArrayList<>();
List<VirtualMachineLease.Range> ports = new ArrayList<>();
ports.add(new VirtualMachineLease.Range(1, 10));
leases.add(LeaseProvider.getLeaseOffer(
"hostA", numCores, numCores*1000, ports, getResSetsAttributesMap("ENIs", numENIs, numIPsPerEni)));
TaskRequest.NamedResourceSetRequest sr1 = new TaskRequest.NamedResourceSetRequest("ENIs", "sg1", 1, 1);
TaskRequest.NamedResourceSetRequest sr2 = new TaskRequest.NamedResourceSetRequest("ENIs", "sg2", 1, 1);
TaskRequest.NamedResourceSetRequest sr3 = new TaskRequest.NamedResourceSetRequest("ENIs", "sg3", 1, 1);
// create three tasks, two asking for sr1 and another one asking sr2
final TaskRequest task1 = TaskRequestProvider.getTaskRequest(
"grp", 0.1, 100, 0, 0, 0, null, null, Collections.singletonMap(sr1.getResName(), sr1));
final TaskRequest.AssignedResources ar1 = new TaskRequest.AssignedResources();
ar1.setConsumedNamedResources(Collections.singletonList(
new PreferentialNamedConsumableResourceSet.ConsumeResult(0, "ENIs", "sg1", 1.0)
));
task1.setAssignedResources(ar1);
final TaskRequest task2 = TaskRequestProvider.getTaskRequest(
"grp", 0.1, 100, 0, 0, 0, null, null, Collections.singletonMap(sr1.getResName(), sr1));
final TaskRequest.AssignedResources ar2 = new TaskRequest.AssignedResources();
ar2.setConsumedNamedResources(Collections.singletonList(
new PreferentialNamedConsumableResourceSet.ConsumeResult(1, "ENIs", "sg1", 1.0)
));
task2.setAssignedResources(ar2);
final TaskRequest task3 = TaskRequestProvider.getTaskRequest(
"grp", 0.1, 100, 0, 0, 0, null, null, Collections.singletonMap(sr2.getResName(), sr2));
final TaskRequest.AssignedResources ar3 = new TaskRequest.AssignedResources();
ar3.setConsumedNamedResources(Collections.singletonList(
new PreferentialNamedConsumableResourceSet.ConsumeResult(2, "ENIs", "sg2", 1.0)
));
task3.setAssignedResources(ar3);
final TaskScheduler taskScheduler = getTaskScheduler();
taskScheduler.getTaskAssigner().call(task1, "hostA");
taskScheduler.getTaskAssigner().call(task2, "hostA");
taskScheduler.getTaskAssigner().call(task3, "hostA");
List<TaskRequest> tasks = new ArrayList<>();
tasks.add(TaskRequestProvider.getTaskRequest(
"grp", 0.1, 100, 0, 0, 0, null, null, Collections.singletonMap(sr1.getResName(), sr1)));
tasks.add(TaskRequestProvider.getTaskRequest(
"grp", 0.1, 100, 0, 0, 0, null, null, Collections.singletonMap(sr3.getResName(), sr3)));
SchedulingResult result = taskScheduler.scheduleOnce(tasks, leases);
Assert.assertEquals(1, result.getFailures().size());
Assert.assertEquals(1, result.getResultMap().size());
Assert.assertEquals(1, result.getResultMap().values().iterator().next().getTasksAssigned().size());
TaskAssignmentResult assignmentResult =
result.getResultMap().values().iterator().next().getTasksAssigned().iterator().next();
Assert.assertEquals("sg1", assignmentResult.getRequest().getCustomNamedResources().values().iterator().next().getResValue());
taskScheduler.getTaskAssigner().call(assignmentResult.getRequest(), "hostA");
tasks.clear();
leases.clear();
leases.add(LeaseProvider.getConsumedLease(result.getResultMap().values().iterator().next()));
tasks.add(TaskRequestProvider.getTaskRequest(
"grp", 0.1, 100, 0, 0, 0, null, null, Collections.singletonMap(sr2.getResName(), sr2)));
tasks.add(TaskRequestProvider.getTaskRequest(
"grp", 0.1, 100, 0, 0, 0, null, null, Collections.singletonMap(sr3.getResName(), sr3)));
result = taskScheduler.scheduleOnce(tasks, leases);
Assert.assertEquals(1, result.getFailures().size());
Assert.assertEquals(1, result.getResultMap().size());
Assert.assertEquals(1, result.getResultMap().values().iterator().next().getTasksAssigned().size());
assignmentResult =
result.getResultMap().values().iterator().next().getTasksAssigned().iterator().next();
Assert.assertEquals("sg2", assignmentResult.getRequest().getCustomNamedResources().values().iterator().next().getResValue());
}
// Test that when resource sets are unavailable on one host, they are assigned on another host
// Set up hostA and hostB each with 3 resource sets, each with 2 sub-resources. Submit 4 tasks, each
// asking for the same resource set, sr1, with 2 sub-resources. Confirm that one of the hosts gets 3 tasks and
// the other host gets 1 task
@Test
public void testTwoHostAssignment() throws Exception {
int numCores=4;
int numENIs=numCores-1;
int numIPsPerEni=2;
List<VirtualMachineLease> leases = new ArrayList<>();
List<VirtualMachineLease.Range> ports = new ArrayList<>();
ports.add(new VirtualMachineLease.Range(1, 10));
leases.add(LeaseProvider.getLeaseOffer(
"hostA", numCores, numCores*1000, ports, getResSetsAttributesMap("ENIs", numENIs, numIPsPerEni)));
leases.add(LeaseProvider.getLeaseOffer(
"hostB", numCores, numCores*1000, ports, getResSetsAttributesMap("ENIs", numENIs, numIPsPerEni)));
TaskRequest.NamedResourceSetRequest sr1 = new TaskRequest.NamedResourceSetRequest("ENIs", "sg1", 1, 2);
List<TaskRequest> tasks = new ArrayList<>();
for(int i=0; i<4; i++)
tasks.add(TaskRequestProvider.getTaskRequest(
"grp", 0.1, 100, 0, 0, 0, null, null, Collections.singletonMap(sr1.getResName(), sr1)));
final TaskScheduler taskScheduler = getTaskScheduler();
final SchedulingResult result = taskScheduler.scheduleOnce(tasks, leases);
Assert.assertEquals(2, result.getResultMap().size());
Assert.assertEquals(0, result.getFailures().size());
Map<String, Integer> counts = new HashMap<>();
for(VMAssignmentResult r: result.getResultMap().values()) {
counts.put(r.getHostname(), r.getTasksAssigned().size());
}
List<Integer> sortedCounts = new ArrayList<>(counts.values());
Collections.sort(sortedCounts);
Assert.assertEquals(1, (int)sortedCounts.get(0));
Assert.assertEquals(3, (int)sortedCounts.get(1));
}
// Test that on a host that has all of its resource sets fully assigned, when all tasks assigned to a resource set
// complete, that resource set is usable for other tasks of a different resource set name.
@Test
public void testReAssignment() throws Exception {
int numCores=4;
int numENIs=numCores-1;
int numIPsPerEni=2;
List<VirtualMachineLease> leases = new ArrayList<>();
List<VirtualMachineLease.Range> ports = new ArrayList<>();
ports.add(new VirtualMachineLease.Range(1, 10));
leases.add(LeaseProvider.getLeaseOffer(
"hostA", numCores, numCores*1000, ports, getResSetsAttributesMap("ENIs", numENIs, numIPsPerEni)));
TaskRequest.NamedResourceSetRequest sr1 = new TaskRequest.NamedResourceSetRequest("ENIs", "sg1", 1, numIPsPerEni);
TaskRequest.NamedResourceSetRequest sr2 = new TaskRequest.NamedResourceSetRequest("ENIs", "sg2", 1, numIPsPerEni);
List<TaskRequest> tasks = new ArrayList<>();
for(int i=0; i<numENIs; i++)
tasks.add(TaskRequestProvider.getTaskRequest(
"grp", 0.1, 100, 0, 0, 0, null, null, Collections.singletonMap(sr1.getResName(), sr1)));
final TaskScheduler taskScheduler = getTaskScheduler();
SchedulingResult result = taskScheduler.scheduleOnce(tasks, leases);
Assert.assertEquals(1, result.getResultMap().size());
int tasksAssigned=0;
String taskId=null;
for(TaskAssignmentResult r: result.getResultMap().values().iterator().next().getTasksAssigned()) {
tasksAssigned++;
taskScheduler.getTaskAssigner().call(r.getRequest(), r.getHostname());
taskId = r.getTaskId();
}
Assert.assertEquals(tasks.size(), tasksAssigned);
tasks.clear();
tasks.add(TaskRequestProvider.getTaskRequest(
"grp", 0.1, 100, 0, 0, 0, null, null, Collections.singletonMap(sr2.getResName(), sr2)));
leases.clear();
leases.add(LeaseProvider.getConsumedLease(result.getResultMap().values().iterator().next()));
result = taskScheduler.scheduleOnce(tasks, leases);
Assert.assertEquals(0, result.getResultMap().size());
Assert.assertEquals(1, result.getFailures().size());
Assert.assertEquals(VMResource.ResourceSet,
result.getFailures().values().iterator().next().iterator().next().getFailures().iterator().next().getResource());
taskScheduler.getTaskUnAssigner().call(taskId, "hostA");
leases.clear();
result = taskScheduler.scheduleOnce(tasks, leases);
Assert.assertEquals(1, result.getResultMap().size());
}
// Test that when we run out of choices for placement due to resource sets, that a scale up is triggered.
@Test
public void testScaleUp() throws Exception {
int numCores=4;
int numENIs=numCores-1;
int numIPsPerEni=2;
List<VirtualMachineLease> leases = new ArrayList<>();
List<VirtualMachineLease.Range> ports = new ArrayList<>();
ports.add(new VirtualMachineLease.Range(1, 10));
leases.add(LeaseProvider.getLeaseOffer(
"hostA", numCores, numCores*1000, ports, getResSetsAttributesMap("ENIs", numENIs, numIPsPerEni)));
leases.add(LeaseProvider.getLeaseOffer(
"hostB", numCores, numCores * 1000, ports, getResSetsAttributesMap("ENIs", numENIs, numIPsPerEni)));
TaskRequest.NamedResourceSetRequest sr1 = new TaskRequest.NamedResourceSetRequest("ENIs", "sg1", 1, numIPsPerEni);
List<TaskRequest> tasks = new ArrayList<>();
for(int i=0; i<numENIs; i++)
tasks.add(TaskRequestProvider.getTaskRequest(
"grp", 0.1, 100, 0, 0, 0, null, null, Collections.singletonMap(sr1.getResName(), sr1)));
final int cooldown=2;
final AtomicBoolean gotScaleupCallback = new AtomicBoolean(false);
final TaskScheduler scheduler = getTaskSchedulerWithAutoscale(true,
new Action1<AutoScaleAction>() {
@Override
public void call(AutoScaleAction autoScaleAction) {
gotScaleupCallback.set(true);
}
},
AutoScaleRuleProvider.createRule(hostAttrVal1, 1, 1, cooldown, 0, 0));
SchedulingResult result=null;
boolean first=true;
for(int i=0; i<cooldown+1; i++) {
result = scheduler.scheduleOnce(tasks, leases);
if(first) {
first = false;
tasks.clear();
leases.clear();
Assert.assertEquals(1, result.getResultMap().size());
Assert.assertEquals(0, result.getFailures().size());
}
Thread.sleep(1000);
}
Assert.assertFalse("Unexpected to get scale up callback", gotScaleupCallback.get());
tasks.add(TaskRequestProvider.getTaskRequest(
"grp", 0.1, 100, 0, 0, 0, null, null, Collections.singletonMap(sr1.getResName(), sr1)));
first=true;
for(int i=0; i<cooldown+1; i++) {
result = scheduler.scheduleOnce(tasks, leases);
if(first) {
first = false;
tasks.clear();
leases.clear();
Assert.assertEquals(1, result.getResultMap().size());
Assert.assertEquals(0, result.getFailures().size());
}
Thread.sleep(1000);
}
Assert.assertTrue("Did not get scale up callback", gotScaleupCallback.get());
}
// Test that expiring a lease does not affect the available resource sets and its current usage counts
@Test
public void testLeaseExpiry() throws Exception {
int numCores=4;
int numENIs=numCores-1;
int numIPsPerEni=2;
List<VirtualMachineLease> leases = new ArrayList<>();
List<VirtualMachineLease.Range> ports = new ArrayList<>();
ports.add(new VirtualMachineLease.Range(1, 10));
leases.add(LeaseProvider.getLeaseOffer(
"hostA", numCores, numCores*1000, ports, getResSetsAttributesMap("ENIs", numENIs, numIPsPerEni)));
TaskRequest.NamedResourceSetRequest sr1 = new TaskRequest.NamedResourceSetRequest("ENIs", "sg1", 1, numIPsPerEni);
List<TaskRequest> tasks = new ArrayList<>();
tasks.add(TaskRequestProvider.getTaskRequest(
"grp", 0.1, 100, 0, 0, 0, null, null, Collections.singletonMap(sr1.getResName(), sr1)));
tasks.add(TaskRequestProvider.getTaskRequest(
"grp", 0.1, 100, 0, 0, 0, null, null, Collections.singletonMap(sr1.getResName(), sr1)));
final TaskScheduler scheduler = getTaskScheduler();
SchedulingResult result = scheduler.scheduleOnce(tasks, leases);
Assert.assertEquals(1, result.getResultMap().size());
Assert.assertEquals(0, result.getFailures().size());
for(TaskAssignmentResult r: result.getResultMap().values().iterator().next().getTasksAssigned()) {
scheduler.getTaskAssigner().call(r.getRequest(), r.getHostname());
}
leases.clear();
leases.add(LeaseProvider.getConsumedLease(result.getResultMap().values().iterator().next()));
tasks.clear();
result = scheduler.scheduleOnce(tasks, leases);
Assert.assertEquals(0, result.getResultMap().size());
Assert.assertEquals(0, result.getFailures().size());
scheduler.expireAllLeases(leases.get(0).hostname());
leases.clear();
tasks.clear();
//scheduler.scheduleOnce(tasks, leases);
// now add new lease for the same hostname
leases.clear();
leases.add(LeaseProvider.getLeaseOffer(
"hostA", numCores, numCores * 1000, ports, getResSetsAttributesMap("ENIs", numENIs, numIPsPerEni)));
// create two new tasks; only one of them should get assigned
tasks.clear();
tasks.add(TaskRequestProvider.getTaskRequest(
"grp", 0.1, 100, 0, 0, 0, null, null, Collections.singletonMap(sr1.getResName(), sr1)));
tasks.add(TaskRequestProvider.getTaskRequest(
"grp", 0.1, 100, 0, 0, 0, null, null, Collections.singletonMap(sr1.getResName(), sr1)));
result = scheduler.scheduleOnce(tasks, leases);
Assert.assertEquals(1, result.getResultMap().size());
Assert.assertEquals(1, result.getFailures().size());
Assert.assertEquals(VMResource.ResourceSet,
result.getFailures().values().iterator().next().iterator().next().getFailures().iterator().next().getResource());
}
// Test that when lease expires and there are no tasks running, the resource set is cleared. A new lease added
// should recreate the resource set. Verify this by changing the resource set available before and after the lease
// expiry.
@Test
public void testLeaseExpiryClearsResourceSets() throws Exception {
int numCores=4;
int numENIs=numCores-1;
int numIPsPerEni=2;
List<VirtualMachineLease> leases = new ArrayList<>();
List<VirtualMachineLease.Range> ports = new ArrayList<>();
ports.add(new VirtualMachineLease.Range(1, 10));
leases.add(LeaseProvider.getLeaseOffer(
"hostA", numCores, numCores*1000, ports, getResSetsAttributesMap("ENIs", numENIs, numIPsPerEni)));
TaskRequest.NamedResourceSetRequest sr1 = new TaskRequest.NamedResourceSetRequest("ENIs", "sg1", 1, numIPsPerEni);
TaskRequest.NamedResourceSetRequest sr2 = new TaskRequest.NamedResourceSetRequest("NewENIs", "sg2", 1, numIPsPerEni);
List<TaskRequest> tasks = new ArrayList<>();
tasks.add(TaskRequestProvider.getTaskRequest(
"grp", 0.1, 100, 0, 0, 0, null, null, Collections.singletonMap(sr1.getResName(), sr1)));
tasks.add(TaskRequestProvider.getTaskRequest(
"grp", 0.1, 100, 0, 0, 0, null, null, Collections.singletonMap(sr1.getResName(), sr1)));
List<TaskRequest> initialTasks = new ArrayList<>(tasks);
final TaskScheduler scheduler = getTaskScheduler();
SchedulingResult result = scheduler.scheduleOnce(tasks, leases);
Assert.assertEquals(1, result.getResultMap().size());
Assert.assertEquals(0, result.getFailures().size());
for(TaskAssignmentResult r: result.getResultMap().values().iterator().next().getTasksAssigned()) {
scheduler.getTaskAssigner().call(r.getRequest(), r.getHostname());
}
leases.clear();
leases.add(LeaseProvider.getConsumedLease(result.getResultMap().values().iterator().next()));
tasks.clear();
result = scheduler.scheduleOnce(tasks, leases);
Assert.assertEquals(0, result.getResultMap().size());
Assert.assertEquals(0, result.getFailures().size());
Thread.sleep(500);
// unassign tasks
for(TaskRequest r: initialTasks)
scheduler.getTaskUnAssigner().call(r.getId(), "hostA");
scheduler.scheduleOnce(Collections.<TaskRequest>emptyList(), Collections.<VirtualMachineLease>emptyList());
scheduler.expireAllLeases(leases.get(0).hostname());
scheduler.scheduleOnce(Collections.<TaskRequest>emptyList(), Collections.<VirtualMachineLease>emptyList());
// now submit 3 tasks of different resource set request and ensure all 3 get assigned
leases.clear();
leases.add(LeaseProvider.getLeaseOffer(
"hostA", numCores, numCores * 1000, ports, getResSetsAttributesMap("NewENIs", numENIs, numIPsPerEni)));
tasks.clear();
for(int i=0; i<numENIs-1; i++)
tasks.add(TaskRequestProvider.getTaskRequest(
"grp", 0.1, 100, 0, 0, 0, null, null, Collections.singletonMap(sr2.getResName(), sr2)));
tasks.add(TaskRequestProvider.getTaskRequest(
"grp", 0.1, 100, 0, 0, 0, null, null, Collections.singletonMap(sr1.getResName(), sr1)));
result = scheduler.scheduleOnce(tasks, leases);
Assert.assertEquals(1, result.getResultMap().size());
Assert.assertEquals(numENIs-1, result.getResultMap().values().iterator().next().getTasksAssigned().size());
Assert.assertEquals(1, result.getFailures().size());
Assert.assertEquals("ENIs",
result.getFailures().keySet().iterator().next().getCustomNamedResources().keySet().iterator().next());
}
// Test that resource status represents the usage of resource sets correctly
@Test
public void testResourceStatusValues() throws Exception {
int numCores=4;
int numENIs=numCores-1;
int numIPsPerEni=2;
List<VirtualMachineLease> leases = new ArrayList<>();
List<VirtualMachineLease.Range> ports = new ArrayList<>();
ports.add(new VirtualMachineLease.Range(1, 10));
leases.add(LeaseProvider.getLeaseOffer(
"hostA", numCores, numCores*1000, ports, getResSetsAttributesMap("ENIs", numENIs, numIPsPerEni)));
TaskRequest.NamedResourceSetRequest sr1 = new TaskRequest.NamedResourceSetRequest("ENIs", "sg1", 1, numIPsPerEni);
TaskRequest.NamedResourceSetRequest sr2 = new TaskRequest.NamedResourceSetRequest("NewENIs", "sg2", 1, numIPsPerEni);
List<TaskRequest> tasks = new ArrayList<>();
tasks.add(TaskRequestProvider.getTaskRequest(
"grp", 0.1, 100, 0, 0, 0, null, null, Collections.singletonMap(sr1.getResName(), sr1)));
tasks.add(TaskRequestProvider.getTaskRequest(
"grp", 0.1, 100, 0, 0, 0, null, null, Collections.singletonMap(sr1.getResName(), sr1)));
final TaskScheduler scheduler = getTaskScheduler();
SchedulingResult result = scheduler.scheduleOnce(tasks, leases);
Assert.assertEquals(1, result.getResultMap().size());
Assert.assertEquals(0, result.getFailures().size());
for(TaskAssignmentResult r: result.getResultMap().values().iterator().next().getTasksAssigned()) {
scheduler.getTaskAssigner().call(r.getRequest(), r.getHostname());
}
leases.clear();
leases.add(LeaseProvider.getConsumedLease(result.getResultMap().values().iterator().next()));
tasks.clear();
scheduler.scheduleOnce(tasks, leases);
final Map<VMResource, Double[]> usage = scheduler.getResourceStatus().get("hostA");
final Double[] cpuUsg = usage.get(VMResource.CPU);
Assert.assertTrue(0.2 == cpuUsg[0]);
Assert.assertTrue(numCores - 0.2 == cpuUsg[1]);
final Double[] rSetUsg = usage.get(VMResource.ResourceSet);
Assert.assertTrue(2.0 == rSetUsg[0]);
Assert.assertTrue(1.0 == rSetUsg[1]);
}
// Test that a task asking for a resource set that doesn't exist does not get assigned
@Test
public void testNonExistentResourceSetRequest() throws Exception {
int numCores=4;
int numENIs=numCores-1;
int numIPsPerEni=2;
List<VirtualMachineLease> leases = new ArrayList<>();
List<VirtualMachineLease.Range> ports = new ArrayList<>();
ports.add(new VirtualMachineLease.Range(1, 10));
leases.add(LeaseProvider.getLeaseOffer(
"hostA", numCores, numCores*1000, ports, null));
TaskRequest.NamedResourceSetRequest sr1 = new TaskRequest.NamedResourceSetRequest("ENIs", "sg1", 1, numIPsPerEni);
List<TaskRequest> tasks = new ArrayList<>();
tasks.add(TaskRequestProvider.getTaskRequest(
"grp", 0.1, 100, 0, 0, 0, null, null, Collections.singletonMap(sr1.getResName(), sr1)));
final TaskScheduler scheduler = getTaskScheduler();
SchedulingResult result = scheduler.scheduleOnce(tasks, leases);
Assert.assertEquals(0, result.getResultMap().size());
Assert.assertEquals(1, result.getFailures().size());
Assert.assertEquals(VMResource.ResourceSet,
result.getFailures().values().iterator().next().get(0).getFailures().iterator().next().getResource());
}
}
| 9,101 |
0 | Create_ds/Fenzo/fenzo-core/src/test/java/com/netflix | Create_ds/Fenzo/fenzo-core/src/test/java/com/netflix/fenzo/TestLongRunningScheduler.java | /*
* Copyright 2015 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.fenzo;
import com.netflix.fenzo.plugins.BinPackingFitnessCalculators;
import com.netflix.fenzo.functions.Action1;
import com.netflix.fenzo.functions.Action2;
import com.netflix.fenzo.functions.Func1;
import java.io.FileNotFoundException;
import java.io.PrintStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
public class TestLongRunningScheduler {
public static interface Strategy {
VMTaskFitnessCalculator getFitnessCalculator();
public List<RandomTaskGenerator.TaskType> getJobTypes();
double getFitnessGoodEnoughValue();
Action1<Map<String, Map<VMResource, Double[]>>> getPrintAction();
Action2<String, RandomTaskGenerator.GeneratedTask> getTaskAssigner();
Action2<String, RandomTaskGenerator.GeneratedTask> getTaskUnAssigner();
}
private static final double NUM_CORES_PER_HOST = 8.0;
private static final int NUM_HOSTS = 2000;
private final RandomTaskGenerator taskGenerator;
private final List<VirtualMachineLease> leases;
private final TaskScheduler taskScheduler;
private final BlockingQueue<RandomTaskGenerator.GeneratedTask> taskQueue;
private final BlockingQueue<RandomTaskGenerator.GeneratedTask> taskCompleterQ = new LinkedBlockingQueue<>();
private final Map<String, RandomTaskGenerator.GeneratedTask> allTasksMap = new HashMap<>();
private static PrintStream outputStream;
private static final long delayMillis=50;
private final Strategy strategy;
public TestLongRunningScheduler(RandomTaskGenerator taskGenerator, List<VirtualMachineLease> leases,
BlockingQueue<RandomTaskGenerator.GeneratedTask> taskQueue,
Strategy strategy) {
this.taskGenerator = taskGenerator;
this.leases = leases;
this.taskQueue = taskQueue;
new TaskCompleter(taskCompleterQ, new Action1<RandomTaskGenerator.GeneratedTask>() {
@Override
public void call(RandomTaskGenerator.GeneratedTask task) {
System.out.println(" Completing task " + task.getId() + " on host " + task.getHostname());
TestLongRunningScheduler.this.taskScheduler.getTaskUnAssigner().call(task.getId(), task.getHostname());
TestLongRunningScheduler.this.strategy.getTaskUnAssigner().call(task.getHostname(), allTasksMap.get(task.getId()));
}
}, delayMillis).start();
this.strategy = strategy;
taskScheduler = new TaskScheduler.Builder()
.withFitnessCalculator(strategy.getFitnessCalculator())
.withFitnessGoodEnoughFunction(new Func1<Double, Boolean>() {
@Override
public Boolean call(Double f) {
return f > TestLongRunningScheduler.this.strategy.getFitnessGoodEnoughValue();
}
})
.withLeaseOfferExpirySecs(1000000)
.withLeaseRejectAction(new Action1<VirtualMachineLease>() {
@Override
public void call(VirtualMachineLease lease) {
System.err.println("Unexpected to reject lease on " + lease.hostname());
}
})
.build();
}
private void runAll() {
final List<TaskRequest> taskRequests = new ArrayList<>();
final Map<String, RandomTaskGenerator.GeneratedTask> pendingTasksMap = new HashMap<>();
taskScheduler.scheduleOnce(taskRequests, leases); // Get the original leases in
strategy.getPrintAction().call(taskScheduler.getResourceStatus());
final List<VirtualMachineLease>[] newLeasesArray = new ArrayList[5];
for(int i=0; i<newLeasesArray.length; i++)
newLeasesArray[i] = new ArrayList<>();
final AtomicInteger counter = new AtomicInteger();
final AtomicInteger totalTasksLaunched = new AtomicInteger();
new ScheduledThreadPoolExecutor(1).scheduleWithFixedDelay(new Runnable() {
@Override
public void run() {
int i = counter.incrementAndGet();
List<VirtualMachineLease> newLeases = newLeasesArray[i % 5];
//taskQueue.drainTo(taskRequests);
taskRequests.addAll(taskGenerator.getTasks());
for(TaskRequest t: taskRequests) {
pendingTasksMap.put(t.getId(), (RandomTaskGenerator.GeneratedTask) t);
allTasksMap.put(t.getId(), (RandomTaskGenerator.GeneratedTask) t);
}
taskRequests.clear();
int tasksToAssign = pendingTasksMap.size();
System.out.println("Calling to schedule " + tasksToAssign + " tasks with " + newLeases.size() + " with new leases");
SchedulingResult schedulingResult = taskScheduler.scheduleOnce(new ArrayList<TaskRequest>(pendingTasksMap.values()), newLeases);
newLeases.clear();
int numTasksLaunched=0;
int numHostsAssigned=0;
if(schedulingResult.getResultMap() != null) {
for(Map.Entry<String, VMAssignmentResult> entry: schedulingResult.getResultMap().entrySet()) {
numHostsAssigned++;
for(TaskAssignmentResult result: entry.getValue().getTasksAssigned()) {
numTasksLaunched++;
totalTasksLaunched.incrementAndGet();
((RandomTaskGenerator.GeneratedTask)result.getRequest()).setHostname(entry.getKey());
taskScheduler.getTaskAssigner().call(result.getRequest(), entry.getKey());
taskCompleterQ.offer((RandomTaskGenerator.GeneratedTask) result.getRequest());
strategy.getTaskAssigner().call(entry.getKey(), (RandomTaskGenerator.GeneratedTask) result.getRequest());
pendingTasksMap.remove(result.getRequest().getId());
}
newLeases.add(LeaseProvider.getConsumedLease(entry.getValue()));
}
}
strategy.getPrintAction().call(taskScheduler.getResourceStatus());
if(tasksToAssign!=numTasksLaunched)
System.out.println("############ tasksToAssign=" + tasksToAssign + ", launched="+numTasksLaunched);
System.out.printf("%d tasks launched on %d hosts, %d pending\n", numTasksLaunched, numHostsAssigned, pendingTasksMap.size());
if(pendingTasksMap.size()>0 || counter.get()>50) {
System.out.println("Reached pending status in " + counter.get() + " iterations, totalTasks launched=" + totalTasksLaunched.get());
System.exit(0);
}
}
}, delayMillis, delayMillis, TimeUnit.MILLISECONDS);
}
private static Action1<Map<String, Map<VMResource, Double[]>>> printResourceUtilization = new Action1<Map<String, Map<VMResource, Double[]>>>() {
@Override
public void call(Map<String, Map<VMResource, Double[]>> resourceStatus) {
if(resourceStatus==null)
return;
int empty=0;
int partial=0;
int full=0;
int totalUsed=0;
for(Map.Entry<String, Map<VMResource, Double[]>> entry: resourceStatus.entrySet()) {
Map<VMResource, Double[]> value = entry.getValue();
for(Map.Entry<VMResource, Double[]> resEntry: value.entrySet()) {
switch (resEntry.getKey()) {
case CPU:
Double available = resEntry.getValue()[1];
Double used = resEntry.getValue()[0];
totalUsed += used;
if(available == NUM_CORES_PER_HOST)
empty++;
else if(used == NUM_CORES_PER_HOST)
full++;
else
partial++;
}
}
}
outputStream.printf("%5.2f, %d, %d,%d\n",
(totalUsed * 100.0) / (double) (NUM_CORES_PER_HOST * NUM_HOSTS), empty, partial, full);
System.out.printf("Utilization=%5.2f%% (%d totalUsed), empty=%d, partial=%d,ful=%d\n",
(totalUsed * 100.0) / (double) (NUM_CORES_PER_HOST * NUM_HOSTS), totalUsed, empty, partial, full);
}
};
static Strategy binPackingStrategy = new Strategy() {
@Override
public VMTaskFitnessCalculator getFitnessCalculator() {
return BinPackingFitnessCalculators.cpuBinPacker;
}
@Override
public double getFitnessGoodEnoughValue() {
return 1.0;
}
@Override
public Action1<Map<String, Map<VMResource, Double[]>>> getPrintAction() {
return printResourceUtilization;
}
@Override
public List<RandomTaskGenerator.TaskType> getJobTypes() {
List<RandomTaskGenerator.TaskType> taskTypes = new ArrayList<>();
taskTypes.add(new RandomTaskGenerator.TaskType(1, 0.75, 20000, 20000));
taskTypes.add(new RandomTaskGenerator.TaskType(3, 0.25, 10000, 10000));
taskTypes.add(new RandomTaskGenerator.TaskType(6, 0.25, 20000, 20000));
return taskTypes;
}
@Override
public Action2<String, RandomTaskGenerator.GeneratedTask> getTaskAssigner() {
return new Action2<String, RandomTaskGenerator.GeneratedTask>() {
@Override
public void call(String s, RandomTaskGenerator.GeneratedTask s2) {
}
};
}
@Override
public Action2<String, RandomTaskGenerator.GeneratedTask> getTaskUnAssigner() {
return new Action2<String, RandomTaskGenerator.GeneratedTask>() {
@Override
public void call(String s, RandomTaskGenerator.GeneratedTask s2) {
}
};
}
};
static Strategy noPackingStrategy = new Strategy() {
@Override
public VMTaskFitnessCalculator getFitnessCalculator() {
return new DefaultFitnessCalculator();
}
@Override
public double getFitnessGoodEnoughValue() {
return 1.0;
}
@Override
public Action1<Map<String, Map<VMResource, Double[]>>> getPrintAction() {
return printResourceUtilization;
}
@Override
public List<RandomTaskGenerator.TaskType> getJobTypes() {
List<RandomTaskGenerator.TaskType> taskTypes = new ArrayList<>();
taskTypes.add(new RandomTaskGenerator.TaskType(1, 0.75, 20000, 20000));
taskTypes.add(new RandomTaskGenerator.TaskType(3, 0.25, 10000, 10000));
taskTypes.add(new RandomTaskGenerator.TaskType(6, 0.25, 20000, 20000));
return taskTypes;
}
@Override
public Action2<String, RandomTaskGenerator.GeneratedTask> getTaskAssigner() {
return new Action2<String, RandomTaskGenerator.GeneratedTask>() {
@Override
public void call(String s, RandomTaskGenerator.GeneratedTask s2) {
}
};
}
@Override
public Action2<String, RandomTaskGenerator.GeneratedTask> getTaskUnAssigner() {
return new Action2<String, RandomTaskGenerator.GeneratedTask>() {
@Override
public void call(String s, RandomTaskGenerator.GeneratedTask s2) {
}
};
}
};
static Strategy taskRuntimeStrategy = new Strategy() {
private Map<String, Set<RandomTaskGenerator.GeneratedTask>> hostToTasksMap = new HashMap<>();
public VMTaskFitnessCalculator getFitnessCalculatorNOT() {
return new DefaultFitnessCalculator();
}
@Override
public VMTaskFitnessCalculator getFitnessCalculator() {
return new VMTaskFitnessCalculator() {
@Override
public String getName() {
return "Task Runtime Fitness Calculator";
}
@Override
public double calculateFitness(TaskRequest taskRequest, VirtualMachineCurrentState targetVM, TaskTrackerState taskTrackerState) {
RandomTaskGenerator.GeneratedTask generatedTask = (RandomTaskGenerator.GeneratedTask)taskRequest;
int sameCount=0;
int total=0;
for(TaskRequest request: targetVM.getRunningTasks()) {
total++;
if(isSame((RandomTaskGenerator.GeneratedTask)request, generatedTask))
sameCount++;
}
for(TaskAssignmentResult result: targetVM.getTasksCurrentlyAssigned()) {
total++;
if(isSame((RandomTaskGenerator.GeneratedTask) result.getRequest(), generatedTask))
sameCount++;
}
if(total==0)
return 1.0;
return (double)sameCount/(double)total;
}
};
}
private boolean isSame(RandomTaskGenerator.GeneratedTask request, RandomTaskGenerator.GeneratedTask generatedTask) {
if(request.getRuntimeMillis() == generatedTask.getRuntimeMillis())
return true;
return false;
}
private boolean isSame(Set<RandomTaskGenerator.GeneratedTask> requests) {
if(requests==null || requests.isEmpty())
return true;
RandomTaskGenerator.GeneratedTask generatedTask = requests.iterator().next();
for(RandomTaskGenerator.GeneratedTask task: requests)
if(!isSame(task, generatedTask))
return false;
return true;
}
@Override
public List<RandomTaskGenerator.TaskType> getJobTypes() {
List<RandomTaskGenerator.TaskType> taskTypes = new ArrayList<>();
taskTypes.add(new RandomTaskGenerator.TaskType(1, 0.5, 10000, 10000));
taskTypes.add(new RandomTaskGenerator.TaskType(1, 0.5, 60000, 60000));
return taskTypes;
}
@Override
public double getFitnessGoodEnoughValue() {
return 1.0;
}
@Override
public Action1<Map<String, Map<VMResource, Double[]>>> getPrintAction() {
return new Action1<Map<String, Map<VMResource, Double[]>>>() {
@Override
public void call(Map<String, Map<VMResource, Double[]>> stringMapMap) {
int same=0;
int diff=0;
int unused=0;
for(String hostname: stringMapMap.keySet()) {
Set<RandomTaskGenerator.GeneratedTask> generatedTasks = hostToTasksMap.get(hostname);
if(generatedTasks==null)
unused++;
else if(isSame(generatedTasks))
same++;
else
diff++;
}
outputStream.printf("%d, %d, %d\n", unused, same, diff);
System.out.printf("Unused=%d, same=%d, different=%d\n", unused, same, diff);
}
};
}
@Override
public Action2<String, RandomTaskGenerator.GeneratedTask> getTaskAssigner() {
return new Action2<String, RandomTaskGenerator.GeneratedTask>() {
@Override
public void call(String hostname, RandomTaskGenerator.GeneratedTask task) {
if(hostToTasksMap.get(hostname)==null)
hostToTasksMap.put(hostname, new HashSet<RandomTaskGenerator.GeneratedTask>());
hostToTasksMap.get(hostname).add(task);
}
};
}
@Override
public Action2<String, RandomTaskGenerator.GeneratedTask> getTaskUnAssigner() {
return new Action2<String, RandomTaskGenerator.GeneratedTask>() {
@Override
public void call(String hostname, RandomTaskGenerator.GeneratedTask task) {
hostToTasksMap.get(hostname).remove(task);
}
};
}
};
public static void main(String[] args) {
try {
final BlockingQueue<RandomTaskGenerator.GeneratedTask> taskQueue = new LinkedBlockingQueue<>();
outputStream = new PrintStream("/tmp/test.out");
//Strategy strategy = noPackingStrategy;
Strategy strategy = taskRuntimeStrategy;
VMTaskFitnessCalculator fitnessCalculator = BinPackingFitnessCalculators.cpuBinPacker;
final double fitnessGoodEnoughValue=1.0;
RandomTaskGenerator taskGenerator = new RandomTaskGenerator(taskQueue, delayMillis, 10, strategy.getJobTypes());
//taskGenerator.start();
TestLongRunningScheduler longRunningScheduler = null;
longRunningScheduler = new TestLongRunningScheduler(
taskGenerator,
LeaseProvider.getLeases(NUM_HOSTS, NUM_CORES_PER_HOST, NUM_CORES_PER_HOST * 1000, 1, 1000),
taskQueue, strategy
);
longRunningScheduler.runAll();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
| 9,102 |
0 | Create_ds/Fenzo/fenzo-core/src/test/java/com/netflix | Create_ds/Fenzo/fenzo-core/src/test/java/com/netflix/fenzo/ResAllocsProvider.java | /*
* Copyright 2015 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.fenzo;
import com.netflix.fenzo.sla.ResAllocs;
public class ResAllocsProvider {
static ResAllocs create(final String name, final double cores, final double memory, final double network, final double disk) {
return new ResAllocs() {
@Override
public String getTaskGroupName() {
return name;
}
@Override
public double getCores() {
return cores;
}
@Override
public double getMemory() {
return memory;
}
@Override
public double getNetworkMbps() {
return network;
}
@Override
public double getDisk() {
return disk;
}
};
}
}
| 9,103 |
0 | Create_ds/Fenzo/fenzo-core/src/test/java/com/netflix | Create_ds/Fenzo/fenzo-core/src/test/java/com/netflix/fenzo/SampleLargeNumTasksToInit.java | package com.netflix.fenzo;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.netflix.fenzo.queues.QAttributes;
import com.netflix.fenzo.queues.QueuableTask;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import java.util.Map;
/**
* A class that provides a sample of large number of tasks to initialize TaskSchedulingService with that caused problems
* in an actual run.
*/
public class SampleLargeNumTasksToInit {
static class Task {
private final String id;
private final String bucket;
private final int tier;
private final double cpu;
private final double memory;
private final double networkMbps;
private final double disk;
private final String host;
@JsonCreator
public Task(@JsonProperty("id") String id,
@JsonProperty("bucket") String bucket,
@JsonProperty("tier") int tier,
@JsonProperty("cpu") double cpu,
@JsonProperty("memory") double memory,
@JsonProperty("networkMbps") double networkMbps,
@JsonProperty("disk") double disk,
@JsonProperty("host") String host) {
this.id = id;
this.bucket = bucket;
this.tier = tier;
this.cpu = cpu;
this.memory = memory;
this.networkMbps = networkMbps;
this.disk = disk;
this.host = host;
}
public String getId() {
return id;
}
public String getBucket() {
return bucket;
}
public int getTier() {
return tier;
}
public double getCpu() {
return cpu;
}
public double getMemory() {
return memory;
}
public double getNetworkMbps() {
return networkMbps;
}
public double getDisk() {
return disk;
}
public String getHost() {
return host;
}
}
static List<Task> getSampleTasksInRunningState() throws IOException {
final InputStream inputStream = SampleLargeNumTasksToInit.class.getClassLoader().getResourceAsStream("largeFenzoTasksInput.json");
byte[] buf = new byte[1024];
int n=0;
StringBuilder json = new StringBuilder();
while (n >= 0) {
n = inputStream.read(buf, 0, 1024);
if (n>0)
json.append(new String(buf, 0, n));
}
ObjectMapper mapper = new ObjectMapper();
return mapper.readValue(json.toString(), new TypeReference<List<Task>>() {});
}
static QueuableTask toQueuableTask(final Task t) {
final QAttributes a = new QAttributes.QAttributesAdaptor(0, t.bucket);
return new QueuableTask() {
@Override
public QAttributes getQAttributes() {
return a;
}
@Override
public String getId() {
return t.id;
}
@Override
public String taskGroupName() {
return null;
}
@Override
public double getCPUs() {
return t.cpu;
}
@Override
public double getMemory() {
return t.memory;
}
@Override
public double getNetworkMbps() {
return t.networkMbps;
}
@Override
public double getDisk() {
return t.disk;
}
@Override
public int getPorts() {
return 0;
}
@Override
public Map<String, Double> getScalarRequests() {
return null;
}
@Override
public Map<String, NamedResourceSetRequest> getCustomNamedResources() {
return null;
}
@Override
public List<? extends ConstraintEvaluator> getHardConstraints() {
return null;
}
@Override
public List<? extends VMTaskFitnessCalculator> getSoftConstraints() {
return null;
}
@Override
public void setAssignedResources(AssignedResources assignedResources) {
}
@Override
public AssignedResources getAssignedResources() {
return null;
}
};
}
}
| 9,104 |
0 | Create_ds/Fenzo/fenzo-core/src/test/java/com/netflix | Create_ds/Fenzo/fenzo-core/src/test/java/com/netflix/fenzo/NaiveShortfallEvaluatorTest.java | package com.netflix.fenzo;
import com.netflix.fenzo.queues.QAttributes;
import com.netflix.fenzo.queues.QueuableTask;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import static java.util.Arrays.asList;
import static java.util.Collections.singletonList;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.is;
import static org.mockito.Mockito.mock;
public class NaiveShortfallEvaluatorTest {
private static final String HOST_ATTR_VAL = "4coreServers";
private static final String ADJUSTED_HOST_ATTR_VAL = "adjusted4coreServers";
private static final int CPU = 4;
private static final int MEMORY = 8 * 1024;
private static final Set<String> ATTR_KEYS = new HashSet<>(asList(HOST_ATTR_VAL, ADJUSTED_HOST_ATTR_VAL));
private static final AutoScaleRule STD_RULE = AutoScaleRuleProvider.createRule(
HOST_ATTR_VAL, 0, 10, 600, CPU / 2, MEMORY / 2
);
private static final AutoScaleRule ADJUSTED_RULE = AutoScaleRuleProvider.createRule(
ADJUSTED_HOST_ATTR_VAL, 0, 10, 600, CPU / 2, MEMORY / 2,
numberOfAgents -> numberOfAgents / 2
);
private final AutoScaleRules autoScaleRules = new AutoScaleRules(asList(STD_RULE, ADJUSTED_RULE));
private final TaskScheduler taskScheduler = mock(TaskScheduler.class);
private final ShortfallEvaluator shortfallEvaluator = new NaiveShortfallEvaluator();
@Before
public void setUp() throws Exception {
shortfallEvaluator.setTaskToClustersGetter(task ->
singletonList(task.getId().contains("adjusted") ? ADJUSTED_HOST_ATTR_VAL : HOST_ATTR_VAL)
);
}
@Test
public void testShortfallAdjusting() throws Exception {
Set<TaskRequest> failedTasks = new HashSet<>(asList(
createFailedTask("std#1"), createFailedTask("std#2"),
createFailedTask("adjusted#1"), createFailedTask("adjusted#2")
));
Map<String, Integer> shortfall = shortfallEvaluator.getShortfall(ATTR_KEYS, failedTasks, autoScaleRules);
Assert.assertThat(shortfall.get(HOST_ATTR_VAL), is(equalTo(2)));
Assert.assertThat(shortfall.get(ADJUSTED_HOST_ATTR_VAL), is(equalTo(1)));
}
private QueuableTask createFailedTask(String id) {
return new QueuableTask() {
@Override
public String getId() {
return id;
}
@Override
public String taskGroupName() {
return null;
}
@Override
public double getCPUs() {
return CPU / 4;
}
@Override
public double getMemory() {
return MEMORY / 4;
}
@Override
public double getNetworkMbps() {
return 0;
}
@Override
public double getDisk() {
return 0;
}
@Override
public int getPorts() {
return 0;
}
@Override
public Map<String, Double> getScalarRequests() {
return null;
}
@Override
public Map<String, NamedResourceSetRequest> getCustomNamedResources() {
return null;
}
@Override
public List<? extends ConstraintEvaluator> getHardConstraints() {
return null;
}
@Override
public List<? extends VMTaskFitnessCalculator> getSoftConstraints() {
return null;
}
@Override
public void setAssignedResources(AssignedResources assignedResources) {
}
@Override
public AssignedResources getAssignedResources() {
return null;
}
@Override
public QAttributes getQAttributes() {
return null;
}
};
}
} | 9,105 |
0 | Create_ds/Fenzo/fenzo-core/src/test/java/com/netflix | Create_ds/Fenzo/fenzo-core/src/test/java/com/netflix/fenzo/AutoScalerTest.java | /*
* Copyright 2015 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.fenzo;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;
import com.netflix.fenzo.functions.Action1;
import com.netflix.fenzo.functions.Func1;
import com.netflix.fenzo.plugins.BinPackingFitnessCalculators;
import com.netflix.fenzo.plugins.HostAttrValueConstraint;
import com.netflix.fenzo.queues.QAttributes;
import com.netflix.fenzo.queues.TaskQueue;
import com.netflix.fenzo.queues.TaskQueues;
import com.netflix.fenzo.queues.tiered.QueuableTaskProvider;
import org.apache.mesos.Protos;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
public class AutoScalerTest {
static final Action1<VirtualMachineLease> noOpLeaseReject = lease -> {
};
static String hostAttrName = "MachineType";
final int minIdle = 5;
final int maxIdle = 10;
final long coolDownSecs = 2;
final String hostAttrVal1 = "4coreServers";
final String hostAttrVal2 = "8coreServers";
int cpus1 = 4;
int memory1 = 40000;
final AutoScaleRule rule1 = AutoScaleRuleProvider.createRule(hostAttrVal1, minIdle, maxIdle, coolDownSecs, cpus1 / 2, memory1 / 2);
int cpus2 = 8;
int memory2 = 800; // make this less than memory1/cpus1 to ensure jobs don't get on these
final AutoScaleRule rule2 = AutoScaleRuleProvider.createRule(hostAttrVal2, minIdle, maxIdle, coolDownSecs, cpus2 / 2, memory2 / 2);
/* package */
static TaskScheduler getScheduler(final Action1<VirtualMachineLease> leaseRejectCalback, final Action1<AutoScaleAction> callback,
long delayScaleUpBySecs, long delayScaleDownByDecs,
AutoScaleRule... rules) {
TaskScheduler.Builder builder = new TaskScheduler.Builder()
.withAutoScaleByAttributeName(hostAttrName);
for (AutoScaleRule rule : rules)
builder.withAutoScaleRule(rule);
if (callback != null)
builder.withAutoScalerCallback(callback);
return builder
.withDelayAutoscaleDownBySecs(delayScaleDownByDecs)
.withDelayAutoscaleUpBySecs(delayScaleUpBySecs)
.withFitnessCalculator(BinPackingFitnessCalculators.cpuMemBinPacker)
.withLeaseOfferExpirySecs(3600)
.withLeaseRejectAction(lease -> {
if (leaseRejectCalback == null)
Assert.fail("Unexpected to reject lease " + lease.hostname());
else
leaseRejectCalback.call(lease);
})
.build();
}
@Before
public void setUp() throws Exception {
}
@After
public void tearDown() throws Exception {
}
private TaskScheduler getScheduler(AutoScaleRule... rules) {
return getScheduler(null, rules);
}
private TaskScheduler getScheduler(final Action1<VirtualMachineLease> leaseRejectCalback, AutoScaleRule... rules) {
return getScheduler(leaseRejectCalback, null, 0, 0, rules);
}
private TaskScheduler getScheduler(final Action1<VirtualMachineLease> leaseRejectCalback, final Action1<AutoScaleAction> callback,
AutoScaleRule... rules) {
return getScheduler(leaseRejectCalback, callback, 0, 0, rules);
}
// Test autoscale up on a simple rule
// - Setup an auto scale rule
// - keep calling scheduleOnce() periodically until a time greater than autoscale rule's cooldown period
// - ensure that we get a scale up action within the time
@Test
public void scaleUpTest1() throws Exception {
TaskScheduler scheduler = getScheduler(rule1);
final List<VirtualMachineLease> leases = new ArrayList<>();
final CountDownLatch latch = new CountDownLatch(1);
final AtomicInteger scaleUpRequest = new AtomicInteger(0);
scheduler.setAutoscalerCallback(new Action1<AutoScaleAction>() {
@Override
public void call(AutoScaleAction action) {
if (action instanceof ScaleUpAction) {
int needed = ((ScaleUpAction) action).getScaleUpCount();
scaleUpRequest.set(needed);
latch.countDown();
}
}
});
List<TaskRequest> requests = new ArrayList<>();
int i = 0;
do {
Thread.sleep(1000);
scheduler.scheduleOnce(requests, leases);
} while (i++ < (coolDownSecs + 2) && latch.getCount() > 0);
if (latch.getCount() > 0)
Assert.fail("Timed out scale up action");
else
Assert.assertEquals(maxIdle, scaleUpRequest.get());
}
// Test scale up action repeating after using up all hosts after first scale up action
// Setup an auto scale rule
// start with 0 hosts available
// keep calling TaskScheduler.scheduleOnce()
// ensure we get scale up action
// on first scale up action add some machines
// use up all of those machines in subsequent scheduling
// ensure we get another scale up action after cool down time
@Test
public void scaleUpTest2() throws Exception {
TaskScheduler scheduler = getScheduler(rule1);
final List<VirtualMachineLease> leases = new ArrayList<>();
final CountDownLatch latch = new CountDownLatch(1);
final AtomicBoolean addVMs = new AtomicBoolean(false);
final List<TaskRequest> requests = new ArrayList<>();
for (int i = 0; i < maxIdle * cpus1; i++)
requests.add(TaskRequestProvider.getTaskRequest(1.0, 100, 1));
scheduler.setAutoscalerCallback(new Action1<AutoScaleAction>() {
@Override
public void call(AutoScaleAction action) {
if (action instanceof ScaleUpAction) {
if (!addVMs.compareAndSet(false, true)) {
// second time around here
latch.countDown();
}
}
}
});
int i = 0;
boolean added = false;
do {
Thread.sleep(1000);
if (!added && addVMs.get()) {
leases.addAll(LeaseProvider.getLeases(maxIdle, cpus1, memory1, 1, 10));
added = true;
}
SchedulingResult schedulingResult = scheduler.scheduleOnce(requests, leases);
Map<String, VMAssignmentResult> resultMap = schedulingResult.getResultMap();
if (added) {
int count = 0;
for (VMAssignmentResult result : resultMap.values())
count += result.getTasksAssigned().size();
Assert.assertEquals(requests.size(), count);
requests.clear();
leases.clear();
}
} while (i++ < (2 * coolDownSecs + 2) && latch.getCount() > 0);
Assert.assertTrue("Second scale up action didn't arrive on time", latch.getCount() == 0);
}
/**
* Tests that the rule applies only to the host types specified and not to the other host type.
*
* @throws Exception upon any error
*/
@Test
public void testOneRuleTwoTypes() throws Exception {
final CountDownLatch latch = new CountDownLatch(1);
TaskScheduler scheduler = getScheduler(null, action -> {
if (action instanceof ScaleUpAction) {
if (action.getRuleName().equals(rule1.getRuleName()))
latch.countDown();
}
}, rule2);
final List<TaskRequest> requests = new ArrayList<>();
final List<VirtualMachineLease> leases = new ArrayList<>();
for (int i = 0; i < maxIdle * cpus1; i++)
requests.add(TaskRequestProvider.getTaskRequest(1.0, 100, 1));
int i = 0;
do {
Thread.sleep(1000);
scheduler.scheduleOnce(requests, leases);
} while (i++ < coolDownSecs + 2 && latch.getCount() > 0);
if (latch.getCount() < 1)
Assert.fail("Should not have gotten scale up action for " + rule1.getRuleName());
}
/**
* Tests that of the two AutoScale rules setup, scale up action is called only on the one that is actually short.
*
* @throws Exception
*/
@Test
public void testTwoRulesOneNeedsScaleUp() throws Exception {
TaskScheduler scheduler = getScheduler(rule1, rule2);
final List<TaskRequest> requests = new ArrayList<>();
final List<VirtualMachineLease> leases = new ArrayList<>();
final CountDownLatch latch = new CountDownLatch(1);
scheduler.setAutoscalerCallback(new Action1<AutoScaleAction>() {
@Override
public void call(AutoScaleAction action) {
if (action instanceof ScaleUpAction) {
if (action.getRuleName().equals(rule2.getRuleName()))
latch.countDown();
}
}
});
List<VirtualMachineLease.Range> ports = new ArrayList<>();
ports.add(new VirtualMachineLease.Range(1, 10));
Map<String, Protos.Attribute> attributes = new HashMap<>();
Protos.Attribute attribute = Protos.Attribute.newBuilder().setName(hostAttrName)
.setType(Protos.Value.Type.TEXT)
.setText(Protos.Value.Text.newBuilder().setValue(hostAttrVal2)).build();
attributes.put(hostAttrName, attribute);
for (int l = 0; l < maxIdle; l++) {
leases.add(LeaseProvider.getLeaseOffer("host" + l, 8, 8000, ports, attributes));
}
int i = 0;
do {
Thread.sleep(1000);
scheduler.scheduleOnce(requests, leases);
leases.clear();
} while (i++ < coolDownSecs + 2 && latch.getCount() > 0);
if (latch.getCount() < 1)
Assert.fail("Scale up action received for " + rule2.getRuleName() + " rule, was expecting only on "
+ rule1.getRuleName());
}
/**
* Tests simple scale down action on host type that has excess capacity
*
* @throws Exception
*/
@Test
public void testSimpleScaleDownAction() throws Exception {
final AtomicInteger scaleDownCount = new AtomicInteger();
TaskScheduler scheduler = getScheduler(noOpLeaseReject, rule1);
final List<TaskRequest> requests = new ArrayList<>();
for (int c = 0; c < cpus1; c++) // add as many 1-CPU requests as #cores on a host
requests.add(TaskRequestProvider.getTaskRequest(1, 1000, 1));
final List<VirtualMachineLease> leases = new ArrayList<>();
final CountDownLatch latch = new CountDownLatch(1);
scheduler.setAutoscalerCallback(new Action1<AutoScaleAction>() {
@Override
public void call(AutoScaleAction action) {
if (action instanceof ScaleDownAction) {
scaleDownCount.set(((ScaleDownAction) action).getHosts().size());
latch.countDown();
}
}
});
List<VirtualMachineLease.Range> ports = new ArrayList<>();
ports.add(new VirtualMachineLease.Range(1, 10));
Map<String, Protos.Attribute> attributes = new HashMap<>();
Protos.Attribute attribute = Protos.Attribute.newBuilder().setName(hostAttrName)
.setType(Protos.Value.Type.TEXT)
.setText(Protos.Value.Text.newBuilder().setValue(hostAttrVal1)).build();
attributes.put(hostAttrName, attribute);
int excess = 3;
for (int l = 0; l < maxIdle + excess; l++) {
leases.add(LeaseProvider.getLeaseOffer("host" + l, cpus1, memory1, ports, attributes));
}
int i = 0;
boolean first = true;
do {
Thread.sleep(1000);
final SchedulingResult schedulingResult = scheduler.scheduleOnce(requests, leases);
if (first) {
first = false;
leases.clear();
requests.clear();
}
} while (i++ < coolDownSecs + 2 && latch.getCount() > 0);
Assert.assertEquals(0, latch.getCount());
// expect scale down count to be excess-1 since we used up 1 host
Assert.assertEquals(excess - 1, scaleDownCount.get());
}
/**
* Tests that of the two rules, scale down is called only on the one that is in excess
*
* @throws Exception
*/
@Test
public void testTwoRuleScaleDownAction() throws Exception {
TaskScheduler scheduler = getScheduler(noOpLeaseReject, rule1, rule2);
final List<TaskRequest> requests = new ArrayList<>();
final List<VirtualMachineLease> leases = new ArrayList<>();
final CountDownLatch latch = new CountDownLatch(1);
final String wrongScaleDownRulename = rule1.getRuleName();
scheduler.setAutoscalerCallback(new Action1<AutoScaleAction>() {
@Override
public void call(AutoScaleAction action) {
if (action instanceof ScaleDownAction) {
if (action.getRuleName().equals(wrongScaleDownRulename))
latch.countDown();
}
}
});
// use up servers covered by rule1
for (int r = 0; r < maxIdle * cpus1; r++)
requests.add(TaskRequestProvider.getTaskRequest(1, memory1 / cpus1, 1));
List<VirtualMachineLease.Range> ports = new ArrayList<>();
ports.add(new VirtualMachineLease.Range(1, 10));
Map<String, Protos.Attribute> attributes1 = new HashMap<>();
Protos.Attribute attribute = Protos.Attribute.newBuilder().setName(hostAttrName)
.setType(Protos.Value.Type.TEXT)
.setText(Protos.Value.Text.newBuilder().setValue(hostAttrVal1)).build();
attributes1.put(hostAttrName, attribute);
Map<String, Protos.Attribute> attributes2 = new HashMap<>();
Protos.Attribute attribute2 = Protos.Attribute.newBuilder().setName(hostAttrName)
.setType(Protos.Value.Type.TEXT)
.setText(Protos.Value.Text.newBuilder().setValue(hostAttrVal2)).build();
attributes2.put(hostAttrName, attribute2);
for (int l = 0; l < maxIdle + 3; l++) {
leases.add(LeaseProvider.getLeaseOffer("host" + l, cpus1, memory1, ports, attributes1));
leases.add(LeaseProvider.getLeaseOffer("host" + 100 + l, cpus2, memory2, ports, attributes2));
}
int i = 0;
boolean first = true;
do {
Thread.sleep(1000);
scheduler.scheduleOnce(requests, leases);
if (first) {
first = false;
requests.clear();
leases.clear();
}
} while (i++ < coolDownSecs + 2 && latch.getCount() > 0);
if (latch.getCount() < 1)
Assert.fail("Scale down action received for " + wrongScaleDownRulename + " rule, was expecting only on "
+ rule1.getRuleName());
}
// Tests that when scaling down, a balance is achieved across hosts for the given attribute. That is, about equal
// number of hosts remain after scale down, for each unique value of the given attribute. Say we are trying to
// balance the number of hosts across the zone attribute, then, after scale down there must be equal number of
// hosts for each zone.
@Test
public void testScaleDownBalanced() throws Exception {
final String zoneAttrName = "Zone";
final int mxIdl = 12;
final CountDownLatch latch = new CountDownLatch(1);
final int[] zoneCounts = {0, 0, 0};
final List<TaskRequest> requests = new ArrayList<>();
// add enough jobs to fill two machines of zone 0
List<ConstraintEvaluator> hardConstraints = new ArrayList<>();
hardConstraints.add(ConstraintsProvider.getHostAttributeHardConstraint(zoneAttrName, "" + 1));
for (int j = 0; j < cpus1 * 2; j++) {
requests.add(TaskRequestProvider.getTaskRequest(1, memory1 / cpus1, 1, hardConstraints, null));
}
final List<VirtualMachineLease> leases = new ArrayList<>();
final AutoScaleRule rule = AutoScaleRuleProvider.createRule(hostAttrVal1, 3, mxIdl, coolDownSecs, cpus1 / 2, memory1 / 2);
final TaskScheduler scheduler = new TaskScheduler.Builder()
.withAutoScaleByAttributeName(hostAttrName)
.withAutoScaleDownBalancedByAttributeName(zoneAttrName)
.withFitnessCalculator(BinPackingFitnessCalculators.cpuBinPacker)
.withLeaseOfferExpirySecs(3600)
.withLeaseRejectAction(new Action1<VirtualMachineLease>() {
@Override
public void call(VirtualMachineLease lease) {
//System.out.println("Rejecting lease on " + lease.hostname());
}
})
.withAutoScaleRule(rule)
.build();
scheduler.setAutoscalerCallback(new Action1<AutoScaleAction>() {
@Override
public void call(AutoScaleAction action) {
if (action.getType() == AutoScaleAction.Type.Down) {
final Collection<String> hosts = ((ScaleDownAction) action).getHosts();
for (String h : hosts) {
int zoneNum = Integer.parseInt(h.substring("host".length())) % 3;
//System.out.println("Scaling down host " + h);
zoneCounts[zoneNum]--;
}
latch.countDown();
} else
Assert.fail("Wasn't expecting to scale up");
}
});
List<VirtualMachineLease.Range> ports = new ArrayList<>();
ports.add(new VirtualMachineLease.Range(1, 10));
// create three attributes, each with unique zone value
List<Map<String, Protos.Attribute>> attributes = new ArrayList<>(3);
Protos.Attribute attr = Protos.Attribute.newBuilder().setName(hostAttrName)
.setType(Protos.Value.Type.TEXT)
.setText(Protos.Value.Text.newBuilder().setValue(hostAttrVal1)).build();
for (int i = 0; i < 3; i++) {
attributes.add(new HashMap<String, Protos.Attribute>());
Protos.Attribute attribute = Protos.Attribute.newBuilder().setName(zoneAttrName)
.setType(Protos.Value.Type.TEXT)
.setText(Protos.Value.Text.newBuilder().setValue("" + i)).build();
attributes.get(i).put(zoneAttrName, attribute);
attributes.get(i).put(hostAttrName, attr);
}
for (int l = 0; l < mxIdl + 6; l++) {
final int zoneNum = l % 3;
leases.add(LeaseProvider.getLeaseOffer("host" + l, cpus1, memory1, ports, attributes.get(zoneNum)));
zoneCounts[zoneNum]++;
}
int i = 0;
boolean first = true;
do {
Thread.sleep(1000);
final SchedulingResult schedulingResult = scheduler.scheduleOnce(requests, leases);
// System.out.println("idleVms#: " + schedulingResult.getIdleVMsCount() + ", #leasesAdded=" +
// schedulingResult.getLeasesAdded() + ", #totalVms=" + schedulingResult.getTotalVMsCount());
// System.out.println("#leasesRejected=" + schedulingResult.getLeasesRejected());
final Map<String, VMAssignmentResult> resultMap = schedulingResult.getResultMap();
for (Map.Entry<String, VMAssignmentResult> entry : resultMap.entrySet()) {
final int zn = Integer.parseInt(entry.getValue().getLeasesUsed().get(0).getAttributeMap().get(zoneAttrName).getText().getValue());
zoneCounts[zn]--;
}
if (first) {
first = false;
requests.clear();
leases.clear();
}
} while (i++ < coolDownSecs + 2 && latch.getCount() > 0);
if (latch.getCount() > 0)
Assert.fail("Didn't get scale down");
for (int zoneCount : zoneCounts) {
Assert.assertEquals(4, zoneCount);
}
}
/**
* Test that a scaled down host doesn't get used in spite of receiving an offer for it
*
* @throws Exception
*/
@Test
public void testScaledDownHostOffer() throws Exception {
TaskScheduler scheduler = getScheduler(noOpLeaseReject, rule1);
final CountDownLatch latch = new CountDownLatch(1);
final AtomicReference<Collection<String>> scaleDownHostsRef = new AtomicReference<>();
final List<TaskRequest> requests = new ArrayList<>();
final List<VirtualMachineLease> leases = new ArrayList<>();
for (int j = 0; j < cpus1; j++) // fill one machine
requests.add(TaskRequestProvider.getTaskRequest(1, memory1 / cpus1, 1));
List<VirtualMachineLease.Range> ports = new ArrayList<>();
ports.add(new VirtualMachineLease.Range(1, 10));
Map<String, Protos.Attribute> attributes1 = new HashMap<>();
Protos.Attribute attribute = Protos.Attribute.newBuilder().setName(hostAttrName)
.setType(Protos.Value.Type.TEXT)
.setText(Protos.Value.Text.newBuilder().setValue(hostAttrVal1)).build();
attributes1.put(hostAttrName, attribute);
int excess = 3;
for (int l = 0; l < maxIdle + excess; l++) {
leases.add(LeaseProvider.getLeaseOffer("host" + l, cpus1, memory1, ports, attributes1));
}
scheduler.setAutoscalerCallback(new Action1<AutoScaleAction>() {
@Override
public void call(AutoScaleAction action) {
if (action instanceof ScaleDownAction) {
scaleDownHostsRef.set(((ScaleDownAction) action).getHosts());
latch.countDown();
}
}
});
int i = 0;
boolean first = true;
while (i++ < coolDownSecs + 2 && latch.getCount() > 0) {
scheduler.scheduleOnce(requests, leases);
if (first) {
first = false;
requests.clear();
leases.clear();
}
Thread.sleep(1000);
}
Assert.assertEquals(0, latch.getCount());
final List<VirtualMachineCurrentState> vmCurrentStates = scheduler.getVmCurrentStates();
long now = System.currentTimeMillis();
for (VirtualMachineCurrentState s : vmCurrentStates) {
if (s.getDisabledUntil() > 0)
System.out.println("********** " + s.getHostname() + " disabled for " + (s.getDisabledUntil() - now) +
" mSecs");
}
// remove any existing leases in scheduler
// now generate offers for hosts that were scale down and ensure they don't get used
for (String hostname : scaleDownHostsRef.get()) {
leases.add(LeaseProvider.getLeaseOffer(hostname, cpus1, memory1, ports, attributes1));
}
// now try to fill all machines minus one that we filled before
for (int j = 0; j < (maxIdle + excess - 1) * cpus1; j++)
requests.add(TaskRequestProvider.getTaskRequest(1, memory1 / cpus1, 1));
i = 0;
first = true;
do {
SchedulingResult schedulingResult = scheduler.scheduleOnce(requests, leases);
if (!schedulingResult.getResultMap().isEmpty()) {
for (Map.Entry<String, VMAssignmentResult> entry : schedulingResult.getResultMap().entrySet()) {
Assert.assertFalse("Did not expect scaled down host " + entry.getKey() + " to be assigned again",
isInCollection(entry.getKey(), scaleDownHostsRef.get()));
for (int j = 0; j < entry.getValue().getTasksAssigned().size(); j++)
requests.remove(0);
}
}
if (first) {
leases.clear();
first = false;
}
Thread.sleep(1000);
} while (i++ < coolDownSecs - 1);
}
// Tests that resource shortfall is evaluated and scale up happens beyond what would otherwise request only up to
// maxIdle1 count for the scaling rule. Also, that scale up from shortfall due to new tasks doesn't wait for cooldown
@Test
public void testResourceShortfall() throws Exception {
TaskScheduler scheduler = getScheduler(noOpLeaseReject, AutoScaleRuleProvider.createRule(hostAttrVal1, minIdle, maxIdle, coolDownSecs, 1, 1000));
final List<TaskRequest> requests = new ArrayList<>();
final List<VirtualMachineLease> leases = new ArrayList<>();
for (int i = 0; i < rule1.getMaxIdleHostsToKeep() * 2; i++)
requests.add(TaskRequestProvider.getTaskRequest(1, 1000, 1));
leases.addAll(LeaseProvider.getLeases(2, 1, 1000, 1, 10));
final AtomicInteger scaleUpRequested = new AtomicInteger();
final AtomicReference<CountDownLatch> latchRef = new AtomicReference<>(new CountDownLatch(1));
scheduler.setAutoscalerCallback(new Action1<AutoScaleAction>() {
@Override
public void call(AutoScaleAction action) {
if (action instanceof ScaleUpAction) {
scaleUpRequested.set(((ScaleUpAction) action).getScaleUpCount());
latchRef.get().countDown();
}
}
});
SchedulingResult schedulingResult = scheduler.scheduleOnce(requests.subList(0, leases.size()), leases);
Assert.assertNotNull(schedulingResult);
Thread.sleep(coolDownSecs * 1000 + 1000);
schedulingResult = scheduler.scheduleOnce(requests.subList(leases.size(), requests.size()), new ArrayList<VirtualMachineLease>());
Assert.assertNotNull(schedulingResult);
boolean waitSuccessful = latchRef.get().await(coolDownSecs, TimeUnit.SECONDS);
Assert.assertTrue(waitSuccessful);
final int scaleUp = scaleUpRequested.get();
Assert.assertEquals(requests.size() - leases.size(), scaleUp);
requests.clear();
final int newRequests = rule1.getMaxIdleHostsToKeep() * 3;
for (int i = 0; i < newRequests; i++)
requests.add(TaskRequestProvider.getTaskRequest(1, 1000, 1));
latchRef.set(new CountDownLatch(1));
schedulingResult = scheduler.scheduleOnce(requests, new ArrayList<VirtualMachineLease>());
Assert.assertNotNull(schedulingResult);
waitSuccessful = latchRef.get().await(coolDownSecs, TimeUnit.SECONDS);
Assert.assertTrue(waitSuccessful);
Assert.assertEquals(newRequests, scaleUpRequested.get());
}
@Test
public void testAddingNewRule() throws Exception {
TaskScheduler scheduler = getScheduler(noOpLeaseReject, AutoScaleRuleProvider.createRule(hostAttrVal1, minIdle, maxIdle, coolDownSecs, 1, 1000));
final List<TaskRequest> requests = new ArrayList<>();
final List<VirtualMachineLease> leases = new ArrayList<>();
Map<String, Protos.Attribute> attributes1 = new HashMap<>();
final Protos.Attribute attribute1 = Protos.Attribute.newBuilder().setName(hostAttrName)
.setType(Protos.Value.Type.TEXT)
.setText(Protos.Value.Text.newBuilder().setValue(hostAttrVal1)).build();
attributes1.put(hostAttrName, attribute1);
Map<String, Protos.Attribute> attributes2 = new HashMap<>();
Protos.Attribute attribute2 = Protos.Attribute.newBuilder().setName(hostAttrName)
.setType(Protos.Value.Type.TEXT)
.setText(Protos.Value.Text.newBuilder().setValue(hostAttrVal2)).build();
attributes2.put(hostAttrName, attribute2);
List<VirtualMachineLease.Range> ports = new ArrayList<>();
ports.add(new VirtualMachineLease.Range(1, 10));
for (int l = 0; l < minIdle; l++) {
leases.add(LeaseProvider.getLeaseOffer("smallhost" + l, cpus1, memory1, ports, attributes1));
leases.add(LeaseProvider.getLeaseOffer("bighost" + l, cpus2, memory2, ports, attributes2));
}
// fill the big hosts, there's no autoscale rule for it
// make small tasks sticky on small hosts with a constraint
ConstraintEvaluator attrConstraint = new HostAttrValueConstraint(hostAttrName, new Func1<String, String>() {
@Override
public String call(String s) {
return hostAttrVal1;
}
});
for (int h = 0; h < leases.size() / 2; h++) {
requests.add(TaskRequestProvider.getTaskRequest(6.0, 100, 1));
requests.add(TaskRequestProvider.getTaskRequest(1.0, 10, 1, Collections.singletonList(attrConstraint), null));
}
final CountDownLatch latchSmallHosts = new CountDownLatch(1);
final AtomicReference<Integer> hostsToAdd = new AtomicReference<>(0);
scheduler.setAutoscalerCallback(new Action1<AutoScaleAction>() {
@Override
public void call(AutoScaleAction action) {
switch (action.getRuleName()) {
case hostAttrVal1:
System.out.println("Got scale up for small hosts " + System.currentTimeMillis());
hostsToAdd.set(((ScaleUpAction) action).getScaleUpCount());
latchSmallHosts.countDown();
break;
case hostAttrVal2:
Assert.fail("Wasn't expecting scale action for big hosts");
break;
default:
Assert.fail("Unexpected scale action rule name " + action.getRuleName());
}
}
});
for (int i = 0; i < coolDownSecs + 2; i++) {
final SchedulingResult schedulingResult = scheduler.scheduleOnce(requests, leases);
if (i == 0) {
//Assert.assertTrue(schedulingResult.getFailures().isEmpty());
int successes = 0;
final Map<String, VMAssignmentResult> resultMap = schedulingResult.getResultMap();
for (Map.Entry<String, VMAssignmentResult> entry : resultMap.entrySet()) {
for (TaskAssignmentResult r : entry.getValue().getTasksAssigned())
if (r.isSuccessful()) {
successes++;
scheduler.getTaskAssigner().call(r.getRequest(), entry.getKey());
switch ((int) r.getRequest().getCPUs()) {
case 1:
Assert.assertTrue("Expecting assignment on small host", entry.getKey().startsWith("smallhost"));
break;
case 6:
Assert.assertTrue("Expecting assignment on big host", entry.getKey().startsWith("bighost"));
break;
default:
Assert.fail("Unexpected task CPUs: " + r.getRequest().getCPUs());
}
}
}
Assert.assertEquals("#assigned", requests.size(), successes);
requests.clear();
leases.clear();
}
Thread.sleep(1000);
}
if (!latchSmallHosts.await(5, TimeUnit.SECONDS))
Assert.fail("Small hosts scale up not triggered");
Assert.assertTrue("Small hosts to add>0", hostsToAdd.get() > 0);
for (int i = 0; i < hostsToAdd.get(); i++)
leases.add(LeaseProvider.getLeaseOffer("smallhost" + 100 + i, cpus1, memory1, ports, attributes1));
final CountDownLatch latchBigHosts = new CountDownLatch(1);
scheduler.addOrReplaceAutoScaleRule(AutoScaleRuleProvider.createRule(hostAttrVal2, minIdle, maxIdle, coolDownSecs, 1, 1000));
scheduler.setAutoscalerCallback(new Action1<AutoScaleAction>() {
@Override
public void call(AutoScaleAction action) {
switch (action.getRuleName()) {
case hostAttrVal1:
Assert.fail("Wasn't expecting scale action on " + hostAttrVal1);
break;
case hostAttrVal2:
System.out.println("Got scale up for big hosts " + System.currentTimeMillis());
latchBigHosts.countDown();
break;
default:
Assert.fail("Unknown scale action rule name: " + action.getRuleName());
}
}
});
for (int i = 0; i < coolDownSecs + 2; i++) {
scheduler.scheduleOnce(requests, leases);
if (i == 0) {
leases.clear();
}
Thread.sleep(1000);
}
if (!latchBigHosts.await(5, TimeUnit.SECONDS))
Assert.fail("Big hosts scale up not triggered");
}
@Test
public void testRemovingExistingRule() throws Exception {
TaskScheduler scheduler = getScheduler(noOpLeaseReject, AutoScaleRuleProvider.createRule(hostAttrVal1, minIdle, maxIdle, coolDownSecs, 1, 1000));
final List<TaskRequest> requests = new ArrayList<>();
final List<VirtualMachineLease> leases = new ArrayList<>();
Map<String, Protos.Attribute> attributes1 = new HashMap<>();
final Protos.Attribute attribute1 = Protos.Attribute.newBuilder().setName(hostAttrName)
.setType(Protos.Value.Type.TEXT)
.setText(Protos.Value.Text.newBuilder().setValue(hostAttrVal1)).build();
attributes1.put(hostAttrName, attribute1);
List<VirtualMachineLease.Range> ports = new ArrayList<>();
ports.add(new VirtualMachineLease.Range(1, 10));
for (int l = 0; l < minIdle; l++) {
leases.add(LeaseProvider.getLeaseOffer("smallhost" + l, cpus1, memory1, ports, attributes1));
}
for (int h = 0; h < leases.size() / 2; h++) {
requests.add(TaskRequestProvider.getTaskRequest(3.0, 100, 1));
}
final CountDownLatch latch = new CountDownLatch(1);
final AtomicBoolean keepGoing = new AtomicBoolean(true);
scheduler.setAutoscalerCallback(new Action1<AutoScaleAction>() {
@Override
public void call(AutoScaleAction action) {
if (action.getType() == AutoScaleAction.Type.Up) {
latch.countDown();
keepGoing.set(false);
}
}
});
for (int i = 0; i < coolDownSecs + 2 && keepGoing.get(); i++) {
final SchedulingResult schedulingResult = scheduler.scheduleOnce(requests, leases);
if (i == 0) {
//Assert.assertTrue(schedulingResult.getFailures().isEmpty());
int successes = 0;
final Map<String, VMAssignmentResult> resultMap = schedulingResult.getResultMap();
for (Map.Entry<String, VMAssignmentResult> entry : resultMap.entrySet()) {
for (TaskAssignmentResult r : entry.getValue().getTasksAssigned())
if (r.isSuccessful()) {
successes++;
scheduler.getTaskAssigner().call(r.getRequest(), entry.getKey());
}
}
Assert.assertEquals("#assigned", requests.size(), successes);
requests.clear();
leases.clear();
}
Thread.sleep(1000);
}
if (!latch.await(2, TimeUnit.SECONDS))
Assert.fail("Didn't get scale up action");
scheduler.removeAutoScaleRule(hostAttrVal1);
scheduler.addOrReplaceAutoScaleRule(AutoScaleRuleProvider.createRule(hostAttrVal2, minIdle, maxIdle, coolDownSecs, 1, 1000));
final AtomicBoolean gotHost2scaleup = new AtomicBoolean(false);
scheduler.setAutoscalerCallback(new Action1<AutoScaleAction>() {
@Override
public void call(AutoScaleAction action) {
if (action.getType() == AutoScaleAction.Type.Up) {
switch (action.getRuleName()) {
case hostAttrVal1:
Assert.fail("Shouldn't have gotten autoscale action");
break;
case hostAttrVal2:
gotHost2scaleup.set(true);
break;
}
}
}
});
for (int i = 0; i < coolDownSecs + 2; i++) {
scheduler.scheduleOnce(requests, leases);
Thread.sleep(1000);
}
Assert.assertTrue("Host type 2 scale action", gotHost2scaleup.get());
}
private boolean isInCollection(String host, Collection<String> hostList) {
for (String h : hostList)
if (h.equals(host))
return true;
return false;
}
// Test that s scale up action doesn't kick in for a very short duration breach of minIdle1
@Test
public void testDelayedAutoscaleUp() throws Exception {
testScaleUpDelay(1);
}
// Test that the scale up request delay does expire after a while, and next scale up is delayed again
@Test
public void testScaleUpDelayReset() throws Exception {
testScaleUpDelay(2);
}
private void testScaleUpDelay(int N) throws Exception {
final AtomicBoolean scaleUpReceived = new AtomicBoolean();
final AtomicBoolean scaleDownReceived = new AtomicBoolean();
final Action1<AutoScaleAction> callback = new Action1<AutoScaleAction>() {
@Override
public void call(AutoScaleAction autoScaleAction) {
switch (autoScaleAction.getType()) {
case Down:
scaleDownReceived.set(true);
break;
case Up:
scaleUpReceived.set(true);
break;
}
}
};
long scaleupDelaySecs = 2L;
TaskScheduler scheduler = getScheduler(null, callback, scaleupDelaySecs, 0, rule1);
List<VirtualMachineLease.Range> ports = new ArrayList<>();
ports.add(new VirtualMachineLease.Range(1, 10));
Map<String, Protos.Attribute> attributes = new HashMap<>();
Protos.Attribute attribute = Protos.Attribute.newBuilder().setName(hostAttrName)
.setType(Protos.Value.Type.TEXT)
.setText(Protos.Value.Text.newBuilder().setValue(hostAttrVal1)).build();
attributes.put(hostAttrName, attribute);
final List<VirtualMachineLease> leases = new ArrayList<>();
for (int l = 0; l < minIdle; l++)
leases.add(LeaseProvider.getLeaseOffer("host" + l, cpus1, memory1, ports, attributes));
for (int i = 0; i < coolDownSecs + 1; i++) {
if (i > 0)
leases.clear();
final SchedulingResult result = scheduler.scheduleOnce(Collections.<TaskRequest>emptyList(), leases);
Thread.sleep(1000);
}
Assert.assertFalse("Unexpected to scale DOWN", scaleDownReceived.get());
Assert.assertFalse("Unexpected to scale UP", scaleUpReceived.get());
for (int o = 0; o < N; o++) {
if (o == 1)
Thread.sleep((long) (2.5 * scaleupDelaySecs) * 1000L); // delay next round by a while to reset previous delay
for (int i = 0; i < scaleupDelaySecs + 2; i++) {
List<TaskRequest> tasks = new ArrayList<>();
if (i == 0) {
tasks.add(TaskRequestProvider.getTaskRequest(1, 1000, 1));
}
final SchedulingResult result = scheduler.scheduleOnce(tasks, leases);
final Map<String, VMAssignmentResult> resultMap = result.getResultMap();
if (!tasks.isEmpty()) {
Assert.assertTrue(resultMap.size() == 1);
leases.add(LeaseProvider.getConsumedLease(resultMap.values().iterator().next()));
} else
leases.clear();
Thread.sleep(1000);
}
Assert.assertFalse("Unexpected to scale DOWN", scaleDownReceived.get());
Assert.assertFalse("Unexpected to scale UP", scaleUpReceived.get());
}
// ensure normal scale up request happens after the delay
scheduler.scheduleOnce(Collections.singletonList(TaskRequestProvider.getTaskRequest(1, 1000, 1)),
Collections.<VirtualMachineLease>emptyList());
Thread.sleep(1000);
Assert.assertTrue("Expected to scale UP", scaleUpReceived.get());
}
// Test that a scale down action doesn't kick in for a very short duration breach of maxIdle1
@Test
public void testDelayedAutoscaleDown() throws Exception {
testScaleDownDelay(1);
}
@Test
public void testScaleDownDelayReset() throws Exception {
testScaleDownDelay(2);
}
private void testScaleDownDelay(int N) throws Exception {
final AtomicBoolean scaleUpReceived = new AtomicBoolean();
final AtomicBoolean scaleDownReceived = new AtomicBoolean();
final Action1<AutoScaleAction> callback = new Action1<AutoScaleAction>() {
@Override
public void call(AutoScaleAction autoScaleAction) {
switch (autoScaleAction.getType()) {
case Down:
scaleDownReceived.set(true);
break;
case Up:
scaleUpReceived.set(true);
break;
}
}
};
long scaleDownDelay = 3;
TaskScheduler scheduler = getScheduler(noOpLeaseReject, callback, 0, scaleDownDelay, rule1);
List<VirtualMachineLease.Range> ports = new ArrayList<>();
ports.add(new VirtualMachineLease.Range(1, 10));
Map<String, Protos.Attribute> attributes = new HashMap<>();
Protos.Attribute attribute = Protos.Attribute.newBuilder().setName(hostAttrName)
.setType(Protos.Value.Type.TEXT)
.setText(Protos.Value.Text.newBuilder().setValue(hostAttrVal1)).build();
attributes.put(hostAttrName, attribute);
final List<VirtualMachineLease> leases = new ArrayList<>();
for (int l = 0; l < maxIdle + 2; l++)
leases.add(LeaseProvider.getLeaseOffer("host" + l, cpus1, memory1, ports, attributes));
List<TaskRequest> tasks = new ArrayList<>();
for (int t = 0; t < 2; t++)
tasks.add(TaskRequestProvider.getTaskRequest(cpus1, memory1, 1));
final SchedulingResult result = scheduler.scheduleOnce(tasks, leases);
final Map<String, VMAssignmentResult> resultMap = result.getResultMap();
Assert.assertEquals(tasks.size(), resultMap.size());
tasks.clear();
leases.clear();
Thread.sleep(coolDownSecs * 1000L + 500L);
// mark completion of 1 task; add back one of the leases
leases.add(resultMap.values().iterator().next().getLeasesUsed().iterator().next());
// run scheduler for (scaleDownDelay-1) secs and ensure we didn't get scale down request
for (int i = 0; i < scaleDownDelay - 1; i++) {
scheduler.scheduleOnce(tasks, leases);
if (i == 0)
leases.clear();
Thread.sleep(1000);
}
Assert.assertFalse("Scale down not expected", scaleDownReceived.get());
Assert.assertFalse("Scale up not expected", scaleUpReceived.get());
for (int o = 0; o < N; o++) {
if (o == 1) {
Thread.sleep((long) (2.5 * scaleDownDelay) * 1000L);
leases.add(LeaseProvider.getLeaseOffer("hostFoo", cpus1, memory1, ports, attributes));
} else
tasks.add(TaskRequestProvider.getTaskRequest(cpus1, memory1, 1));
for (int i = 0; i < scaleDownDelay + 1; i++) {
final SchedulingResult result1 = scheduler.scheduleOnce(tasks, leases);
leases.clear();
if (!tasks.isEmpty()) {
Assert.assertEquals(tasks.size(), result1.getResultMap().size());
tasks.clear();
}
Thread.sleep(1000);
}
Assert.assertFalse("Scale down not expected", scaleDownReceived.get());
Assert.assertFalse("Scale up not expected", scaleUpReceived.get());
}
// ensure normal scale down request happens after the delay
for (int l = 0; l < N; l++)
leases.add(LeaseProvider.getLeaseOffer("host" + (100 + l), cpus1, memory1, ports, attributes));
SchedulingResult result1 = scheduler.scheduleOnce(Collections.<TaskRequest>emptyList(), leases);
leases.clear();
Thread.sleep(1000);
Assert.assertFalse("Scale up not expected", scaleUpReceived.get());
Assert.assertTrue("Scale down expected", scaleDownReceived.get());
}
// Test that with a rule that has min size defined, we don't try to scale down below the min size, even though there are too many idle
@Test
public void testRuleWithMinSize() throws Exception {
final int minSize = 10;
final int extra = 2;
long cooldown = 2;
AutoScaleRule rule = AutoScaleRuleProvider.createWithMinSize("cluster1", 2, 5, cooldown, 1.0, 1000, minSize);
Map<String, Protos.Attribute> attributes = new HashMap<>();
Protos.Attribute attribute = Protos.Attribute.newBuilder().setName(hostAttrName)
.setType(Protos.Value.Type.TEXT)
.setText(Protos.Value.Text.newBuilder().setValue("cluster1")).build();
List<VirtualMachineLease.Range> ports = new ArrayList<>();
ports.add(new VirtualMachineLease.Range(1, 10));
attributes.put(hostAttrName, attribute);
final List<VirtualMachineLease> leases = new ArrayList<>();
for (int l = 0; l < minSize + extra; l++)
leases.add(LeaseProvider.getLeaseOffer("host" + l, 4, 4000, ports, attributes));
AtomicInteger scaleDown = new AtomicInteger();
Action1<AutoScaleAction> callback = autoScaleAction -> {
if (autoScaleAction instanceof ScaleDownAction) {
scaleDown.addAndGet(((ScaleDownAction) autoScaleAction).getHosts().size());
}
};
final TaskScheduler scheduler = getScheduler(noOpLeaseReject, callback, rule);
for (int i = 0; i < cooldown + 1; i++) {
scheduler.scheduleOnce(Collections.emptyList(), leases);
leases.clear();
Thread.sleep(1000);
}
Assert.assertEquals(extra, scaleDown.get());
}
// Test that with a rule that has min size defined, we don't try to scale down at all if total size < minSize, even though there are too many idle
@Test
public void testRuleWithMinSize2() throws Exception {
final int minSize = 10;
long cooldown = 2;
AutoScaleRule rule = AutoScaleRuleProvider.createWithMinSize("cluster1", 2, 5, cooldown, 1.0, 1000, minSize);
Map<String, Protos.Attribute> attributes = new HashMap<>();
Protos.Attribute attribute = Protos.Attribute.newBuilder().setName(hostAttrName)
.setType(Protos.Value.Type.TEXT)
.setText(Protos.Value.Text.newBuilder().setValue("cluster1")).build();
List<VirtualMachineLease.Range> ports = new ArrayList<>();
ports.add(new VirtualMachineLease.Range(1, 10));
attributes.put(hostAttrName, attribute);
final List<VirtualMachineLease> leases = new ArrayList<>();
for (int l = 0; l < minSize - 2; l++)
leases.add(LeaseProvider.getLeaseOffer("host" + l, 4, 4000, ports, attributes));
AtomicInteger scaleDown = new AtomicInteger();
Action1<AutoScaleAction> callback = autoScaleAction -> {
if (autoScaleAction instanceof ScaleDownAction) {
scaleDown.addAndGet(((ScaleDownAction) autoScaleAction).getHosts().size());
}
};
final TaskScheduler scheduler = getScheduler(noOpLeaseReject, callback, rule);
for (int i = 0; i < cooldown + 1; i++) {
scheduler.scheduleOnce(Collections.emptyList(), leases);
leases.clear();
Thread.sleep(1000);
}
Assert.assertEquals(0, scaleDown.get());
}
// Test that with a rule that has the max size defined, we don't try to scale up beyond the max, even if there's not enough idle
@Test
public void testRuleWithMaxSize() throws Exception {
final int maxSize = 10;
final int leaveIdle = 2;
final long cooldown = 2;
final AutoScaleRule rule = AutoScaleRuleProvider.createWithMaxSize("cluster1", leaveIdle * 2, leaveIdle * 2 + 1, cooldown, 1, 1000, maxSize);
Map<String, Protos.Attribute> attributes = new HashMap<>();
Protos.Attribute attribute = Protos.Attribute.newBuilder().setName(hostAttrName)
.setType(Protos.Value.Type.TEXT)
.setText(Protos.Value.Text.newBuilder().setValue("cluster1")).build();
List<VirtualMachineLease.Range> ports = new ArrayList<>();
ports.add(new VirtualMachineLease.Range(1, 10));
attributes.put(hostAttrName, attribute);
final List<VirtualMachineLease> leases = new ArrayList<>();
for (int l = 0; l < maxSize - leaveIdle; l++)
leases.add(LeaseProvider.getLeaseOffer("host" + l, 4, 4000, ports, attributes));
AtomicInteger scaleUp = new AtomicInteger();
Action1<AutoScaleAction> callback = autoScaleAction -> {
if (autoScaleAction instanceof ScaleUpAction) {
System.out.println("**************** scale up by " + ((ScaleUpAction) autoScaleAction).getScaleUpCount());
scaleUp.addAndGet(((ScaleUpAction) autoScaleAction).getScaleUpCount());
}
};
final TaskScheduler scheduler = getScheduler(noOpLeaseReject, callback, rule);
// create enough tasks to fill up the Vms
List<TaskRequest> tasks = new ArrayList<>();
for (int l = 0; l < maxSize - leaveIdle; l++)
tasks.add(TaskRequestProvider.getTaskRequest(4, 4000, 1));
boolean first = true;
for (int i = 0; i < cooldown + 1; i++) {
final SchedulingResult result = scheduler.scheduleOnce(tasks, leases);
if (first) {
first = false;
leases.clear();
int assigned = 0;
Assert.assertTrue(result.getResultMap().size() > 0);
for (VMAssignmentResult r : result.getResultMap().values()) {
for (TaskAssignmentResult task : r.getTasksAssigned()) {
assigned++;
scheduler.getTaskAssigner().call(task.getRequest(), r.getHostname());
}
}
Assert.assertEquals(maxSize - leaveIdle, assigned);
tasks.clear();
}
Thread.sleep(1000);
}
Assert.assertEquals(leaveIdle, scaleUp.get());
}
// Test that with a rule that has the max size defined, we don't try to scale up at all if total size > maxSize, even if there's no idle left
@Test
public void testRuleWithMaxSize2() throws Exception {
final int maxSize = 10;
final long cooldown = 2;
final AutoScaleRule rule = AutoScaleRuleProvider.createWithMaxSize("cluster1", 2, 5, cooldown, 1, 1000, maxSize);
Map<String, Protos.Attribute> attributes = new HashMap<>();
Protos.Attribute attribute = Protos.Attribute.newBuilder().setName(hostAttrName)
.setType(Protos.Value.Type.TEXT)
.setText(Protos.Value.Text.newBuilder().setValue("cluster1")).build();
List<VirtualMachineLease.Range> ports = new ArrayList<>();
ports.add(new VirtualMachineLease.Range(1, 10));
attributes.put(hostAttrName, attribute);
final List<VirtualMachineLease> leases = new ArrayList<>();
for (int l = 0; l < maxSize + 2; l++)
leases.add(LeaseProvider.getLeaseOffer("host" + l, 4, 4000, ports, attributes));
AtomicInteger scaleUp = new AtomicInteger();
Action1<AutoScaleAction> callback = autoScaleAction -> {
if (autoScaleAction instanceof ScaleUpAction) {
System.out.println("**************** scale up by " + ((ScaleUpAction) autoScaleAction).getScaleUpCount());
scaleUp.addAndGet(((ScaleUpAction) autoScaleAction).getScaleUpCount());
}
};
final TaskScheduler scheduler = getScheduler(noOpLeaseReject, callback, rule);
// create enough tasks to fill up the Vms
List<TaskRequest> tasks = new ArrayList<>();
for (int l = 0; l < maxSize + 2; l++)
tasks.add(TaskRequestProvider.getTaskRequest(4, 4000, 1));
boolean first = true;
for (int i = 0; i < cooldown + 1; i++) {
final SchedulingResult result = scheduler.scheduleOnce(tasks, leases);
if (first) {
first = false;
leases.clear();
int assigned = 0;
Assert.assertTrue(result.getResultMap().size() > 0);
for (VMAssignmentResult r : result.getResultMap().values()) {
for (TaskAssignmentResult task : r.getTasksAssigned()) {
assigned++;
scheduler.getTaskAssigner().call(task.getRequest(), r.getHostname());
}
}
Assert.assertEquals(maxSize + 2, assigned);
tasks.clear();
}
Thread.sleep(1000);
}
Assert.assertEquals(0, scaleUp.get());
}
// Test that aggressive scale up gives a callback only for the cluster, among multiple clusters, that is mapped
// to by the mapper supplied to task scheduling service. The other cluster should not get scale up request for
// aggressive scale up.
@Test
public void testTask2ClustersGetterAggressiveScaleUp() throws Exception {
final long cooldownMillis = 3000;
final AutoScaleRule rule1 = AutoScaleRuleProvider.createRule("cluster1", minIdle, maxIdle, cooldownMillis / 1000L, 1, 1000);
final AutoScaleRule rule2 = AutoScaleRuleProvider.createRule("cluster2", minIdle, maxIdle, cooldownMillis / 1000L, 1, 1000);
Map<String, Protos.Attribute> attributes1 = new HashMap<>();
Protos.Attribute attribute1 = Protos.Attribute.newBuilder().setName(hostAttrName)
.setType(Protos.Value.Type.TEXT)
.setText(Protos.Value.Text.newBuilder().setValue("cluster1")).build();
List<VirtualMachineLease.Range> ports = new ArrayList<>();
ports.add(new VirtualMachineLease.Range(1, 10));
attributes1.put(hostAttrName, attribute1);
Map<String, Protos.Attribute> attributes2 = new HashMap<>();
Protos.Attribute attribute2 = Protos.Attribute.newBuilder().setName(hostAttrName)
.setType(Protos.Value.Type.TEXT)
.setText(Protos.Value.Text.newBuilder().setValue("cluster2")).build();
attributes2.put(hostAttrName, attribute1);
final List<VirtualMachineLease> leases = new ArrayList<>();
for (int l = 0; l < minIdle; l++)
leases.add(LeaseProvider.getLeaseOffer("host" + l, cpus1, memory1, ports, attributes1));
final Map<String, Integer> scaleUpRequests = new HashMap<>();
final CountDownLatch initialScaleUpLatch = new CountDownLatch(2);
final AtomicReference<CountDownLatch> scaleUpLatchRef = new AtomicReference<>();
Action1<AutoScaleAction> callback = autoScaleAction -> {
if (autoScaleAction instanceof ScaleUpAction) {
final ScaleUpAction action = (ScaleUpAction) autoScaleAction;
System.out.println("**************** scale up by " + action.getScaleUpCount());
scaleUpRequests.putIfAbsent(action.getRuleName(), 0);
scaleUpRequests.put(action.getRuleName(), scaleUpRequests.get(action.getRuleName()) + action.getScaleUpCount());
if (scaleUpLatchRef.get() != null)
scaleUpLatchRef.get().countDown();
}
};
scaleUpLatchRef.set(initialScaleUpLatch);
final TaskScheduler scheduler = getScheduler(null, callback, rule1, rule2);
final TaskQueue queue = TaskQueues.createTieredQueue(2);
int numTasks = minIdle * cpus1; // minIdle1 number of hosts each with cpu1 number of cpus
final CountDownLatch latch = new CountDownLatch(numTasks);
final AtomicReference<List<Exception>> exceptions = new AtomicReference<>();
final TaskSchedulingService schedulingService = new TaskSchedulingService.Builder()
.withMaxDelayMillis(100)
.withLoopIntervalMillis(20)
.withTaskQueue(queue)
.withTaskScheduler(scheduler)
.withSchedulingResultCallback(schedulingResult -> {
final List<Exception> elist = schedulingResult.getExceptions();
if (elist != null && !elist.isEmpty())
exceptions.set(elist);
final Map<String, VMAssignmentResult> resultMap = schedulingResult.getResultMap();
if (resultMap != null && !resultMap.isEmpty()) {
for (VMAssignmentResult vmar : resultMap.values()) {
vmar.getTasksAssigned().forEach(t -> latch.countDown());
}
}
})
.build();
schedulingService.setTaskToClusterAutoScalerMapGetter(task -> Collections.singletonList("cluster1"));
schedulingService.start();
schedulingService.addLeases(leases);
for (int i = 0; i < numTasks; i++)
queue.queueTask(
QueuableTaskProvider.wrapTask(
new QAttributes.QAttributesAdaptor(0, "default"),
TaskRequestProvider.getTaskRequest(1, 10, 1)
)
);
if (!latch.await(10, TimeUnit.SECONDS))
Assert.fail("Timeout waiting for tasks to get assigned");
// wait for scale up to happen
if (!initialScaleUpLatch.await(cooldownMillis + 1000, TimeUnit.MILLISECONDS))
Assert.fail("Timeout waiting for initial scale up request");
Assert.assertEquals(2, scaleUpRequests.size());
scaleUpRequests.clear();
scaleUpLatchRef.set(null);
// now submit more tasks for aggressive scale up to trigger
int laterTasksSize = numTasks * 3;
for (int i = 0; i < laterTasksSize; i++) {
queue.queueTask(
QueuableTaskProvider.wrapTask(
new QAttributes.QAttributesAdaptor(0, "default"),
TaskRequestProvider.getTaskRequest(1, 10, 1)
)
);
}
// wait for less than cooldown time to get aggressive scale up requests
Thread.sleep(cooldownMillis / 2);
// expect to get scale up request only for cluster1 VMs
Assert.assertEquals(1, scaleUpRequests.size());
Assert.assertEquals("cluster1", scaleUpRequests.keySet().iterator().next());
Assert.assertEquals(laterTasksSize, scaleUpRequests.values().iterator().next().intValue());
}
// Test that when blocking the autoscaler callback, tasks are not scheduled on machines that are scheduled to be terminated
@Test
public void testAutoscalerBlockingCallback() throws Exception {
int minIdle = 1;
int maxIdle = 1;
int numberOfHostsPerCluster = maxIdle * 2;
final long cooldownMillis = 1_000;
final String CLUSTER1 = "cluster1";
final String CLUSTER2 = "cluster2";
final CountDownLatch countDownLatch = new CountDownLatch(2);
// create autoscaling rules for 2 clusters
final AutoScaleRule cluster1Rule = AutoScaleRuleProvider.createWithMaxSize(CLUSTER1, minIdle, maxIdle, cooldownMillis / 1000L, 1, 1000, numberOfHostsPerCluster);
final AutoScaleRule cluster2Rule = AutoScaleRuleProvider.createWithMaxSize(CLUSTER2, minIdle, maxIdle, cooldownMillis / 1000L, 1, 1000, numberOfHostsPerCluster);
// create the maxIdle * 2 leases (machines) for each cluster
Map<String, Protos.Attribute> attributes1 = new HashMap<>();
Protos.Attribute attribute1 = Protos.Attribute.newBuilder().setName(hostAttrName)
.setType(Protos.Value.Type.TEXT)
.setText(Protos.Value.Text.newBuilder().setValue(CLUSTER1)).build();
List<VirtualMachineLease.Range> ports = new ArrayList<>();
ports.add(new VirtualMachineLease.Range(1, 10));
attributes1.put(hostAttrName, attribute1);
Map<String, Protos.Attribute> attributes2 = new HashMap<>();
Protos.Attribute attribute2 = Protos.Attribute.newBuilder().setName(hostAttrName)
.setType(Protos.Value.Type.TEXT)
.setText(Protos.Value.Text.newBuilder().setValue(CLUSTER2)).build();
attributes2.put(hostAttrName, attribute2);
final List<VirtualMachineLease> leases = new ArrayList<>();
for (int l = 0; l < numberOfHostsPerCluster; l++) {
leases.add(LeaseProvider.getLeaseOffer("cluster1Host" + l, cpus1, memory1, ports, attributes1));
leases.add(LeaseProvider.getLeaseOffer("cluster2Host" + l, cpus1, memory1, ports, attributes2));
}
// create task scheduler with a callback action that blocks for 100ms
Set<String> hostsToScaleDown = new HashSet<>();
Action1<AutoScaleAction> callback = action -> {
try {
if (action instanceof ScaleDownAction) {
ScaleDownAction scaleDownAction = (ScaleDownAction) action;
hostsToScaleDown.addAll(scaleDownAction.getHosts());
countDownLatch.countDown();
Thread.sleep(100);
}
} catch (InterruptedException ignored) {
}
};
final TaskScheduler scheduler = getScheduler(noOpLeaseReject, callback, cluster1Rule, cluster2Rule);
// run a scheduling iteration and wait until the callback is called
scheduler.scheduleOnce(Collections.emptyList(), leases);
while (countDownLatch.getCount() != 1) {
Thread.sleep(10);
scheduler.scheduleOnce(Collections.emptyList(), Collections.emptyList());
}
// create maxIdle tasks that each fill up a machine and run scheduling iteration
final List<TaskRequest> requests = new ArrayList<>();
for (int i = 0; i < (numberOfHostsPerCluster * 1.5); i++) {
requests.add(TaskRequestProvider.getTaskRequest(cpus1, memory1, 0));
}
SchedulingResult schedulingResult = scheduler.scheduleOnce(requests, Collections.emptyList());
// verify that half of the tasks failed placement as half of the instances should have been disabled by the autoscaler
int expectedFailures = numberOfHostsPerCluster / 2;
Map<TaskRequest, List<TaskAssignmentResult>> failures = schedulingResult.getFailures();
Assert.assertEquals(expectedFailures + " tasks should have failed placement", expectedFailures, failures.size());
// verify that none of the placements happened on a down scaled host
Map<String, VMAssignmentResult> resultMap = schedulingResult.getResultMap();
resultMap.values().forEach(result -> Assert.assertFalse(hostsToScaleDown.contains(result.getHostname())));
}
}
| 9,106 |
0 | Create_ds/Fenzo/fenzo-core/src/test/java/com/netflix | Create_ds/Fenzo/fenzo-core/src/test/java/com/netflix/fenzo/ConstraintsProvider.java | /*
* Copyright 2015 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.fenzo;
import org.apache.mesos.Protos;
import java.util.Map;
public class ConstraintsProvider {
public static ConstraintEvaluator getHostAttributeHardConstraint(final String attributeName, final String value) {
return new ConstraintEvaluator() {
@Override
public String getName() {
return "HostAttributeHardConstraint";
}
@Override
public Result evaluate(TaskRequest taskRequest, VirtualMachineCurrentState targetVM, TaskTrackerState taskTrackerState) {
final Map<String, Protos.Attribute> attributeMap = targetVM.getCurrAvailableResources().getAttributeMap();
if(attributeMap==null || attributeMap.isEmpty())
return new Result(false, "No Attributes for host " + targetVM.getCurrAvailableResources().hostname());
final Protos.Attribute val = attributeMap.get(attributeName);
if(val==null)
return new Result(false, "No " + attributeName + " attribute for host " + targetVM.getCurrAvailableResources().hostname());
if(val.hasText()) {
if(val.getText().getValue().equals(value))
return new Result(true, "");
else
return new Result(false, "asking for " + value + ", have " + val.getText().getValue() + " on host " +
targetVM.getCurrAvailableResources().hostname());
}
return new Result(false, "Attribute has no value");
}
};
}
}
| 9,107 |
0 | Create_ds/Fenzo/fenzo-core/src/test/java/com/netflix | Create_ds/Fenzo/fenzo-core/src/test/java/com/netflix/fenzo/ScaleDownConstraintExecutorTest.java | package com.netflix.fenzo;
import org.junit.Before;
import org.junit.Test;
import org.mockito.invocation.InvocationOnMock;
import java.util.*;
import java.util.stream.Collectors;
import static com.netflix.fenzo.plugins.TestableVirtualMachineLease.leasesWithIds;
import static java.util.Arrays.asList;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.fail;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
public class ScaleDownConstraintExecutorTest {
private final ScaleDownOrderEvaluator orderEvaluator = mock(ScaleDownOrderEvaluator.class);
private final ScaleDownConstraintEvaluator<Void> evenFirstEvaluator = mock(ScaleDownConstraintEvaluator.class);
private final ScaleDownConstraintEvaluator<Void> oddFirstEvaluator = mock(ScaleDownConstraintEvaluator.class);
private ScaleDownConstraintExecutor executor;
@Before
public void setUp() throws Exception {
when(evenFirstEvaluator.getName()).thenReturn("evenFirstEvaluator");
when(oddFirstEvaluator.getName()).thenReturn("oddFirstEvaluator");
}
@Test
public void testScaleDownOrdering() throws Exception {
Map<ScaleDownConstraintEvaluator, Double> scoringEvaluators = new HashMap<>();
scoringEvaluators.put(evenFirstEvaluator, 10.0);
scoringEvaluators.put(oddFirstEvaluator, 2.0);
executor = new ScaleDownConstraintExecutor(orderEvaluator, scoringEvaluators);
List<VirtualMachineLease> candidates = leasesWithIds("l0", "l1", "l2", "l3", "l4");
when(orderEvaluator.evaluate(candidates)).thenReturn(
asList(asSet(candidates.get(0), candidates.get(2), candidates.get(3)), asSet(candidates.get(1), candidates.get(4)))
);
when(evenFirstEvaluator.evaluate(any(), any())).then(a -> {
int idx = leaseIndexOf(a);
return ScaleDownConstraintEvaluator.Result.of(idx == 0 ? 0 : (idx % 2 == 0 ? 1 : 0.5));
});
when(oddFirstEvaluator.evaluate(any(), any())).then(a -> {
int idx = leaseIndexOf(a);
return ScaleDownConstraintEvaluator.Result.of(idx == 0 ? 0 : (idx % 2 == 1 ? 1 : 0.5));
});
List<VirtualMachineLease> order = executor.evaluate(candidates);
List<String> ids = order.stream().map(VirtualMachineLease::getId).collect(Collectors.toList());
assertThat(ids, is(equalTo(asList("l2", "l3", "l4", "l1"))));
}
@Test
public void testWeightsValidation() throws Exception {
Map<ScaleDownConstraintEvaluator, Double> scoringEvaluators = new HashMap<>();
scoringEvaluators.put(evenFirstEvaluator, -5.0);
scoringEvaluators.put(oddFirstEvaluator, 0.0);
try {
new ScaleDownConstraintExecutor(orderEvaluator, scoringEvaluators);
fail("Expected to fail argument validation");
} catch (IllegalArgumentException e) {
assertThat(e.getMessage().contains("evenFirstEvaluator=-5.0"), is(true));
assertThat(e.getMessage().contains("oddFirstEvaluator=0.0"), is(true));
}
}
private static <T> Set<T> asSet(T... values) {
Set<T> result = new HashSet<>();
Collections.addAll(result, values);
return result;
}
private static int leaseIndexOf(InvocationOnMock invocation) {
String id = ((VirtualMachineLease) invocation.getArgument(0)).getId();
return Integer.parseInt("" + id.charAt(1));
}
} | 9,108 |
0 | Create_ds/Fenzo/fenzo-core/src/test/java/com/netflix | Create_ds/Fenzo/fenzo-core/src/test/java/com/netflix/fenzo/SingleOfferModelTests.java | /*
* Copyright 2015 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.fenzo;
import com.netflix.fenzo.functions.Action1;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import java.util.*;
public class SingleOfferModelTests {
private TaskScheduler taskScheduler;
@Before
public void setUp() throws Exception {
taskScheduler = new TaskScheduler.Builder()
.withLeaseOfferExpirySecs(1000000)
.withSingleOfferPerVM(true)
.withLeaseRejectAction(new Action1<VirtualMachineLease>() {
@Override
public void call(VirtualMachineLease virtualMachineLease) {
System.out.println("Rejecting offer on host " + virtualMachineLease.hostname());
}
})
.build();
}
@After
public void tearDown() throws Exception {
}
@Test
public void testSingleOfferMultipleIterations() throws Exception {
List<VirtualMachineLease> leases = LeaseProvider.getLeases(1, 4, 100, 1, 10);
List<TaskRequest> taskRequests = new ArrayList<>();
taskRequests.add(TaskRequestProvider.getTaskRequest(1, 10, 1));
Map<String,VMAssignmentResult> resultMap = taskScheduler.scheduleOnce(taskRequests, leases).getResultMap();
Assert.assertEquals(1, resultMap.size());
taskScheduler.getTaskAssigner().call(taskRequests.get(0), resultMap.keySet().iterator().next());
leases.clear();
taskRequests.clear();
taskRequests.add(TaskRequestProvider.getTaskRequest(1, 10, 1));
taskRequests.add(TaskRequestProvider.getTaskRequest(1, 10, 1));
taskRequests.add(TaskRequestProvider.getTaskRequest(1, 10, 1));
resultMap = taskScheduler.scheduleOnce(taskRequests, leases).getResultMap();
Assert.assertEquals(1, resultMap.size());
Assert.assertEquals(3, resultMap.entrySet().iterator().next().getValue().getTasksAssigned().size());
for(Map.Entry<String, VMAssignmentResult> entry: resultMap.entrySet()) {
for(TaskAssignmentResult r: entry.getValue().getTasksAssigned()) {
taskScheduler.getTaskAssigner().call(r.getRequest(), entry.getKey());
}
}
taskRequests.clear();
taskRequests.add(TaskRequestProvider.getTaskRequest(1, 10, 1));
resultMap = taskScheduler.scheduleOnce(taskRequests, leases).getResultMap();
Assert.assertEquals(0, resultMap.size());
}
@Test
public void testWithInitialJobsAlreadyOnHost() throws Exception {
List<VirtualMachineLease> leases = LeaseProvider.getLeases(1, 4, 100, 1, 10);
TaskRequest t = TaskRequestProvider.getTaskRequest(1, 10, 1);
// indicate that the host already has one task running on it.
taskScheduler.getTaskAssigner().call(t, leases.get(0).hostname());
// now send the one time resource offer to scheduler
List<TaskRequest> taskRequests = new ArrayList<>();
taskScheduler.scheduleOnce(taskRequests, leases);
leases.clear();
// now create 3 other tasks to fill rest of the host
taskRequests.add(TaskRequestProvider.getTaskRequest(1, 10, 1));
taskRequests.add(TaskRequestProvider.getTaskRequest(1, 10, 1));
taskRequests.add(TaskRequestProvider.getTaskRequest(1, 10, 1));
Map<String,VMAssignmentResult> resultMap = taskScheduler.scheduleOnce(taskRequests, leases).getResultMap();
Assert.assertEquals(1, resultMap.size());
Assert.assertEquals(3, resultMap.entrySet().iterator().next().getValue().getTasksAssigned().size());
for(Map.Entry<String, VMAssignmentResult> entry: resultMap.entrySet()) {
for(TaskAssignmentResult r: entry.getValue().getTasksAssigned()) {
taskScheduler.getTaskAssigner().call(r.getRequest(), entry.getKey());
}
}
taskRequests.clear();
taskRequests.add(TaskRequestProvider.getTaskRequest(1, 10, 1));
resultMap = taskScheduler.scheduleOnce(taskRequests, leases).getResultMap();
Assert.assertEquals(0, resultMap.size());
}
@Test
public void testMultipleOffers() throws Exception {
VirtualMachineLease host1 = LeaseProvider.getLeaseOffer("host1", 4, 4000, 1, 10);
final TaskRequest taskRequest = TaskRequestProvider.getTaskRequest(1, 1000, 1);
taskScheduler.scheduleOnce(Collections.<TaskRequest>emptyList(), Collections.singletonList(host1));
host1 = LeaseProvider.getLeaseOffer("host1", 4, 4000, 1, 10);
SchedulingResult result = taskScheduler.scheduleOnce(Collections.singletonList(taskRequest), Collections.singletonList(host1));
final Map<String, VMAssignmentResult> resultMap = result.getResultMap();
for(Map.Entry<String, VMAssignmentResult> e: resultMap.entrySet()) {
Assert.assertEquals(1, e.getValue().getLeasesUsed().size());
}
}
}
| 9,109 |
0 | Create_ds/Fenzo/fenzo-core/src/test/java/com/netflix | Create_ds/Fenzo/fenzo-core/src/test/java/com/netflix/fenzo/TaskRequestProvider.java | /*
* Copyright 2015 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.fenzo;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;
public class TaskRequestProvider {
private static final AtomicInteger id = new AtomicInteger();
public static TaskRequest getTaskRequest(final double cpus, final double memory, final int ports) {
return getTaskRequest("", cpus, memory, 0.0, ports, null, null);
}
public static TaskRequest getTaskRequest(final double cpus, final double memory, double network, final int ports) {
return getTaskRequest("", cpus, memory, network, ports, null, null);
}
public static TaskRequest getTaskRequest(final double cpus, final double memory, final int ports,
final List<? extends ConstraintEvaluator> hardConstraints,
final List<? extends VMTaskFitnessCalculator> softConstraints) {
return getTaskRequest("", cpus, memory, 0.0, ports, hardConstraints, softConstraints);
}
public static TaskRequest getTaskRequest(final String grpName, final double cpus, final double memory, double network, final int ports) {
return getTaskRequest(grpName, cpus, memory, network, ports, null, null);
}
public static TaskRequest getTaskRequest(final String grpName, final double cpus, final double memory, final double network, final int ports,
final List<? extends ConstraintEvaluator> hardConstraints,
final List<? extends VMTaskFitnessCalculator> softConstraints) {
return getTaskRequest(grpName, cpus, memory, 0, network, ports, hardConstraints, softConstraints);
}
public static TaskRequest getTaskRequest(final String grpName, final double cpus, final double memory, final double disk,
final double network, final int ports,
final List<? extends ConstraintEvaluator> hardConstraints,
final List<? extends VMTaskFitnessCalculator> softConstraints) {
return getTaskRequest(grpName, cpus, memory, disk, network, ports, hardConstraints, softConstraints,
Collections.<String, TaskRequest.NamedResourceSetRequest>emptyMap());
}
public static TaskRequest getTaskRequest(final String grpName, final double cpus, final double memory, final double disk,
final double network, final int ports,
final List<? extends ConstraintEvaluator> hardConstraints,
final List<? extends VMTaskFitnessCalculator> softConstraints,
final Map<String, TaskRequest.NamedResourceSetRequest> resourceSets
) {
return getTaskRequest(grpName, cpus, memory, disk, network, ports, hardConstraints, softConstraints, resourceSets, null);
}
public static TaskRequest getTaskRequest(final String grpName, final double cpus, final double memory, final double disk,
final double network, final int ports,
final List<? extends ConstraintEvaluator> hardConstraints,
final List<? extends VMTaskFitnessCalculator> softConstraints,
final Map<String, TaskRequest.NamedResourceSetRequest> resourceSets,
final Map<String, Double> scalarRequests
) {
final String taskId = ""+id.incrementAndGet();
final AtomicReference<TaskRequest.AssignedResources> arRef = new AtomicReference<>();
return new TaskRequest() {
@Override
public String getId() {
return taskId;
}
@Override
public String taskGroupName() {
return grpName;
}
@Override
public double getCPUs() {
return cpus;
}
@Override
public double getMemory() {
return memory;
}
@Override
public double getNetworkMbps() {
return network;
}
@Override
public double getDisk() {
return disk;
}
@Override
public int getPorts() {
return ports;
}
@Override
public Map<String, Double> getScalarRequests() {
return scalarRequests;
}
@Override
public List<? extends ConstraintEvaluator> getHardConstraints() {
return hardConstraints;
}
@Override
public List<? extends VMTaskFitnessCalculator> getSoftConstraints() {
return softConstraints;
}
@Override
public void setAssignedResources(AssignedResources assignedResources) {
arRef.set(assignedResources);
}
@Override
public AssignedResources getAssignedResources() {
return arRef.get();
}
@Override
public Map<String, NamedResourceSetRequest> getCustomNamedResources() {
return resourceSets;
}
};
}
}
| 9,110 |
0 | Create_ds/Fenzo/fenzo-core/src/test/java/com/netflix | Create_ds/Fenzo/fenzo-core/src/test/java/com/netflix/fenzo/ResAllocsTests.java | /*
* Copyright 2015 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.fenzo;
import com.netflix.fenzo.plugins.BinPackingFitnessCalculators;
import com.netflix.fenzo.sla.ResAllocs;
import org.apache.mesos.Protos;
import org.junit.Assert;
import org.junit.Test;
import com.netflix.fenzo.functions.Action1;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.atomic.AtomicBoolean;
public class ResAllocsTests {
private static final String grp1="App1";
private static final String grp2="App2";
static String hostAttrName = "MachineType";
final int minIdle=5;
final int maxIdle=10;
final long coolDownSecs=2;
String hostAttrVal1="4coreServers";
int cpus1=4;
int memory1=40000;
final AutoScaleRule rule1 = AutoScaleRuleProvider.createRule(hostAttrVal1, minIdle, maxIdle, coolDownSecs, cpus1/2, memory1/2);
private TaskScheduler getSchedulerNoResAllocs() {
return new TaskScheduler.Builder()
.withFitnessCalculator(BinPackingFitnessCalculators.cpuBinPacker)
.withLeaseOfferExpirySecs(3600)
.withLeaseRejectAction(new Action1<VirtualMachineLease>() {
@Override
public void call(VirtualMachineLease lease) {
Assert.fail("Unexpected to reject lease " + lease.hostname());
}
})
.build();
}
private TaskScheduler getScheduler() {
Map<String, ResAllocs> resAllocs = new HashMap<>();
resAllocs.put(grp1, ResAllocsProvider.create(grp1, 4, 4000, Double.MAX_VALUE, Double.MAX_VALUE));
resAllocs.put(grp2, ResAllocsProvider.create(grp2, 8, 8000, Double.MAX_VALUE, Double.MAX_VALUE));
return new TaskScheduler.Builder()
.withInitialResAllocs(resAllocs)
.withFitnessCalculator(BinPackingFitnessCalculators.cpuBinPacker)
.withLeaseOfferExpirySecs(3600)
.withLeaseRejectAction(new Action1<VirtualMachineLease>() {
@Override
public void call(VirtualMachineLease lease) {
Assert.fail("Unexpected to reject lease " + lease.hostname());
}
})
.build();
}
private TaskScheduler getAutoscalingScheduler(AutoScaleRule... rules) {
TaskScheduler.Builder builder = new TaskScheduler.Builder()
.withAutoScaleByAttributeName(hostAttrName);
Map<String, ResAllocs> resAllocs = new HashMap<>();
resAllocs.put(grp1, ResAllocsProvider.create(grp1, cpus1, memory1, Double.MAX_VALUE, Double.MAX_VALUE));
resAllocs.put(grp2, ResAllocsProvider.create(grp2, cpus1 * 2, memory1 * 2, Double.MAX_VALUE, Double.MAX_VALUE));
for(AutoScaleRule rule: rules)
builder.withAutoScaleRule(rule);
return builder
.withInitialResAllocs(resAllocs)
.withFitnessCalculator(BinPackingFitnessCalculators.cpuBinPacker)
.withLeaseOfferExpirySecs(3600)
.withLeaseRejectAction(new Action1<VirtualMachineLease>() {
@Override
public void call(VirtualMachineLease lease) {
Assert.fail("Unexpected to reject lease " + lease.hostname());
}
})
.build();
}
@Test
public void testNoResAllocsMeansUnlimited() {
final TaskScheduler scheduler = getSchedulerNoResAllocs();
final List<VirtualMachineLease> leases = LeaseProvider.getLeases(10, 4.0, 4000.0, 1024.0, 1, 100);
final List<TaskRequest> tasks = new ArrayList<>();
for(int i=0; i<leases.size()*4; i++)
tasks.add(TaskRequestProvider.getTaskRequest(1.0, 10.0, 1));
final SchedulingResult schedulingResult = scheduler.scheduleOnce(tasks, leases);
final Map<String, VMAssignmentResult> resultMap = schedulingResult.getResultMap();
int successes=0;
for(Map.Entry<String, VMAssignmentResult> entry : resultMap.entrySet()) {
for(TaskAssignmentResult r: entry.getValue().getTasksAssigned()) {
if(r.isSuccessful())
successes++;
}
}
Assert.assertEquals("#success assignments: ", tasks.size(), successes);
Assert.assertEquals("#failures: ", 0, schedulingResult.getFailures().size());
}
@Test
public void testSingleAppRsv() throws Exception {
final TaskScheduler scheduler = getScheduler();
final List<VirtualMachineLease> leases = LeaseProvider.getLeases(2, 4.0, 4000.0, 1024.0, 1, 100);
final List<TaskRequest> tasks = new ArrayList<>();
final int numCores = (int)scheduler.getResAllocs().get(grp1).getCores();
for(int i=0; i<numCores+1; i++)
tasks.add(TaskRequestProvider.getTaskRequest(grp1, 1.0, 1000.0, 100.0, 1));
final SchedulingResult schedulingResult = scheduler.scheduleOnce(tasks, leases);
final Map<String, VMAssignmentResult> resultMap = schedulingResult.getResultMap();
int successes=0;
for(Map.Entry<String, VMAssignmentResult> entry : resultMap.entrySet()) {
for(TaskAssignmentResult r: entry.getValue().getTasksAssigned()) {
if(r.isSuccessful())
successes++;
}
}
Assert.assertEquals("#success assignments: ", numCores, successes);
Assert.assertEquals("#failures: ", 1, schedulingResult.getFailures().size());
final VMResource resource = schedulingResult.getFailures().values().iterator().next().get(0).getFailures().get(0).getResource();
Assert.assertTrue("Unexpected failure type: " + resource, resource == VMResource.ResAllocs);
}
@Test
public void testTwoAppRsv() throws Exception {
final TaskScheduler scheduler = getScheduler();
final List<VirtualMachineLease> leases = LeaseProvider.getLeases(4, 4.0, 4000.0, 1024.0, 1, 100);
final List<TaskRequest> tasks = new ArrayList<>();
final int numCores = (int)scheduler.getResAllocs().get(grp1).getCores();
for(int i=0; i<numCores+1; i++) {
tasks.add(TaskRequestProvider.getTaskRequest(grp1, 1.0, 1000.0, 100.0, 1));
tasks.add(TaskRequestProvider.getTaskRequest(grp2, 1.0, 1000.0, 100.0, 1));
}
final SchedulingResult schedulingResult = scheduler.scheduleOnce(tasks, leases);
final Map<String, VMAssignmentResult> resultMap = schedulingResult.getResultMap();
int grp1Success=0;
int grp2Success=0;
for(Map.Entry<String, VMAssignmentResult> entry : resultMap.entrySet()) {
for(TaskAssignmentResult r: entry.getValue().getTasksAssigned()) {
if(r.isSuccessful())
switch (r.getRequest().taskGroupName()) {
case grp1:
grp1Success++;
break;
case grp2:
grp2Success++;
break;
}
}
}
Assert.assertEquals(grp1Success, numCores);
Assert.assertEquals(grp2Success, numCores+1);
Assert.assertEquals("Incorrect #failures: ", 1, schedulingResult.getFailures().size());
final VMResource resource = schedulingResult.getFailures().values().iterator().next().get(0).getFailures().get(0).getResource();
Assert.assertTrue("Unexpected failure type: " + resource, resource == VMResource.ResAllocs);
}
// Test that scale up isn't called when tasks from a group, grp1, are limited by its resAllocs. Then, ensure that
// tasks of a different group, grp2, do actually invoke scale up while grp1 tasks don't.
@Test
public void testScaleUpForRsv() throws Exception {
TaskScheduler scheduler = getAutoscalingScheduler(rule1);
final List<VirtualMachineLease> leases = new ArrayList<>();
List<VirtualMachineLease.Range> ports = new ArrayList<>();
ports.add(new VirtualMachineLease.Range(1, 10));
Map<String, Protos.Attribute> attributes = new HashMap<>();
Protos.Attribute attribute = Protos.Attribute.newBuilder().setName(hostAttrName)
.setType(Protos.Value.Type.TEXT)
.setText(Protos.Value.Text.newBuilder().setValue(hostAttrVal1)).build();
attributes.put(hostAttrName, attribute);
for(int l=0; l<minIdle+1; l++)
leases.add(LeaseProvider.getLeaseOffer("host"+l, cpus1, memory1, 1024.0, ports, attributes));
final List<TaskRequest> tasks = new ArrayList<>();
for(int t=0; t<cpus1*2; t++)
tasks.add(TaskRequestProvider.getTaskRequest(grp1, 1, 100, 10, 1));
final AtomicBoolean gotScaleUpRequest = new AtomicBoolean();
scheduler.setAutoscalerCallback(new Action1<AutoScaleAction>() {
@Override
public void call(AutoScaleAction action) {
if(action instanceof ScaleUpAction) {
int needed = ((ScaleUpAction)action).getScaleUpCount();
gotScaleUpRequest.set(true);
}
}
});
Set<String> assignedHosts = new HashSet<>();
long now = System.currentTimeMillis();
for(int i=0; i<coolDownSecs+2; i++) {
if(i>0) {
tasks.clear();
leases.clear();
}
final SchedulingResult schedulingResult = scheduler.scheduleOnce(tasks, leases);
if(i==0) {
Assert.assertEquals(1, schedulingResult.getResultMap().size());
int successes=0;
for(Map.Entry<String, VMAssignmentResult> entry: schedulingResult.getResultMap().entrySet()) {
for(TaskAssignmentResult r: entry.getValue().getTasksAssigned()) {
if(r.isSuccessful()) {
assignedHosts.add(entry.getKey());
successes++;
scheduler.getTaskAssigner().call(r.getRequest(), entry.getKey());
}
}
}
}
Thread.sleep(1000);
}
System.out.println("mSecs taken: " + (System.currentTimeMillis()-now));
Assert.assertEquals("Assigned hosts should have been 1, it is: " + assignedHosts, 1, assignedHosts.size());
Assert.assertFalse("Unexpected to get scale up request", gotScaleUpRequest.get());
for(int t=0; t<cpus1*2; t++)
tasks.add(TaskRequestProvider.getTaskRequest(grp2, 1, 100, 10, 1));
tasks.add(TaskRequestProvider.getTaskRequest(grp1, 1, 100, 10, 1));
for(int i=0; i<coolDownSecs+2 && !gotScaleUpRequest.get(); i++) {
final Map<String, VMAssignmentResult> resultMap = scheduler.scheduleOnce(tasks, leases).getResultMap();
if(i==0) {
int successes1=0;
int successes2=0;
assignedHosts.clear();
for(Map.Entry<String, VMAssignmentResult> entry: resultMap.entrySet()) {
for(TaskAssignmentResult r: entry.getValue().getTasksAssigned()) {
if(r.isSuccessful()) {
if(r.getRequest().taskGroupName().equals(grp2)) {
successes2++;
assignedHosts.add(entry.getKey());
}
else
successes1++;
}
}
}
Assert.assertEquals("Didn't expect grp1 task to be assigned", successes1, 0);
Assert.assertEquals(successes2, tasks.size()-1);
Assert.assertEquals(2, assignedHosts.size());
tasks.clear();
leases.clear();
}
Thread.sleep(1000);
}
Thread.sleep(coolDownSecs+1); // wait for scale up request to happen
Assert.assertTrue("Didn't get scale up request", gotScaleUpRequest.get());
}
@Test
public void testResAllocsModification() throws Exception {
final TaskScheduler scheduler = getScheduler();
final int numCores = (int)scheduler.getResAllocs().get(grp1).getCores();
final List<VirtualMachineLease> leases = LeaseProvider.getLeases(2, (double)numCores, numCores*1000.0, 1024.0, 1, 100);
final List<TaskRequest> tasks = new ArrayList<>();
for(int i=0; i<numCores; i++)
tasks.add(TaskRequestProvider.getTaskRequest(grp1, 1.0, 1000.0, 100.0, 1));
SchedulingResult schedulingResult = scheduler.scheduleOnce(tasks, leases);
Map<String, VMAssignmentResult> resultMap = schedulingResult.getResultMap();
int successes=0;
for(Map.Entry<String, VMAssignmentResult> entry : resultMap.entrySet()) {
for(TaskAssignmentResult r: entry.getValue().getTasksAssigned()) {
if(r.isSuccessful()) {
successes++;
scheduler.getTaskAssigner().call(r.getRequest(), entry.getKey());
}
}
}
Assert.assertEquals("#success assignments: ", numCores, successes);
Assert.assertEquals("Not expecting assignment failures: ", 0, schedulingResult.getFailures().size());
// now confirm that next task fails with resAllocs type failure
tasks.clear();
tasks.add(TaskRequestProvider.getTaskRequest(grp1, 1.0, 1000.0, 100.0, 1));
leases.clear();
schedulingResult = scheduler.scheduleOnce(tasks, leases);
Assert.assertEquals("#failures", 1, schedulingResult.getFailures().size());
final VMResource resource = schedulingResult.getFailures().values().iterator().next().get(0).getFailures().get(0).getResource();
Assert.assertTrue("Unexpected failure type: " + resource, resource == VMResource.ResAllocs);
// now increase resAllocs and confirm that the new task gets assigned
scheduler.addOrReplaceResAllocs(ResAllocsProvider.create(grp1, numCores + 1, (numCores + 1) * 1000.0, Double.MAX_VALUE, Double.MAX_VALUE));
schedulingResult = scheduler.scheduleOnce(tasks, leases);
resultMap = schedulingResult.getResultMap();
successes=0;
for(Map.Entry<String, VMAssignmentResult> entry : resultMap.entrySet()) {
for(TaskAssignmentResult r: entry.getValue().getTasksAssigned()) {
if(r.isSuccessful())
successes++;
}
}
Assert.assertEquals("Incorrect #success assignments: ", 1, successes);
Assert.assertEquals("Not expecting assignment failures: ", 0, schedulingResult.getFailures().size());
}
@Test
public void testAbsentResAllocs() throws Exception {
final TaskScheduler scheduler = getScheduler();
final int numCores = (int)scheduler.getResAllocs().get(grp1).getCores();
final List<VirtualMachineLease> leases = LeaseProvider.getLeases(2, (double)numCores, numCores*1000.0, 1024.0, 1, 100);
final List<TaskRequest> tasks = new ArrayList<>();
tasks.add(TaskRequestProvider.getTaskRequest("AbsentGrp", 1.0, 1000.0, 100.0, 1));
SchedulingResult schedulingResult = scheduler.scheduleOnce(tasks, leases);
Assert.assertEquals("#failures: ", 1, schedulingResult.getFailures().size());
final VMResource resource = schedulingResult.getFailures().values().iterator().next().get(0).getFailures().get(0).getResource();
Assert.assertTrue("Failure type: " + resource, resource == VMResource.ResAllocs);
}
@Test
public void testAddingNewResAllocs() throws Exception {
final String nwGrpName="AbsentGrp";
final TaskScheduler scheduler = getScheduler();
final int numCores = (int)scheduler.getResAllocs().get(grp1).getCores();
final List<VirtualMachineLease> leases = LeaseProvider.getLeases(2, (double)numCores, numCores*1000.0, 1024.0, 1, 100);
final List<TaskRequest> tasks = new ArrayList<>();
tasks.add(TaskRequestProvider.getTaskRequest(nwGrpName, 1.0, 1000.0, 100.0, 1));
SchedulingResult schedulingResult = scheduler.scheduleOnce(tasks, leases);
Assert.assertEquals("#failures: ", 1, schedulingResult.getFailures().size());
final VMResource resource = schedulingResult.getFailures().values().iterator().next().get(0).getFailures().get(0).getResource();
Assert.assertTrue("Failure type: " + resource, resource == VMResource.ResAllocs);
scheduler.addOrReplaceResAllocs(ResAllocsProvider.create(nwGrpName, 4, 4000, Double.MAX_VALUE, Double.MAX_VALUE));
leases.clear();
schedulingResult = scheduler.scheduleOnce(tasks, leases);
int successes=0;
for(Map.Entry<String, VMAssignmentResult> entry : schedulingResult.getResultMap().entrySet()) {
for(TaskAssignmentResult r: entry.getValue().getTasksAssigned()) {
if(r.isSuccessful())
successes++;
}
}
Assert.assertEquals("Incorrect #success assignments: ", 1, successes);
Assert.assertEquals("#failures: ", 0, schedulingResult.getFailures().size());
}
}
| 9,111 |
0 | Create_ds/Fenzo/fenzo-core/src/test/java/com/netflix | Create_ds/Fenzo/fenzo-core/src/test/java/com/netflix/fenzo/RandomTaskGenerator.java | /*
* Copyright 2015 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.fenzo;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
public class RandomTaskGenerator {
public static class TaskType {
private final double coreSize;
private final double ratioOfTasks;
private final long minRunDurationMillis;
private final long maxRunDurationMillis;
public TaskType(double coreSize, double ratioOfTasks, long minRunDurationMillis, long maxRunDurationMillis) {
this.coreSize = coreSize;
this.ratioOfTasks = ratioOfTasks;
this.minRunDurationMillis = minRunDurationMillis;
this.maxRunDurationMillis = maxRunDurationMillis;
}
public double getCoreSize() {
return coreSize;
}
public double getRatioOfTasks() {
return ratioOfTasks;
}
public long getMinRunDurationMillis() {
return minRunDurationMillis;
}
public long getMaxRunDurationMillis() {
return maxRunDurationMillis;
}
}
public static class GeneratedTask implements TaskRequest, Comparable<GeneratedTask> {
private final TaskRequest taskRequest;
private final long runUntilMillis;
private final long runtimeMillis;
private String hostname;
private AssignedResources assignedResources=null;
public GeneratedTask(final TaskRequest taskRequest, final long runtimeMillis, final long runUntilMillis) {
this.taskRequest = taskRequest;
this.runUntilMillis = runUntilMillis;
this.runtimeMillis = runtimeMillis;
}
public long getRunUntilMillis() {
return runUntilMillis;
}
public long getRuntimeMillis() {
return runtimeMillis;
}
@Override
public String getId() {
return taskRequest.getId();
}
@Override
public String taskGroupName() {
return "";
}
@Override
public double getCPUs() {
return taskRequest.getCPUs();
}
@Override
public double getMemory() {
return taskRequest.getMemory();
}
@Override
public double getNetworkMbps() {
return 0.0;
}
@Override
public double getDisk() {
return taskRequest.getDisk();
}
@Override
public int getPorts() {
return taskRequest.getPorts();
}
@Override
public Map<String, Double> getScalarRequests() {
return null;
}
@Override
public List<? extends ConstraintEvaluator> getHardConstraints() {
return taskRequest.getHardConstraints();
}
@Override
public List<? extends VMTaskFitnessCalculator> getSoftConstraints() {
return taskRequest.getSoftConstraints();
}
@Override
public void setAssignedResources(AssignedResources assignedResources) {
this.assignedResources = assignedResources;
}
@Override
public AssignedResources getAssignedResources() {
return assignedResources;
}
@Override
public Map<String, NamedResourceSetRequest> getCustomNamedResources() {
return Collections.emptyMap();
}
@Override
public int compareTo(GeneratedTask o) {
if(o==null)
return -1;
return Long.compare(runUntilMillis, o.runUntilMillis);
}
public String getHostname() {
return hostname;
}
public void setHostname(String hostname) {
this.hostname = hostname;
}
}
private final List<TaskType> taskTypes;
private final double memoryPerCore=1000.0;
private final int minTasksPerCoreSizePerBatch;
private final long interBatchIntervalMillis;
private double minRatio;
private final BlockingQueue<GeneratedTask> taskQueue;
RandomTaskGenerator(BlockingQueue<GeneratedTask> taskQueue, long interBatchIntervalMillis, int minTasksPerCoreSizePerBatch, List<TaskType> taskTypes) {
if(taskTypes==null || taskTypes.isEmpty())
throw new IllegalArgumentException();
this.taskQueue = taskQueue;
this.interBatchIntervalMillis = interBatchIntervalMillis;
this.minTasksPerCoreSizePerBatch = minTasksPerCoreSizePerBatch;
minRatio=Double.MAX_VALUE;
this.taskTypes = taskTypes;
for(TaskType j: taskTypes)
if(j.getRatioOfTasks()<minRatio)
minRatio = j.getRatioOfTasks();
}
void start() {
new ScheduledThreadPoolExecutor(1).scheduleWithFixedDelay(new Runnable() {
@Override
public void run() {
long now = System.currentTimeMillis();
int numTasksGenerated=0;
for(TaskType taskType: taskTypes) {
int numTasks = (int) (taskType.getRatioOfTasks()*minTasksPerCoreSizePerBatch/minRatio);
for(int t=0; t<numTasks; t++) {
long runtime = getRuntime(taskType.minRunDurationMillis, taskType.maxRunDurationMillis);
taskQueue.offer(new GeneratedTask(
TaskRequestProvider.getTaskRequest(taskType.coreSize, taskType.coreSize*memoryPerCore, 1),
runtime, now+runtime
));
numTasksGenerated++;
}
}
System.out.println(" " + numTasksGenerated + " tasks generated");
}
}, interBatchIntervalMillis, interBatchIntervalMillis, TimeUnit.MILLISECONDS);
}
List<GeneratedTask> getTasks() {
List<GeneratedTask> tasks = new ArrayList<>();
long now = System.currentTimeMillis();
for(TaskType taskType: taskTypes) {
int numTasks = (int) (taskType.getRatioOfTasks()*minTasksPerCoreSizePerBatch/minRatio);
for(int t=0; t<numTasks; t++) {
long runtime = getRuntime(taskType.minRunDurationMillis, taskType.maxRunDurationMillis);
tasks.add(new GeneratedTask(
TaskRequestProvider.getTaskRequest(taskType.coreSize, taskType.coreSize*memoryPerCore, 1),
runtime, now+runtime
));
}
}
return tasks;
}
private long getRuntime(long minRunDurationMillis, long maxRunDurationMillis) {
return minRunDurationMillis + (long)(Math.random() * (double)(maxRunDurationMillis-minRunDurationMillis));
}
}
| 9,112 |
0 | Create_ds/Fenzo/fenzo-core/src/test/java/com/netflix | Create_ds/Fenzo/fenzo-core/src/test/java/com/netflix/fenzo/ConstraintsTests.java | /*
* Copyright 2015 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.fenzo;
import com.netflix.fenzo.functions.Action1;
import com.netflix.fenzo.functions.Func1;
import com.netflix.fenzo.plugins.BalancedHostAttrConstraint;
import com.netflix.fenzo.plugins.BinPackingFitnessCalculators;
import com.netflix.fenzo.plugins.ExclusiveHostConstraint;
import com.netflix.fenzo.plugins.HostAttrValueConstraint;
import com.netflix.fenzo.plugins.UniqueHostAttrConstraint;
import org.junit.Assert;
import org.apache.mesos.Protos;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import java.util.*;
public class ConstraintsTests {
private final static String zoneAttrName="Zone";
private final int numZones=3;
Map<String, Protos.Attribute> attributesA = new HashMap<>();
Map<String, Protos.Attribute> attributesB = new HashMap<>();
Map<String, Protos.Attribute> attributesC = new HashMap<>();
@Before
public void setUp() throws Exception {
Protos.Attribute attributeA = Protos.Attribute.newBuilder().setName(zoneAttrName)
.setType(Protos.Value.Type.TEXT)
.setText(Protos.Value.Text.newBuilder().setValue("zoneA")).build();
attributesA.put(zoneAttrName, attributeA);
Protos.Attribute attributeB = Protos.Attribute.newBuilder().setName(zoneAttrName)
.setType(Protos.Value.Type.TEXT)
.setText(Protos.Value.Text.newBuilder().setValue("zoneB")).build();
attributesB.put(zoneAttrName, attributeB);
Protos.Attribute attributeC = Protos.Attribute.newBuilder().setName(zoneAttrName)
.setType(Protos.Value.Type.TEXT)
.setText(Protos.Value.Text.newBuilder().setValue("zoneC")).build();
attributesC.put(zoneAttrName, attributeC);
}
private TaskScheduler getTaskScheduler() {
return getTaskScheduler(true);
}
private TaskScheduler getTaskScheduler(boolean useBinPacking) {
TaskScheduler.Builder builder = new TaskScheduler.Builder()
.withLeaseOfferExpirySecs(1000000)
.withLeaseRejectAction(new Action1<VirtualMachineLease>() {
@Override
public void call(VirtualMachineLease virtualMachineLease) {
System.out.println("Rejecting offer on host " + virtualMachineLease.hostname());
Assert.fail();
}
})
.withFitnessGoodEnoughFunction(new Func1<Double, Boolean>() {
@Override
public Boolean call(Double aDouble) {
return aDouble > 1.0;
}
});
if(useBinPacking)
builder = builder
.withFitnessCalculator(BinPackingFitnessCalculators.cpuMemBinPacker);
return builder.build();
}
@After
public void tearDown() throws Exception {
}
// Test that hard constraint setup for one task per zone is honored by scheduling three tasks using three hosts.
// All three tasks and three hosts are scheduled in one iteration. Each host could hold all three tasks if the constraint
// isn't evaluated, which fail this test.
@Test
public void testHardConstraint1() throws Exception {
Map<String, TaskRequest> taskMap = new HashMap<>();
final Map<String, Set<String>> taskToCoTasksMap = new HashMap<>();
ConstraintEvaluator zoneConstraint = new UniqueHostAttrConstraint(new Func1<String, Set<String>>() {
@Override
public Set<String> call(String s) {
return taskToCoTasksMap.get(s);
}
}, zoneAttrName);
List<TaskRequest> tasks = getThreeTasks(taskMap, taskToCoTasksMap, zoneConstraint, null);
List<VirtualMachineLease> leases = getThreeVMs();
TaskScheduler taskScheduler = getTaskScheduler();
SchedulingResult schedulingResult = taskScheduler.scheduleOnce(tasks, leases);
Assert.assertEquals(numZones, schedulingResult.getResultMap().size());
}
// Test that a hard constraint setup for one task per zone is honored by scheduling one task per iteration. First,
// test that without using the constraint three tasks land on the same host. Then, test with three other tasks with
// the constraint and ensure they land on different hosts, one per zone.
@Test
public void testHardConstraint2() throws Exception {
// first, make sure that when not using zone constraint, 3 tasks land on the same zone
Set<String> zonesUsed = getZonesUsed(new HashMap<String, TaskRequest>(), new HashMap<String, Set<String>>(), null, null);
Assert.assertEquals("Without zone constraints expecting 3 tasks to land on same zone", 1, zonesUsed.size());
// now test with zone constraint and make sure they go on to one zone each
Map<String, TaskRequest> taskMap = new HashMap<>();
final Map<String, Set<String>> taskToCoTasksMap = new HashMap<>();
ConstraintEvaluator zoneConstraint = new UniqueHostAttrConstraint(new Func1<String, Set<String>>() {
@Override
public Set<String> call(String s) {
return taskToCoTasksMap.get(s);
}
}, zoneAttrName);
zonesUsed = getZonesUsed(taskMap, taskToCoTasksMap, zoneConstraint, null);
Assert.assertEquals("With zone constraint, expecting 3 tasks to land on 3 zones", 3, zonesUsed.size());
}
// Test that using soft constraints also lands three tasks on three different hosts like in hard constraints case.
@Test
public void testSoftConstraint1() throws Exception {
Map<String, TaskRequest> taskMap = new HashMap<>();
final Map<String, Set<String>> taskToCoTasksMap = new HashMap<>();
UniqueHostAttrConstraint zoneConstraint = new UniqueHostAttrConstraint(new Func1<String, Set<String>>() {
@Override
public Set<String> call(String s) {
return taskToCoTasksMap.get(s);
}
}, zoneAttrName);
Set<String> zonesUsed = getZonesUsed(taskMap, taskToCoTasksMap, null, AsSoftConstraint.get(zoneConstraint));
Assert.assertEquals(3, zonesUsed.size());
}
// test that when using a soft constraint, tasks get assigned even if constraint were to fail. We submit three tasks
// with a soft constraint of wanting to land on different zones. But, provide only two hosts. All three tasks should
// get assigned on the two hosts, not just one host.
@Test
public void testSoftConstraint2() throws Exception {
Map<String, TaskRequest> taskMap = new HashMap<>();
final Map<String, Set<String>> taskToCoTasksMap = new HashMap<>();
UniqueHostAttrConstraint zoneConstraint = new UniqueHostAttrConstraint(new Func1<String, Set<String>>() {
@Override
public Set<String> call(String s) {
return taskToCoTasksMap.get(s);
}
}, zoneAttrName);
List<TaskRequest> threeTasks = getThreeTasks(taskMap, taskToCoTasksMap, null, AsSoftConstraint.get(zoneConstraint));
List<VirtualMachineLease> twoVMs = getThreeVMs().subList(0, 2);
TaskScheduler taskScheduler = getTaskScheduler();
Map<String, VMAssignmentResult> resultMap = taskScheduler.scheduleOnce(threeTasks, twoVMs).getResultMap();
Assert.assertNotNull(resultMap);
Assert.assertEquals(twoVMs.size(), resultMap.size());
int tasksAssigned=0;
Set<String> zonesUsed = new HashSet<>();
for(VMAssignmentResult r: resultMap.values()) {
Assert.assertEquals(1, r.getLeasesUsed().size());
VirtualMachineLease lease = r.getLeasesUsed().get(0);
zonesUsed.add(lease.getAttributeMap().get(zoneAttrName).getText().getValue());
tasksAssigned += r.getTasksAssigned().size();
}
Assert.assertEquals(twoVMs.size(), zonesUsed.size());
Assert.assertEquals(3, tasksAssigned);
}
@Test
public void testBalancedHostAttrSoftConstraint() throws Exception {
Map<String, TaskRequest> taskMap = new HashMap<>();
final Map<String, Set<String>> taskToCoTasksMap = new HashMap<>();
BalancedHostAttrConstraint constraint = new BalancedHostAttrConstraint(new Func1<String, Set<String>>() {
@Override
public Set<String> call(String s) {
return taskToCoTasksMap.get(s);
}
}, zoneAttrName, 3);
List<TaskRequest> sixTasks = getThreeTasks(taskMap, taskToCoTasksMap, null, constraint.asSoftConstraint());
sixTasks.addAll(getThreeTasks(taskMap, taskToCoTasksMap, null, constraint.asSoftConstraint()));
final List<VirtualMachineLease> threeVMs = getThreeVMs();
final TaskScheduler taskScheduler = getTaskScheduler();
final Map<String, VMAssignmentResult> resultMap = taskScheduler.scheduleOnce(sixTasks, threeVMs).getResultMap();
Assert.assertNotNull(resultMap);
Assert.assertEquals(3, resultMap.size());
for(VMAssignmentResult r: resultMap.values()) {
Assert.assertEquals(2, r.getTasksAssigned().size());
}
}
@Test
public void testBalancedHostAttrHardConstraint() throws Exception {
Map<String, TaskRequest> taskMap = new HashMap<>();
final Map<String, Set<String>> taskToCoTasksMap = new HashMap<>();
BalancedHostAttrConstraint constraint = new BalancedHostAttrConstraint(new Func1<String, Set<String>>() {
@Override
public Set<String> call(String s) {
return taskToCoTasksMap.get(s);
}
}, zoneAttrName, 3);
List<TaskRequest> sixTasks = getThreeTasks(taskMap, taskToCoTasksMap, constraint, null);
sixTasks.addAll(getThreeTasks(taskMap, taskToCoTasksMap, constraint, null));
final List<VirtualMachineLease> threeVMs = getThreeVMs();
final TaskScheduler taskScheduler = getTaskScheduler();
final Map<String, VMAssignmentResult> resultMap = taskScheduler.scheduleOnce(sixTasks, threeVMs).getResultMap();
Assert.assertNotNull(resultMap);
Assert.assertEquals(3, resultMap.size());
for(VMAssignmentResult r: resultMap.values()) {
Assert.assertEquals(2, r.getTasksAssigned().size());
}
}
// test that tasks that specify unique hosts land on separate hosts
@Test
public void testUniqueHostConstraint() throws Exception {
final Map<String, Set<String>> taskToCoTasksMap = new HashMap<>();
UniqueHostAttrConstraint uniqueHostConstraint = new UniqueHostAttrConstraint(new Func1<String, Set<String>>() {
@Override
public Set<String> call(String s) {
return taskToCoTasksMap.get(s);
}
});
List<TaskRequest> tasks = new ArrayList<>();
// First, create 5 tasks without unique host constraint
for(int i=0; i<5; i++)
tasks.add(TaskRequestProvider.getTaskRequest(1, 1000, 1));
TaskScheduler taskScheduler = getTaskScheduler();
List<VirtualMachineLease> leases = LeaseProvider.getLeases(5, 8, 8000, 1, 10);
Map<String, VMAssignmentResult> resultMap = taskScheduler.scheduleOnce(tasks, leases).getResultMap();
leases.clear();
Assert.assertNotNull(resultMap);
Assert.assertEquals("Tasks without unique host constraints should've landed on one host", 1, resultMap.size());
int numAssigned=0;
for(VMAssignmentResult r: resultMap.values()) {
numAssigned += r.getTasksAssigned().size();
double usedCpus=0.0;
double usedMemory=0.0;
List<Integer> usedPorts = new ArrayList<>();
for(TaskAssignmentResult a: r.getTasksAssigned()) {
taskScheduler.getTaskAssigner().call(a.getRequest(), r.getHostname());
usedCpus += a.getRequest().getCPUs();
usedMemory += a.getRequest().getMemory();
usedPorts.addAll(a.getAssignedPorts());
}
leases.add(LeaseProvider.getConsumedLease(r.getLeasesUsed().get(0), usedCpus, usedMemory, usedPorts));
}
Assert.assertEquals("Tasks without unique host constraints should've gotten assigned", tasks.size(), numAssigned);
// now test with tasks with unique host constraint
tasks.clear();
for(int i=0; i<5; i++)
tasks.add(TaskRequestProvider.getTaskRequest(1, 1000, 1, Arrays.asList(uniqueHostConstraint), null));
for(TaskRequest r: tasks) {
taskToCoTasksMap.put(r.getId(), new HashSet<String>());
for(TaskRequest rr: tasks)
if(!rr.getId().equals(r.getId()))
taskToCoTasksMap.get(r.getId()).add(rr.getId());
}
resultMap = taskScheduler.scheduleOnce(tasks, leases).getResultMap();
Assert.assertNotNull(resultMap);
Assert.assertEquals(tasks.size(), resultMap.size());
}
// tests that a task with exclusive host constraint gets assigned a host that has no other tasks on it
@Test
public void testExclusiveHostConstraint() throws Exception {
List<TaskRequest> tasks = new ArrayList<>();
tasks.add(TaskRequestProvider.getTaskRequest(1, 1000, 1));
List<VirtualMachineLease> leases = LeaseProvider.getLeases(2, 8, 8000, 1, 10);
TaskScheduler taskScheduler = getTaskScheduler();
Map<String, VMAssignmentResult> resultMap = taskScheduler.scheduleOnce(tasks, leases).getResultMap();
Assert.assertNotNull(resultMap);
Assert.assertEquals(1, resultMap.size());
VMAssignmentResult vmAssignmentResult = resultMap.values().iterator().next();
String usedHostname = vmAssignmentResult.getHostname();
Assert.assertEquals(1, vmAssignmentResult.getTasksAssigned().size());
TaskAssignmentResult taskAssigned = vmAssignmentResult.getTasksAssigned().iterator().next();
leases.clear();
leases.add(LeaseProvider.getConsumedLease(vmAssignmentResult.getLeasesUsed().get(0),
taskAssigned.getRequest().getCPUs(), taskAssigned.getRequest().getMemory(),
taskAssigned.getAssignedPorts()));
// now submit two tasks, one of them with exclusive host constraint. The one with the constraint should land
// on a host that is not the usedHostname, and the other task should land on usedHostname
tasks.clear();
TaskRequest noCtask = TaskRequestProvider.getTaskRequest(1, 1000, 1);
tasks.add(noCtask);
TaskRequest yesCTask = TaskRequestProvider.getTaskRequest(1, 1000, 1, Arrays.asList(new ExclusiveHostConstraint()), null);
tasks.add(yesCTask);
resultMap = taskScheduler.scheduleOnce(tasks, leases).getResultMap();
Assert.assertEquals(2, resultMap.size());
for(VMAssignmentResult result: resultMap.values()) {
Assert.assertEquals(1, result.getTasksAssigned().size());
TaskAssignmentResult tResult = result.getTasksAssigned().iterator().next();
if(tResult.getRequest().getId().equals(noCtask.getId()))
Assert.assertEquals("Task with no constraint should've landed on the already used host", usedHostname, result.getHostname());
else
Assert.assertFalse(usedHostname.equals(result.getHostname()));
}
}
// Test that a host that already has a task with an exclusive host constraint isn't picked for a new task
@Test
public void testExclusiveHostOnExistingTask() throws Exception {
List<TaskRequest> tasks = new ArrayList<>();
tasks.add(TaskRequestProvider.getTaskRequest(1, 1000, 1, Arrays.asList(new ExclusiveHostConstraint()), null));
List<VirtualMachineLease> leases = new ArrayList<>();
leases.add(LeaseProvider.getLeaseOffer("hostA", 8, 8000, 1, 10));
TaskScheduler taskScheduler = getTaskScheduler();
Map<String, VMAssignmentResult> resultMap = taskScheduler.scheduleOnce(tasks, leases).getResultMap();
Assert.assertNotNull(resultMap);
Assert.assertEquals(1, resultMap.size());
taskScheduler.getTaskAssigner().call(tasks.get(0), "hostA");
tasks.clear();
leases.clear();
leases.add(LeaseProvider.getConsumedLease(resultMap.values().iterator().next()));
tasks.add(TaskRequestProvider.getTaskRequest(1, 1000, 1));
resultMap = taskScheduler.scheduleOnce(tasks, leases).getResultMap();
Assert.assertNotNull(resultMap);
Assert.assertEquals("New task shouldn't have been assigned a host with a task that has exclusiveHost constraint", 0, resultMap.size());
leases.clear();
leases.add(LeaseProvider.getLeaseOffer("hostB", 8, 8000, 1, 10));
resultMap = taskScheduler.scheduleOnce(tasks, leases).getResultMap();
Assert.assertNotNull(resultMap);
Assert.assertEquals(1, resultMap.size());
Assert.assertEquals("hostB", resultMap.values().iterator().next().getHostname());
}
// Tests that a task gets assigned a host that has the zone attribute that the task asked for
@Test
public void testHostAttrValueConstraint() throws Exception {
List<VirtualMachineLease> threeVMs = getThreeVMs();
final String[] zones = new String[threeVMs.size()];
int i=0;
for(VirtualMachineLease l: threeVMs)
zones[i++] = l.getAttributeMap().get(zoneAttrName).getText().getValue();
// first submit two tasks and ensure they land on same machine, should be the case since we use bin packing
List<TaskRequest> tasks = new ArrayList<>();
tasks.add(TaskRequestProvider.getTaskRequest(1, 1000, 1));
tasks.add(TaskRequestProvider.getTaskRequest(1, 1000, 1));
TaskScheduler taskScheduler = getTaskScheduler();
Map<String, VMAssignmentResult> resultMap = taskScheduler.scheduleOnce(tasks, threeVMs).getResultMap();
Assert.assertNotNull(resultMap);
Assert.assertEquals(1, resultMap.size());
VMAssignmentResult onlyResult = resultMap.values().iterator().next();
List<VirtualMachineLease> remainingLeases = Arrays.asList(LeaseProvider.getConsumedLease(onlyResult));
String usedZone = onlyResult.getLeasesUsed().iterator().next().getAttributeMap().get(zoneAttrName).getText().getValue();
final int useZoneIndex = usedZone.equals(zones[0])? 1 : 0; // pick a zone other than used
HostAttrValueConstraint c = new HostAttrValueConstraint(zoneAttrName, new Func1<String, String>() {
@Override
public String call(String s) {
return zones[useZoneIndex];
}
});
tasks.clear();
tasks.add(TaskRequestProvider.getTaskRequest(1, 1000, 1));
// now add task with host attr value constraint
TaskRequest tForPickedZone = TaskRequestProvider.getTaskRequest(1, 1000, 1, Arrays.asList(c), null);
tasks.add(tForPickedZone);
resultMap = taskScheduler.scheduleOnce(tasks, remainingLeases).getResultMap();
Assert.assertNotNull(resultMap);
Assert.assertTrue("Couldn't confirm test, all tasks landed on same machine", resultMap.size() > 1);
boolean found=false;
for(VMAssignmentResult result: resultMap.values()) {
for(TaskAssignmentResult assigned: result.getTasksAssigned()) {
if(assigned.getRequest().getId().equals(tForPickedZone.getId())) {
Assert.assertEquals(zones[useZoneIndex],
result.getLeasesUsed().iterator().next().getAttributeMap().get(zoneAttrName).getText().getValue());
found = true;
}
}
}
Assert.assertTrue(found);
}
@Test
public void testHostnameValueConstraint() throws Exception {
final List<VirtualMachineLease> threeVMs = getThreeVMs();
List<TaskRequest> tasks = new ArrayList<>();
tasks.add(TaskRequestProvider.getTaskRequest(1, 1000, 1));
HostAttrValueConstraint c1 = new HostAttrValueConstraint(null, new Func1<String, String>() {
@Override
public String call(String s) {
return threeVMs.get(0).hostname();
}
});
HostAttrValueConstraint c2 = new HostAttrValueConstraint(null, new Func1<String, String>() {
@Override
public String call(String s) {
return threeVMs.get(1).hostname();
}
});
TaskRequest t1 = TaskRequestProvider.getTaskRequest(1, 1000, 1, Arrays.asList(c1), null);
TaskRequest t2 = TaskRequestProvider.getTaskRequest(1, 1000, 1, Arrays.asList(c2), null);
tasks.add(t1);
tasks.add(t2);
Map<String, VMAssignmentResult> resultMap = getTaskScheduler().scheduleOnce(tasks, threeVMs.subList(0,2)).getResultMap();
Assert.assertNotNull(resultMap);
Assert.assertEquals(2, resultMap.size());
for(VMAssignmentResult result: resultMap.values()) {
for(TaskAssignmentResult r: result.getTasksAssigned()) {
if(r.getRequest().getId().equals(t1.getId()))
Assert.assertEquals(threeVMs.get(0).hostname(), result.getHostname());
else if(r.getRequest().getId().equals(t2.getId()))
Assert.assertEquals(threeVMs.get(1).hostname(), result.getHostname());
}
}
}
private Set<String> getZonesUsed(Map<String, TaskRequest> taskMap, Map<String, Set<String>> taskToCoTasksMap,
ConstraintEvaluator hardConstraint, VMTaskFitnessCalculator softConstraint) {
List<TaskRequest> tasks1 = getThreeTasks(taskMap, taskToCoTasksMap, hardConstraint, softConstraint);
List<VirtualMachineLease> leases1 = getThreeVMs();
TaskScheduler taskScheduler1 = getTaskScheduler();
Set<String> zonesUsed1 = new HashSet<>();
for(int i=0; i<tasks1.size(); i++) {
Map<String, VMAssignmentResult> resultMap = taskScheduler1.scheduleOnce(tasks1.subList(i, i + 1), leases1).getResultMap();
leases1.clear();
Assert.assertNotNull(resultMap);
Assert.assertEquals(1, resultMap.size());
VMAssignmentResult result = resultMap.values().iterator().next();
VirtualMachineLease lease = result.getLeasesUsed().get(0);
zonesUsed1.add(lease.getAttributeMap().get(zoneAttrName).getText().getValue());
Assert.assertEquals(1, result.getTasksAssigned().size());
TaskAssignmentResult aResult = result.getTasksAssigned().iterator().next();
TaskRequest request = aResult.getRequest();
taskScheduler1.getTaskAssigner().call(request, lease.hostname());
VirtualMachineLease unUsedLease = LeaseProvider.getConsumedLease(lease, request.getCPUs(), request.getMemory(), aResult.getAssignedPorts());
leases1.add(unUsedLease);
}
return zonesUsed1;
}
private List<VirtualMachineLease> getThreeVMs() {
List<VirtualMachineLease> leases = new ArrayList<>();
List<VirtualMachineLease.Range> ports = new ArrayList<>();
ports.add(new VirtualMachineLease.Range(1, 10));
leases.add(LeaseProvider.getLeaseOffer("hostA", 4, 4000, ports, attributesA));
leases.add(LeaseProvider.getLeaseOffer("hostB", 4, 4000, ports, attributesB));
leases.add(LeaseProvider.getLeaseOffer("hostC", 4, 4000, ports, attributesC));
return leases;
}
private List<TaskRequest> getThreeTasks(Map<String, TaskRequest> taskMap, Map<String, Set<String>> taskToCoTasksMap,
ConstraintEvaluator hardConstraint, VMTaskFitnessCalculator softConstraint) {
List<TaskRequest> tasks = new ArrayList<>(3);
List<ConstraintEvaluator> constraintEvaluators = new ArrayList<>(1);
if(hardConstraint!=null)
constraintEvaluators.add(hardConstraint);
List<VMTaskFitnessCalculator> softConstraints = new ArrayList<>();
if(softConstraint!=null)
softConstraints.add(softConstraint);
for(int i=0; i<numZones; i++) {
TaskRequest t = TaskRequestProvider.getTaskRequest(1, 1000, 1, constraintEvaluators, softConstraints);
taskMap.put(t.getId(), t);
tasks.add(t);
}
for(TaskRequest t: taskMap.values()) {
Set<String> coTasks = new HashSet<>();
taskToCoTasksMap.put(t.getId(), coTasks);
for(TaskRequest i: taskMap.values())
coTasks.add(i.getId());
}
return tasks;
}
@Test
public void testExceptionInConstraints() throws Exception {
final List<VirtualMachineLease> threeVMs = getThreeVMs();
List<TaskRequest> tasks = new ArrayList<>();
tasks.add(TaskRequestProvider.getTaskRequest(1, 1000, 1));
HostAttrValueConstraint c1 = new HostAttrValueConstraint(null, new Func1<String, String>() {
@Override
public String call(String s) {
throw new NullPointerException("Test exception");
}
});
tasks.add(TaskRequestProvider.getTaskRequest(1, 100, 1));
tasks.add(TaskRequestProvider.getTaskRequest(1, 1000, 1, Collections.singletonList(c1), null));
tasks.add(TaskRequestProvider.getTaskRequest(1, 100, 1));
try {
final SchedulingResult result = getTaskScheduler().scheduleOnce(tasks, threeVMs);
// expect to see 1 result for the first task before encountering exception with the 2nd task
Assert.assertEquals(0, result.getResultMap().size());
Assert.assertEquals(1, result.getExceptions().size());
}
catch (IllegalStateException e) {
Assert.fail("Unexpected exception: " + e.getMessage());
}
}
}
| 9,113 |
0 | Create_ds/Fenzo/fenzo-core/src/test/java/com/netflix | Create_ds/Fenzo/fenzo-core/src/test/java/com/netflix/fenzo/LeaseProvider.java | /*
* Copyright 2015 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.fenzo;
import org.apache.mesos.Protos;
import java.util.*;
public class LeaseProvider {
public static VirtualMachineLease getLeaseOffer(final String hostname, final double cpus,
final double memory, final List<VirtualMachineLease.Range> portRanges) {
return getLeaseOffer(hostname, cpus, memory, 0.0, portRanges, null);
}
public static VirtualMachineLease getLeaseOffer(final String hostname, final double cpus, final double memory,
final double network, final List<VirtualMachineLease.Range> portRanges) {
return getLeaseOffer(hostname, cpus, memory, network, portRanges, null);
}
public static VirtualMachineLease getLeaseOffer(final String hostname, final double cpus, final double memory,
final List<VirtualMachineLease.Range> portRanges,
final Map<String, Protos.Attribute> attributesMap) {
return getLeaseOffer(hostname, cpus, memory, 0.0, portRanges, attributesMap);
}
public static VirtualMachineLease getLeaseOffer(final String hostname, final double cpus, final double memory, final double disk,
final double network, final List<VirtualMachineLease.Range> portRanges,
final Map<String, Protos.Attribute> attributesMap) {
return getLeaseOffer(hostname, cpus, memory, disk, network, portRanges, attributesMap, null);
}
public static VirtualMachineLease getLeaseOffer(final String hostname, final double cpus, final double memory, final double disk,
final double network, final List<VirtualMachineLease.Range> portRanges,
final Map<String, Protos.Attribute> attributesMap, Map<String, Double> scalarResources) {
final long offeredTime = System.currentTimeMillis();
final String id = UUID.randomUUID().toString();
final String vmId = UUID.randomUUID().toString();
final Map<String, Double> scalars = scalarResources==null? Collections.<String, Double>emptyMap() : scalarResources;
return new VirtualMachineLease() {
@Override
public String getId() {
return id;
}
@Override
public long getOfferedTime() {
return offeredTime;
}
@Override
public String hostname() {
return hostname;
}
@Override
public String getVMID() {
return vmId;
}
@Override
public double cpuCores() {
return cpus;
}
@Override
public double memoryMB() {
return memory;
}
public double networkMbps() {
return network;
}
@Override
public double diskMB() {
return disk;
}
@Override
public List<Range> portRanges() {
return portRanges;
}
@Override
public Protos.Offer getOffer() {
return Protos.Offer.getDefaultInstance()
.toBuilder()
.setId(Protos.OfferID.getDefaultInstance().toBuilder().setValue(id).build())
.setHostname(hostname)
.setSlaveId(Protos.SlaveID.getDefaultInstance().toBuilder().setValue(vmId).build())
.setFrameworkId(Protos.FrameworkID.getDefaultInstance().toBuilder().setValue("Testing").build())
.build();
}
@Override
public Map<String, Protos.Attribute> getAttributeMap() {
return attributesMap==null? null : attributesMap;
}
@Override
public Double getScalarValue(String name) {
return scalars.get(name);
}
@Override
public Map<String, Double> getScalarValues() {
return scalars;
}
};
}
public static VirtualMachineLease getLeaseOffer(final String hostname, final double cpus, final double memory,
final double network, final List<VirtualMachineLease.Range> portRanges,
final Map<String, Protos.Attribute> attributesMap) {
return getLeaseOffer(hostname, cpus, memory, 500000, network, portRanges, attributesMap);
}
public static VirtualMachineLease getLeaseOffer(final String hostname, final double cpus,
final double memory, final int portBegin, final int portEnd) {
List<VirtualMachineLease.Range> ranges = new ArrayList<>(1);
ranges.add(new VirtualMachineLease.Range(portBegin, portEnd));
return getLeaseOffer(hostname, cpus, memory, ranges);
}
public static List<VirtualMachineLease> getLeases(int numHosts, double cpus, double memory,
int portBeg, int portEnd) {
return getLeases(numHosts, cpus, memory, 0.0, portBeg, portEnd);
}
public static List<VirtualMachineLease> getLeases(int numHosts, double cpus, double memory, double network,
int portBeg, int portEnd) {
return getLeases(0, numHosts, cpus, memory, network, portBeg, portEnd);
}
public static List<VirtualMachineLease> getLeases(int hostSuffixBegin, int numHosts, double cpus, double memory,
int portBeg, int portEnd) {
return getLeases(hostSuffixBegin, numHosts, cpus, memory, 0.0, portBeg, portEnd);
}
public static List<VirtualMachineLease> getLeases(int hostSuffixBegin, int numHosts, double cpus, double memory,
double network, int portBeg, int portEnd) {
VirtualMachineLease.Range range = new VirtualMachineLease.Range(portBeg, portEnd);
List<VirtualMachineLease.Range> ranges = new ArrayList<>(1);
ranges.add(range);
return getLeases(hostSuffixBegin, numHosts, cpus, memory, network, ranges);
}
public static List<VirtualMachineLease> getLeases(int numHosts, double cpus, double memory,
List<VirtualMachineLease.Range> ports) {
return getLeases(0, numHosts, cpus, memory, ports);
}
public static List<VirtualMachineLease> getLeases(int hostSuffixBegin, int numHosts, double cpus, double memory,
List<VirtualMachineLease.Range> ports) {
return getLeases(hostSuffixBegin, numHosts, cpus, memory, 0.0, ports);
}
public static List<VirtualMachineLease> getLeases(int hostSuffixBegin, int numHosts, double cpus, double memory,
double network, List<VirtualMachineLease.Range> ports) {
List<VirtualMachineLease> leases = new ArrayList<>(numHosts);
for(int i=hostSuffixBegin; i<(hostSuffixBegin+numHosts); i++)
leases.add(getLeaseOffer("host"+i, cpus, memory, network, ports));
return leases;
}
private static List<VirtualMachineLease.Range> getRangesAfterConsuming(List<VirtualMachineLease.Range> orig, int consumePort) {
List<VirtualMachineLease.Range> result = new ArrayList<>();
for(int i=0; i<orig.size(); i++) {
VirtualMachineLease.Range range = orig.get(i);
if(consumePort<range.getBeg() || consumePort>range.getEnd()) {
result.add(range);
continue;
}
if(range.getBeg() != range.getEnd()) {
if(consumePort>range.getBeg()) {
VirtualMachineLease.Range split = new VirtualMachineLease.Range(range.getBeg(), consumePort-1);
result.add(split);
}
if(consumePort<range.getEnd())
result.add(new VirtualMachineLease.Range(consumePort+1, range.getEnd()));
}
for(int j=i+1; j<orig.size(); j++)
result.add(orig.get(j));
return result;
}
throw new IllegalArgumentException("Unexpected to not find " + consumePort + " within the ranges provided");
}
public static VirtualMachineLease getConsumedLease(VMAssignmentResult result) {
double cpus=0.0;
double memory=0.0;
double network = 0.0;
List<Integer> ports = new ArrayList<>();
for(TaskAssignmentResult r: result.getTasksAssigned()) {
cpus += r.getRequest().getCPUs();
memory += r.getRequest().getMemory();
network += r.getRequest().getNetworkMbps();
ports.addAll(r.getAssignedPorts());
}
double totalCpus=0.0;
double totalMem=0.0;
double totalNetwork=0.0;
List<VirtualMachineLease.Range> totPortRanges = new ArrayList<>();
String hostname="";
Map<String, Protos.Attribute> attributes = null;
for(VirtualMachineLease l: result.getLeasesUsed()) {
hostname = l.hostname();
attributes = l.getAttributeMap();
totalCpus += l.cpuCores();
totalMem += l.memoryMB();
totalNetwork += l.networkMbps();
totPortRanges.addAll(l.portRanges());
}
for(Integer port: ports)
totPortRanges = getRangesAfterConsuming(totPortRanges, port);
return getLeaseOffer(hostname, totalCpus-cpus, totalMem-memory, totalNetwork-network, totPortRanges, attributes);
}
public static VirtualMachineLease getConsumedLease(VirtualMachineLease orig, double consumedCpu, double consumedMemory, List<Integer> consumedPorts) {
final double cpu = orig.cpuCores() - consumedCpu;
final double memory = orig.memoryMB() - consumedMemory;
List<VirtualMachineLease.Range> ranges = orig.portRanges();
for(Integer port: consumedPorts) {
ranges = getRangesAfterConsuming(ranges, port);
}
return getLeaseOffer(orig.hostname(), cpu, memory, 0.0, ranges, orig.getAttributeMap());
}
}
| 9,114 |
0 | Create_ds/Fenzo/fenzo-core/src/test/java/com/netflix | Create_ds/Fenzo/fenzo-core/src/test/java/com/netflix/fenzo/BinPackingSchedulerTests.java | /*
* Copyright 2015 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.fenzo;
import com.netflix.fenzo.plugins.BinPackingFitnessCalculators;
import org.junit.Assert;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.netflix.fenzo.functions.Action1;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
public class BinPackingSchedulerTests {
private static final Logger logger = LoggerFactory.getLogger(BinPackingSchedulerTests.class);
@Before
public void setUp() throws Exception {
}
@After
public void tearDown() throws Exception {
}
private TaskScheduler getScheduler(VMTaskFitnessCalculator fitnessCalculator) {
return new TaskScheduler.Builder()
.withFitnessCalculator(fitnessCalculator)
.withLeaseOfferExpirySecs(1000000)
.withLeaseRejectAction(virtualMachineLease -> logger.info("Rejecting lease on " + virtualMachineLease.hostname()))
.build();
}
@Test
public void testCPUBinPacking1() {
double totalCores=4;
double usedCores=1;
double totalMemory=100;
double usedMemory=10;
TaskScheduler scheduler = getScheduler(BinPackingFitnessCalculators.cpuBinPacker);
List<VirtualMachineLease> leases = LeaseProvider.getLeases(2, totalCores, totalMemory, 1, 10);
List<TaskRequest> taskRequests = new ArrayList<>();
taskRequests.add(TaskRequestProvider.getTaskRequest(usedCores, usedMemory, 1));
Map<String,VMAssignmentResult> resultMap = scheduler.scheduleOnce(taskRequests, leases).getResultMap();
Assert.assertEquals(1, resultMap.size());
String usedHostname = resultMap.keySet().iterator().next();
leases.clear();
leases.add(LeaseProvider.getLeaseOffer(usedHostname, totalCores-usedCores, totalMemory-usedMemory, 1, 10));
taskRequests.clear();
taskRequests.add(TaskRequestProvider.getTaskRequest(usedCores, usedMemory, 1));
resultMap = scheduler.scheduleOnce(taskRequests, leases).getResultMap();
Assert.assertEquals(1, resultMap.size());
Assert.assertEquals(usedHostname, resultMap.keySet().iterator().next());
}
@Test
public void testCPUBinPacking2() {
double totalCores=4;
double usedCores=1;
double totalMemory=100;
double usedMemory=10;
TaskRequest task1 = TaskRequestProvider.getTaskRequest(usedCores, usedMemory, 1);
TaskRequest task2 = TaskRequestProvider.getTaskRequest(usedCores*2, usedMemory, 1);
TaskScheduler scheduler = getScheduler(BinPackingFitnessCalculators.cpuBinPacker);
List<VirtualMachineLease> leases = LeaseProvider.getLeases(2, totalCores, totalMemory, 1, 10);
List<TaskRequest> taskRequests = new ArrayList<>();
taskRequests.add(task1);
// First schedule just task1 with both leases, one of the leases should get used
Map<String,VMAssignmentResult> resultMap = scheduler.scheduleOnce(taskRequests, leases).getResultMap();
Assert.assertEquals(1, resultMap.size());
String usedHostname1 = resultMap.keySet().iterator().next();
scheduler.getTaskAssigner().call(task1, usedHostname1);
taskRequests.clear();
taskRequests.add(task2);
leases.clear();
// Now submit task2 without any new leases. The other lease should get used
resultMap = scheduler.scheduleOnce(taskRequests, leases).getResultMap();
Assert.assertEquals(1, resultMap.size());
String usedHostname2 = resultMap.keySet().iterator().next();
Assert.assertTrue(!usedHostname1.equals(usedHostname2));
scheduler.getTaskAssigner().call(task2, usedHostname2);
// Now add back both leases with remaining resources and submit task 3. Should go to the 2nd host's lease since
// more of its CPUs are already in use
leases.add(LeaseProvider.getLeaseOffer(usedHostname2, totalCores-task2.getCPUs(), totalMemory-task2.getMemory(), 2, 10));
leases.add(LeaseProvider.getLeaseOffer(usedHostname1, totalCores-task1.getCPUs(), totalMemory-task1.getMemory(), 2, 10));
taskRequests.clear();
taskRequests.add(TaskRequestProvider.getTaskRequest(usedCores, usedMemory, 1));
resultMap = scheduler.scheduleOnce(taskRequests, leases).getResultMap();
Assert.assertEquals(1, resultMap.size());
Assert.assertTrue("CPU Bin packing failed", usedHostname2.equals(resultMap.keySet().iterator().next()));
}
@Test
public void testCPUBinPackingWithSeveralHosts() {
testBinPackingWithSeveralHosts("CPU");
}
@Test
public void testMemoryBinPackingWithSeveralHosts() {
testBinPackingWithSeveralHosts("Memory");
}
@Test
public void testNetworkBinPackingWithSeveralHosts() {
testBinPackingWithSeveralHosts("Network");
}
private void testBinPackingWithSeveralHosts(String resource) {
TaskScheduler scheduler=null;
switch (resource) {
case "CPU":
scheduler = getScheduler(BinPackingFitnessCalculators.cpuBinPacker);
break;
case "Memory":
scheduler = getScheduler(BinPackingFitnessCalculators.memoryBinPacker);
break;
case "Network":
scheduler = getScheduler(BinPackingFitnessCalculators.networkBinPacker);
break;
default:
Assert.fail("Unknown resource type " + resource);
}
double cpuCores1=4;
double cpuCores2=8;
double memory1=400;
double memory2=800;
double network1=400;
double network2 = 800;
int N = 10; // #instances
// First create N 8-core machines and then N 4-core machines
List<VirtualMachineLease> leases = LeaseProvider.getLeases(N, cpuCores2, memory2, network2, 1, 100);
leases.addAll(LeaseProvider.getLeases(N, N, cpuCores1, memory1, network1, 1, 100));
// Create as many tasks as to fill all of the 4-core machines, and then one more
List<TaskRequest> taskRequests = new ArrayList<>();
for(int i=0; i<N*cpuCores1+1; i++)
taskRequests.add(TaskRequestProvider.getTaskRequest(1, memory1/cpuCores1, network1/cpuCores1, 1));
Map<String,VMAssignmentResult> resultMap = scheduler.scheduleOnce(taskRequests, leases).getResultMap();
Assert.assertEquals(N+1, resultMap.size());
int hosts1=0;
int hosts2=0;
for(VMAssignmentResult result: resultMap.values()) {
List<VirtualMachineLease> leasesUsed = result.getLeasesUsed();
Assert.assertEquals(1, leasesUsed.size());
if(leasesUsed.get(0).cpuCores() == cpuCores1)
hosts1++;
else
hosts2++;
}
Assert.assertEquals(N, hosts1);
Assert.assertEquals(1, hosts2);
}
/**
* Test memory bin packing when servers have memory inversely proportional to CPUs
* @throws Exception
*/
@Test
public void testMemoryBinPacking2() throws Exception {
double cpus1=4;
double memory1=800;
double cpus2=8;
double memory2=400;
int N=10;
// First create N servers of cpus1/memory1 and then N of cpus2/memory2
List<VirtualMachineLease> leases = LeaseProvider.getLeases(N, cpus1, memory1, 1, 100);
leases.addAll(LeaseProvider.getLeases(N, N, cpus2, memory2, 1, 100));
// create as many tasks as to fill all of the memory2 hosts, and then one more
List<TaskRequest> taskRequests = new ArrayList<>();
double memToAsk=100;
for(int i=0; i<(N*memory2/memToAsk)+1; i++)
taskRequests.add(TaskRequestProvider.getTaskRequest(1, memToAsk, 1));
TaskScheduler scheduler = getScheduler(BinPackingFitnessCalculators.memoryBinPacker);
SchedulingResult schedulingResult = scheduler.scheduleOnce(taskRequests, leases);
Assert.assertEquals(N+1, schedulingResult.getResultMap().size());
int hosts1=0;
int hosts2=0;
for(VMAssignmentResult result: schedulingResult.getResultMap().values()) {
List<VirtualMachineLease> leasesUsed = result.getLeasesUsed();
Assert.assertEquals(1, leasesUsed.size());
if(leasesUsed.get(0).cpuCores() == cpus1)
hosts1++;
else
hosts2++;
}
Assert.assertEquals(N, hosts2);
Assert.assertEquals(1, hosts1);
}
// ToDo need a test to confirm BinPackingFitnessCalculators.getCpuAndMemoryBinPacker()
}
| 9,115 |
0 | Create_ds/Fenzo/fenzo-core/src/test/java/com/netflix | Create_ds/Fenzo/fenzo-core/src/test/java/com/netflix/fenzo/BasicSchedulerTests.java | /*
* Copyright 2015 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.fenzo;
import com.netflix.fenzo.functions.Action1;
import com.netflix.fenzo.plugins.BinPackingFitnessCalculators;
import org.junit.Assert;
import org.apache.mesos.Protos;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import java.util.*;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;
public class BasicSchedulerTests {
private TaskScheduler taskScheduler;
@Before
public void setUp() throws Exception {
taskScheduler = new TaskScheduler.Builder()
.withLeaseOfferExpirySecs(1000000)
.withLeaseRejectAction(new Action1<VirtualMachineLease>() {
@Override
public void call(VirtualMachineLease virtualMachineLease) {
System.out.println("Rejecting offer on host " + virtualMachineLease.hostname());
}
})
.build();
}
@After
public void tearDown() throws Exception {
}
// verify that we're using all resources on one lease
@Test
public void testScheduler1() throws Exception {
List<VirtualMachineLease> leases = LeaseProvider.getLeases(1, 4, 100, 1, 10);
String host1 = leases.get(0).hostname();
List<TaskRequest> taskRequests = new ArrayList<>();
taskRequests.add(TaskRequestProvider.getTaskRequest(1, 10, 1));
taskRequests.add(TaskRequestProvider.getTaskRequest(2, 10, 1));
taskRequests.add(TaskRequestProvider.getTaskRequest(1, 10, 1));
Map<String,VMAssignmentResult> resultMap = taskScheduler.scheduleOnce(taskRequests, leases).getResultMap();
Assert.assertEquals(1, resultMap.entrySet().size());
Assert.assertEquals(host1, resultMap.keySet().iterator().next());
Assert.assertEquals(host1, resultMap.values().iterator().next().getHostname());
Assert.assertEquals(1, resultMap.values().iterator().next().getLeasesUsed().size());
Assert.assertEquals(taskRequests.size(), resultMap.values().iterator().next().getTasksAssigned().size());
}
@Test
public void testInsufficientCPUs() throws Exception {
List<VirtualMachineLease> leases = LeaseProvider.getLeases(1, 4, 100, 1, 10);
List<TaskRequest> taskRequests = new ArrayList<>();
taskRequests.add(TaskRequestProvider.getTaskRequest(5, 10, 1));
Map<String,VMAssignmentResult> resultMap = taskScheduler.scheduleOnce(taskRequests, leases).getResultMap();
Assert.assertEquals(0, resultMap.entrySet().size());
}
@Test
public void testInsufficientCPUs2() throws Exception {
List<VirtualMachineLease> leases = LeaseProvider.getLeases(1, 4, 100, 1, 10);
List<TaskRequest> taskRequests = new ArrayList<>();
taskRequests.add(TaskRequestProvider.getTaskRequest(2, 10, 1));
taskRequests.add(TaskRequestProvider.getTaskRequest(2, 10, 1));
taskRequests.add(TaskRequestProvider.getTaskRequest(1, 10, 1));
Map<String,VMAssignmentResult> resultMap = taskScheduler.scheduleOnce(taskRequests, leases).getResultMap();
Assert.assertEquals(1, resultMap.entrySet().size());
Assert.assertEquals(2, resultMap.values().iterator().next().getTasksAssigned().size());
}
@Test
public void testInsufficientMemory() throws Exception {
List<VirtualMachineLease> leases = LeaseProvider.getLeases(1, 4, 100, 1, 10);
List<TaskRequest> taskRequests = new ArrayList<>();
taskRequests.add(TaskRequestProvider.getTaskRequest(1, 95, 1));
taskRequests.add(TaskRequestProvider.getTaskRequest(2, 95, 1));
taskRequests.add(TaskRequestProvider.getTaskRequest(1, 95, 1));
Map<String,VMAssignmentResult> resultMap = taskScheduler.scheduleOnce(taskRequests, leases).getResultMap();
Assert.assertEquals(1, resultMap.entrySet().size());
Assert.assertEquals(1, resultMap.values().iterator().next().getTasksAssigned().size());
}
@Test
public void testInsufficientNetworkMbps() throws Exception {
List<VirtualMachineLease> leases = new ArrayList<>();
leases.add(LeaseProvider.getLeaseOffer("server1", 4, 100, 1024, null));
List<TaskRequest> taskRequests = new ArrayList<>();
taskRequests.add(TaskRequestProvider.getTaskRequest(1, 5, 512, 0));
taskRequests.add(TaskRequestProvider.getTaskRequest(1, 5, 512, 0));
taskRequests.add(TaskRequestProvider.getTaskRequest(1, 5, 512, 0));
Map<String,VMAssignmentResult> resultMap = taskScheduler.scheduleOnce(taskRequests, leases).getResultMap();
Assert.assertEquals(1, resultMap.entrySet().size());
Assert.assertEquals(2, resultMap.values().iterator().next().getTasksAssigned().size());
}
@Test
public void testInsufficientPorts() throws Exception {
List<VirtualMachineLease> leases = LeaseProvider.getLeases(1, 4, 100, 1, 10);
List<TaskRequest> taskRequests = new ArrayList<>();
taskRequests.add(TaskRequestProvider.getTaskRequest(1, 10, 6));
taskRequests.add(TaskRequestProvider.getTaskRequest(2, 10, 6));
taskRequests.add(TaskRequestProvider.getTaskRequest(1, 10, 6));
Map<String,VMAssignmentResult> resultMap = taskScheduler.scheduleOnce(taskRequests, leases).getResultMap();
Assert.assertEquals(1, resultMap.entrySet().size());
Assert.assertEquals(1, resultMap.values().iterator().next().getTasksAssigned().size());
}
private boolean atLeastOneInRange(List<Integer> check, int beg, int end) {
for(Integer c: check)
if(c>=beg && c<=end)
return true;
return false;
}
@Test
public void testPortsUsedAcrossRanges() throws Exception {
VirtualMachineLease.Range range1 = new VirtualMachineLease.Range(1, 4);
VirtualMachineLease.Range range2 = new VirtualMachineLease.Range(5, 10);
List<VirtualMachineLease.Range> ranges = new ArrayList<>(2);
ranges.add(range1);
ranges.add(range2);
List<VirtualMachineLease> leases = LeaseProvider.getLeases(1, 4, 100, ranges);
List<TaskRequest> taskRequests = new ArrayList<>();
taskRequests.add(TaskRequestProvider.getTaskRequest(1, 10, 6));
Map<String,VMAssignmentResult> resultMap = taskScheduler.scheduleOnce(taskRequests, leases).getResultMap();
Assert.assertEquals(1, resultMap.entrySet().size());
Assert.assertEquals(1, resultMap.values().iterator().next().getTasksAssigned().size());
TaskAssignmentResult result = resultMap.values().iterator().next().getTasksAssigned().iterator().next();
List<Integer> ports = result.getAssignedPorts();
Assert.assertEquals(6, ports.size());
Assert.assertEquals(true, atLeastOneInRange(ports, range1.getBeg(), range1.getEnd()));
Assert.assertEquals(true, atLeastOneInRange(ports, range2.getBeg(), range2.getEnd()));
}
@Test
public void testRepeatedPortsUsage() throws Exception {
// verify that all ports of a machine can get used with repeated allocation, i.e., there is no ports leak
double memPerJob=2;
int portBeg=1;
int portEnd=10;
int numPortsPerJob=2;
int numJobs = (portEnd-portBeg+1)/numPortsPerJob;
List<VirtualMachineLease> leases = new ArrayList<>();
List<TaskRequest> taskRequests = new ArrayList<>();
VirtualMachineLease host1 = LeaseProvider.getLeaseOffer("host1", numJobs, numJobs*memPerJob, portBeg, portEnd);
leases.add(host1);
for(int j=0; j<numJobs; j++) {
taskRequests.clear();
taskRequests.add(TaskRequestProvider.getTaskRequest(1, memPerJob, numPortsPerJob));
// assume ports are contiguous
Map<String,VMAssignmentResult> resultMap = taskScheduler.scheduleOnce(taskRequests, leases).getResultMap();
Assert.assertEquals(1, resultMap.entrySet().size());
Assert.assertEquals(1, resultMap.values().iterator().next().getTasksAssigned().size());
leases.clear();
host1 = LeaseProvider.getConsumedLease(host1, 1, memPerJob, resultMap.values().iterator().next().getTasksAssigned().iterator().next().getAssignedPorts());
leases.add(host1);
}
}
@Test
public void testMultiportJob() throws Exception {
final VirtualMachineLease host1 = LeaseProvider.getLeaseOffer("host1", 4, 4000, 1, 100);
List<VirtualMachineLease> leases = new ArrayList<>();
leases.add(host1);
List<TaskRequest> taskRequests = new ArrayList<>();
taskRequests.add(TaskRequestProvider.getTaskRequest(1, 2, 3));
taskRequests.add(TaskRequestProvider.getTaskRequest(1, 2, 3));
Map<String, VMAssignmentResult> resultMap = taskScheduler.scheduleOnce(taskRequests, leases).getResultMap();
Assert.assertEquals(1, resultMap.size());
final Set<TaskAssignmentResult> tasksAssigned = resultMap.values().iterator().next().getTasksAssigned();
for(TaskAssignmentResult r: tasksAssigned) {
final List<Integer> assignedPorts = r.getAssignedPorts();
for(int p: assignedPorts)
System.out.println(p);
}
}
@Test
public void testMultiportJob2() throws Exception {
final VirtualMachineLease host1 = LeaseProvider.getLeaseOffer("host1", 4, 4000, 1, 100);
List<VirtualMachineLease> leases = new ArrayList<>();
leases.add(host1);
List<TaskRequest> taskRequests = new ArrayList<>();
taskRequests.add(TaskRequestProvider.getTaskRequest(1, 2, 3));
Map<String, VMAssignmentResult> resultMap = taskScheduler.scheduleOnce(taskRequests, leases).getResultMap();
Assert.assertEquals(1, resultMap.size());
Set<TaskAssignmentResult> tasksAssigned = resultMap.values().iterator().next().getTasksAssigned();
for(TaskAssignmentResult r: tasksAssigned) {
final List<Integer> assignedPorts = r.getAssignedPorts();
for(int p: assignedPorts)
System.out.println(p);
}
taskRequests.clear();
taskRequests.add(TaskRequestProvider.getTaskRequest(1, 2, 3));
leases.clear();
leases.add(LeaseProvider.getConsumedLease(resultMap.values().iterator().next()));
resultMap = taskScheduler.scheduleOnce(taskRequests, leases).getResultMap();
Assert.assertEquals(1, resultMap.size());
tasksAssigned = resultMap.values().iterator().next().getTasksAssigned();
for(TaskAssignmentResult r: tasksAssigned) {
final List<Integer> assignedPorts = r.getAssignedPorts();
for(int p: assignedPorts)
System.out.println(p);
}
}
@Test
public void testPortAllocation() throws Exception {
VirtualMachineLease host1 = LeaseProvider.getLeaseOffer("host1", 4, 10, 1, 5);
List<VirtualMachineLease> leases = new ArrayList<>();
leases.add(host1);
List<TaskRequest> taskRequests = new ArrayList<>();
taskRequests.add(TaskRequestProvider.getTaskRequest(1, 2, 1));
Map<String,VMAssignmentResult> resultMap = taskScheduler.scheduleOnce(taskRequests, leases).getResultMap();
Assert.assertEquals(1, resultMap.entrySet().size());
VMAssignmentResult result = resultMap.values().iterator().next();
int port = result.getTasksAssigned().iterator().next().getAssignedPorts().iterator().next();
taskRequests.clear();
taskRequests.add(TaskRequestProvider.getTaskRequest(1, 2, 1));
VirtualMachineLease host11 = LeaseProvider.getLeaseOffer("host1", 3, 8, port + 1, 5);
leases.clear();
leases.add(host11);
resultMap = taskScheduler.scheduleOnce(taskRequests, leases).getResultMap();
Assert.assertEquals(1, resultMap.entrySet().size());
result = resultMap.values().iterator().next();
int port2 = result.getTasksAssigned().iterator().next().getAssignedPorts().iterator().next();
Assert.assertTrue(port != port2);
}
@Test
public void testMultipleOffersOnOneHost() throws Exception {
List<VirtualMachineLease> leases = new ArrayList<>();
String host1 = "host1";
int cores1=2;
int cores2=2;
VirtualMachineLease lease1 = LeaseProvider.getLeaseOffer(host1, cores1, 20, 1, 5);
VirtualMachineLease lease2 = LeaseProvider.getLeaseOffer(host1, cores2, 60, 6, 10);
leases.add(lease1);
leases.add(lease2);
List<TaskRequest> taskRequests = new ArrayList<>();
for(int t=0; t<cores1+cores2; t++) {
taskRequests.add(TaskRequestProvider.getTaskRequest(1, 40, 1));
}
Map<String,VMAssignmentResult> resultMap = taskScheduler.scheduleOnce(taskRequests, leases).getResultMap();
Assert.assertEquals(1, resultMap.entrySet().size());
Assert.assertEquals(2, resultMap.values().iterator().next().getTasksAssigned().size());
}
@Test
public void testMultipleHostsAndTasks() throws Exception {
int numHosts=2;
int numCoresPerHost=4;
List<VirtualMachineLease> leases = LeaseProvider.getLeases(numHosts, numCoresPerHost, 100, 1, 10);
List<TaskRequest> taskRequests = new ArrayList<>();
for(int t=0; t<numCoresPerHost*numHosts; t++) {
taskRequests.add(TaskRequestProvider.getTaskRequest(1, 1, 1));
}
Map<String,VMAssignmentResult> resultMap = taskScheduler.scheduleOnce(taskRequests, leases).getResultMap();
Assert.assertEquals(numHosts, resultMap.entrySet().size());
Iterator<VMAssignmentResult> iterator = resultMap.values().iterator();
while (iterator.hasNext()) {
Assert.assertEquals(numCoresPerHost, iterator.next().getTasksAssigned().size());
}
}
@Test
public void testOfferReuse() throws Exception {
List<VirtualMachineLease> leases = LeaseProvider.getLeases(1, 4, 100, 1, 10);
List<TaskRequest> taskRequests = new ArrayList<>();
taskRequests.add(TaskRequestProvider.getTaskRequest(5, 10, 1));
Map<String,VMAssignmentResult> resultMap = taskScheduler.scheduleOnce(taskRequests, leases).getResultMap();
Assert.assertEquals(0, resultMap.entrySet().size());
leases.clear(); // don't pass the same lease again
taskRequests.clear();
taskRequests.add(TaskRequestProvider.getTaskRequest(4, 10, 1));
resultMap = taskScheduler.scheduleOnce(taskRequests, leases).getResultMap();
Assert.assertEquals(1, resultMap.entrySet().size());
}
@Test
public void testOfferExpiry() throws Exception {
final AtomicBoolean leaseRejected = new AtomicBoolean(false);
final long leaseExpirySecs=1;
TaskScheduler myTaskScheduler = new TaskScheduler.Builder()
.withLeaseOfferExpirySecs(leaseExpirySecs)
.withLeaseRejectAction(new Action1<VirtualMachineLease>() {
@Override
public void call(VirtualMachineLease virtualMachineLease) {
leaseRejected.set(true);
}
})
.build();
List<VirtualMachineLease> leases = LeaseProvider.getLeases(1, 4, 100, 1, 10);
List<TaskRequest> taskRequests = new ArrayList<>();
taskRequests.add(TaskRequestProvider.getTaskRequest(5, 10, 1));
Map<String,VMAssignmentResult> resultMap = myTaskScheduler.scheduleOnce(taskRequests, leases).getResultMap();
Assert.assertEquals(0, resultMap.entrySet().size());
leases.clear(); // don't pass in the same lease again.
// wait for lease to expire
try{Thread.sleep(leaseExpirySecs*1000+200);}catch (InterruptedException ie){}
taskRequests.clear();
taskRequests.add(TaskRequestProvider.getTaskRequest(5, 10, 1)); // make sure task doesn't get assigned
resultMap = myTaskScheduler.scheduleOnce(taskRequests, leases).getResultMap();
Assert.assertEquals(true, leaseRejected.get());
}
@Test
public void testOfferExpiryOnSeveralVms() throws Exception {
final AtomicInteger rejectCount = new AtomicInteger();
final long leaseExpirySecs=1;
TaskScheduler scheduler = new TaskScheduler.Builder()
.withLeaseOfferExpirySecs(leaseExpirySecs)
.withLeaseRejectAction(new Action1<VirtualMachineLease>() {
@Override
public void call(VirtualMachineLease lease) {
rejectCount.incrementAndGet();
}
})
.build();
List<VirtualMachineLease> leases = LeaseProvider.getLeases(10, 4, 4000, 1, 10);
List<TaskRequest> taskRequests = new ArrayList<>();
taskRequests.add(TaskRequestProvider.getTaskRequest(5, 10, 1));
Map<String,VMAssignmentResult> resultMap = scheduler.scheduleOnce(taskRequests, leases).getResultMap();
Assert.assertEquals(0, resultMap.entrySet().size());
leases.clear(); // don't pass in the same lease again.
// wait for lease to expire
try{Thread.sleep(leaseExpirySecs*1000+250);}catch (InterruptedException ie){}
taskRequests.clear();
taskRequests.add(TaskRequestProvider.getTaskRequest(5, 10, 1)); // make sure task doesn't get assigned
resultMap = scheduler.scheduleOnce(taskRequests, leases).getResultMap();
Assert.assertEquals(0, resultMap.size());
Assert.assertTrue(rejectCount.get() > 0);
}
/**
* Test that the TaskTrackerState object passed into fitness calculator has the right jobs in it.
* @throws Exception
*/
@Test
public void testTaskTrackerState1() throws Exception {
final AtomicReference<Set<String>> runningTasks = new AtomicReference<Set<String>>(new HashSet<String>());
final AtomicReference<Set<String>> assignedTasks = new AtomicReference<Set<String>>(new HashSet<String>());
TaskScheduler scheduler = new TaskScheduler.Builder()
.withLeaseOfferExpirySecs(10000)
.withLeaseRejectAction(new Action1<VirtualMachineLease>() {
@Override
public void call(VirtualMachineLease l) {
Assert.fail("Unexpected lease reject called on " + l.getOffer().getHostname());
}
})
.withFitnessCalculator(new VMTaskFitnessCalculator() {
@Override
public String getName() {
return "DummyFitnessCalculator";
}
@Override
public double calculateFitness(TaskRequest taskRequest, VirtualMachineCurrentState targetVM, TaskTrackerState taskTrackerState) {
Assert.assertEquals(assignedTasks.get().size(), taskTrackerState.getAllCurrentlyAssignedTasks().size());
Assert.assertEquals(runningTasks.get().size(), taskTrackerState.getAllRunningTasks().size());
assignedTasks.get().add(taskRequest.getId());
return 1.0; // always fits
}
})
.build();
List<VirtualMachineLease> leases = LeaseProvider.getLeases(1, 4, 100, 1, 10);
List<TaskRequest> taskRequests = new ArrayList<>();
taskRequests.add(TaskRequestProvider.getTaskRequest(1, 10, 1));
SchedulingResult schedulingResult = scheduler.scheduleOnce(taskRequests, leases);
Assert.assertEquals(1, schedulingResult.getResultMap().size());
Assert.assertEquals(1, assignedTasks.get().size());
VMAssignmentResult res = schedulingResult.getResultMap().values().iterator().next();
TaskRequest request = res.getTasksAssigned().iterator().next().getRequest();
scheduler.getTaskAssigner().call(request, res.getHostname());
runningTasks.get().add(request.getId());
assignedTasks.get().remove(request.getId());
leases.clear();
leases.addAll(LeaseProvider.getLeases(1, 3, 90, 2, 10));
taskRequests.clear();
taskRequests.add(TaskRequestProvider.getTaskRequest(1, 10, 1));
taskRequests.add(TaskRequestProvider.getTaskRequest(1, 10, 1));
schedulingResult = scheduler.scheduleOnce(taskRequests, leases);
Assert.assertTrue(schedulingResult.getResultMap()!=null);
Assert.assertEquals(1, schedulingResult.getResultMap().size());
Assert.assertEquals(2, assignedTasks.get().size());
}
/**
* Test that when all leases are expired, a task isn't scheduled on an offer that is released during the iteration.
* @throws Exception
*/
@Test
public void testVmCleanupAtBeginning() throws Exception {
final List<VirtualMachineLease> leases = new ArrayList<>();
leases.add(LeaseProvider.getLeaseOffer("host1", 4, 4000, 1, 10));
TaskScheduler scheduler = new TaskScheduler.Builder()
.withLeaseOfferExpirySecs(10000)
.withLeaseRejectAction(new Action1<VirtualMachineLease>() {
@Override
public void call(VirtualMachineLease virtualMachineLease) {
}
})
.withFitnessCalculator(BinPackingFitnessCalculators.cpuMemBinPacker)
.build();
List<TaskRequest> requests = new ArrayList<>();
Assert.assertEquals(1, leases.size());
scheduler.scheduleOnce(requests, leases).getResultMap();
leases.clear();
scheduler.expireAllLeases();
requests.add(TaskRequestProvider.getTaskRequest(1, 100, 1));
Map<String, VMAssignmentResult> resultMap = scheduler.scheduleOnce(requests, leases).getResultMap();
Assert.assertEquals(0, resultMap.size());
leases.add(LeaseProvider.getLeaseOffer("host1", 4, 4000, 1, 10));
resultMap = scheduler.scheduleOnce(requests, leases).getResultMap();
Assert.assertEquals(1, resultMap.size());
final VMAssignmentResult result = resultMap.values().iterator().next();
Assert.assertEquals(1, result.getLeasesUsed().size());
Assert.assertEquals(1, result.getTasksAssigned().size());
}
@Test
public void testASGsOfTwoTypes() throws Exception {
TaskScheduler scheduler = new TaskScheduler.Builder()
.withFitnessCalculator(BinPackingFitnessCalculators.cpuMemBinPacker)
.withLeaseOfferExpirySecs(100000000)
.withLeaseRejectAction(new Action1<VirtualMachineLease>() {
@Override
public void call(VirtualMachineLease virtualMachineLease) {
Assert.fail("Unexpected to reject lease");
//System.out.println("Rejecting lease on " + virtualMachineLease.hostname());
}
})
.build();
final List<VirtualMachineLease> leases = new ArrayList<>();
int nHosts8core=3;
int nHosts16core=1;
List<VirtualMachineLease.Range> ports = new ArrayList<>();
ports.add(new VirtualMachineLease.Range(1, 100));
Map<String, Protos.Attribute> attributes = new HashMap<>();
Protos.Attribute attribute = Protos.Attribute.newBuilder().setName("ASG")
.setType(Protos.Value.Type.TEXT)
.setText(Protos.Value.Text.newBuilder().setValue("8cores")).build();
attributes.put("ASG", attribute);
for(int l=0; l<nHosts8core; l++)
leases.add(LeaseProvider.getLeaseOffer("host"+l, 8, 32000, 1024.0, ports, attributes));
attributes = new HashMap<>();
Protos.Attribute attribute2 = Protos.Attribute.newBuilder().setName("ASG")
.setType(Protos.Value.Type.TEXT)
.setText(Protos.Value.Text.newBuilder().setValue("16cores")).build();
attributes.put("ASG", attribute2);
for(int l=0; l<nHosts16core; l++)
leases.add(LeaseProvider.getLeaseOffer("bighost" + l, 16, 64000, 1024.0, ports, attributes));
List<TaskRequest> tasks = Arrays.asList(TaskRequestProvider.getTaskRequest(1, 100, 1));
SchedulingResult schedulingResult = scheduler.scheduleOnce(tasks, leases);
Assert.assertEquals(1, schedulingResult.getResultMap().size());
Assert.assertTrue("Unexpected hostname for task", schedulingResult.getResultMap().keySet().iterator().next().startsWith("host"));
System.out.println("result map #elements: " + schedulingResult.getResultMap().size());
Assert.assertEquals(0, schedulingResult.getFailures().size());
schedulingResult = scheduler.scheduleOnce(Arrays.asList(TaskRequestProvider.getTaskRequest(16, 1000, 1)), Collections.EMPTY_LIST);
Assert.assertEquals(1, schedulingResult.getResultMap().size());
Assert.assertTrue("Unexpected hostname for task", schedulingResult.getResultMap().keySet().iterator().next().startsWith("bighost"));
System.out.println("result map #elements: " + schedulingResult.getResultMap().size());
Assert.assertEquals(0, schedulingResult.getFailures().size());
}
@Test
public void testInsufficientDisk() throws Exception {
List<VirtualMachineLease> leases = Collections.singletonList(LeaseProvider.getLeaseOffer("hostA", 4, 4000, 1000, 10,
Collections.singletonList(new VirtualMachineLease.Range(1, 10)), null));
List<TaskRequest> taskRequests = new ArrayList<>();
taskRequests.add(TaskRequestProvider.getTaskRequest(null, 1, 95, 800, 1, 1, null, null));
taskRequests.add(TaskRequestProvider.getTaskRequest(null, 1, 95, 800, 1, 1, null, null));
taskRequests.add(TaskRequestProvider.getTaskRequest(null, 1, 95, 800, 1, 1, null, null));
Map<String,VMAssignmentResult> resultMap = taskScheduler.scheduleOnce(taskRequests, leases).getResultMap();
Assert.assertEquals(1, resultMap.entrySet().size());
Assert.assertEquals(1, resultMap.values().iterator().next().getTasksAssigned().size());
}
@Test
public void testOffersListInConstraintPlugin() throws Exception {
TaskScheduler scheduler = new TaskScheduler.Builder()
.withLeaseOfferExpirySecs(1000000)
.withLeaseRejectAction(new Action1<VirtualMachineLease>() {
@Override
public void call(VirtualMachineLease virtualMachineLease) {
}
})
.build();
final CountDownLatch latch = new CountDownLatch(1);
final AtomicReference<Collection<Protos.Offer>> ref = new AtomicReference<>();
ConstraintEvaluator c = new ConstraintEvaluator() {
@Override
public String getName() {
return "cEvaltr";
}
@Override
public Result evaluate(TaskRequest taskRequest, VirtualMachineCurrentState targetVM, TaskTrackerState taskTrackerState) {
ref.set(targetVM.getAllCurrentOffers());
return new Result(true, "");
}
};
final TaskRequest t = TaskRequestProvider.getTaskRequest(1, 100, 1, Collections.singletonList(c), null);
SchedulingResult result = scheduler.scheduleOnce(Collections.singletonList(t), LeaseProvider.getLeases(1, 4, 4000, 1, 10));
Assert.assertFalse("Got no scheduling assignments", result.getResultMap().isEmpty());
final String hostname = result.getResultMap().keySet().iterator().next();
Assert.assertTrue(ref.get() != null);
Assert.assertEquals(1, ref.get().size());
ref.set(null);
final TaskRequest t2 = TaskRequestProvider.getTaskRequest(4, 100, 1, Collections.singletonList(c), null);
result = scheduler.scheduleOnce(
Collections.singletonList(t2),
Collections.singletonList(
LeaseProvider.getConsumedLease(result.getResultMap().values().iterator().next())
)
);
Assert.assertEquals(0, result.getResultMap().size());
Assert.assertNotNull(ref.get());
Assert.assertEquals(1, ref.get().size());
// add another offer
ref.set(null);
result = scheduler.scheduleOnce(
Collections.singletonList(t2),
Collections.singletonList(
LeaseProvider.getLeaseOffer(hostname, 4, 4000, 1, 10)
)
);
Assert.assertEquals(1, result.getResultMap().size());
Assert.assertNotNull(ref.get());
Assert.assertEquals(2, ref.get().size());
}
@Test
public void testTaskBatchSize() {
TaskScheduler taskScheduler = new TaskScheduler.Builder()
.withLeaseOfferExpirySecs(1000000)
.withLeaseRejectAction(virtualMachineLease -> System.out.println("Rejecting offer on host " + virtualMachineLease.hostname()))
.withTaskBatchSizeSupplier(() -> 2L)
.build();
List<VirtualMachineLease> leases = LeaseProvider.getLeases(1, 5, 50, 1, 10);
List<TaskRequest> taskRequests = new ArrayList<>();
taskRequests.add(TaskRequestProvider.getTaskRequest(1, 10, 0));
taskRequests.add(TaskRequestProvider.getTaskRequest(1, 10, 0));
taskRequests.add(TaskRequestProvider.getTaskRequest(1, 10, 0));
taskRequests.add(TaskRequestProvider.getTaskRequest(1, 10, 0));
taskRequests.add(TaskRequestProvider.getTaskRequest(1, 10, 0));
SchedulingResult schedulingResult = taskScheduler.scheduleOnce(taskRequests, leases);
Assert.assertEquals(2, schedulingResult.getResultMap().values().iterator().next().getTasksAssigned().size());
taskRequests = new ArrayList<>();
taskRequests.add(TaskRequestProvider.getTaskRequest(1, 10, 0));
schedulingResult = taskScheduler.scheduleOnce(taskRequests, leases);
Assert.assertEquals(1, schedulingResult.getResultMap().values().iterator().next().getTasksAssigned().size());
taskRequests = new ArrayList<>();
schedulingResult = taskScheduler.scheduleOnce(taskRequests, leases);
Assert.assertEquals(0, schedulingResult.getResultMap().size());
}
}
| 9,116 |
0 | Create_ds/Fenzo/fenzo-core/src/test/java/com/netflix | Create_ds/Fenzo/fenzo-core/src/test/java/com/netflix/fenzo/TaskSchedulingServiceTest.java | /*
* Copyright 2016 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.fenzo;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.atomic.AtomicReference;
import java.util.stream.Collectors;
import com.netflix.fenzo.functions.Action0;
import com.netflix.fenzo.functions.Action1;
import com.netflix.fenzo.functions.Func1;
import com.netflix.fenzo.plugins.BinPackingFitnessCalculators;
import com.netflix.fenzo.queues.QAttributes;
import com.netflix.fenzo.queues.QueuableTask;
import com.netflix.fenzo.queues.TaskQueue;
import com.netflix.fenzo.queues.TaskQueueException;
import com.netflix.fenzo.queues.TaskQueueMultiException;
import com.netflix.fenzo.queues.TaskQueues;
import com.netflix.fenzo.queues.tiered.QueuableTaskProvider;
import org.junit.Assert;
import org.junit.Test;
public class TaskSchedulingServiceTest {
private final QAttributes tier1bktA = new QAttributes.QAttributesAdaptor(0, "A");
private final QAttributes tier1bktB = new QAttributes.QAttributesAdaptor(0, "B");
private final QAttributes tier1bktC = new QAttributes.QAttributesAdaptor(0, "C");
private final QAttributes tier1bktD1 = new QAttributes.QAttributesAdaptor(1, "D1");
private TaskSchedulingService getSchedulingService(TaskQueue queue, TaskScheduler scheduler, long loopMillis,
Action1<SchedulingResult> resultCallback) {
return getSchedulingService(queue, scheduler, loopMillis, loopMillis, resultCallback);
}
private TaskSchedulingService getSchedulingService(TaskQueue queue, TaskScheduler scheduler, long loopMillis,
long maxDelayMillis, Action1<SchedulingResult> resultCallback) {
return new TaskSchedulingService.Builder()
.withTaskQueue(queue)
.withLoopIntervalMillis(loopMillis)
.withMaxDelayMillis(maxDelayMillis)
.withPreSchedulingLoopHook(() -> {
//System.out.println("Pre-scheduling hook");
})
.withSchedulingResultCallback(resultCallback)
.withTaskScheduler(scheduler)
.build();
}
public TaskScheduler getScheduler() {
return getScheduler(avms -> avms);
}
public TaskScheduler getScheduler(Func1<List<AssignableVirtualMachine>, List<AssignableVirtualMachine>> assignableVMsEvaluator) {
return new TaskScheduler.Builder()
.withLeaseOfferExpirySecs(1000000)
.withLeaseRejectAction(virtualMachineLease -> System.out.println("Rejecting offer on host " + virtualMachineLease.hostname()))
.withFitnessCalculator(BinPackingFitnessCalculators.cpuMemBinPacker)
.withAssignableVMsEvaluator(assignableVMsEvaluator)
.build();
}
@Test
public void testOneTaskAssignment() throws Exception {
testOneTaskInternal(
QueuableTaskProvider.wrapTask(tier1bktA, TaskRequestProvider.getTaskRequest(2, 2000, 1)),
() -> {}
);
}
private void testOneTaskInternal(QueuableTask queuableTask, Action0 action) throws Exception {
final CountDownLatch latch = new CountDownLatch(1);
TaskQueue queue = TaskQueues.createTieredQueue(2);
final TaskScheduler scheduler = getScheduler();
Action1<SchedulingResult> resultCallback = schedulingResult -> {
//System.out.println("Got scheduling result with " + schedulingResult.getResultMap().size() + " results");
if (schedulingResult.getResultMap().size() > 0) {
//System.out.println("Assignment on host " + schedulingResult.getResultMap().values().iterator().next().getHostname());
latch.countDown();
scheduler.shutdown();
}
};
final TaskSchedulingService schedulingService = getSchedulingService(queue, scheduler, 1000L, resultCallback);
schedulingService.start();
List<VirtualMachineLease.Range> ports = new ArrayList<>();
ports.add(new VirtualMachineLease.Range(1, 10));
schedulingService.addLeases(
Collections.singletonList(LeaseProvider.getLeaseOffer(
"hostA", 4, 4000, ports,
ResourceSetsTests.getResSetsAttributesMap("ENIs", 2, 2))));
queue.queueTask(queuableTask);
if (!latch.await(20000, TimeUnit.MILLISECONDS))
Assert.fail("Did not assign resources in time");
if (action != null)
action.call();
}
@Test
public void testOneTaskWithResourceSet() throws Exception {
TaskRequest.NamedResourceSetRequest sr1 =
new TaskRequest.NamedResourceSetRequest("ENIs", "sg1", 1, 1);
final QueuableTask task = QueuableTaskProvider.wrapTask(
tier1bktA,
TaskRequestProvider.getTaskRequest("grp", 1, 100, 0, 0, 0,
null, null, Collections.singletonMap(sr1.getResName(), sr1))
);
testOneTaskInternal(
task,
() -> {
final TaskRequest.AssignedResources assignedResources = task.getAssignedResources();
Assert.assertNotNull(assignedResources);
final List<PreferentialNamedConsumableResourceSet.ConsumeResult> cnrs = assignedResources.getConsumedNamedResources();
Assert.assertNotNull(cnrs);
Assert.assertEquals(1, cnrs.size());
Assert.assertEquals(sr1.getResValue(), cnrs.get(0).getResName());
}
);
}
@Test
public void testMultipleTaskAssignments() throws Exception {
int numTasks = 4;
long loopMillis=100;
TaskQueue queue = TaskQueues.createTieredQueue(2);
final CountDownLatch latch = new CountDownLatch(numTasks);
final TaskScheduler scheduler = getScheduler();
final AtomicReference<TaskSchedulingService> ref = new AtomicReference<>();
Action1<SchedulingResult> resultCallback = schedulingResult -> {
//System.out.println("Got scheduling result with " + schedulingResult.getResultMap().size() + " results");
if (!schedulingResult.getExceptions().isEmpty()) {
Assert.fail(schedulingResult.getExceptions().get(0).getMessage());
}
else if (schedulingResult.getResultMap().size() > 0) {
final VMAssignmentResult vmAssignmentResult = schedulingResult.getResultMap().values().iterator().next();
// System.out.println("Assignment on host " + vmAssignmentResult.getHostname() +
// " with " + vmAssignmentResult.getTasksAssigned().size() + " tasks"
// );
for (TaskAssignmentResult r: vmAssignmentResult.getTasksAssigned()) {
latch.countDown();
}
ref.get().addLeases(
Collections.singletonList(LeaseProvider.getConsumedLease(vmAssignmentResult))
);
}
else {
final Map<TaskRequest, List<TaskAssignmentResult>> failures = schedulingResult.getFailures();
if (!failures.isEmpty()) {
Assert.fail(failures.values().iterator().next().iterator().next().toString());
}
}
};
final TaskSchedulingService schedulingService = getSchedulingService(queue, scheduler, loopMillis, resultCallback);
ref.set(schedulingService);
schedulingService.start();
schedulingService.addLeases(LeaseProvider.getLeases(1, 4, 4000, 1, 10));
for (int i=0; i<numTasks; i++) {
queue.queueTask(QueuableTaskProvider.wrapTask(tier1bktA, TaskRequestProvider.getTaskRequest(1, 1000, 1)));
Thread.sleep(loopMillis); // simulate that tasks are added across different scheduling iterations
}
if (!latch.await(loopMillis * (numTasks + 2), TimeUnit.MILLISECONDS))
Assert.fail(latch.getCount() + " of " + numTasks + " not scheduled within time");
}
// Test that tasks are assigned in the order based on current usage among multiple buckets within a tier
@Test
public void testOrderedAssignments() throws Exception {
TaskQueue queue = TaskQueues.createTieredQueue(2);
final TaskScheduler scheduler = getScheduler();
final BlockingQueue<QueuableTask> assignmentResults = new LinkedBlockingQueue<>();
Action1<SchedulingResult> resultCallback = schedulingResult -> {
final Map<String, VMAssignmentResult> resultMap = schedulingResult.getResultMap();
if (!resultMap.isEmpty()) {
for (VMAssignmentResult r: resultMap.values()) {
for (TaskAssignmentResult t: r.getTasksAssigned()) {
assignmentResults.offer((QueuableTask)t.getRequest());
//System.out.println("******* Assignment for task " + t.getTaskId());
}
}
}
// final Map<TaskRequest, List<TaskAssignmentResult>> failures = schedulingResult.getFailures();
// if (!failures.isEmpty()) {
// for (Map.Entry<TaskRequest, List<TaskAssignmentResult>> entry: failures.entrySet()) {
// System.out.println("****** failures for task " + entry.getKey().getId());
// }
// }
};
final TaskSchedulingService schedulingService = getSchedulingService(queue, scheduler, 50L, resultCallback);
// First, fill 4 VMs, each with 8 cores, with A using 15 cores, B using 6 cores, and C using 11 cores, with
// memory used in the same ratios
for (int i=0; i<15; i++)
queue.queueTask(QueuableTaskProvider.wrapTask(tier1bktA, TaskRequestProvider.getTaskRequest(1, 10, 1)));
for (int i=0; i<6; i++)
queue.queueTask(QueuableTaskProvider.wrapTask(tier1bktB, TaskRequestProvider.getTaskRequest(1, 10, 1)));
for (int i=0; i<11; i++)
queue.queueTask(QueuableTaskProvider.wrapTask(tier1bktC, TaskRequestProvider.getTaskRequest(1, 10, 1)));
schedulingService.start();
schedulingService.addLeases(LeaseProvider.getLeases(4, 8, 8000, 1, 1000));
int numTasks = 32;
while (numTasks > 0) {
final QueuableTask task = assignmentResults.poll(2000, TimeUnit.MILLISECONDS);
if (task == null)
Assert.fail("Time out waiting for task to get assigned");
else {
numTasks--;
}
}
// Now submit one task for each of A, B, and C, and create one offer that will only fit one of the tasks. Ensure
// that the only task assigned is from B.
queue.queueTask(QueuableTaskProvider.wrapTask(tier1bktA, TaskRequestProvider.getTaskRequest(4, 40, 1)));
queue.queueTask(QueuableTaskProvider.wrapTask(tier1bktB, TaskRequestProvider.getTaskRequest(4, 40, 1)));
queue.queueTask(QueuableTaskProvider.wrapTask(tier1bktC, TaskRequestProvider.getTaskRequest(4, 40, 1)));
schedulingService.addLeases(LeaseProvider.getLeases(1, 4, 4000, 1, 100));
QueuableTask task = assignmentResults.poll(1000, TimeUnit.MILLISECONDS);
if (task == null)
Assert.fail("Time out waiting for just one task to get assigned");
Assert.assertEquals(tier1bktB.getBucketName(), task.getQAttributes().getBucketName());
// queueTask another task for B and make sure it gets launched ahead of A and C after adding one more offer
queue.queueTask(QueuableTaskProvider.wrapTask(tier1bktB, TaskRequestProvider.getTaskRequest(4, 40, 1)));
schedulingService.addLeases(LeaseProvider.getLeases(1, 4, 4000, 1, 100));
task = assignmentResults.poll(1000, TimeUnit.MILLISECONDS);
if (task == null)
Assert.fail("Time out waiting for just one task to get assigned");
Assert.assertEquals(tier1bktB.getBucketName(), task.getQAttributes().getBucketName());
// now add another offer and ensure task from C gets launched
schedulingService.addLeases(LeaseProvider.getLeases(1, 4, 4000, 1, 100));
task = assignmentResults.poll(1000, TimeUnit.MILLISECONDS);
if (task == null)
Assert.fail("Time out waiting for just one task to get assigned");
Assert.assertEquals(tier1bktC.getBucketName(), task.getQAttributes().getBucketName());
// a final offer and the task from A should get launched
schedulingService.addLeases(LeaseProvider.getLeases(1, 4, 4000, 1, 100));
task = assignmentResults.poll(1000, TimeUnit.MILLISECONDS);
if (task == null)
Assert.fail("Time out waiting for just one task to get assigned");
Assert.assertEquals(tier1bktA.getBucketName(), task.getQAttributes().getBucketName());
}
@Test
public void testMultiTierAllocation() throws Exception {
TaskQueue queue = TaskQueues.createTieredQueue(2);
final TaskScheduler scheduler = getScheduler();
final BlockingQueue<QueuableTask> assignmentResults = new LinkedBlockingQueue<>();
Action1<SchedulingResult> resultCallback = schedulingResult -> {
final Map<String, VMAssignmentResult> resultMap = schedulingResult.getResultMap();
if (!resultMap.isEmpty()) {
for (VMAssignmentResult r: resultMap.values()) {
for (TaskAssignmentResult t: r.getTasksAssigned()) {
assignmentResults.offer((QueuableTask)t.getRequest());
//System.out.println("******* Assignment for task " + t.getTaskId());
}
}
}
// final Map<TaskRequest, List<TaskAssignmentResult>> failures = schedulingResult.getFailures();
// if (!failures.isEmpty()) {
// for (Map.Entry<TaskRequest, List<TaskAssignmentResult>> entry: failures.entrySet()) {
// System.out.println("****** failures for task " + entry.getKey().getId());
// }
// }
};
final TaskSchedulingService schedulingService = getSchedulingService(queue, scheduler, 50L, resultCallback);
// fill 4 hosts with tasks from A (tier 0) and tasks from D1 (tier 1)
for (int i=0; i<20; i++)
queue.queueTask(QueuableTaskProvider.wrapTask(tier1bktA, TaskRequestProvider.getTaskRequest(1, 10, 1)));
for (int i=0; i<12; i++)
queue.queueTask(QueuableTaskProvider.wrapTask(tier1bktD1, TaskRequestProvider.getTaskRequest(1, 10, 1)));
schedulingService.start();
schedulingService.addLeases(LeaseProvider.getLeases(4, 8, 8000, 1, 1000));
int numTasks = 32;
while (numTasks > 0) {
final QueuableTask task = assignmentResults.poll(2000, TimeUnit.MILLISECONDS);
if (task == null)
Assert.fail("Time out waiting for task to get assigned");
else {
numTasks--;
}
}
// now submit a task from A that will only fill part of next offer, and a few tasks from D1 each of which
// can fill the entire offer. Ensure that only task from A gets launched
queue.queueTask(QueuableTaskProvider.wrapTask(tier1bktA, TaskRequestProvider.getTaskRequest(1, 10, 1)));
for (int i=0; i<3; i++)
queue.queueTask(QueuableTaskProvider.wrapTask(tier1bktD1, TaskRequestProvider.getTaskRequest(4, 40, 1)));
schedulingService.addLeases(LeaseProvider.getLeases(1, 4, 4000, 1, 1000));
final QueuableTask task = assignmentResults.poll(1000, TimeUnit.MILLISECONDS);
Assert.assertNotNull("Time out waiting for just one task to get assigned", task);
Assert.assertEquals(tier1bktA.getBucketName(), task.getQAttributes().getBucketName());
final CountDownLatch latch = new CountDownLatch(1);
final AtomicReference<Map<TaskQueue.TaskState, Collection<QueuableTask>>> ref = new AtomicReference<>();
schedulingService.requestAllTasks(stateCollectionMap -> {
//System.out.println("**************** Got tasks collection");
final Collection<QueuableTask> tasks = stateCollectionMap.get(TaskQueue.TaskState.QUEUED);
//System.out.println("********* size=" + tasks.size());
// if (!tasks.isEmpty())
// System.out.println("******** bucket: " + tasks.iterator().next().getQAttributes().getBucketName());
ref.set(stateCollectionMap);
latch.countDown();
});
if (!latch.await(1000, TimeUnit.MILLISECONDS))
Assert.fail("Time out waiting for tasks collection");
final Map<TaskQueue.TaskState, Collection<QueuableTask>> map = ref.get();
Assert.assertNotNull(map);
Assert.assertNotNull(map.get(TaskQueue.TaskState.QUEUED));
Assert.assertEquals(tier1bktD1.getBucketName(), map.get(TaskQueue.TaskState.QUEUED).iterator().next().getQAttributes().getBucketName());
}
// test that dominant resource share works for ordering of buckets - test by having equal resource usage among two
// buckets A and B, then let A use more CPUs and B use more Memory.
@Test
public void testMultiResAllocation() throws Exception {
TaskQueue queue = TaskQueues.createTieredQueue(2);
final TaskScheduler scheduler = getScheduler();
final BlockingQueue<QueuableTask> assignmentResults = new LinkedBlockingQueue<>();
final AtomicReference<TaskSchedulingService> ref = new AtomicReference<>();
Action1<SchedulingResult> resultCallback = schedulingResult -> {
final Map<String, VMAssignmentResult> resultMap = schedulingResult.getResultMap();
if (!resultMap.isEmpty()) {
for (VMAssignmentResult r: resultMap.values()) {
for (TaskAssignmentResult t: r.getTasksAssigned()) {
assignmentResults.offer((QueuableTask)t.getRequest());
}
ref.get().addLeases(Collections.singletonList(LeaseProvider.getConsumedLease(r)));
}
}
// final Map<TaskRequest, List<TaskAssignmentResult>> failures = schedulingResult.getFailures();
// if (!failures.isEmpty()) {
// for (Map.Entry<TaskRequest, List<TaskAssignmentResult>> entry: failures.entrySet()) {
// System.out.println("****** failures for task " + entry.getKey().getId());
// }
// }
};
final TaskSchedulingService schedulingService = getSchedulingService(queue, scheduler, 50L, resultCallback);
ref.set(schedulingService);
// let us use VMs having 8 cores and 8000 MB of memory each and.
// create 2 VMs and fill their usage with A filling 2 CPUs at a time with little memory and B filling 2000 MB
// at a time with very little CPUs.
for (int i=0; i<4; i++)
queue.queueTask(QueuableTaskProvider.wrapTask(tier1bktA, TaskRequestProvider.getTaskRequest(3, 1000, 1)));
for (int i=0; i<4; i++)
queue.queueTask(QueuableTaskProvider.wrapTask(tier1bktB, TaskRequestProvider.getTaskRequest(1, 3000, 1)));
schedulingService.start();
List<VirtualMachineLease> leases = LeaseProvider.getLeases(2, 8, 8000, 1, 100);
schedulingService.addLeases(leases);
if (!unqueueTaskResults(8, assignmentResults))
Assert.fail("Timeout waiting for 16 tasks");
// now A is using 12 of the 16 total CPUs in use, and B is using 12,000 of 16,000 total MB, so their
// dominant resource usage share is equivalent.
// now submit a task from A to use 1 CPU and 10 MB memory and another task from B to use 1 CPU and 4000 MB memory
// ensure that they are assigned on a new VM
queue.queueTask(QueuableTaskProvider.wrapTask(tier1bktA, TaskRequestProvider.getTaskRequest(1, 10, 1)));
queue.queueTask(QueuableTaskProvider.wrapTask(tier1bktB, TaskRequestProvider.getTaskRequest(1, 7000, 1)));
leases = LeaseProvider.getLeases(2, 1, 8, 8000, 1, 100);
schedulingService.addLeases(leases);
if (!unqueueTaskResults(2, assignmentResults))
Assert.fail("Timeout waiting for 2 task assignments");
// now submit a task from just A with 1 CPU, 10 memory, it should get assigned right away
queue.queueTask(QueuableTaskProvider.wrapTask(tier1bktA, TaskRequestProvider.getTaskRequest(1, 10, 1)));
if (!unqueueTaskResults(1, assignmentResults))
Assert.fail("Timeout waiting for 1 task assignment");
// we now have 3 CPUs and 7020 MB memory being used out of 8 and 8000 respectively
// now submit 5 tasks from A with 1 CPU, 1 memory each to possibly fill the host as well as a task from B with 1 CPU, 1000 memory.
// ensure that only the tasks from A get assigned and that the task from B stays queued
for (int i=0; i<5; i++)
queue.queueTask(QueuableTaskProvider.wrapTask(tier1bktA, TaskRequestProvider.getTaskRequest(1, 1, 1)));
queue.queueTask(QueuableTaskProvider.wrapTask(tier1bktB, TaskRequestProvider.getTaskRequest(1, 1000, 1)));
int numTasks = 2;
while (numTasks > 0) {
final QueuableTask task = assignmentResults.poll(2000, TimeUnit.MILLISECONDS);
if (task == null)
Assert.fail("Timeout waiting for task assignment");
Assert.assertEquals(tier1bktA.getBucketName(), task.getQAttributes().getBucketName());
numTasks--;
}
final AtomicReference<String> bucketRef = new AtomicReference<>();
final CountDownLatch latch = new CountDownLatch(1);
schedulingService.requestAllTasks(stateCollectionMap -> {
final Collection<QueuableTask> tasks = stateCollectionMap.get(TaskQueue.TaskState.QUEUED);
if (tasks != null && !tasks.isEmpty()) {
for (QueuableTask t : tasks)
bucketRef.set(t.getQAttributes().getBucketName());
latch.countDown();
}
});
if (!latch.await(2000, TimeUnit.MILLISECONDS))
Assert.fail("Can't get confirmation on task from B to be queued");
Assert.assertNotNull(bucketRef.get());
Assert.assertEquals(tier1bktB.getBucketName(), bucketRef.get());
}
@Test
public void testRemoveFromQueue() throws Exception {
final CountDownLatch latch = new CountDownLatch(1);
TaskQueue queue = TaskQueues.createTieredQueue(2);
final TaskScheduler scheduler = getScheduler();
Action1<SchedulingResult> resultCallback = schedulingResult -> {
//System.out.println("Got scheduling result with " + schedulingResult.getResultMap().size() + " results");
if (schedulingResult.getResultMap().size() > 0) {
//System.out.println("Assignment on host " + schedulingResult.getResultMap().values().iterator().next().getHostname());
latch.countDown();
}
};
final TaskSchedulingService schedulingService = getSchedulingService(queue, scheduler, 100L, 200L, resultCallback);
schedulingService.start();
final List<VirtualMachineLease> leases = LeaseProvider.getLeases(1, 4, 4000, 1, 10);
schedulingService.addLeases(leases);
final QueuableTask task = QueuableTaskProvider.wrapTask(tier1bktA, TaskRequestProvider.getTaskRequest(2, 2000, 1));
queue.queueTask(task);
if (!latch.await(5, TimeUnit.SECONDS))
Assert.fail("Did not assign resources in time");
final CountDownLatch latch2 = new CountDownLatch(1);
final AtomicBoolean found = new AtomicBoolean();
schedulingService.requestVmCurrentStates(states -> {
for (VirtualMachineCurrentState s: states) {
for (TaskRequest t: s.getRunningTasks()) {
if (t.getId().equals(task.getId())) {
found.set(true);
latch2.countDown();
}
}
}
});
if (!latch2.await(5, TimeUnit.SECONDS)) {
Assert.fail("Didn't get vm states in time");
}
Assert.assertTrue("Did not find task on vm", found.get());
schedulingService.removeTask(task.getId(), task.getQAttributes(), leases.get(0).hostname());
found.set(false);
final CountDownLatch latch3 = new CountDownLatch(1);
schedulingService.requestVmCurrentStates(states -> {
for (VirtualMachineCurrentState s: states) {
for (TaskRequest t: s.getRunningTasks()) {
if (t.getId().equals(task.getId())) {
found.set(true);
latch3.countDown();
}
}
}
latch3.countDown();
});
if (!latch3.await(5, TimeUnit.SECONDS)) {
Assert.fail("Timeout waiting for vm states");
}
Assert.assertFalse("Unexpected to find removed task on vm", found.get());
scheduler.shutdown();
}
@Test
public void testMaxSchedIterDelay() throws Exception {
TaskQueue queue = TaskQueues.createTieredQueue(2);
final TaskScheduler scheduler = getScheduler();
queue.queueTask(QueuableTaskProvider.wrapTask(tier1bktA, TaskRequestProvider.getTaskRequest(1, 100, 1)));
Action1<SchedulingResult> resultCallback = schedulingResult -> {
// no-op
};
final long maxDelay = 500L;
final long loopMillis = 50L;
final TaskSchedulingService schedulingService = getSchedulingService(queue, scheduler, loopMillis, maxDelay, resultCallback);
schedulingService.start();
long startAt = System.currentTimeMillis();
Thread.sleep(51L);
final AtomicLong gotTasksAt = new AtomicLong();
CountDownLatch latch = new CountDownLatch(1);
setupTaskGetter(schedulingService, gotTasksAt, latch);
if (!latch.await(maxDelay + 100L, TimeUnit.MILLISECONDS)) {
Assert.fail("Timeout waiting for tasks list");
}
Assert.assertTrue("Got task list too soon", (gotTasksAt.get() - startAt) > maxDelay);
// now test that when queue does change, we get it sooner
startAt = System.currentTimeMillis();
latch = new CountDownLatch(1);
setupTaskGetter(schedulingService, gotTasksAt, latch);
queue.queueTask(QueuableTaskProvider.wrapTask(tier1bktA, TaskRequestProvider.getTaskRequest(1, 100, 1)));
if (!latch.await(maxDelay + 100L, TimeUnit.MILLISECONDS)) {
Assert.fail("Timeout waiting for tasks list");
}
Assert.assertTrue("Got task list too late", (gotTasksAt.get() - startAt) < (maxDelay + 2 * loopMillis));
// repeat with adding lease
startAt = System.currentTimeMillis();
latch = new CountDownLatch(1);
setupTaskGetter(schedulingService, gotTasksAt, latch);
schedulingService.addLeases(LeaseProvider.getLeases(1, 1, 100, 1, 10));
if (!latch.await(maxDelay + 100L, TimeUnit.MILLISECONDS)) {
Assert.fail("Timeout waiting for tasks list");
}
Assert.assertTrue("Got tasks list too late", (gotTasksAt.get() - startAt) < (maxDelay + 2 * loopMillis));
}
@Test
public void testInitWithPrevRunningTasks() throws Exception {
TaskQueue queue = TaskQueues.createTieredQueue(2);
final TaskScheduler scheduler = getScheduler();
Action1<SchedulingResult> resultCallback = schedulingResult -> {
// no-op
};
final long maxDelay = 500L;
final long loopMillis = 50L;
final TaskSchedulingService schedulingService = getSchedulingService(queue, scheduler, loopMillis, maxDelay, resultCallback);
schedulingService.start();
final String hostname = "hostA";
schedulingService.initializeRunningTask(
QueuableTaskProvider.wrapTask(tier1bktA, TaskRequestProvider.getTaskRequest(1, 100, 1)),
hostname
);
final AtomicReference<String> ref = new AtomicReference<>();
final CountDownLatch latch = new CountDownLatch(1);
schedulingService.requestVmCurrentStates(
states -> {
if (states != null && !states.isEmpty()) {
final VirtualMachineCurrentState state = states.iterator().next();
ref.set(state.getHostname());
}
latch.countDown();
}
);
if (!latch.await(maxDelay * 2, TimeUnit.MILLISECONDS)) {
Assert.fail("Timeout waiting for vm states");
}
Assert.assertEquals(hostname, ref.get());
}
// Test with a large number of tasks captured from a run that caused problems to tier buckets' sorting. Ensure that
//
@Test
public void testLargeTasksToInitInRunningState() throws Exception {
final List<SampleLargeNumTasksToInit.Task> runningTasks = SampleLargeNumTasksToInit.getSampleTasksInRunningState();
System.out.println("GOT " + runningTasks.size() + " tasks");
TaskQueue queue = TaskQueues.createTieredQueue(2);
final TaskScheduler scheduler = getScheduler();
final CountDownLatch latch = new CountDownLatch(6);
final AtomicReference<List<Exception>> ref = new AtomicReference<>();
final AtomicBoolean printFailures = new AtomicBoolean();
Action1<SchedulingResult> resultCallback = schedulingResult -> {
final List<Exception> exceptions = schedulingResult.getExceptions();
if (exceptions != null && !exceptions.isEmpty())
ref.set(exceptions);
else if (!schedulingResult.getResultMap().isEmpty())
System.out.println("#Assignments: " + schedulingResult.getResultMap().values().iterator().next().getTasksAssigned().size());
else if(printFailures.get()) {
final Map<TaskRequest, List<TaskAssignmentResult>> failures = schedulingResult.getFailures();
if (!failures.isEmpty()) {
for (Map.Entry<TaskRequest, List<TaskAssignmentResult>> entry: failures.entrySet()) {
System.out.println(" Failure for " + entry.getKey().getId() + ":");
for(TaskAssignmentResult r: entry.getValue())
System.out.println(" " + r.toString());
}
}
}
latch.countDown();
};
final long maxDelay = 100L;
final long loopMillis = 20L;
final TaskSchedulingService schedulingService = getSchedulingService(queue, scheduler, loopMillis, maxDelay, resultCallback);
Map<String, SampleLargeNumTasksToInit.Task> uniqueTasks = new HashMap<>();
for(SampleLargeNumTasksToInit.Task t: runningTasks) {
if (!uniqueTasks.containsKey(t.getBucket()))
uniqueTasks.put(t.getBucket(), t);
schedulingService.initializeRunningTask(SampleLargeNumTasksToInit.toQueuableTask(t), t.getHost());
}
schedulingService.start();
// add a few new tasks
int id=0;
for(SampleLargeNumTasksToInit.Task t: uniqueTasks.values()) {
queue.queueTask(
SampleLargeNumTasksToInit.toQueuableTask(
new SampleLargeNumTasksToInit.Task("newTask-" + id++, t.getBucket(), t.getTier(), t.getCpu(), t.getMemory(), t.getNetworkMbps(), t.getDisk(), null)
)
);
}
schedulingService.addLeases(LeaseProvider.getLeases(1000, 1, 32, 500000, 2000, 0, 100));
Thread.sleep(loopMillis*2);
printFailures.set(true);
if (!latch.await(1000, TimeUnit.MILLISECONDS)) {
Assert.fail("Unexpected to not get enough sched iterations done");
}
final List<Exception> exceptions = ref.get();
if (exceptions != null) {
for(Exception e: exceptions) {
if (e instanceof TaskQueueMultiException) {
for (Exception ee : ((TaskQueueMultiException) e).getExceptions())
ee.printStackTrace();
}
else
e.printStackTrace();
}
}
Assert.assertNull(exceptions);
}
@Test
public void testNotReadyTask() throws Exception {
TaskQueue queue = TaskQueues.createTieredQueue(2);
final TaskScheduler scheduler = getScheduler();
final AtomicReference<List<Exception>> ref = new AtomicReference<>();
final CountDownLatch latch = new CountDownLatch(1);
final AtomicReference<List<String>> assignedTaskIds = new AtomicReference<>(new LinkedList<>());
final AtomicReference<List<String>> failedTaskIds = new AtomicReference<>(new LinkedList<>());
Action1<SchedulingResult> resultCallback = schedulingResult -> {
final List<Exception> exceptions = schedulingResult.getExceptions();
final Map<String, VMAssignmentResult> resultMap = schedulingResult.getResultMap();
if (exceptions != null && !exceptions.isEmpty())
ref.set(exceptions);
else if (!resultMap.isEmpty()) {
resultMap.forEach((key, value) -> value.getTasksAssigned().forEach(t -> assignedTaskIds.get().add(t.getTaskId())));
}
schedulingResult.getFailures().forEach((t, r) -> failedTaskIds.get().add(t.getId()));
latch.countDown();
};
final long maxDelay = 100L;
final long loopMillis = 20L;
final TaskSchedulingService schedulingService = getSchedulingService(queue, scheduler, loopMillis, maxDelay, resultCallback);
final QueuableTask task1 = QueuableTaskProvider.wrapTask(tier1bktA, TaskRequestProvider.getTaskRequest(1, 100, 1));
queue.queueTask(task1);
final QueuableTask task2 = QueuableTaskProvider.wrapTask(tier1bktA, TaskRequestProvider.getTaskRequest(1, 100, 1));
task2.safeSetReadyAt(System.currentTimeMillis() + 1000000L);
queue.queueTask(task2);
schedulingService.addLeases(LeaseProvider.getLeases(2, 4, 8000, 2000, 1, 100));
schedulingService.start();
if (!latch.await(2, TimeUnit.SECONDS)) {
Assert.fail("Unexpected to not get assignments in time");
}
Assert.assertEquals(1, assignedTaskIds.get().size());
Assert.assertEquals(task1.getId(), assignedTaskIds.get().iterator().next());
Assert.assertEquals(0, failedTaskIds.get().size());
schedulingService.shutdown();
}
@Test
public void testAssignableVMsEvaluator() throws Exception {
int numVms = 10;
int numTasks = 5;
long loopMillis = 100;
TaskQueue queue = TaskQueues.createTieredQueue(2);
final CountDownLatch latch = new CountDownLatch(1);
final TaskScheduler scheduler = getScheduler(avms -> avms.stream().limit(1).collect(Collectors.toList()));
final AtomicReference<TaskSchedulingService> ref = new AtomicReference<>();
Action1<SchedulingResult> resultCallback = schedulingResult -> {
if (schedulingResult.getTotalVMsCount() == numVms && schedulingResult.getFailures().size() == numTasks - 1) {
latch.countDown();
}
};
final TaskSchedulingService schedulingService = getSchedulingService(queue, scheduler, loopMillis, resultCallback);
ref.set(schedulingService);
schedulingService.start();
schedulingService.addLeases(LeaseProvider.getLeases(numVms, 1, 4000, 1, 10));
for (int i = 0; i < numTasks; i++) {
queue.queueTask(QueuableTaskProvider.wrapTask(tier1bktA, TaskRequestProvider.getTaskRequest(1, 1000, 1)));
}
if (!latch.await(loopMillis * 10, TimeUnit.MILLISECONDS)) {
Assert.fail("Latch timed out without having a successful scheduling result");
}
}
private void setupTaskGetter(TaskSchedulingService schedulingService, final AtomicLong gotTasksAt, final CountDownLatch latch) throws TaskQueueException {
schedulingService.requestAllTasks(stateCollectionMap -> {
gotTasksAt.set(System.currentTimeMillis());
latch.countDown();
});
}
private boolean unqueueTaskResults(int numTasks, BlockingQueue<QueuableTask> assignmentResults) throws InterruptedException {
while (numTasks > 0) {
final QueuableTask task = assignmentResults.poll(2000, TimeUnit.MILLISECONDS);
if (task == null)
return false;
else
numTasks--;
}
return true;
}
} | 9,117 |
0 | Create_ds/Fenzo/fenzo-core/src/test/java/com/netflix | Create_ds/Fenzo/fenzo-core/src/test/java/com/netflix/fenzo/AutoScaleRuleProvider.java | /*
* Copyright 2015 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.fenzo;
import java.util.function.Function;
public class AutoScaleRuleProvider {
static AutoScaleRule createRule(final String name, final int min, final int max, final long coolDownSecs,
final double cpuTooSmall, final double memoryTooSmall,
Function<Integer, Integer> shortfallAdjustingFunc) {
return new AutoScaleRule() {
@Override
public String getRuleName() {
return name;
}
@Override
public int getMinIdleHostsToKeep() {
return min;
}
@Override
public int getMaxIdleHostsToKeep() {
return max;
}
@Override
public long getCoolDownSecs() {
return coolDownSecs;
}
@Override
public int getShortfallAdjustedAgents(int numberOfAgents) {
return shortfallAdjustingFunc.apply(numberOfAgents);
}
@Override
public boolean idleMachineTooSmall(VirtualMachineLease lease) {
return (lease.cpuCores() < cpuTooSmall || lease.memoryMB() < memoryTooSmall);
}
};
}
static AutoScaleRule createRule(final String name, final int min, final int max, final long coolDownSecs,
final double cpuTooSmall, final double memoryTooSmall) {
return createRule(name, min, max, coolDownSecs, cpuTooSmall, memoryTooSmall, Function.identity());
}
static AutoScaleRule createWithMinSize(final String name, final int min, final int max, final long coolDownSecs,
final double cpuTooSmall, final double memoryTooSmall, int minSize) {
return new AutoScaleRule() {
@Override
public String getRuleName() {
return name;
}
@Override
public int getMinIdleHostsToKeep() {
return min;
}
@Override
public int getMaxIdleHostsToKeep() {
return max;
}
@Override
public long getCoolDownSecs() {
return coolDownSecs;
}
@Override
public boolean idleMachineTooSmall(VirtualMachineLease lease) {
return (lease.cpuCores() < cpuTooSmall || lease.memoryMB() < memoryTooSmall);
}
@Override
public int getMinSize() {
return minSize;
}
};
}
static AutoScaleRule createWithMaxSize(final String name, final int min, final int max, final long coolDownSecs,
final double cpuTooSmall, final double memoryTooSmall, int maxSize) {
return new AutoScaleRule() {
@Override
public String getRuleName() {
return name;
}
@Override
public int getMinIdleHostsToKeep() {
return min;
}
@Override
public int getMaxIdleHostsToKeep() {
return max;
}
@Override
public long getCoolDownSecs() {
return coolDownSecs;
}
@Override
public boolean idleMachineTooSmall(VirtualMachineLease lease) {
return (lease.cpuCores() < cpuTooSmall || lease.memoryMB() < memoryTooSmall);
}
@Override
public int getMaxSize() {
return maxSize;
}
};
}
}
| 9,118 |
0 | Create_ds/Fenzo/fenzo-core/src/test/java/com/netflix | Create_ds/Fenzo/fenzo-core/src/test/java/com/netflix/fenzo/TaskCompleter.java | /*
* Copyright 2015 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.fenzo;
import com.netflix.fenzo.functions.Action1;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.SortedSet;
import java.util.TreeSet;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
public class TaskCompleter {
private final SortedSet<RandomTaskGenerator.GeneratedTask> sortedTaskSet;
private final BlockingQueue<RandomTaskGenerator.GeneratedTask> taskInputQ;
private final Action1<RandomTaskGenerator.GeneratedTask> taskCompleter;
private final long delayMillis;
public TaskCompleter(BlockingQueue<RandomTaskGenerator.GeneratedTask> taskInputQ,
Action1<RandomTaskGenerator.GeneratedTask> taskCompleter, long delayMillis) {
sortedTaskSet = new TreeSet<>();
this.taskInputQ = taskInputQ;
this.taskCompleter = taskCompleter;
this.delayMillis = delayMillis;
}
public void start() {
final List<RandomTaskGenerator.GeneratedTask> newTasks = new ArrayList<>();
new ScheduledThreadPoolExecutor(1).scheduleWithFixedDelay(
new Runnable() {
@Override
public void run() {
try {
newTasks.clear();
taskInputQ.drainTo(newTasks);
if(!newTasks.isEmpty()) {
for(RandomTaskGenerator.GeneratedTask t: newTasks)
sortedTaskSet.add(t);
}
if(sortedTaskSet.isEmpty())
return;
RandomTaskGenerator.GeneratedTask runningTask = sortedTaskSet.first();
long now = System.currentTimeMillis();
// System.out.println(" Looking at next task to complete: now=" +
// now + ", task's completion is " + runningTask.getRunUntilMillis());
if(runningTask.getRunUntilMillis()<=now) {
Iterator<RandomTaskGenerator.GeneratedTask> iterator = sortedTaskSet.iterator();
while(iterator.hasNext()) {
RandomTaskGenerator.GeneratedTask nextTask = iterator.next();
if(nextTask.getRunUntilMillis()>now)
return;
taskCompleter.call(nextTask);
iterator.remove();
}
}
}
catch (Exception e) {
e.printStackTrace();
}
}
},
delayMillis, delayMillis, TimeUnit.MILLISECONDS
);
}
}
| 9,119 |
0 | Create_ds/Fenzo/fenzo-core/src/test/java/com/netflix | Create_ds/Fenzo/fenzo-core/src/test/java/com/netflix/fenzo/ActiveVmGroupsTests.java | /*
* Copyright 2015 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.fenzo;
import com.netflix.fenzo.plugins.BinPackingFitnessCalculators;
import org.junit.Assert;
import org.apache.mesos.Protos;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import com.netflix.fenzo.functions.Action1;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
public class ActiveVmGroupsTests {
private static final String activeVmGrpAttrName = "ASG";
private static final String activeVmGrp = "test1";
private TaskScheduler taskScheduler;
private final Map<String, Protos.Attribute> attributes1 = new HashMap<>();
private final Map<String, Protos.Attribute> attributes2 = new HashMap<>();
@Before
public void setUp() throws Exception {
taskScheduler = new TaskScheduler.Builder()
.withLeaseOfferExpirySecs(1000000)
.withLeaseRejectAction(new Action1<VirtualMachineLease>() {
@Override
public void call(VirtualMachineLease virtualMachineLease) {
System.out.println("Rejecting offer on host " + virtualMachineLease.hostname());
}
})
.build();
taskScheduler.setActiveVmGroupAttributeName(activeVmGrpAttrName);
taskScheduler.setActiveVmGroups(Arrays.asList(activeVmGrp));
Protos.Attribute attribute1 = Protos.Attribute.newBuilder().setName(activeVmGrpAttrName)
.setType(Protos.Value.Type.TEXT)
.setText(Protos.Value.Text.newBuilder().setValue("test1")).build();
attributes1.put(activeVmGrpAttrName, attribute1);
Protos.Attribute attribute2 = Protos.Attribute.newBuilder().setName(activeVmGrpAttrName)
.setType(Protos.Value.Type.TEXT)
.setText(Protos.Value.Text.newBuilder().setValue("test2")).build();
attributes2.put(activeVmGrpAttrName, attribute2);
}
@After
public void tearDown() throws Exception {
}
@Test
public void testInactiveVmGroup() {
List<VirtualMachineLease.Range> ports = new ArrayList<>();
ports.add(new VirtualMachineLease.Range(1, 10));
List<VirtualMachineLease> leases = Collections.singletonList(LeaseProvider.getLeaseOffer("host1", 4, 4000, ports, attributes2));
List<TaskRequest> tasks = Collections.singletonList(TaskRequestProvider.getTaskRequest(1, 1000, 1));
Map<String, VMAssignmentResult> resultMap = taskScheduler.scheduleOnce(tasks, leases).getResultMap();
Assert.assertEquals(0, resultMap.size());
leases = Collections.singletonList(LeaseProvider.getLeaseOffer("host2", 4, 4000, ports, attributes1));
resultMap = taskScheduler.scheduleOnce(tasks, leases).getResultMap();
Assert.assertEquals(1, resultMap.size());
Assert.assertEquals(tasks.get(0).getId(), resultMap.values().iterator().next().getTasksAssigned().iterator().next().getTaskId());
}
@Test
public void testOffersRejectOnInactiveVMs() {
final Set<String> hostsSet = new HashSet<>();
for(int i=0; i<10; i++)
hostsSet.add("host"+i);
TaskScheduler ts = new TaskScheduler.Builder()
.withLeaseOfferExpirySecs(2)
.withLeaseRejectAction(new Action1<VirtualMachineLease>() {
@Override
public void call(VirtualMachineLease lease) {
hostsSet.remove(lease.hostname());
}
})
.build();
ts.setActiveVmGroupAttributeName(activeVmGrpAttrName);
ts.setActiveVmGroups(Arrays.asList(activeVmGrp));
List<VirtualMachineLease> leases = new ArrayList<>();
List<VirtualMachineLease.Range> ports = new ArrayList<>();
ports.add(new VirtualMachineLease.Range(1, 10));
for(String h: hostsSet) {
leases.add(LeaseProvider.getLeaseOffer(h, 4, 4000, ports, attributes2));
}
leases.add(LeaseProvider.getLeaseOffer("hostA", 4, 4000, ports, attributes1));
leases.add(LeaseProvider.getLeaseOffer("hostB", 4, 4000, ports, attributes1));
ts.scheduleOnce(Collections.EMPTY_LIST, leases);
for(int i=0; i< 3; i++) {
ts.scheduleOnce(Collections.EMPTY_LIST, Collections.EMPTY_LIST);
System.out.println("...");
try{Thread.sleep(1000);}catch(InterruptedException ie){}
}
System.out.println("Not rejected leases for " + hostsSet.size() + " hosts");
Assert.assertEquals(0, hostsSet.size());
}
@Test
public void testRandomizedOfferRejection() {
final Set<String> hostsSet = new HashSet<>();
final List<String> hostsToAdd = new ArrayList<>();
final List<VirtualMachineLease> leases = LeaseProvider.getLeases(10, 4, 4000, 1, 10);
TaskScheduler ts = new TaskScheduler.Builder()
.withLeaseOfferExpirySecs(2)
.withLeaseRejectAction(new Action1<VirtualMachineLease>() {
@Override
public void call(VirtualMachineLease virtualMachineLease) {
hostsSet.add(virtualMachineLease.hostname());
hostsToAdd.add(virtualMachineLease.hostname());
}
})
.build();
for(int i=0; i<9; i++) {
if(!hostsToAdd.isEmpty()) {
for(String h: hostsToAdd)
leases.add(LeaseProvider.getLeaseOffer(h, 4, 4000, 1, 10));
hostsToAdd.clear();
}
ts.scheduleOnce(Collections.EMPTY_LIST, leases);
leases.clear();
try{Thread.sleep(1000);}catch(InterruptedException ie){}
}
Assert.assertTrue(hostsSet.size()>2);
}
// Test that having two different asg types enabled and a task asking for larger #cpus, that only fits on one of the
// types, works when both asg types are enabled.
@Test
public void testActiveASGsOfTwoTypes() throws Exception {
TaskScheduler scheduler = new TaskScheduler.Builder()
.withFitnessCalculator(BinPackingFitnessCalculators.cpuMemBinPacker)
.withLeaseOfferExpirySecs(100000000)
.withLeaseRejectAction(new Action1<VirtualMachineLease>() {
@Override
public void call(VirtualMachineLease virtualMachineLease) {
Assert.fail("Unexpected to reject lease");
//System.out.println("Rejecting lease on " + virtualMachineLease.hostname());
}
})
.build();
scheduler.setActiveVmGroupAttributeName("ASG");
scheduler.setActiveVmGroups(Arrays.asList("8cores", "16cores"));
final List<VirtualMachineLease> leases = new ArrayList<>();
int nHosts8core=3;
int nHosts16core=1;
List<VirtualMachineLease.Range> ports = new ArrayList<>();
ports.add(new VirtualMachineLease.Range(1, 100));
Map<String, Protos.Attribute> attributes = new HashMap<>();
Protos.Attribute attribute = Protos.Attribute.newBuilder().setName("ASG")
.setType(Protos.Value.Type.TEXT)
.setText(Protos.Value.Text.newBuilder().setValue("8cores")).build();
attributes.put("ASG", attribute);
for(int l=0; l<nHosts8core; l++)
leases.add(LeaseProvider.getLeaseOffer("host"+l, 8, 32000, 1024.0, ports, attributes));
attributes = new HashMap<>();
Protos.Attribute attribute2 = Protos.Attribute.newBuilder().setName("ASG")
.setType(Protos.Value.Type.TEXT)
.setText(Protos.Value.Text.newBuilder().setValue("16cores")).build();
attributes.put("ASG", attribute2);
for(int l=0; l<nHosts16core; l++)
leases.add(LeaseProvider.getLeaseOffer("bighost" + l, 16, 64000, 1024.0, ports, attributes));
List<TaskRequest> tasks = Arrays.asList(TaskRequestProvider.getTaskRequest(1, 100, 1));
SchedulingResult schedulingResult = scheduler.scheduleOnce(tasks, leases);
Assert.assertEquals(1, schedulingResult.getResultMap().size());
System.out.println("result map #elements: " + schedulingResult.getResultMap().size());
Assert.assertEquals(0, schedulingResult.getFailures().size());
schedulingResult = scheduler.scheduleOnce(Arrays.asList(TaskRequestProvider.getTaskRequest(16, 1000, 1)), Collections.EMPTY_LIST);
Assert.assertEquals(1, schedulingResult.getResultMap().size());
System.out.println("result map #elements: " + schedulingResult.getResultMap().size());
Assert.assertEquals(0, schedulingResult.getFailures().size());
}
}
| 9,120 |
0 | Create_ds/Fenzo/fenzo-core/src/test/java/com/netflix | Create_ds/Fenzo/fenzo-core/src/test/java/com/netflix/fenzo/ShortfallAutoscalerTest.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.fenzo;
import com.netflix.fenzo.functions.Action0;
import com.netflix.fenzo.functions.Action1;
import com.netflix.fenzo.queues.QAttributes;
import com.netflix.fenzo.queues.QueuableTask;
import com.netflix.fenzo.queues.TaskQueue;
import com.netflix.fenzo.queues.TaskQueues;
import com.netflix.fenzo.queues.tiered.QueuableTaskProvider;
import org.apache.mesos.Protos;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
public class ShortfallAutoscalerTest {
private static String hostAttrName = "MachineType";
private static String activeVmAttrName = "asg";
private final int cpus1=4;
private final int cpus2=8;
private final int memMultiplier=1000;
private final int minIdle1 =1;
private final int maxIdle1 =1;
private final int minIdle2 =1;
private final int maxIdle2 =1;
private final int maxSize1=4;
private final int maxSize2=10;
private final long coolDownSecs=5;
private final String hostAttrVal1="4coreServers";
private final String asg1 = "asg1";
private final String hostAttrVal2="4cS2";
private final String asg2 = "asg2";
private final Map<String, Protos.Attribute> attributes1 = new HashMap<>();
private final Map<String, Protos.Attribute> attributes2 = new HashMap<>();
private final List<VirtualMachineLease.Range> ports = new ArrayList<>();
private final QAttributes qA1 = new QAttributes.QAttributesAdaptor(0, "bucketA");
private final QAttributes qA2 = new QAttributes.QAttributesAdaptor(0, "bucketB");
@Before
public void setUp() throws Exception {
Protos.Attribute attribute = Protos.Attribute.newBuilder().setName(hostAttrName)
.setType(Protos.Value.Type.TEXT)
.setText(Protos.Value.Text.newBuilder().setValue(hostAttrVal1)).build();
attributes1.put(hostAttrName, attribute);
Protos.Attribute activeAttr = Protos.Attribute.newBuilder().setName(activeVmAttrName)
.setType(Protos.Value.Type.TEXT)
.setText(Protos.Value.Text.newBuilder().setValue(asg1)).build();
attributes1.put(activeVmAttrName, activeAttr);
Protos.Attribute attribute2 = Protos.Attribute.newBuilder().setName(hostAttrName)
.setType(Protos.Value.Type.TEXT)
.setText(Protos.Value.Text.newBuilder().setValue(hostAttrVal2)).build();
attributes2.put(hostAttrName, attribute2);
Protos.Attribute activeAttr2 = Protos.Attribute.newBuilder().setName(activeVmAttrName)
.setType(Protos.Value.Type.TEXT)
.setText(Protos.Value.Text.newBuilder().setValue(asg2)).build();
attributes2.put(activeVmAttrName, activeAttr2);
ports.add(new VirtualMachineLease.Range(1, 100));
}
private TaskScheduler getScheduler(final Action1<VirtualMachineLease> leaseRejectAction, final Action1<AutoScaleAction> callback,
long delayScaleUpBySecs, long delayScaleDownByDecs,
AutoScaleRule... rules) {
return AutoScalerTest.getScheduler(leaseRejectAction, callback, delayScaleUpBySecs, delayScaleDownByDecs,
rules);
}
private TaskSchedulingService getSchedulingService(TaskQueue queue, Action0 preHook, TaskScheduler scheduler,
Action1<SchedulingResult> resultCallback) {
return new TaskSchedulingService.Builder()
.withLoopIntervalMillis(20)
.withMaxDelayMillis(100)
.withPreSchedulingLoopHook(preHook)
.withSchedulingResultCallback(resultCallback)
.withTaskQueue(queue)
.withTaskScheduler(scheduler)
.withOptimizingShortfallEvaluator()
.build();
}
@Test
public void testShortfallScaleUp1group() throws Exception {
testShortfallScaleUp1group(false);
}
@Test
public void testShortfallScaleUp1groupWithActiveVms() throws Exception {
testShortfallScaleUp1group(true);
}
private void testShortfallScaleUp1group(boolean useActiveVms) throws Exception {
final AutoScaleRule rule = AutoScaleRuleProvider.createRule(hostAttrVal1, minIdle1, maxIdle1, coolDownSecs*100,
1, 1000);
AtomicInteger scaleUpReceived = new AtomicInteger();
Action1<AutoScaleAction> callback = (action) -> {
if (action instanceof ScaleUpAction) {
final int scaleUpCount = ((ScaleUpAction) action).getScaleUpCount();
scaleUpReceived.addAndGet(scaleUpCount);
}
};
final List<String> rejectedHosts = new ArrayList<>();
TaskScheduler scheduler = getScheduler(l -> rejectedHosts.add(l.hostname()),
callback, 0, 0, rule);
if(useActiveVms) {
scheduler.setActiveVmGroupAttributeName(activeVmAttrName);
scheduler.setActiveVmGroups(Arrays.asList(asg1, asg2));
}
Action0 preHook = () -> {};
BlockingQueue<SchedulingResult> resultQ = new LinkedBlockingQueue<>();
TaskQueue queue = TaskQueues.createTieredQueue(1);
Action1<SchedulingResult> resultCallback = result -> {
final List<Exception> exceptions = result.getExceptions();
if (exceptions != null && !exceptions.isEmpty()) {
for (Exception e: exceptions)
e.printStackTrace();
Assert.fail("Exceptions in scheduling result");
} else {
final Map<TaskRequest, List<TaskAssignmentResult>> failures = result.getFailures();
if (failures != null && !failures.isEmpty()) {
printFailures(failures);
}
resultQ.offer(result);
}
};
final TaskSchedulingService schedulingService = getSchedulingService(
queue, preHook, scheduler, resultCallback);
final List<QueuableTask> requests = new ArrayList<>();
for(int i = 0; i<rule.getMaxIdleHostsToKeep()*8* cpus1; i++)
requests.add(QueuableTaskProvider.wrapTask(qA1, TaskRequestProvider .getTaskRequest(1, memMultiplier, 1)));
System.out.println("Created " + requests.size() + " tasks");
final List<VirtualMachineLease> leases = new ArrayList<>();
leases.add(LeaseProvider.getLeaseOffer("host1", cpus1, cpus1 * memMultiplier, ports, attributes1));
leases.add(LeaseProvider.getLeaseOffer("host2", cpus1, cpus1 * memMultiplier, ports, attributes1));
schedulingService.addLeases(leases);
for (QueuableTask t: requests) {
queue.queueTask(t);
}
schedulingService.start();
SchedulingResult result = resultQ.poll(1, TimeUnit.SECONDS);
Assert.assertNotNull("Timeout waiting for result", result);
Thread.sleep(500); // at least two times schedulingSvc maxIterDelay
Integer scaleUpNoticed = scaleUpReceived.getAndSet(0);
Assert.assertNotNull(scaleUpNoticed);
int expected = (requests.size() - (leases.size()* cpus1))/ cpus1;
Assert.assertEquals(expected, scaleUpNoticed.intValue());
requests.clear();
final int newRequests = rule.getMaxIdleHostsToKeep() * 3 * cpus1;
for(int i=0; i<newRequests; i++)
queue.queueTask(QueuableTaskProvider.wrapTask(qA1, TaskRequestProvider.getTaskRequest(1, 1000, 1)));
result = resultQ.poll(1, TimeUnit.SECONDS);
Assert.assertNotNull(result);
expected = newRequests;
expected /= cpus1;
Thread.sleep(500); // at least two times schedulingSvc maxIterDelay
scaleUpNoticed = scaleUpReceived.getAndSet(0);
Assert.assertEquals(expected, scaleUpNoticed.intValue());
if (!rejectedHosts.isEmpty()) {
for (String h: rejectedHosts) {
Assert.fail("Unexpected to reject lease on host " + h);
}
}
schedulingService.shutdown();
}
@Test
public void testShortfallScaleup2groups() throws Exception {
final AutoScaleRule rule1 = AutoScaleRuleProvider.createWithMaxSize(hostAttrVal1, minIdle1, maxIdle1, coolDownSecs,
1, 1000, maxSize1);
final AutoScaleRule rule2 = AutoScaleRuleProvider.createWithMaxSize(hostAttrVal2, minIdle2, maxIdle2, coolDownSecs,
1, 1000, maxSize2);
BlockingQueue<Map<String, Integer>> scaleupActionsQ = new LinkedBlockingQueue<>();
Action1<AutoScaleAction> callback = (action) -> {
if (action instanceof ScaleUpAction) {
scaleupActionsQ.offer(Collections.singletonMap(action.getRuleName(),
((ScaleUpAction) action).getScaleUpCount()));
}
};
TaskScheduler scheduler = getScheduler(AutoScalerTest.noOpLeaseReject, callback,
0, 0, rule1, rule2);
Action0 preHook = () -> {};
BlockingQueue<SchedulingResult> resultQ = new LinkedBlockingQueue<>();
TaskQueue queue = TaskQueues.createTieredQueue(1);
// create 3 VMs for group1 and 1 VM for group2
int hostIdx=0;
final List<VirtualMachineLease> leases = new ArrayList<>();
leases.add(LeaseProvider.getLeaseOffer("host" + hostIdx++, cpus1, cpus1 * memMultiplier,
0, 0, ports, attributes1, Collections.singletonMap("GPU", 1.0)));
leases.add(LeaseProvider.getLeaseOffer("host" + hostIdx++, cpus1, cpus1 * memMultiplier,
0, 0, ports, attributes1, Collections.singletonMap("GPU", 1.0)));
leases.add(LeaseProvider.getLeaseOffer("host" + hostIdx++, cpus1, cpus1 * memMultiplier,
0, 0, ports, attributes1, Collections.singletonMap("GPU", 1.0)));
leases.add(LeaseProvider.getLeaseOffer("host" + hostIdx++, cpus2, cpus2 * memMultiplier,
0, 0, ports, attributes2, Collections.singletonMap("GPU", 2.0)));
// create 1-cpu tasks to fill VMS equal to two times the max size of group1, and also group2
for (int i=0; i < (cpus1*rule1.getMaxSize() + cpus2* rule2.getMaxSize()); i++) {
queue.queueTask(QueuableTaskProvider.wrapTask(qA1, TaskRequestProvider.getTaskRequest(1, memMultiplier, 1)));
queue.queueTask(QueuableTaskProvider.wrapTask(qA2, TaskRequestProvider.getTaskRequest(1, memMultiplier, 1)));
}
// setup scheduling service
Action1<SchedulingResult> resultCallback = result -> {
final List<Exception> exceptions = result.getExceptions();
if (exceptions != null && !exceptions.isEmpty()) {
for (Exception e: exceptions)
e.printStackTrace();
Assert.fail("Exceptions in scheduling result");
} else {
final Map<TaskRequest, List<TaskAssignmentResult>> failures = result.getFailures();
if (failures != null && !failures.isEmpty()) {
printFailures(failures);
}
resultQ.offer(result);
}
};
final TaskSchedulingService schedulingService = getSchedulingService(
queue, preHook, scheduler, resultCallback);
// wait for scheduling result
schedulingService.addLeases(leases);
schedulingService.start();
final SchedulingResult result = resultQ.poll(1, TimeUnit.SECONDS);
Assert.assertNotNull(result);
Assert.assertEquals(3*cpus1 + cpus2, getNumTasksAssigned(result));
// wait for scale up actions
int waitingFor = 2;
while (waitingFor > 0) {
final Map<String, Integer> map = scaleupActionsQ.poll(1, TimeUnit.SECONDS);
Assert.assertNotNull(map);
for (Map.Entry<String, Integer> entry: map.entrySet()) {
waitingFor--;
switch (entry.getKey()) {
case hostAttrVal1:
Assert.assertEquals(rule1.getMaxSize() - 3, entry.getValue().intValue());
break;
case hostAttrVal2:
Assert.assertEquals(rule2.getMaxSize() - 1, entry.getValue().intValue());
break;
default:
Assert.fail("Unknown scale up group: " + entry.getKey() + " for " + entry.getValue() + " VMs");
}
}
}
schedulingService.shutdown();
}
private int getNumTasksAssigned(SchedulingResult result) {
if (result == null)
return 0;
final Map<String, VMAssignmentResult> resultMap = result.getResultMap();
if (resultMap == null || resultMap.isEmpty())
return 0;
int n=0;
for (VMAssignmentResult r: resultMap.values())
n += r.getTasksAssigned().size();
return n;
}
private void printFailures(Map<TaskRequest, List<TaskAssignmentResult>> failures) {
// for (Map.Entry<TaskRequest, List<TaskAssignmentResult>> entry: failures.entrySet()) {
// System.out.println("************** Failures for task " + entry.getKey().getId());
// for (TaskAssignmentResult r: entry.getValue())
// for (AssignmentFailure f: r.getFailures())
// System.out.println("*************** " + r.getHostname() + "::" + f.toString());
// }
}
}
| 9,121 |
0 | Create_ds/Fenzo/fenzo-core/src/test/java/com/netflix | Create_ds/Fenzo/fenzo-core/src/test/java/com/netflix/fenzo/SpreadingSchedulerTests.java | /*
* Copyright 2015 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.fenzo;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import com.netflix.fenzo.plugins.SpreadingFitnessCalculators;
import org.junit.Assert;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class SpreadingSchedulerTests {
private static final Logger logger = LoggerFactory.getLogger(SpreadingSchedulerTests.class);
private TaskScheduler getScheduler(VMTaskFitnessCalculator fitnessCalculator) {
return new TaskScheduler.Builder()
.withFitnessCalculator(fitnessCalculator)
.withLeaseOfferExpirySecs(1000000)
.withLeaseRejectAction(virtualMachineLease -> logger.info("Rejecting lease on " + virtualMachineLease.hostname()))
.build();
}
/**
* Tests whether or not the tasks will be spread out across the hosts based on cpu such that each host has a single task.
*/
@Test
public void testCPUBinPackingWithSeveralHosts() {
testBinPackingWithSeveralHosts("CPU");
}
/**
* Tests whether or not the tasks will be spread out across the hosts based on memory such that each host has a single task.
*/
@Test
public void testMemoryBinPackingWithSeveralHosts() {
testBinPackingWithSeveralHosts("Memory");
}
/**
* Tests whether or not the tasks will be spread out across the hosts based on network such that each host has a single task.
*/
@Test
public void testNetworkBinPackingWithSeveralHosts() {
testBinPackingWithSeveralHosts("Network");
}
private void testBinPackingWithSeveralHosts(String resource) {
TaskScheduler scheduler = null;
switch (resource) {
case "CPU":
scheduler = getScheduler(SpreadingFitnessCalculators.cpuSpreader);
break;
case "Memory":
scheduler = getScheduler(SpreadingFitnessCalculators.memorySpreader);
break;
case "Network":
scheduler = getScheduler(SpreadingFitnessCalculators.networkSpreader);
break;
default:
Assert.fail("Unknown resource type " + resource);
}
double cpuCores = 4;
double memory = 1024;
double network = 1024;
int numberOfInstances = 10;
List<VirtualMachineLease> leases = LeaseProvider.getLeases(numberOfInstances, cpuCores, memory, network, 1, 100);
List<TaskRequest> taskRequests = new ArrayList<>();
for (int i = 0; i < numberOfInstances; i++) {
taskRequests.add(TaskRequestProvider.getTaskRequest(1, 256, 256, 0));
}
Map<String, VMAssignmentResult> resultMap = scheduler.scheduleOnce(taskRequests, leases).getResultMap();
Assert.assertEquals(resultMap.size(), numberOfInstances);
Map<String, Long> assignmentCountPerHost = resultMap.values().stream().collect(Collectors.groupingBy(
VMAssignmentResult::getHostname, Collectors.counting()));
boolean duplicates = assignmentCountPerHost.entrySet().stream().anyMatch(e -> e.getValue() > 1);
Assert.assertEquals(duplicates, false);
}
}
| 9,122 |
0 | Create_ds/Fenzo/fenzo-core/src/test/java/com/netflix/fenzo | Create_ds/Fenzo/fenzo-core/src/test/java/com/netflix/fenzo/plugins/BalancedScaleDownConstraintEvaluatorTest.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.fenzo.plugins;
import com.netflix.fenzo.ScaleDownConstraintEvaluator.Result;
import com.netflix.fenzo.VirtualMachineLease;
import org.junit.Test;
import java.util.Map;
import java.util.Optional;
import static com.netflix.fenzo.plugins.TestableVirtualMachineLease.leaseWithId;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
public class BalancedScaleDownConstraintEvaluatorTest {
private BalancedScaleDownConstraintEvaluator evaluator;
@Test
public void testBalancing() throws Exception {
evaluator = new BalancedScaleDownConstraintEvaluator(
this::keyExtractor, 0.5, 0.1
);
Optional<Map<String, Integer>> context = evaluateAndVerify(leaseWithId("l1"), Optional.empty(), 0.5);
evaluateAndVerify(leaseWithId("l2"), context, 0.6);
evaluateAndVerify(leaseWithId("l3"), context, 0.65);
evaluateAndVerify(leaseWithId("l4"), context, 0.675);
}
private String keyExtractor(VirtualMachineLease lease) {
return "myZone";
}
private Optional<Map<String, Integer>> evaluateAndVerify(VirtualMachineLease lease,
Optional<Map<String, Integer>> context,
double expectedScore) {
Result<Map<String, Integer>> result = evaluator.evaluate(lease, context);
assertThat(result.getScore(), is(equalTo(expectedScore)));
return result.getContext();
}
} | 9,123 |
0 | Create_ds/Fenzo/fenzo-core/src/test/java/com/netflix/fenzo | Create_ds/Fenzo/fenzo-core/src/test/java/com/netflix/fenzo/plugins/TestableVirtualMachineLease.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.fenzo.plugins;
import com.netflix.fenzo.VirtualMachineLease;
import org.apache.mesos.Protos;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
public class TestableVirtualMachineLease implements VirtualMachineLease {
private final String id;
private TestableVirtualMachineLease(String id) {
this.id = id;
}
@Override
public String getId() {
return id;
}
@Override
public long getOfferedTime() {
return 0;
}
@Override
public String hostname() {
return null;
}
@Override
public String getVMID() {
return null;
}
@Override
public double cpuCores() {
return 0;
}
@Override
public double memoryMB() {
return 0;
}
@Override
public double networkMbps() {
return 0;
}
@Override
public double diskMB() {
return 0;
}
@Override
public List<Range> portRanges() {
return null;
}
@Override
public Protos.Offer getOffer() {
return null;
}
@Override
public Map<String, Protos.Attribute> getAttributeMap() {
return null;
}
@Override
public Double getScalarValue(String name) {
return null;
}
@Override
public Map<String, Double> getScalarValues() {
return null;
}
public static TestableVirtualMachineLease leaseWithId(String id) {
return new TestableVirtualMachineLease(id);
}
public static List<VirtualMachineLease> leasesWithIds(String... ids) {
List<VirtualMachineLease> leases = new ArrayList<>(ids.length);
for (String id : ids) {
leases.add(new TestableVirtualMachineLease(id));
}
return leases;
}
}
| 9,124 |
0 | Create_ds/Fenzo/fenzo-core/src/test/java/com/netflix/fenzo | Create_ds/Fenzo/fenzo-core/src/test/java/com/netflix/fenzo/plugins/WeightedAverageFitnessCalculatorTest.java | package com.netflix.fenzo.plugins;
import java.util.Arrays;
import java.util.List;
import com.netflix.fenzo.TaskRequest;
import com.netflix.fenzo.TaskTrackerState;
import com.netflix.fenzo.VMTaskFitnessCalculator;
import com.netflix.fenzo.VirtualMachineCurrentState;
import com.netflix.fenzo.plugins.WeightedAverageFitnessCalculator.WeightedFitnessCalculator;
import org.junit.Assert;
import org.junit.Test;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
public class WeightedAverageFitnessCalculatorTest {
@Test(expected = IllegalArgumentException.class)
public void testWeightsMustEqualOne() throws Exception {
VMTaskFitnessCalculator fitnessCalculator = mock(VMTaskFitnessCalculator.class);
List<WeightedFitnessCalculator> weightedFitnessCalculators = Arrays.asList(
new WeightedFitnessCalculator(fitnessCalculator, 0.3),
new WeightedFitnessCalculator(fitnessCalculator, 0.75)
);
new WeightedAverageFitnessCalculator(weightedFitnessCalculators);
}
@Test
public void testCalculatorWeightedAverage() throws Exception {
VMTaskFitnessCalculator fitnessCalculator1 = mock(VMTaskFitnessCalculator.class);
when(fitnessCalculator1.calculateFitness(any(), any(), any())).thenReturn(0.5);
VMTaskFitnessCalculator fitnessCalculator2 = mock(VMTaskFitnessCalculator.class);
when(fitnessCalculator2.calculateFitness(any(), any(), any())).thenReturn(1.0);
List<WeightedFitnessCalculator> weightedFitnessCalculators = Arrays.asList(
new WeightedFitnessCalculator(fitnessCalculator1, 0.5),
new WeightedFitnessCalculator(fitnessCalculator2, 0.5)
);
WeightedAverageFitnessCalculator calculator = new WeightedAverageFitnessCalculator(weightedFitnessCalculators);
double fitness = calculator.calculateFitness(mock(TaskRequest.class), mock(VirtualMachineCurrentState.class), mock(TaskTrackerState.class));
Assert.assertEquals(0.75, fitness, 0.0);
}
@Test
public void testCalculatorWeightedAverageWithZero() throws Exception {
VMTaskFitnessCalculator fitnessCalculator1 = mock(VMTaskFitnessCalculator.class);
when(fitnessCalculator1.calculateFitness(any(), any(), any())).thenReturn(0.0);
VMTaskFitnessCalculator fitnessCalculator2 = mock(VMTaskFitnessCalculator.class);
when(fitnessCalculator2.calculateFitness(any(), any(), any())).thenReturn(1.0);
List<WeightedFitnessCalculator> weightedFitnessCalculators = Arrays.asList(
new WeightedFitnessCalculator(fitnessCalculator1, 0.3),
new WeightedFitnessCalculator(fitnessCalculator2, 0.7)
);
WeightedAverageFitnessCalculator calculator = new WeightedAverageFitnessCalculator(weightedFitnessCalculators);
double fitness = calculator.calculateFitness(mock(TaskRequest.class), mock(VirtualMachineCurrentState.class), mock(TaskTrackerState.class));
Assert.assertEquals(0.0, fitness, 0.0);
}
} | 9,125 |
0 | Create_ds/Fenzo/fenzo-core/src/test/java/com/netflix/fenzo/queues | Create_ds/Fenzo/fenzo-core/src/test/java/com/netflix/fenzo/queues/tiered/TieredQueueSlasTest.java | package com.netflix.fenzo.queues.tiered;
import org.junit.Test;
import java.util.Map;
import static com.netflix.fenzo.queues.tiered.SampleDataGenerator.createResAllocs;
import static com.netflix.fenzo.sla.ResAllocsUtil.hasEqualResources;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
public class TieredQueueSlasTest {
private static final String BUCKET_0 = "bucket#0";
private static final String BUCKET_1 = "bucket#1";
private final SampleDataGenerator generator = new SampleDataGenerator()
.addTier(0, createResAllocs(8))
.addBucket(0, BUCKET_0, createResAllocs(4))
.addBucket(0, BUCKET_1, createResAllocs(4));
@Test
public void testSlas() throws Exception {
Map<Integer, TierSla> slas = new TieredQueueSlas(generator.getTierCapacities(), generator.getBucketCapacities()).getSlas();
assertThat(slas.size(), is(equalTo(1)));
TierSla tier0Sla = slas.get(0);
assertThat(hasEqualResources(tier0Sla.getTierCapacity(), createResAllocs(8)), is(true));
assertThat(hasEqualResources(tier0Sla.getBucketAllocs(BUCKET_0), createResAllocs(4)), is(true));
assertThat(tier0Sla.evalAllocationShare(BUCKET_0), is(equalTo(0.5)));
}
} | 9,126 |
0 | Create_ds/Fenzo/fenzo-core/src/test/java/com/netflix/fenzo/queues | Create_ds/Fenzo/fenzo-core/src/test/java/com/netflix/fenzo/queues/tiered/QueueBucketTest.java | package com.netflix.fenzo.queues.tiered;
import com.netflix.fenzo.queues.QueuableTask;
import com.netflix.fenzo.queues.UsageTrackedQueue.ResUsage;
import com.netflix.fenzo.sla.ResAllocs;
import com.netflix.fenzo.sla.ResAllocsBuilder;
import org.junit.Test;
import java.util.function.BiFunction;
import static com.netflix.fenzo.sla.ResAllocsUtil.hasEqualResources;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
import static org.mockito.ArgumentMatchers.anyInt;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
public class QueueBucketTest {
private static final String BUCKET_NAME = "bucket#0";
private final SampleDataGenerator generator = new SampleDataGenerator();
private final QueuableTask smallTask = generator.createTask(
new ResAllocsBuilder(BUCKET_NAME).withCores(1).withMemory(1).withDisk(1).withNetworkMbps(1).build()
);
private final ResUsage tierUsage = new ResUsage();
private final BiFunction<Integer, String, Double> allocsShareGetter = mock(BiFunction.class);
private final QueueBucket queueBucket = new QueueBucket(0, BUCKET_NAME, tierUsage, allocsShareGetter);
@Test
public void testBucketGuaranteesAffectEffectiveUsageComputation() throws Exception {
ResAllocs bucketCapacity = generator.createResAllocs(BUCKET_NAME, 2);
queueBucket.setBucketGuarantees(bucketCapacity);
// No usage
assertThat(hasEqualResources(queueBucket.getEffectiveUsage(), bucketCapacity), is(true));
assertThat(queueBucket.hasGuaranteedCapacityFor(smallTask), is(true));
// Half usage
queueBucket.launchTask(generator.createTask(generator.createResAllocs("task#0", 1)));
assertThat(hasEqualResources(queueBucket.getEffectiveUsage(), bucketCapacity), is(true));
assertThat(queueBucket.hasGuaranteedCapacityFor(smallTask), is(true));
// Full bucket usage
queueBucket.launchTask(generator.createTask(generator.createResAllocs("task#1", 1)));
assertThat(hasEqualResources(queueBucket.getEffectiveUsage(), bucketCapacity), is(true));
assertThat(queueBucket.hasGuaranteedCapacityFor(smallTask), is(false));
// Above bucket usage
queueBucket.launchTask(generator.createTask(generator.createResAllocs("task#2", 1)));
assertThat(hasEqualResources(queueBucket.getEffectiveUsage(), generator.createResAllocs(3)), is(true));
assertThat(queueBucket.hasGuaranteedCapacityFor(smallTask), is(false));
}
@Test
public void testDominantUsageShare() throws Exception {
when(allocsShareGetter.apply(anyInt(), anyString())).thenReturn(1.0);
tierUsage.addUsage(generator.createTask(generator.createResAllocs(4)));
// Half-fill the bucket, so share == 1/4 of current tier usage
ResAllocs bucketCapacity = generator.createResAllocs(BUCKET_NAME, 2);
queueBucket.setBucketGuarantees(bucketCapacity);
QueuableTask task = generator.createTask(generator.createResAllocs("task#0", 1));
queueBucket.launchTask(task);
assertThat(queueBucket.getDominantUsageShare(), is(equalTo(0.25)));
// Set tier capacity explicitly to be twice as much as its current usage
queueBucket.setTotalResources(generator.createResAllocs(8));
assertThat(queueBucket.getDominantUsageShare(), is(equalTo(0.125)));
}
}
| 9,127 |
0 | Create_ds/Fenzo/fenzo-core/src/test/java/com/netflix/fenzo/queues | Create_ds/Fenzo/fenzo-core/src/test/java/com/netflix/fenzo/queues/tiered/SortedBucketsTest.java | /*
* Copyright 2016 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.fenzo.queues.tiered;
import com.netflix.fenzo.TaskRequestProvider;
import com.netflix.fenzo.queues.QAttributes;
import com.netflix.fenzo.queues.QueuableTask;
import com.netflix.fenzo.queues.UsageTrackedQueue;
import org.junit.Assert;
import org.junit.Test;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
public class SortedBucketsTest {
@Test
public void testSorting() throws Exception {
UsageTrackedQueue.ResUsage parentUsage = new UsageTrackedQueue.ResUsage();
QAttributes tier1bktA = new QAttributes.QAttributesAdaptor(1, "Parent");
parentUsage.addUsage(QueuableTaskProvider.wrapTask(tier1bktA, TaskRequestProvider.getTaskRequest(100, 1000, 100)));
SortedBuckets sortedBuckets = new SortedBuckets(parentUsage);
final QueueBucket a = new QueueBucket(1, "A", parentUsage, null);
final QAttributes attrA = new QAttributes.QAttributesAdaptor(1, "A");
a.launchTask(QueuableTaskProvider.wrapTask(attrA, TaskRequestProvider.getTaskRequest(10, 100, 10)));
sortedBuckets.add(a);
final QueueBucket b = new QueueBucket(1, "B", parentUsage, null);
final QAttributes attrB = new QAttributes.QAttributesAdaptor(1, "B");
b.launchTask(QueuableTaskProvider.wrapTask(attrB, TaskRequestProvider.getTaskRequest(20, 200, 20)));
sortedBuckets.add(b);
final QueueBucket c = new QueueBucket(1, "C", parentUsage, null);
final QAttributes attrC = new QAttributes.QAttributesAdaptor(1, "C");
c.launchTask(QueuableTaskProvider.wrapTask(attrC, TaskRequestProvider.getTaskRequest(15, 150, 15)));
sortedBuckets.add(c);
final QueueBucket d = new QueueBucket(1, "D", parentUsage, null);
final QAttributes attrD = new QAttributes.QAttributesAdaptor(1, "D");
d.launchTask(QueuableTaskProvider.wrapTask(attrD, TaskRequestProvider.getTaskRequest(10, 100, 10)));
sortedBuckets.add(d);
final List<QueueBucket> sortedList = sortedBuckets.getSortedList();
QueueBucket prev = sortedList.get(0);
for (int i = 1; i < sortedList.size(); i++) {
Assert.assertTrue(prev.getDominantUsageShare() <= sortedList.get(i).getDominantUsageShare());
prev = sortedList.get(i);
}
}
@Test
public void testDominantResourceUsageRebalancing() throws Exception {
TieredQueue queue = new TieredQueue(3);
QAttributes bucketA = new QAttributes.QAttributesAdaptor(0, "A");
QAttributes bucketB = new QAttributes.QAttributesAdaptor(0, "B");
QAttributes bucketC = new QAttributes.QAttributesAdaptor(0, "C");
QueuableTask taskA = QueuableTaskProvider.wrapTask(bucketA, TaskRequestProvider.getTaskRequest(2, 1, 0));
QueuableTask taskB = QueuableTaskProvider.wrapTask(bucketB, TaskRequestProvider.getTaskRequest(1, 10, 0));
QueuableTask taskC = QueuableTaskProvider.wrapTask(bucketC, TaskRequestProvider.getTaskRequest(1, 20, 0));
queue.queueTask(taskA);
queue.queueTask(taskB);
queue.getUsageTracker().launchTask(taskA);
queue.getUsageTracker().launchTask(taskB);
// Adding this task breaks buckets queue ordering
queue.queueTask(taskC);
queue.getUsageTracker().launchTask(taskC);
// Now add another task to bucket A - this would trigger an exception if sorting order is incorrect,
// as was observed due to a previous bug
QueuableTask taskA2 = QueuableTaskProvider.wrapTask(bucketA, TaskRequestProvider.getTaskRequest(2, 1, 0));
queue.queueTask(taskA2);
queue.getUsageTracker().launchTask(taskA2);
}
public static void main(String[] args) {
List<Integer> list = Arrays.asList(10, 20, 30, 40, 50, 60);
Comparator<Integer> comparator = new Comparator<Integer>() {
@Override
public int compare(Integer o1, Integer o2) {
return o1.compareTo(o2);
}
};
System.out.println("Inserting 15 at " + Collections.binarySearch(list, 15, comparator));
System.out.println("Inserting 25 at " + Collections.binarySearch(list, 25, comparator));
System.out.println("Inserting 65 at " + Collections.binarySearch(list, 65, comparator));
System.out.println("Inserting 5 at " + Collections.binarySearch(list, 5, comparator));
System.out.println("Inserting 20 at " + Collections.binarySearch(list, 20, comparator));
}
} | 9,128 |
0 | Create_ds/Fenzo/fenzo-core/src/test/java/com/netflix/fenzo/queues | Create_ds/Fenzo/fenzo-core/src/test/java/com/netflix/fenzo/queues/tiered/TierTest.java | package com.netflix.fenzo.queues.tiered;
import com.netflix.fenzo.queues.Assignable;
import com.netflix.fenzo.queues.QueuableTask;
import com.netflix.fenzo.queues.TaskQueueException;
import com.netflix.fenzo.sla.ResAllocs;
import org.junit.Before;
import org.junit.Test;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.function.BiFunction;
import static com.netflix.fenzo.queues.tiered.SampleDataGenerator.createResAllocs;
import static org.hamcrest.CoreMatchers.*;
import static org.junit.Assert.assertThat;
import static org.mockito.ArgumentMatchers.anyInt;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
public class TierTest {
private static final String BUCKET_0 = "bucket#0";
private static final String BUCKET_1 = "bucket#1";
private static final String UNUSED_BUCKET = "unusedBucket";
private static final String BEST_EFFORT_BUCKET = "bestEffortBucket";
private final SampleDataGenerator generator = new SampleDataGenerator()
.addTier(0, createResAllocs(10))
.addBucket(0, BUCKET_0, createResAllocs(2))
.addBucket(0, BUCKET_1, createResAllocs(4))
.addBucket(0, UNUSED_BUCKET, createResAllocs(4));
private final BiFunction<Integer, String, Double> allocsShareGetter = mock(BiFunction.class);
private final Tier tier = new Tier(0, allocsShareGetter);
@Before
public void setUp() throws Exception {
when(allocsShareGetter.apply(anyInt(), anyString())).thenReturn(1.0);
tier.setTierSla(generator.getTierSla(0));
}
@Test
public void testTaskAreLaunchedInCorrectOrder() throws Exception {
List<String> queue0Tasks = queue(5, createResAllocs(BUCKET_0, 1));
List<String> queue1Tasks = queue(5, createResAllocs(BUCKET_1, 1));
Set<String> scheduledTasks = new HashSet<>();
for (int i = 0; i < 10; i++) {
Assignable<QueuableTask> taskOrFailure = tier.nextTaskToLaunch();
if (!taskOrFailure.hasFailure()) {
QueuableTask next = taskOrFailure.getTask();
scheduledTasks.add(next.getId());
tier.assignTask(next);
}
}
Set<String> expected = new HashSet<>();
expected.addAll(queue0Tasks.subList(0, 2));
expected.addAll(queue1Tasks.subList(0, 4));
assertThat(scheduledTasks, is(equalTo(expected)));
// Anything left is kept for the guaranteed capacity
assertThat(tier.nextTaskToLaunch(), is(nullValue()));
}
@Test
public void testTasksInQueueWithoutSlaConsumeRemainingCapacityOnly() throws Exception {
// Add extra capacity
generator.updateTier(0, createResAllocs(12));
tier.setTierSla(generator.getTierSla(0));
// Take as much as you can for best effort tasks
queue(10, createResAllocs(BEST_EFFORT_BUCKET, 1));
int counter = consumeAll();
assertThat(counter, is(equalTo(2)));
// Now schedule task from the guaranteed queue
tier.reset();
List<String> queue0Tasks = queue(5, createResAllocs(BUCKET_0, 1));
for (int i = 0; i < 2; i++) {
Assignable<QueuableTask> next = tier.nextTaskToLaunch();
assertThat(next, is(notNullValue()));
assertThat(next.hasFailure(), is(false));
assertThat(queue0Tasks.contains(next.getTask().getId()), is(true));
tier.assignTask(next.getTask());
}
}
/**
* If a queue is removed, and it had SLA defined, we should no longer consider it. As a result a remaining/left
* over capacity should be increased by this amount.
*/
@Test
public void testRemovingQueueWithGuaranteesReleasesItsResources() throws Exception {
queue(10, createResAllocs(BEST_EFFORT_BUCKET, 1));
// No spare capacity == nothing queued
assertThat(consumeAll(), is(equalTo(0)));
// Release bucket
generator.removeBucket(0, BUCKET_0);
tier.setTierSla(generator.getTierSla(0));
tier.reset();
assertThat(consumeAll(), is(equalTo(2)));
}
private List<String> queue(int numberOfTasks, ResAllocs resAllocs) throws TaskQueueException {
List<String> taskids = new ArrayList<>(numberOfTasks);
for (int i = 0; i < numberOfTasks; i++) {
QueuableTask task = generator.createTask(resAllocs);
tier.queueTask(task);
taskids.add(task.getId());
}
return taskids;
}
private int consumeAll() throws TaskQueueException {
int counter = 0;
Assignable<QueuableTask> taskOrFailure;
while ((taskOrFailure = tier.nextTaskToLaunch()) != null) {
if (!taskOrFailure.hasFailure()) {
tier.assignTask(taskOrFailure.getTask());
counter++;
}
}
return counter;
}
} | 9,129 |
0 | Create_ds/Fenzo/fenzo-core/src/test/java/com/netflix/fenzo/queues | Create_ds/Fenzo/fenzo-core/src/test/java/com/netflix/fenzo/queues/tiered/SampleDataGenerator.java | package com.netflix.fenzo.queues.tiered;
import com.netflix.fenzo.ConstraintEvaluator;
import com.netflix.fenzo.VMTaskFitnessCalculator;
import com.netflix.fenzo.queues.QAttributes;
import com.netflix.fenzo.queues.QueuableTask;
import com.netflix.fenzo.sla.ResAllocs;
import com.netflix.fenzo.sla.ResAllocsBuilder;
import com.netflix.fenzo.sla.ResAllocsUtil;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* Test data generator.
*/
public class SampleDataGenerator {
private int taskIdx;
private final Map<Integer, TierState> tiers = new HashMap<>();
public SampleDataGenerator addTier(int tierNumber, ResAllocs tierCapacity) {
tiers.put(tierNumber, new TierState(tierNumber, tierCapacity));
return this;
}
public SampleDataGenerator updateTier(int tier, ResAllocs tierCapacity) {
TierState tierState = tiers.get(tier);
if (tierState == null) {
throw new IllegalArgumentException("Tier " + tier + " not defined");
}
tierState.updateTer(tierCapacity);
return this;
}
public SampleDataGenerator addBucket(int tierNumber, String bucketName, ResAllocs bucketCapacity) {
TierState tierState = tiers.computeIfAbsent(tierNumber, k -> new TierState(tierNumber, ResAllocsUtil.empty()));
tierState.addBucket(bucketName, bucketCapacity);
return this;
}
public void removeBucket(int tierNumber, String bucketName) {
TierState tierState = tiers.get(tierNumber);
if (tierState == null) {
throw new IllegalArgumentException("Tier " + tierNumber + " not defined");
}
tierState.removeBucket(bucketName);
}
public static ResAllocs createResAllocs(int multiplier) {
return createResAllocs("anonymous", multiplier);
}
public static ResAllocs createResAllocs(String name, int multiplier) {
return new ResAllocsBuilder(name)
.withCores(1.0 * multiplier)
.withMemory(1024 * multiplier)
.withNetworkMbps(128 * multiplier)
.withDisk(32 * multiplier)
.build();
}
public QueuableTask createTask(ResAllocs taskAllocs) {
return new TestableQueuableTask(taskAllocs.getTaskGroupName(), taskAllocs.getCores(), taskAllocs.getMemory(),
taskAllocs.getNetworkMbps(), taskAllocs.getDisk()
);
}
public Map<Integer, ResAllocs> getTierCapacities() {
HashMap<Integer, ResAllocs> result = new HashMap<>();
tiers.forEach((tidx, state) -> result.put(tidx, state.getTierCapacity()));
return result;
}
public Map<Integer, Map<String, ResAllocs>> getBucketCapacities() {
HashMap<Integer, Map<String, ResAllocs>> result = new HashMap<>();
tiers.forEach((tidx, state) -> result.put(tidx, state.getBucketCapacities()));
return result;
}
public TierSla getTierSla(int tierNumber) {
TierSla tierSla = new TierSla();
TierState tierState = tiers.get(tierNumber);
tierSla.setTierCapacity(tierState.getTierCapacity());
tierState.getBucketCapacities().forEach(tierSla::setAlloc);
return tierSla;
}
public class TierState {
private final int tierNumber;
private ResAllocs tierCapacity;
private Map<String, ResAllocs> bucketCapacities;
private TierState(int tierNumber, ResAllocs tierCapacity) {
this.tierNumber = tierNumber;
this.tierCapacity = tierCapacity;
this.bucketCapacities = new HashMap<>();
}
public int getTierNumber() {
return tierNumber;
}
public ResAllocs getTierCapacity() {
return tierCapacity;
}
public Map<String, ResAllocs> getBucketCapacities() {
return bucketCapacities;
}
private void addBucket(String name, ResAllocs bucketCapacity) {
bucketCapacities.put(name, ResAllocsUtil.rename(name, bucketCapacity));
}
private void removeBucket(String bucketName) {
if (bucketCapacities.remove(bucketName) == null) {
throw new IllegalArgumentException("Unknown bucket " + bucketName);
}
}
private void updateTer(ResAllocs tierCapacity) {
this.tierCapacity = tierCapacity;
}
}
class TestableQueuableTask implements QueuableTask {
private final String id;
private final String taskGroupName;
private final double cpu;
private final double memory;
private final double networkMbps;
private final double disk;
private final QAttributes qAttributes;
private AssignedResources assignedResources;
TestableQueuableTask(String taskGroupName, double cpu, double memory, double networkMbps, double disk) {
this.id = "task#" + taskIdx++;
this.taskGroupName = taskGroupName;
this.cpu = cpu;
this.memory = memory;
this.networkMbps = networkMbps;
this.disk = disk;
this.qAttributes = new QAttributes() {
@Override
public String getBucketName() {
return taskGroupName;
}
@Override
public int getTierNumber() {
throw new IllegalStateException("method not supported");
}
};
}
@Override
public QAttributes getQAttributes() {
return qAttributes;
}
@Override
public String getId() {
return id;
}
@Override
public String taskGroupName() {
return taskGroupName;
}
@Override
public double getCPUs() {
return cpu;
}
@Override
public double getMemory() {
return memory;
}
@Override
public double getNetworkMbps() {
return networkMbps;
}
@Override
public double getDisk() {
return disk;
}
@Override
public int getPorts() {
return 0;
}
@Override
public Map<String, Double> getScalarRequests() {
return Collections.emptyMap();
}
@Override
public Map<String, NamedResourceSetRequest> getCustomNamedResources() {
return Collections.emptyMap();
}
@Override
public List<? extends ConstraintEvaluator> getHardConstraints() {
return Collections.emptyList();
}
@Override
public List<? extends VMTaskFitnessCalculator> getSoftConstraints() {
return Collections.emptyList();
}
@Override
public void setAssignedResources(AssignedResources assignedResources) {
this.assignedResources = assignedResources;
}
@Override
public AssignedResources getAssignedResources() {
return assignedResources;
}
}
}
| 9,130 |
0 | Create_ds/Fenzo/fenzo-core/src/test/java/com/netflix/fenzo/queues | Create_ds/Fenzo/fenzo-core/src/test/java/com/netflix/fenzo/queues/tiered/TieredQueueTest.java | /*
* Copyright 2016 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.fenzo.queues.tiered;
import com.netflix.fenzo.*;
import com.netflix.fenzo.functions.Action0;
import com.netflix.fenzo.functions.Action1;
import com.netflix.fenzo.queues.*;
import com.netflix.fenzo.TaskSchedulingService;
import com.netflix.fenzo.sla.ResAllocs;
import com.netflix.fenzo.sla.ResAllocsBuilder;
import org.junit.Assert;
import org.junit.Test;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;
import static java.util.Collections.singletonMap;
public class TieredQueueTest {
@Test
public void testAddingTasks() throws Exception {
InternalTaskQueue queue = new TieredQueue(3);
QAttributes tier1bktA = new QAttributes.QAttributesAdaptor(0, "A");
QAttributes tier1bktB = new QAttributes.QAttributesAdaptor(0, "B");
QAttributes tier2bktC = new QAttributes.QAttributesAdaptor(1, "C");
QAttributes tier2bktD = new QAttributes.QAttributesAdaptor(1, "D");
QAttributes tier3bktE = new QAttributes.QAttributesAdaptor(2, "E");
int tier1=3;
int tier2=3;
int tier3=1;
queue.queueTask(QueuableTaskProvider.wrapTask(tier1bktA, TaskRequestProvider.getTaskRequest(1, 100, 1)));
queue.queueTask(QueuableTaskProvider.wrapTask(tier1bktA, TaskRequestProvider.getTaskRequest(1, 100, 1)));
queue.queueTask(QueuableTaskProvider.wrapTask(tier1bktB, TaskRequestProvider.getTaskRequest(1, 100, 1)));
queue.queueTask(QueuableTaskProvider.wrapTask(tier2bktC, TaskRequestProvider.getTaskRequest(1, 100, 1)));
queue.queueTask(QueuableTaskProvider.wrapTask(tier2bktD, TaskRequestProvider.getTaskRequest(1, 100, 1)));
queue.queueTask(QueuableTaskProvider.wrapTask(tier2bktC, TaskRequestProvider.getTaskRequest(1, 100, 1)));
queue.queueTask(QueuableTaskProvider.wrapTask(tier3bktE, TaskRequestProvider.getTaskRequest(1, 100, 1)));
queue.reset();
Assignable<QueuableTask> taskOrFailure;
while ((taskOrFailure = (Assignable<QueuableTask>)queue.next()) != null) {
QueuableTask t = taskOrFailure.getTask();
switch (t.getQAttributes().getTierNumber()) {
case 0:
tier1--;
break;
case 1:
tier2--;
break;
case 2:
tier3--;
}
// System.out.println("id; " + t.getId() +
// ", tier: " + t.getQAttributes().getTierNumber() +
// ", bkt: " + t.getQAttributes().getBucketName()
// );
}
Assert.assertEquals(0, tier1);
Assert.assertEquals(0, tier2);
Assert.assertEquals(0, tier3);
}
@Test
public void testAddRunningTasks() throws Exception {
InternalTaskQueue queue = new TieredQueue(3);
QAttributes tier1bktA = new QAttributes.QAttributesAdaptor(0, "A");
QAttributes tier1bktB = new QAttributes.QAttributesAdaptor(0, "B");
QAttributes tier1bktC = new QAttributes.QAttributesAdaptor(0, "C");
final TaskScheduler scheduler = getScheduler();
final TaskSchedulingService schedulingService = getSchedulingService(queue, scheduler,
schedulingResult -> System.out.println("Got scheduling result with " +
schedulingResult.getResultMap().size() + " results"));
int A1=0;
int B1=0;
int C1=0;
for (int i=0; i<2; i++)
schedulingService.initializeRunningTask(
QueuableTaskProvider.wrapTask(tier1bktA, TaskRequestProvider.getTaskRequest(2, 2000, 1)),
"hostA"
);
for (int i=0; i<4; i++)
schedulingService.initializeRunningTask(
QueuableTaskProvider.wrapTask(tier1bktB, TaskRequestProvider.getTaskRequest(2, 2000, 1)),
"hostB"
);
for (int i=0; i<3; i++)
schedulingService.initializeRunningTask(
QueuableTaskProvider.wrapTask(tier1bktC, TaskRequestProvider.getTaskRequest(2, 2000, 1)),
"hostC"
);
for(int i=0; i<4; i++, A1++)
queue.queueTask(QueuableTaskProvider.wrapTask(tier1bktA, TaskRequestProvider.getTaskRequest(2, 2000, 1)));
for(int i=0; i<4; i++, B1++)
queue.queueTask(QueuableTaskProvider.wrapTask(tier1bktB, TaskRequestProvider.getTaskRequest(2, 2000, 1)));
for(int i=0; i<4; i++, C1++)
queue.queueTask(QueuableTaskProvider.wrapTask(tier1bktC, TaskRequestProvider.getTaskRequest(2, 2000, 1)));
queue.reset();
Assignable<QueuableTask> taskOrFailure;
while ((taskOrFailure = (Assignable<QueuableTask>)queue.next()) != null) {
QueuableTask t = taskOrFailure.getTask();
switch (t.getQAttributes().getBucketName()) {
case "A":
A1--;
break;
case "B":
B1--;
break;
case "C":
C1--;
break;
}
// System.out.println("id; " + t.getId() +
// ", tier: " + t.getQAttributes().getTierNumber() +
// ", bkt: " + t.getQAttributes().getBucketName()
// );
}
Assert.assertEquals(0, A1);
Assert.assertEquals(0, B1);
Assert.assertEquals(0, C1);
}
// Test weighted DRF across buckets of a tier when SLAs are given
// Set up 3 buckets and ensure that the resources (which are less than the total requested from all 3 buckets) are
// assigned to the buckets with the ratio equal to the ratio of the buckets' tier SLAs.
@Test
public void testTierSlas() throws Exception {
TaskQueue queue = new TieredQueue(2);
Map<String, Double> bucketWeights = new HashMap<>();
bucketWeights.put("A", 1.0);
bucketWeights.put("B", 2.0);
bucketWeights.put("C", 1.0);
queue.setSla(new TieredQueueSlas(Collections.emptyMap(), getTierAllocsForBuckets(bucketWeights)));
final AtomicInteger countA = new AtomicInteger();
final AtomicInteger countB = new AtomicInteger();
final AtomicInteger countC = new AtomicInteger();
final CountDownLatch latch = new CountDownLatch(40); // 40 1-cpu slots based on adding leases below
final TaskSchedulingService schedulingService = setupSchedSvcWithAssignmentCounters(queue, new AtomicReference<>(latch), countA, countB, countC);
// create 25 1-cpu tasks for each bucket
createTasksForBuckets(queue, 25, "A", "B", "C");
schedulingService.addLeases(LeaseProvider.getLeases(10, 4.0, 4000.0, 4000.0, 1, 100));
schedulingService.start();
Assert.assertTrue("Timeout waiting for assignments", latch.await(2, TimeUnit.SECONDS));
Thread.sleep(500); // Additional way due to race conditions
Assert.assertEquals(10, countA.get());
Assert.assertEquals(20, countB.get());
Assert.assertEquals(10, countC.get());
}
// Test that weighted DRF is maintained beyond initial assignments when tiered queue sla is modified.
// Set up 3 buckets, ensure that resources are assigned based on the tiered slas, similar to how it is done in
// another test, testTierSlas(). Then, change the queue slas to alter weights from A=1,B=2,C=1 to A=1,B=1,C=2.
// Add more tasks and agents such that there are more tasks from each bucket than can be assigned. Ensure weighted
// DRF now reflects the new weights.
@Test
public void testTierSlas2() throws Exception {
TaskQueue queue = new TieredQueue(2);
Map<String, Double> bucketWeights = new HashMap<>();
bucketWeights.put("A", 1.0);
bucketWeights.put("B", 2.0);
bucketWeights.put("C", 1.0);
ResAllocs tier1Capacity = new ResAllocsBuilder("tier#0")
.withCores(10 * 4)
.withMemory(10 * 4000)
.withNetworkMbps(10 * 4000)
.build();
queue.setSla(new TieredQueueSlas(singletonMap(1, tier1Capacity), getTierAllocsForBuckets(bucketWeights)));
final AtomicInteger countA = new AtomicInteger();
final AtomicInteger countB = new AtomicInteger();
final AtomicInteger countC = new AtomicInteger();
final CountDownLatch latch = new CountDownLatch(40);
final AtomicReference<CountDownLatch> latchRef = new AtomicReference<>(latch);
final TaskSchedulingService schedulingService = setupSchedSvcWithAssignmentCounters(queue, latchRef, countA, countB, countC);
// create 25 1-cpu tasks for each bucket
createTasksForBuckets(queue, 25, "A", "B", "C");
schedulingService.addLeases(LeaseProvider.getLeases(10, 4.0, 4000.0, 4000.0, 1, 100));
schedulingService.start();
Assert.assertTrue("Timeout waiting for assignments", latch.await(2, TimeUnit.SECONDS));
Thread.sleep(500); // Additional way due to race conditions
Assert.assertEquals(10, countA.get());
Assert.assertEquals(20, countB.get());
Assert.assertEquals(10, countC.get());
// change the weights
bucketWeights.clear();
bucketWeights.put("A", 1.0);
bucketWeights.put("B", 1.0);
bucketWeights.put("C", 2.0);
// Double the tier capacity
ResAllocs doubledTier1Capacity = new ResAllocsBuilder("tier#0")
.withCores(20 * 4)
.withMemory(20 * 4000)
.withNetworkMbps(20 * 4000)
.build();
queue.setSla(new TieredQueueSlas(singletonMap(0, doubledTier1Capacity), getTierAllocsForBuckets(bucketWeights)));
// reset latch to new one
latchRef.set(new CountDownLatch(40));
// reset counters
countA.set(0); countB.set(0); countC.set(0);
// create additional 25 1-cpu tasks each
createTasksForBuckets(queue, 25, "A", "B", "C");
// add new leases
schedulingService.addLeases(LeaseProvider.getLeases(10, 4.0, 4000.0, 4000.0, 1, 100));
Assert.assertTrue("Timeout waiting for assignments", latchRef.get().await(2, TimeUnit.SECONDS));
Thread.sleep(500); // Additional way due to race conditions
Assert.assertEquals(10, countA.get()); // total 20
Assert.assertEquals(0, countB.get()); // total 20
Assert.assertEquals(30, countC.get()); // total 40
}
// Test that weighted DRF is maintained correctly even when starting with a scheduler initialized with previously
// running tasks
@Test
public void testTierSlasWithPreviouslyRunningTasks() throws Exception {
TaskQueue queue = new TieredQueue(2);
Map<String, Double> bucketWeights = new HashMap<>();
bucketWeights.put("A", 1.0);
bucketWeights.put("B", 2.0);
bucketWeights.put("C", 1.0);
queue.setSla(new TieredQueueSlas(Collections.emptyMap(), getTierAllocsForBuckets(bucketWeights)));
final AtomicInteger countA = new AtomicInteger();
final AtomicInteger countB = new AtomicInteger();
final AtomicInteger countC = new AtomicInteger();
final CountDownLatch latch = new CountDownLatch(32);
final AtomicReference<CountDownLatch> latchRef = new AtomicReference<>(latch);
final TaskSchedulingService schedulingService = setupSchedSvcWithAssignmentCounters(queue, latchRef, countA, countB, countC);
initializeRunningTasksForBuckets(schedulingService, 5, "A");
initializeRunningTasksForBuckets(schedulingService, 3, "C");
createTasksForBuckets(queue, 25, "A", "B", "C");
schedulingService.addLeases(LeaseProvider.getLeases(8, 4.0, 4000.0, 4000.0, 1, 100));
schedulingService.start();
Assert.assertTrue("Timeout waiting for assignments", latchRef.get().await(2, TimeUnit.SECONDS));
Thread.sleep(500); // Additional way due to race conditions
Assert.assertEquals(10-5, countA.get());
Assert.assertEquals(20, countB.get());
Assert.assertEquals(10-3, countC.get());
}
@Test
public void testTierSlasWithOneBucketWithNoTasks() throws Exception {
TaskQueue queue = new TieredQueue(2);
Map<String, Double> bucketWeights = new HashMap<>();
bucketWeights.put("A", 1.0);
bucketWeights.put("B", 2.0);
bucketWeights.put("C", 1.0);
ResAllocs tier1Capacity = new ResAllocsBuilder("tier#0")
.withCores(70 * 4)
.withMemory(70 * 4000)
.withNetworkMbps(70 * 4000)
.build();
queue.setSla(new TieredQueueSlas(singletonMap(0, tier1Capacity), getTierAllocsForBuckets(bucketWeights)));
final AtomicInteger countA = new AtomicInteger();
final AtomicInteger countB = new AtomicInteger();
final AtomicInteger countC = new AtomicInteger();
final CountDownLatch latch = new CountDownLatch(40);
final AtomicReference<CountDownLatch> latchRef = new AtomicReference<>(latch);
final TaskSchedulingService schedulingService = setupSchedSvcWithAssignmentCounters(queue, latchRef, countA, countB, countC);
// create 25 1-cpu tasks for each bucket
createTasksForBuckets(queue, 25, "A", "C");
schedulingService.addLeases(LeaseProvider.getLeases(10, 4.0, 4000.0, 4000.0, 1, 100));
schedulingService.start();
Assert.assertTrue("Timeout waiting for assignments", latch.await(2, TimeUnit.SECONDS));
Thread.sleep(500); // Additional way due to race conditions
Assert.assertEquals(20, countA.get());
Assert.assertEquals(0, countB.get());
Assert.assertEquals(20, countC.get());
}
private void createTasksForBuckets(TaskQueue queue, int numTasks, String... bucketNames) {
for (String b: bucketNames) {
QAttributes tier1bkt = new QAttributes.QAttributesAdaptor(0, b);
for (int i = 0; i < numTasks; i++)
queue.queueTask(QueuableTaskProvider.wrapTask(tier1bkt, TaskRequestProvider.getTaskRequest(1, 100, 1)));
}
}
// initializes scheduling service with given number of tasks for each bucket name. Sets the host name for each running
// task to a random hostname.
private void initializeRunningTasksForBuckets(TaskSchedulingService schedulingService, int numTasks, String... bucketNames) {
Random r = new Random(System.currentTimeMillis());
for (String b: bucketNames) {
QAttributes tier1bkt = new QAttributes.QAttributesAdaptor(0, b);
for (int i = 0; i < numTasks; i++)
schedulingService.initializeRunningTask(
QueuableTaskProvider.wrapTask(tier1bkt, TaskRequestProvider.getTaskRequest(1, 100, 1)), "host" + r.nextInt());
}
}
// sets up scheduling service and increments counters for each bucket name, where names are assumed to
// upper case letters starting from A. That is, the first counter is incremented for A, 2nd for B, etc. The latch
// is counted down for each task assignment.
private TaskSchedulingService setupSchedSvcWithAssignmentCounters(TaskQueue queue, AtomicReference<CountDownLatch> latch, AtomicInteger... counters) {
return getSchedulingService(queue, getScheduler(),
result -> {
if (!result.getResultMap().isEmpty()) {
for (Map.Entry<String, VMAssignmentResult> entry: result.getResultMap().entrySet()) {
for (TaskAssignmentResult t: entry.getValue().getTasksAssigned()) {
latch.get().countDown();
int idx = ((QueuableTask) t.getRequest()).getQAttributes().getBucketName().charAt(0) - 'A';
counters[idx].incrementAndGet();
}
}
}
}
);
}
// Returns a map with key=tier number (only uses tier 0) and value of a map with keys=bucket names (A, B, and C),
// and values of ResAllocs. A has 10 cpus, B has 20 cpus, and C has 10 cpus. Memory, network and disk are 100x the
// the number of cpus.
private Map<Integer, Map<String, ResAllocs>> getTierAllocsForBuckets(Map<String, Double> bucketWeights) {
Map<Integer, Map<String, ResAllocs>> tierAllocs = new HashMap<>();
tierAllocs.put(0, new HashMap<>());
for (Map.Entry<String, Double> entry: bucketWeights.entrySet()) {
tierAllocs.get(0).put(entry.getKey(),
new ResAllocsBuilder(entry.getKey())
.withCores(10 * entry.getValue())
.withMemory(1000 * entry.getValue())
.withNetworkMbps(1000 * entry.getValue())
.withDisk(1000 * entry.getValue())
.build()
);
}
return tierAllocs;
}
private TaskSchedulingService getSchedulingService(TaskQueue queue, TaskScheduler scheduler,
Action1<SchedulingResult> resultCallback) {
return new TaskSchedulingService.Builder()
.withTaskQueue(queue)
.withLoopIntervalMillis(100L)
.withPreSchedulingLoopHook(new Action0() {
@Override
public void call() {
System.out.println("Pre-scheduling hook");
}
})
.withSchedulingResultCallback(resultCallback)
.withTaskScheduler(scheduler)
.build();
}
private TaskScheduler getScheduler() {
return new TaskScheduler.Builder()
.withLeaseOfferExpirySecs(1000000)
.withLeaseRejectAction(new Action1<VirtualMachineLease>() {
@Override
public void call(VirtualMachineLease virtualMachineLease) {
System.out.println("Rejecting offer on host " + virtualMachineLease.hostname());
}
})
.build();
}
} | 9,131 |
0 | Create_ds/Fenzo/fenzo-core/src/test/java/com/netflix/fenzo/queues | Create_ds/Fenzo/fenzo-core/src/test/java/com/netflix/fenzo/queues/tiered/QueuableTaskProvider.java | /*
* Copyright 2016 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.fenzo.queues.tiered;
import com.netflix.fenzo.ConstraintEvaluator;
import com.netflix.fenzo.TaskRequest;
import com.netflix.fenzo.VMTaskFitnessCalculator;
import com.netflix.fenzo.queues.QAttributes;
import com.netflix.fenzo.queues.QueuableTask;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicLong;
public class QueuableTaskProvider {
public static QueuableTask wrapTask(final QAttributes qAttributes, final TaskRequest taskRequest) {
final AtomicLong readyAt = new AtomicLong(0L);
return new QueuableTask() {
@Override
public QAttributes getQAttributes() {
return qAttributes;
}
@Override
public String getId() {
return taskRequest.getId();
}
@Override
public String taskGroupName() {
return taskRequest.taskGroupName();
}
@Override
public double getCPUs() {
return taskRequest.getCPUs();
}
@Override
public double getMemory() {
return taskRequest.getMemory();
}
@Override
public double getNetworkMbps() {
return taskRequest.getNetworkMbps();
}
@Override
public double getDisk() {
return taskRequest.getDisk();
}
@Override
public int getPorts() {
return taskRequest.getPorts();
}
@Override
public Map<String, Double> getScalarRequests() {
return taskRequest.getScalarRequests();
}
@Override
public Map<String, NamedResourceSetRequest> getCustomNamedResources() {
return taskRequest.getCustomNamedResources();
}
@Override
public List<? extends ConstraintEvaluator> getHardConstraints() {
return taskRequest.getHardConstraints();
}
@Override
public List<? extends VMTaskFitnessCalculator> getSoftConstraints() {
return taskRequest.getSoftConstraints();
}
@Override
public void setAssignedResources(AssignedResources assignedResources) {
taskRequest.setAssignedResources(assignedResources);
}
@Override
public AssignedResources getAssignedResources() {
return taskRequest.getAssignedResources();
}
@Override
public void safeSetReadyAt(long when) {
readyAt.set(when);
}
@Override
public long getReadyAt() {
return readyAt.get();
}
};
}
}
| 9,132 |
0 | Create_ds/Fenzo/fenzo-core/src/test/java/com/netflix/fenzo | Create_ds/Fenzo/fenzo-core/src/test/java/com/netflix/fenzo/sla/ResAllocsUtilTest.java | package com.netflix.fenzo.sla;
import com.netflix.fenzo.VMResource;
import com.netflix.fenzo.queues.QueuableTask;
import com.netflix.fenzo.queues.tiered.SampleDataGenerator;
import org.junit.Test;
import java.util.HashMap;
import java.util.Map;
import static com.netflix.fenzo.sla.ResAllocsUtil.hasEqualResources;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
public class ResAllocsUtilTest {
private final SampleDataGenerator generator = new SampleDataGenerator();
@Test
public void testAdd() throws Exception {
ResAllocs result = ResAllocsUtil.add(generator.createResAllocs(1), generator.createResAllocs(1));
assertThat(hasEqualResources(result, generator.createResAllocs(2)), is(true));
}
@Test
public void testSubtract() throws Exception {
ResAllocs result = ResAllocsUtil.subtract(generator.createResAllocs(2), generator.createResAllocs(1));
assertThat(hasEqualResources(result, generator.createResAllocs(1)), is(true));
}
@Test
public void testCeilingOf() throws Exception {
ResAllocs result = ResAllocsUtil.ceilingOf(
new ResAllocsBuilder("any").withCores(10).withMemory(20).withNetworkMbps(30).withDisk(40).build(),
new ResAllocsBuilder("any").withCores(5).withMemory(25).withNetworkMbps(15).withDisk(45).build()
);
assertThat(hasEqualResources(
new ResAllocsBuilder("any").withCores(10).withMemory(25).withNetworkMbps(30).withDisk(45).build(),
result
), is(true));
}
@Test
public void testIsBounded() throws Exception {
ResAllocs reference = generator.createResAllocs(2);
assertThat(ResAllocsUtil.isBounded(generator.createResAllocs(1), reference), is(true));
assertThat(ResAllocsUtil.isBounded(generator.createResAllocs(2), reference), is(true));
assertThat(ResAllocsUtil.isBounded(generator.createResAllocs(3), reference), is(false));
// Task variant
QueuableTask taskReference = generator.createTask(reference);
assertThat(ResAllocsUtil.isBounded(generator.createResAllocs(1), taskReference), is(true));
assertThat(ResAllocsUtil.isBounded(generator.createResAllocs(2), taskReference), is(true));
assertThat(ResAllocsUtil.isBounded(generator.createResAllocs(3), taskReference), is(false));
}
@Test
public void testToResAllocs() throws Exception {
Map<VMResource, Double> resourceMap = new HashMap<>();
assertThat(hasEqualResources(ResAllocsUtil.toResAllocs("my", resourceMap), ResAllocsUtil.empty()), is(true));
}
} | 9,133 |
0 | Create_ds/Fenzo/fenzo-core/src/main/java/com/netflix | Create_ds/Fenzo/fenzo-core/src/main/java/com/netflix/fenzo/VMTaskFitnessCalculator.java | /*
* Copyright 2015 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.fenzo;
/**
* Interface representing a task fitness calculator, or scheduling optimization plugin. A task may fit on
* multiple hosts. Use a fitness calculator to determine how well a task fits on a particular host given the
* current state of task assignments and running tasks throughout the system.
*/
public interface VMTaskFitnessCalculator {
/**
* Get the name of this fitness calculator.
*
* @return Name of the fitness calculator.
*/
public String getName();
/**
* Calculates how well the task fits on the host. This method does not have to check to see that the
* proposed host has sufficient resources for the proposed task. It can assume that this has already been
* done.
*
* @param taskRequest the task whose resource requirements can be met by the Virtual Machine
* @param targetVM the prospective target host (VM) for given {@code taskRequest}
* @param taskTrackerState state of the task tracker that contains all tasks currently running and assigned
* @return a value between 0.0 and 1.0, with higher values representing better fit of the task on the host
*/
public double calculateFitness(TaskRequest taskRequest, VirtualMachineCurrentState targetVM,
TaskTrackerState taskTrackerState);
}
| 9,134 |
0 | Create_ds/Fenzo/fenzo-core/src/main/java/com/netflix | Create_ds/Fenzo/fenzo-core/src/main/java/com/netflix/fenzo/AssignableVMs.java | /*
* Copyright 2015 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.fenzo;
import com.netflix.fenzo.functions.Action1;
import com.netflix.fenzo.functions.Func1;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.*;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;
class AssignableVMs {
static class VMRejectLimiter {
private long lastRejectAt=0;
private int rejectedCount;
private final int limit;
private final long rejectDelay;
VMRejectLimiter(int limit, long leaseOfferExpirySecs) {
this.limit = limit;
this.rejectDelay = leaseOfferExpirySecs*1000L;
}
synchronized boolean reject() {
if(rejectedCount==limit)
return false;
rejectedCount++;
lastRejectAt = System.currentTimeMillis();
return true;
}
boolean limitReached() {
return rejectedCount == limit;
}
private void reset() {
if(System.currentTimeMillis() > (lastRejectAt + rejectDelay))
rejectedCount=0;
}
}
private static class HostDisablePair {
private final String host;
private final Long until;
HostDisablePair(String host, Long until) {
this.host = host;
this.until = until;
}
}
private final VMCollection vmCollection;
private static final Logger logger = LoggerFactory.getLogger(AssignableVMs.class);
private final ConcurrentMap<String, String> leaseIdToHostnameMap = new ConcurrentHashMap<>();
private final ConcurrentMap<String, String> vmIdToHostnameMap = new ConcurrentHashMap<>();
private final BlockingQueue<HostDisablePair> disableRequests = new LinkedBlockingQueue<>();
private final TaskTracker taskTracker;
private final String attrNameToGroupMaxResources;
private final Map<String, Map<VMResource, Double>> maxResourcesMap;
private final Map<VMResource, Double> totalResourcesMap;
private final VMRejectLimiter vmRejectLimiter;
private final AssignableVirtualMachine dummyVM = new AssignableVirtualMachine(null, null, null, "", null, 0L, null) {
@Override
void assignResult(TaskAssignmentResult result) {
throw new UnsupportedOperationException();
}
};
private final ActiveVmGroups activeVmGroups;
private String activeVmGroupAttributeName=null;
private final BlockingQueue<String> unknownLeaseIdsToExpire = new LinkedBlockingQueue<>();
AssignableVMs(TaskTracker taskTracker, Action1<VirtualMachineLease> leaseRejectAction,
PreferentialNamedConsumableResourceEvaluator preferentialNamedConsumableResourceEvaluator,
long leaseOfferExpirySecs, int maxOffersToReject,
String attrNameToGroupMaxResources, boolean singleLeaseMode, String autoScaleByAttributeName) {
this.taskTracker = taskTracker;
vmCollection = new VMCollection(
hostname -> new AssignableVirtualMachine(preferentialNamedConsumableResourceEvaluator, vmIdToHostnameMap, leaseIdToHostnameMap, hostname,
leaseRejectAction, leaseOfferExpirySecs, taskTracker, singleLeaseMode),
autoScaleByAttributeName
);
this.attrNameToGroupMaxResources = attrNameToGroupMaxResources;
maxResourcesMap = new HashMap<>();
totalResourcesMap = new HashMap<>();
vmRejectLimiter = new VMRejectLimiter(maxOffersToReject, leaseOfferExpirySecs); // ToDo make this configurable?
activeVmGroups = new ActiveVmGroups();
}
VMCollection getVmCollection() {
return vmCollection;
}
Map<String, List<String>> createPseudoHosts(Map<String, Integer> groupCounts, Func1<String, AutoScaleRule> ruleGetter) {
return vmCollection.clonePseudoVMsForGroups(groupCounts, ruleGetter, lease ->
lease != null &&
(lease.getAttributeMap() == null ||
lease.getAttributeMap().get(activeVmGroupAttributeName) == null ||
isInActiveVmGroup(lease.getAttributeMap().get(activeVmGroupAttributeName).getText().getValue())
)
);
}
void removePseudoHosts(Map<String, List<String>> hostsMap) {
if (hostsMap != null && !hostsMap.isEmpty()) {
for (Map.Entry<String, List<String>> entry: hostsMap.entrySet()) {
for (String h: entry.getValue()) {
final AssignableVirtualMachine avm = vmCollection.unsafeRemoveVm(h, entry.getKey());
if (avm != null)
avm.removeExpiredLeases(true, false);
}
}
}
}
Map<String, Map<VMResource, Double[]>> getResourceStatus() {
Map<String, Map<VMResource, Double[]>> result = new HashMap<>();
for(AssignableVirtualMachine avm: vmCollection.getAllVMs())
result.put(avm.getHostname(), avm.getResourceStatus());
return result;
}
void setTaskAssigned(TaskRequest request, String host) {
vmCollection.getOrCreate(host).setAssignedTask(request);
}
void unAssignTask(String taskId, String host) {
final Optional<AssignableVirtualMachine> vmByName = vmCollection.getVmByName(host);
if(vmByName.isPresent()) {
vmByName.get().markTaskForUnassigning(taskId);
}
else
logger.warn("No VM for host " + host + " to unassign task " + taskId);
}
private int addLeases(List<VirtualMachineLease> leases) {
if(logger.isDebugEnabled())
logger.debug("Adding leases");
for(AssignableVirtualMachine avm: vmCollection.getAllVMs())
avm.resetResources();
int rejected=0;
for(VirtualMachineLease l: leases) {
if(vmCollection.addLease(l))
rejected++;
}
for(AssignableVirtualMachine avm: vmCollection.getAllVMs()) {
if(logger.isDebugEnabled())
logger.debug("Updating total lease on " + avm.getHostname());
avm.updateCurrTotalLease();
final VirtualMachineLease currTotalLease = avm.getCurrTotalLease();
if(logger.isDebugEnabled()) {
if (currTotalLease == null)
logger.debug("Updated total lease is null for " + avm.getHostname());
else {
logger.debug("Updated total lease for {} has cpu={}, mem={}, disk={}, network={}",
avm.getHostname(), currTotalLease.cpuCores(), currTotalLease.memoryMB(),
currTotalLease.diskMB(), currTotalLease.networkMbps()
);
}
}
}
return rejected;
}
void expireLease(String leaseId) {
final String hostname = leaseIdToHostnameMap.get(leaseId);
if(hostname==null) {
logger.debug("Received expiry request for an unknown lease: {}", leaseId);
unknownLeaseIdsToExpire.offer(leaseId);
return;
}
internalExpireLease(leaseId, hostname);
}
private void internalExpireLease(String leaseId, String hostname) {
final Optional<AssignableVirtualMachine> vmByName = vmCollection.getVmByName(hostname);
if(vmByName.isPresent()) {
if(logger.isDebugEnabled())
logger.debug("Expiring lease offer id " + leaseId + " on host " + hostname);
vmByName.get().expireLease(leaseId);
}
}
void expireAllLeases(String hostname) {
final Optional<AssignableVirtualMachine> vmByName = vmCollection.getVmByName(hostname);
if(vmByName.isPresent())
vmByName.get().expireAllLeases();
}
void expireAllLeases() {
for(AssignableVirtualMachine avm: vmCollection.getAllVMs())
avm.expireAllLeases();
}
void disableUntil(String host, long until) {
disableRequests.offer(new HostDisablePair(host, until));
}
private void disableVMs() {
if (disableRequests.peek() == null)
return;
List<HostDisablePair> disablePairs = new LinkedList<>();
disableRequests.drainTo(disablePairs);
for (HostDisablePair hostDisablePair: disablePairs) {
final Optional<AssignableVirtualMachine> vmByName = vmCollection.getVmByName(hostDisablePair.host);
if (vmByName.isPresent())
vmByName.get().setDisabledUntil(hostDisablePair.until);
}
}
void enableVM(String host) {
final Optional<AssignableVirtualMachine> vmByName = vmCollection.getVmByName(host);
if(vmByName.isPresent())
vmByName.get().enable();
else
logger.warn("Can't enable host " + host + ", no such host");
}
String getHostnameFromVMId(String vmId) {
return vmIdToHostnameMap.get(vmId);
}
void setActiveVmGroupAttributeName(String attributeName) {
this.activeVmGroupAttributeName = attributeName;
}
void setActiveVmGroups(List<String> vmGroups) {
activeVmGroups.setActiveVmGroups(vmGroups);
}
private boolean isInActiveVmGroup(AssignableVirtualMachine avm) {
final String attrValue = avm.getAttrValue(activeVmGroupAttributeName);
return isInActiveVmGroup(attrValue);
}
private boolean isInActiveVmGroup(String attrValue) {
return activeVmGroups.isActiveVmGroup(attrValue, false);
}
private void expireAnyUnknownLeaseIds() {
List<String> unknownExpiredLeases = new ArrayList<>();
unknownLeaseIdsToExpire.drainTo(unknownExpiredLeases);
for(String leaseId: unknownExpiredLeases) {
final String hostname = leaseIdToHostnameMap.get(leaseId);
if(hostname!=null)
internalExpireLease(leaseId, hostname);
}
}
List<AssignableVirtualMachine> prepareAndGetOrderedVMs(List<VirtualMachineLease> newLeases, AtomicInteger rejectedCount) {
disableVMs();
removeExpiredLeases();
rejectedCount.addAndGet(addLeases(newLeases));
expireAnyUnknownLeaseIds();
List<AssignableVirtualMachine> vms = new ArrayList<>();
taskTracker.clearAssignedTasks();
vmRejectLimiter.reset();
resetTotalResources();
// ToDo make this parallel maybe?
for(AssignableVirtualMachine avm: vmCollection.getAllVMs()) {
avm.prepareForScheduling();
if(isInActiveVmGroup(avm) && avm.isAssignableNow()) {
// for now, only add it if it is available right now
if(logger.isDebugEnabled())
logger.debug("Host " + avm.getHostname() + " available for assignments");
vms.add(avm);
}
else if(logger.isDebugEnabled())
logger.debug("Host " + avm.getHostname() + " not available for assignments");
saveMaxResources(avm);
if (isInActiveVmGroup(avm) && !avm.isDisabled())
addTotalResources(avm);
}
taskTracker.setTotalResources(totalResourcesMap);
//Collections.sort(vms);
return vms;
}
List<AssignableVirtualMachine> getInactiveVMs() {
return vmCollection.getAllVMs().stream().filter(avm -> !isInActiveVmGroup(avm)).collect(Collectors.toList());
}
private void resetTotalResources() {
totalResourcesMap.clear();
}
private void addTotalResources(AssignableVirtualMachine avm) {
final Map<VMResource, Double> maxResources = avm.getMaxResources();
for (VMResource r: maxResources.keySet()) {
Double v = maxResources.get(r);
if (v != null) {
if (totalResourcesMap.get(r) == null)
totalResourcesMap.put(r, v);
else
totalResourcesMap.put(r, totalResourcesMap.get(r) + v);
}
}
}
private void removeExpiredLeases() {
for(AssignableVirtualMachine avm: vmCollection.getAllVMs())
avm.removeExpiredLeases(!isInActiveVmGroup(avm));
}
int removeLimitedLeases(List<VirtualMachineLease> idleResourcesList) {
int rejected=0;
List<VirtualMachineLease> randomized = new ArrayList<>(idleResourcesList);
// randomize the list so we don't always reject leases of the same VM before hitting the reject limit
Collections.shuffle(randomized);
for(VirtualMachineLease lease: randomized) {
if(vmRejectLimiter.limitReached())
break;
final Optional<AssignableVirtualMachine> vmByName = vmCollection.getVmByName(lease.hostname());
if (vmByName.isPresent())
rejected += vmByName.get().expireLimitedLeases(vmRejectLimiter);
}
return rejected;
}
int getTotalNumVMs() {
return vmCollection.size();
}
void purgeInactiveVMs(Set<String> excludeVms) {
for(AssignableVirtualMachine avm: vmCollection.getAllVMs()) {
if(avm != null) {
if (!excludeVms.contains(avm.getHostname())) {
if (!avm.isActive()) {
vmCollection.remove(avm);
if (avm.getCurrVMId() != null)
vmIdToHostnameMap.remove(avm.getCurrVMId(), avm.getHostname());
logger.debug("Removed inactive host " + avm.getHostname());
}
}
}
}
}
private void saveMaxResources(AssignableVirtualMachine avm) {
if(attrNameToGroupMaxResources!=null && !attrNameToGroupMaxResources.isEmpty()) {
String attrValue = avm.getAttrValue(attrNameToGroupMaxResources);
if(attrValue !=null) {
Map<VMResource, Double> maxResources = avm.getMaxResources();
Map<VMResource, Double> savedMaxResources = maxResourcesMap.get(attrValue);
if(savedMaxResources==null) {
savedMaxResources = new HashMap<>();
maxResourcesMap.put(attrValue, savedMaxResources);
}
for(VMResource r: VMResource.values()) {
switch (r) {
case CPU:
case Disk:
case Memory:
case Ports:
case Network:
Double savedVal = savedMaxResources.get(r)==null? 0.0 : savedMaxResources.get(r);
savedMaxResources.put(r, Math.max(savedVal, maxResources.get(r)));
}
}
}
}
}
Map<VMResource, Double> getMaxResources(String attrValue) {
return maxResourcesMap.get(attrValue);
}
AssignmentFailure getFailedMaxResource(String attrValue, TaskRequest task) {
AssignmentFailure savedFailure = null;
for(Map.Entry<String, Map<VMResource, Double>> entry: maxResourcesMap.entrySet()) {
if(attrValue!=null && !attrValue.equals(entry.getKey()))
continue;
final Map<VMResource, Double> maxResources = entry.getValue();
AssignmentFailure failure = null;
for(VMResource res: VMResource.values()) {
switch (res) {
case CPU:
if(maxResources.get(VMResource.CPU) < task.getCPUs()) {
failure = new AssignmentFailure(
VMResource.CPU, task.getCPUs(), 0.0, maxResources.get(VMResource.CPU), "");
}
break;
case Memory:
if(maxResources.get(VMResource.Memory) < task.getMemory())
failure = new AssignmentFailure(
VMResource.Memory, task.getMemory(), 0.0, maxResources.get(VMResource.Memory), "");
break;
case Disk:
if(maxResources.get(VMResource.Disk) < task.getDisk())
failure = new AssignmentFailure(
VMResource.Disk, task.getDisk(), 0.0, maxResources.get(VMResource.Disk), "");
break;
case Ports:
if(maxResources.get(VMResource.Ports) < task.getPorts())
failure = new AssignmentFailure(
VMResource.Ports, task.getPorts(), 0.0, maxResources.get(VMResource.Ports), "");
break;
case Network:
if(maxResources.get(VMResource.Network) < task.getNetworkMbps())
failure = new AssignmentFailure(
VMResource.Network, task.getNetworkMbps(), 0.0, maxResources.get(VMResource.Network), "");
break;
case VirtualMachine:
case Fitness:
case ResAllocs:
case ResourceSet:
case Other:
break;
default:
logger.error("Unknown resource type: " + res);
}
if(failure!=null)
break;
}
if(failure == null)
return null;
savedFailure = failure;
}
return savedFailure;
}
ActiveVmGroups getActiveVmGroups() {
return activeVmGroups;
}
List<VirtualMachineCurrentState> getVmCurrentStates() {
List<VirtualMachineCurrentState> result = new ArrayList<>();
for(AssignableVirtualMachine avm: vmCollection.getAllVMs())
result.add(avm.getVmCurrentState());
return result;
}
AssignableVirtualMachine getDummyVM() {
return dummyVM;
}
}
| 9,135 |
0 | Create_ds/Fenzo/fenzo-core/src/main/java/com/netflix | Create_ds/Fenzo/fenzo-core/src/main/java/com/netflix/fenzo/ScaleDownConstraintExecutor.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.fenzo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;
/**
* {@link ScaleDownConstraintExecutor} uses {@link ScaleDownOrderEvaluator} and multiple
* {@link ScaleDownConstraintEvaluator}s to determine termination order of candidate VM list. The evaluation process
* includes the following steps:
* <ul>
* <li>{@link ScaleDownOrderEvaluator} splits candidate VMs into ordered list of equivalence groups</li>
* <li>For each equivalence group multiple {@link ScaleDownOrderEvaluator}s are executed to produce a score for each VM</li>
* <li>VMs are ordered in each equivalence group with the highest score first</li>
* <li>The ordered equivalence groups are merged into single list, preserving the partitioning order computed by
* {@link ScaleDownConstraintExecutor}. This list is returned as a result.
* </li>
* </ul>
*/
class ScaleDownConstraintExecutor {
private static final Logger logger = LoggerFactory.getLogger(ScaleDownConstraintExecutor.class);
private static final double NOT_REMOVABLE_MARKER = -1;
private final ScaleDownOrderEvaluator orderEvaluator;
private final Map<ScaleDownConstraintEvaluator, Double> scoringEvaluators;
ScaleDownConstraintExecutor(ScaleDownOrderEvaluator orderEvaluator, Map<ScaleDownConstraintEvaluator, Double> weightedScoringEvaluators) {
checkArguments(weightedScoringEvaluators);
this.orderEvaluator = orderEvaluator;
this.scoringEvaluators = weightedScoringEvaluators;
}
List<VirtualMachineLease> evaluate(Collection<VirtualMachineLease> candidates) {
List<Set<VirtualMachineLease>> fixedOrder = orderEvaluator.evaluate(candidates);
List<VirtualMachineLease> scaleDownOrder = scoringEvaluators.isEmpty()
? fixedOrder.stream().flatMap(Set::stream).collect(Collectors.toList())
: fixedOrder.stream().flatMap(this::groupEvaluator).collect(Collectors.toList());
if (logger.isDebugEnabled()) {
List<String> hosts = scaleDownOrder.stream().map(VirtualMachineLease::hostname).collect(Collectors.toList());
logger.debug("Evaluated scale down order: {}", hosts);
}
return scaleDownOrder;
}
private void checkArguments(Map<ScaleDownConstraintEvaluator, Double> weightedScoringEvaluators) {
List<String> evaluatorsWithInvalidWeights = weightedScoringEvaluators.entrySet().stream()
.filter(e -> e.getValue() <= 0)
.map(e -> e.getKey().getName() + '=' + e.getValue())
.collect(Collectors.toList());
if (!evaluatorsWithInvalidWeights.isEmpty()) {
throw new IllegalArgumentException("Evaluator weighs must be > 0. This invariant is violated by " + evaluatorsWithInvalidWeights);
}
}
private Stream<VirtualMachineLease> groupEvaluator(Set<VirtualMachineLease> groupCandidates) {
Map<VirtualMachineLease, Double> scores = new HashMap<>();
scoringEvaluators.forEach((e, weight) -> {
Optional<? super Object> optionalContext = Optional.empty();
for (VirtualMachineLease lease : groupCandidates) {
double currentScore = scores.getOrDefault(lease, 0.0);
if (currentScore != NOT_REMOVABLE_MARKER) {
ScaleDownConstraintEvaluator.Result result = e.evaluate(lease, optionalContext);
double newScore = result.getScore() * weight;
if (newScore == 0) {
scores.put(lease, NOT_REMOVABLE_MARKER);
} else {
scores.put(lease, currentScore + newScore);
}
optionalContext = result.getContext();
}
}
});
return scores.entrySet().stream()
.filter(e -> e.getValue() != NOT_REMOVABLE_MARKER)
.sorted((e1, e2) -> Double.compare(e2.getValue(), e1.getValue())) // Descending order
.map(Map.Entry::getKey);
}
}
| 9,136 |
0 | Create_ds/Fenzo/fenzo-core/src/main/java/com/netflix | Create_ds/Fenzo/fenzo-core/src/main/java/com/netflix/fenzo/TaskScheduler.java | /*
* Copyright 2015 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.fenzo;
import com.netflix.fenzo.common.ThreadFactoryBuilder;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.Supplier;
import java.util.stream.Collectors;
import com.netflix.fenzo.functions.Action1;
import com.netflix.fenzo.functions.Action2;
import com.netflix.fenzo.functions.Func1;
import com.netflix.fenzo.plugins.NoOpScaleDownOrderEvaluator;
import com.netflix.fenzo.queues.Assignable;
import com.netflix.fenzo.queues.QueuableTask;
import com.netflix.fenzo.sla.ResAllocs;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* A scheduling service that you can use to optimize the assignment of tasks to hosts within a Mesos framework.
* Call the {@link #scheduleOnce scheduleOnce()} method with a list of task requests and a list of new resource
* lease offers, and that method will return a set of task assignments.
* <p>
* The {@code TaskScheduler} stores any unused lease offers and will apply them during future calls to
* {@code scheduleOnce()} until a time expires, which is defined by the lease offer expiry time that you set
* when you build the {@code TaskScheduler} (the default is 10 seconds). Upon reaching the expiry time, the
* {@code TaskScheduler} rejects expired resource lease offers by invoking the action you supplied then you
* built the {@code TaskScheduler}.
* <p>
* Note that when you launch a task that has been scheduled by the {@code TaskScheduler}, you should call
* the task assigner action available from the {@link #getTaskAssigner getTaskAssigner()} method. When that
* task completes, you should call the task unassigner action available from the
* {@link #getTaskUnAssigner getTaskUnAssigner()} method. These actions make the {@code TaskScheduler} keep
* track of launched tasks. The {@code TaskScheduler} then makes these tracked tasks available to its
* scheduling optimization functions.
* <p>
* Do not call the scheduler concurrently. The scheduler assigns tasks in the order that they are received in a
* particular list. It checks each task against available resources until it finds a match.
* <p>
* You create your {@code TaskScheduler} by means of the {@link TaskScheduler.Builder}. It provides methods with
* which you can adjust the scheduler's autoscaling rules, fitness calculators, and so forth.
*
* @see <a href="https://en.wikipedia.org/wiki/Builder_pattern">Wikipedia: Builder pattern</a>
*/
public class TaskScheduler {
private static final int PARALLEL_SCHED_EVAL_MIN_BATCH_SIZE = 30;
/**
* The Builder is how you construct a {@link TaskScheduler} object with particular characteristics. Chain
* its methods and then call {@link #build build()} to create a {@code TaskScheduler}.
*
* @see <a href="https://en.wikipedia.org/wiki/Builder_pattern">Wikipedia: Builder pattern</a>
*/
public final static class Builder {
private Action1<VirtualMachineLease> leaseRejectAction = null;
private long leaseOfferExpirySecs = 120;
private int maxOffersToReject = 4;
private boolean rejectAllExpiredOffers = false;
private VMTaskFitnessCalculator fitnessCalculator = new DefaultFitnessCalculator();
private String autoScaleByAttributeName = null;
private String autoScalerMapHostnameAttributeName = null;
private String autoScaleDownBalancedByAttributeName = null;
private ScaleDownOrderEvaluator scaleDownOrderEvaluator;
private Map<ScaleDownConstraintEvaluator, Double> weightedScaleDownConstraintEvaluators;
private PreferentialNamedConsumableResourceEvaluator preferentialNamedConsumableResourceEvaluator = new DefaultPreferentialNamedConsumableResourceEvaluator();
private Action1<AutoScaleAction> autoscalerCallback = null;
private long delayAutoscaleUpBySecs = 0L;
private long delayAutoscaleDownBySecs = 0L;
private long disabledVmDurationInSecs = 0L;
private List<AutoScaleRule> autoScaleRules = new ArrayList<>();
private Func1<Double, Boolean> isFitnessGoodEnoughFunction = f -> f > 1.0;
private boolean disableShortfallEvaluation = false;
private Map<String, ResAllocs> resAllocs = null;
private boolean singleOfferMode = false;
private final List<SchedulingEventListener> schedulingEventListeners = new ArrayList<>();
private int maxConcurrent = Runtime.getRuntime().availableProcessors();
private Supplier<Long> taskBatchSizeSupplier = () -> Long.MAX_VALUE;
private Func1<List<AssignableVirtualMachine>, List<AssignableVirtualMachine>> assignableVMsEvaluator = null;
/**
* (Required) Call this method to establish a method that your task scheduler will call to notify you
* that it has rejected a resource offer. In this method, you should tell Mesos that you are declining
* the associated offer.
*
* @param leaseRejectAction the action to trigger when the task scheduler rejects a VM lease, with the
* lease being rejected as the only argument
* @return this same {@code Builder}, suitable for further chaining or to build the {@link TaskScheduler}
*/
public Builder withLeaseRejectAction(Action1<VirtualMachineLease> leaseRejectAction) {
this.leaseRejectAction = leaseRejectAction;
return this;
}
/**
* Call this method to set the expiration time for resource offers. Your task scheduler will reject any
* offers that remain unused if this expiration period from the time of the offer expires. This ensures
* your scheduler will not hoard unuseful offers. The default is 120 seconds.
*
* @param leaseOfferExpirySecs the amount of time the scheduler will keep an unused lease available for
* a later-scheduled task before it considers the lease to have expired, in
* seconds
* @return this same {@code Builder}, suitable for further chaining or to build the {@link TaskScheduler}
*/
public Builder withLeaseOfferExpirySecs(long leaseOfferExpirySecs) {
this.leaseOfferExpirySecs = leaseOfferExpirySecs;
return this;
}
/**
* Call this method to set the maximum number of offers to reject within a time period equal to lease expiry
* seconds, set with {@code leaseOfferExpirySecs()}. Default is 4.
*
* @param maxOffersToReject Maximum number of offers to reject.
* @return this same {@code Builder}, suitable for further chaining or to build the {@link TaskScheduler}
*/
public Builder withMaxOffersToReject(int maxOffersToReject) {
if (!rejectAllExpiredOffers) {
this.maxOffersToReject = maxOffersToReject;
}
return this;
}
/**
* Indicate that all offers older than the set expiry time must be rejected. By default this is set to false.
* If false, Fenzo rejects a maximum number of offers set using {@link #withMaxOffersToReject(int)} per each
* time period spanning the expiry time, set by {@link #withLeaseOfferExpirySecs(long)}.
*
* @return this same {@code Builder}, suitable for further chaining or to build the {@link TaskScheduler}
*/
public Builder withRejectAllExpiredOffers() {
this.rejectAllExpiredOffers = true;
this.maxOffersToReject = Integer.MAX_VALUE;
return this;
}
/**
* Call this method to add a fitness calculator that your scheduler will use to compute the suitability
* of a particular host for a particular task. You can only add a single fitness calculator to a
* scheduler; if you attempt to add a second fitness calculator, it will override the first one.
*
* @param fitnessCalculator the fitness calculator you want this scheduler to use in its evaluations
* @return this same {@code Builder}, suitable for further chaining or to build the {@link TaskScheduler}
* @see <a href="https://github.com/Netflix/Fenzo/wiki/Fitness-Calculators">Fitness Calculators</a>
*/
public Builder withFitnessCalculator(VMTaskFitnessCalculator fitnessCalculator) {
this.fitnessCalculator = fitnessCalculator;
return this;
}
public Builder withSchedulingEventListener(SchedulingEventListener schedulingEventListener) {
this.schedulingEventListeners.add(schedulingEventListener);
return this;
}
/**
* Call this method to indicate which host attribute you want your task scheduler to use in order to
* distinguish which hosts are in which autoscaling groups. You must call this method before you call
* {@link #withAutoScaleRule(AutoScaleRule)}.
*
* @param name the name of the host attribute that defines which autoscaling group it is in
* @return this same {@code Builder}, suitable for further chaining or to build the {@link TaskScheduler}
* @see <a href="https://github.com/Netflix/Fenzo/wiki/Autoscaling">Autoscaling</a>
*/
public Builder withAutoScaleByAttributeName(String name) {
this.autoScaleByAttributeName = name;
return this;
}
/**
* Use the given host attribute name to determine the alternate hostname of virtual machine to use as an
* argument for an autoscaling action.
* <p>
* In some circumstances (for instance with Amazon Web Services), the host name is not the correct
* identifier for the host in the context of an autoscaling action (for instance, in AWS, you need the
* EC2 instance identifier). If this is the case for your system, you need to implement a function that
* maps the host name to the identifier for the host in an autoscaling context so that Fenzo can perform
* autoscaling properly. You provide this function to the task manager by means of this builder method.
*
* @param name the attribute name to use as the alternate host identifier in an autoscaling context
* @return this same {@code Builder}, suitable for further chaining or to build the {@link TaskScheduler}
* @see <a href="https://github.com/Netflix/Fenzo/wiki/Autoscaling">Autoscaling</a>
*/
public Builder withAutoScalerMapHostnameAttributeName(String name) {
this.autoScalerMapHostnameAttributeName = name;
return this;
}
/**
* Call this method to tell the autoscaler to try to maintain a balance of host varieties when it scales
* down a cluster. Pass the method a host attribute, and the autoscaler will attempt to scale down in
* such a way as to maintain a similar number of hosts with each value for that attribute.
*
* @param name the name of the attribute
* @return this same {@code Builder}, suitable for further chaining or to build the {@link TaskScheduler}
* @see <a href="https://github.com/Netflix/Fenzo/wiki/Autoscaling">Autoscaling</a>
*/
public Builder withAutoScaleDownBalancedByAttributeName(String name) {
this.autoScaleDownBalancedByAttributeName = name;
return this;
}
/**
* Call this method to set {@link ScaleDownOrderEvaluator}.
*
* @param scaleDownOrderEvaluator scale down ordering evaluator
* @return this same {@code Builder}, suitable for further chaining or to build the {@link TaskScheduler}
*/
public Builder withScaleDownOrderEvaluator(ScaleDownOrderEvaluator scaleDownOrderEvaluator) {
this.scaleDownOrderEvaluator = scaleDownOrderEvaluator;
return this;
}
/**
* Ordered list of scale down constraints evaluators.
*
* @param weightedScaleDownConstraintEvaluators scale down evaluators
* @return this same {@code Builder}, suitable for further chaining or to build the {@link TaskScheduler}
*/
public Builder withWeightedScaleDownConstraintEvaluators(Map<ScaleDownConstraintEvaluator, Double> weightedScaleDownConstraintEvaluators) {
this.weightedScaleDownConstraintEvaluators = weightedScaleDownConstraintEvaluators;
return this;
}
public Builder withPreferentialNamedConsumableResourceEvaluator(PreferentialNamedConsumableResourceEvaluator preferentialNamedConsumableResourceEvaluator) {
this.preferentialNamedConsumableResourceEvaluator = preferentialNamedConsumableResourceEvaluator;
return this;
}
/**
* Use the given function to determine if the fitness of a host for a task is good enough that the task
* scheduler should stop looking for a more fit host. Pass this method a function that takes a value
* between 0.0 (completely unfit) and 1.0 (perfectly fit) that describes the fitness of a particular
* host for a particular task, and decides, by returning a boolean value, whether that value is a "good
* enough" fit such that the task scheduler should go ahead and assign the task to the host. If you
* write this function to only return true for values at or near 1.0, the task scheduler will spend more
* time searching for a good fit; if you write the function to return true for lower values, the task
* scheduler will be able to find a host to assign the task to more quickly.
* <p>
* By default, if you do not build your task scheduler by passing a function into this method, the
* task scheduler will always search all of the available hosts for the best possible fit for every
* task.
*
* @param f a single-argument function that accepts a double parameter, representing the fitness, and
* returns a {@code Boolean} indicating whether the fitness is good enough to constitute a
* successful match between the host and task
* @return this same {@code Builder}, suitable for further chaining or to build the {@link TaskScheduler}
*/
public Builder withFitnessGoodEnoughFunction(Func1<Double, Boolean> f) {
this.isFitnessGoodEnoughFunction = f;
return this;
}
/**
* Disable resource shortfall evaluation. The shortfall evaluation is performed when evaluating the
* autoscaling needs. This is useful for evaluating the actual resources needed to scale up by, for
* pending tasks, which may be greater than the number of resources scaled up by thresholds based scale
* up.
* <p>
* This evaluation can be computaionally expensive and/or may scale up aggressively, initially, to more
* resources than needed. The initial aggressive scale up is corrected later by scale down, which is
* triggered by scale down evaluation after a cool down period transpires.
*
* @return this same {@code Builder}, suitable for further chaining or to build the {@link TaskScheduler}
* @see <a href="https://github.com/Netflix/Fenzo/wiki/Autoscaling">Autoscaling</a>
*/
public Builder disableShortfallEvaluation() {
disableShortfallEvaluation = true;
return this;
}
/**
* Call this method to set the initial limitations on how many resources will be available to each task
* group.
*
* @param resAllocs a Map with the task group name as keys and resource allocation limits as values
* @return this same {@code Builder}, suitable for further chaining or to build the {@link TaskScheduler}
* @see <a href="https://github.com/Netflix/Fenzo/wiki/Resource-Allocation-Limits">Resource Allocation
* Limits</a>
*/
public Builder withInitialResAllocs(Map<String, ResAllocs> resAllocs) {
this.resAllocs = resAllocs;
return this;
}
/**
* Adds an autoscaling rule that governs the behavior by which this scheduler will autoscale hosts of a
* certain type. You can chain this method multiple times, adding a new autoscaling rule each time (one
* for each autoscale group).
* <p>
* Before you call this method you must first call
* {@link #withAutoScaleByAttributeName withAutoScaleByAttributeName()} to indicate which host
* attribute you are using to identify which hosts are in which autoscaling groups.
*
* @param rule the autoscaling rule to add
* @return this same {@code Builder}, suitable for further chaining or to build the {@link TaskScheduler}
* @throws IllegalArgumentException if you have not properly initialized autoscaling or if your rule is
* poorly formed
* @see <a href="https://github.com/Netflix/Fenzo/wiki/Autoscaling">Autoscaling</a>
*/
public Builder withAutoScaleRule(AutoScaleRule rule) {
if (autoScaleByAttributeName == null || autoScaleByAttributeName.isEmpty()) {
throw new IllegalArgumentException("Auto scale by attribute name must be set before setting rules");
}
if (rule.getMinIdleHostsToKeep() < 1) {
throw new IllegalArgumentException("Min Idle must be >0");
}
if (rule.getMinIdleHostsToKeep() > rule.getMaxIdleHostsToKeep()) {
throw new IllegalArgumentException("Min Idle must be <= Max Idle hosts");
}
this.autoScaleRules.add(rule);
return this;
}
/*
* The callback you pass to this method receives an indication when an autoscale action is to be
* performed. This indicates which autoscale rule prompted the action and whether the action is to scale
* up or scale down the autoscale group. The callback then initiates the appropriate scaling actions.
*
* @see <a href="https://github.com/Netflix/Fenzo/wiki/Autoscaling">Autoscaling</a>
*/
public Builder withAutoScalerCallback(Action1<AutoScaleAction> callback) {
this.autoscalerCallback = callback;
return this;
}
/**
* Delay the autoscale up actions to reduce unnecessary actions due to short periods of breach of scale up
* policy rules. Such scale ups can be caused by, for example, the periodic offer rejections that result in
* offers coming back shortly. They can also be caused by certain environments where tasks are first scheduled
* to replace existing tasks.
* <p>
* The autoscaler takes the scale up action based on the latest scale up request value after the delay.
* <p>
* The default is 0 secs. Ideally, you should set this to be at least two times the larger of the two values:
* <UL>
* <LI>Delay between successive calls to {@link TaskScheduler#scheduleOnce(List, List)}.</LI>
* <LI>Delay in get a rejected offer back from Mesos.</LI>
* </UL>
*
* @param delayAutoscaleUpBySecs Delay autoscale up actions by this many seconds.
* @return this same {@code Builder}, suitable for further chaining or to build the {@link TaskScheduler}
* @throws IllegalArgumentException if you give negative number for {@code delayAutoscalerbySecs}.
* @see <a href="https://github.com/Netflix/Fenzo/wiki/Autoscaling">Autoscaling</a>
*/
public Builder withDelayAutoscaleUpBySecs(long delayAutoscaleUpBySecs) {
if (delayAutoscaleUpBySecs < 0L) {
throw new IllegalArgumentException("Delay secs can't be negative: " + delayAutoscaleUpBySecs);
}
this.delayAutoscaleUpBySecs = delayAutoscaleUpBySecs;
return this;
}
/**
* Delay the autoscale down actions to reduce unnecessary actions due to short periods of breach of scale down
* policy rules. Such scale downs can be caused by, for example, certain environments where existing tasks are
* removed before replacing them with new tasks.
* <p>
* The autoscaler takes the scale down action based on the latest scale down request value after the delay.
* <p>
* The default is 0 secs. Ideally, you should set this to be at least two times the delay before terminated
* tasks are replaced successfully.
*
* @param delayAutoscaleDownBySecs Delay autoscale down actions by this many seconds.
* @return this same {@code Builder}, suitable for further chaining or to build the {@link TaskScheduler}
* @throws IllegalArgumentException if you give negative number for {@code delayAutoscalerbySecs}.
* @see <a href="https://github.com/Netflix/Fenzo/wiki/Autoscaling">Autoscaling</a>
*/
public Builder withDelayAutoscaleDownBySecs(long delayAutoscaleDownBySecs) {
if (delayAutoscaleDownBySecs < 0L) {
throw new IllegalArgumentException("Delay secs can't be negative: " + delayAutoscaleDownBySecs);
}
this.delayAutoscaleDownBySecs = delayAutoscaleDownBySecs;
return this;
}
/**
* How long to disable a VM when going through a scale down action. Note that the value used will be the max
* between this value and the {@link AutoScaleRule#getCoolDownSecs()} value and that this value should be
* greater than the {@link AutoScaleRule#getCoolDownSecs()} value. If the supplied {@link AutoScaleAction}
* does not actually terminate the instance in this time frame then the VM will become enabled. This option is useful
* when you want to increase the disabled time of a VM because the implementation of the {@link AutoScaleAction} may
* take longer than the cooldown period.
*
* @param disabledVmDurationInSecs Disable VMs about to be terminated by this many seconds.
* @return this same {@code Builder}, suitable for further chaining or to build the {@link TaskScheduler}
* @throws IllegalArgumentException if {@code disabledVmDurationInSecs} is not greater than 0.
* @see <a href="https://github.com/Netflix/Fenzo/wiki/Autoscaling">Autoscaling</a>
*/
public Builder withAutoscaleDisabledVmDurationInSecs(long disabledVmDurationInSecs) {
if (disabledVmDurationInSecs <= 0L) {
throw new IllegalArgumentException("disabledVmDurationInSecs must be greater than 0: " + disabledVmDurationInSecs);
}
this.disabledVmDurationInSecs = disabledVmDurationInSecs;
return this;
}
/**
* Indicate that the cluster receives resource offers only once per VM (host). Normally, Mesos sends resource
* offers multiple times, as resources free up on the host upon completion of various tasks. This method
* provides an experimental support for a mode where Fenzo can be made aware of the entire set of resources
* on hosts once, in a model similar to Amazon ECS. Fenzo internally keeps track of total versus used resources
* on the host based on tasks assigned and then later unassigned. No further resource offers are expected after
* the initial one.
*
* @param b True if only one resource offer is expected per host, false by default.
* @return this same {@code Builder}, suitable for further chaining or to build the {@link TaskScheduler}
*/
public Builder withSingleOfferPerVM(boolean b) {
this.singleOfferMode = b;
return this;
}
/**
* Fenzo creates multiple threads to speed up task placement evaluation. By default the number of threads
* created is equal to the number of available CPUs. As the computation cost is a multiplication of
* (scheduling_loop_rate * number_of_agents * number_of_tasks_in_queue), having a large agent fleet with
* an accumulated unscheduled workload may easily saturate all available CPUs, affecting the whole system
* performance. To avoid this, it is recommended to configure Fenzo with a fewer amount of threads.
*
* @param maxConcurrent maximum number of threads Fenzo is allowed to use
* @return this same {@code Builder}, suitable for further chaining or to build the {@link TaskScheduler}
*/
public Builder withMaxConcurrent(int maxConcurrent) {
this.maxConcurrent = maxConcurrent;
return this;
}
/**
* Use the given supplier to determine how many successful tasks should be evaluated in the next scheduling iteration. This
* can be used to dynamically change how many successful task evaluations are done in order to increase/reduce the scheduling iteration
* duration. The default supplier implementation will return {@link Long#MAX_VALUE} such that all tasks will be
* evaluated.
*
* @param taskBatchSizeSupplier the supplier that returns the task batch size for the next scheduling iteration.
* @return this same {@code Builder}, suitable for further chaining or to build the {@link TaskSchedulingService}.
*/
public Builder withTaskBatchSizeSupplier(Supplier<Long> taskBatchSizeSupplier) {
this.taskBatchSizeSupplier = taskBatchSizeSupplier;
return this;
}
/**
* A provided function that can transform the assignable virtual machines that will be used during a scheduling
* iteration right before the scheduling iteration happens. This function is useful for global filtering and sorting
* right before the VMs are used to make scheduling decisions. Since this function blocks the scheduling loop, the expectation
* is that it returns very quickly.
* <b>This API is experimental and subject to change.</b>
*
* @param function that takes in a list of the current VMs and returns a list with VMs.
* @return this same {@code Builder}, suitable for further chaining or to build the {@link TaskScheduler}
*/
public Builder withAssignableVMsEvaluator(Func1<List<AssignableVirtualMachine>, List<AssignableVirtualMachine>> function) {
this.assignableVMsEvaluator = function;
return this;
}
/**
* Creates a {@link TaskScheduler} based on the various builder methods you have chained.
*
* @return a {@code TaskScheduler} built according to the specifications you indicated
*/
public TaskScheduler build() {
if (scaleDownOrderEvaluator == null) {
if (weightedScaleDownConstraintEvaluators != null) {
scaleDownOrderEvaluator = new NoOpScaleDownOrderEvaluator();
}
} else {
if (weightedScaleDownConstraintEvaluators == null) {
weightedScaleDownConstraintEvaluators = Collections.emptyMap();
}
}
return new TaskScheduler(this);
}
}
private static class EvalResult {
List<TaskAssignmentResult> assignmentResults;
TaskAssignmentResult result;
int numAllocationTrials;
Exception exception;
private EvalResult(List<TaskAssignmentResult> assignmentResults, TaskAssignmentResult result, int numAllocationTrials, Exception e) {
this.assignmentResults = assignmentResults;
this.result = result;
this.numAllocationTrials = numAllocationTrials;
this.exception = e;
}
}
private final AssignableVMs assignableVMs;
private static final Logger logger = LoggerFactory.getLogger(TaskScheduler.class);
private static final long purgeVMsIntervalSecs = 60;
private long lastVMPurgeAt = System.currentTimeMillis();
private final Builder builder;
private final StateMonitor stateMonitor;
private final SchedulingEventListener schedulingEventListener;
private final AutoScaler autoScaler;
private final int maxConcurrent;
private final ExecutorService executorService;
private final AtomicBoolean isShutdown = new AtomicBoolean();
private final ResAllocsEvaluater resAllocsEvaluator;
private final TaskTracker taskTracker;
private volatile boolean usingSchedulingService = false;
private final String usingSchedSvcMesg = "Invalid call when using task scheduling service";
private final Func1<List<AssignableVirtualMachine>, List<AssignableVirtualMachine>> assignableVMsEvaluator;
private TaskScheduler(Builder builder) {
if (builder.leaseRejectAction == null) {
throw new IllegalArgumentException("Lease reject action must be non-null");
}
this.builder = builder;
this.maxConcurrent = builder.maxConcurrent;
ThreadFactory threadFactory = ThreadFactoryBuilder.newBuilder().withNameFormat("fenzo-worker-%d").build();
this.executorService = Executors.newFixedThreadPool(maxConcurrent, threadFactory);
this.stateMonitor = new StateMonitor();
this.schedulingEventListener = CompositeSchedulingEventListener.of(builder.schedulingEventListeners);
taskTracker = new TaskTracker();
resAllocsEvaluator = new ResAllocsEvaluater(taskTracker, builder.resAllocs);
assignableVMs = new AssignableVMs(taskTracker, builder.leaseRejectAction, builder.preferentialNamedConsumableResourceEvaluator,
builder.leaseOfferExpirySecs, builder.maxOffersToReject, builder.autoScaleByAttributeName,
builder.singleOfferMode, builder.autoScaleByAttributeName);
if (builder.autoScaleByAttributeName != null && !builder.autoScaleByAttributeName.isEmpty()) {
ScaleDownConstraintExecutor scaleDownConstraintExecutor = builder.scaleDownOrderEvaluator == null
? null : new ScaleDownConstraintExecutor(builder.scaleDownOrderEvaluator, builder.weightedScaleDownConstraintEvaluators);
autoScaler = new AutoScaler(builder.autoScaleByAttributeName, builder.autoScalerMapHostnameAttributeName,
builder.autoScaleDownBalancedByAttributeName,
builder.autoScaleRules, assignableVMs,
builder.disableShortfallEvaluation, assignableVMs.getActiveVmGroups(),
assignableVMs.getVmCollection(), scaleDownConstraintExecutor);
if (builder.autoscalerCallback != null) {
autoScaler.setCallback(builder.autoscalerCallback);
}
if (builder.delayAutoscaleDownBySecs > 0L) {
autoScaler.setDelayScaleDownBySecs(builder.delayAutoscaleDownBySecs);
}
if (builder.delayAutoscaleUpBySecs > 0L) {
autoScaler.setDelayScaleUpBySecs(builder.delayAutoscaleUpBySecs);
}
if (builder.disabledVmDurationInSecs > 0L) {
autoScaler.setDisabledVmDurationInSecs(builder.disabledVmDurationInSecs);
}
} else {
autoScaler = null;
}
assignableVMsEvaluator = builder.assignableVMsEvaluator == null ? avms -> avms : builder.assignableVMsEvaluator;
}
void checkIfShutdown() throws IllegalStateException {
if (isShutdown.get()) {
throw new IllegalStateException("TaskScheduler already shutdown");
}
}
/**
* Set the autoscale call back action. The callback you pass to this method receives an indication when an
* autoscale action is to be performed, telling it which autoscale rule prompted the action and whether the
* action is to scale up or scale down the autoscale group. The callback then initiates the appropriate
* scaling actions.
*
* @param callback the callback to invoke for autoscale actions
* @throws IllegalStateException if no autoscaler was established
* @see <a href="https://github.com/Netflix/Fenzo/wiki/Autoscaling">Autoscaling</a>
*/
public void setAutoscalerCallback(Action1<AutoScaleAction> callback) throws IllegalStateException {
checkIfShutdown();
if (autoScaler == null) {
throw new IllegalStateException("No autoScaler setup");
}
autoScaler.setCallback(callback);
}
public TaskTracker getTaskTracker() {
return taskTracker;
}
private TaskAssignmentResult getSuccessfulResult(List<TaskAssignmentResult> results) {
double bestFitness = 0.0;
TaskAssignmentResult bestResult = null;
for (int r = results.size() - 1; r >= 0; r--) {
// change to using fitness value from assignment result
TaskAssignmentResult res = results.get(r);
if (res != null && res.isSuccessful()) {
if (bestResult == null || res.getFitness() > bestFitness ||
(res.getFitness() == bestFitness && res.getHostname().compareTo(bestResult.getHostname()) < 0)) {
bestFitness = res.getFitness();
bestResult = res;
}
}
}
return bestResult;
}
private boolean isGoodEnough(TaskAssignmentResult result) {
return builder.isFitnessGoodEnoughFunction.call(result.getFitness());
}
/**
* Get the current mapping of resource allocations registered with the scheduler.
*
* @return current mapping of resource allocations
* @see <a href="https://github.com/Netflix/Fenzo/wiki/Resource-Allocation-Limits">Resource Allocation
* Limits</a>
*/
public Map<String, ResAllocs> getResAllocs() {
return resAllocsEvaluator.getResAllocs();
}
/**
* Add a new resource allocation, or replace an existing one of the same name.
*
* @param resAllocs the resource allocation to add or replace
* @see <a href="https://github.com/Netflix/Fenzo/wiki/Resource-Allocation-Limits">Resource Allocation
* Limits</a>
*/
public void addOrReplaceResAllocs(ResAllocs resAllocs) {
resAllocsEvaluator.replaceResAllocs(resAllocs);
}
/**
* Remove a resource allocation associated with the specified name.
*
* @param groupName the name of the resource allocation to remove
* @see <a href="https://github.com/Netflix/Fenzo/wiki/Resource-Allocation-Limits">Resource Allocation
* Limits</a>
*/
public void removeResAllocs(String groupName) {
resAllocsEvaluator.remResAllocs(groupName);
}
/**
* Get the autoscale rules currently registered with the scheduler.
*
* @return a collection of currently registered autoscale rules
* @see <a href="https://github.com/Netflix/Fenzo/wiki/Autoscaling">Autoscaling</a>
*/
public Collection<AutoScaleRule> getAutoScaleRules() {
if (autoScaler == null) {
return Collections.emptyList();
}
return autoScaler.getRules();
}
/**
* Add a new autoscale rule to those used by this scheduler. If a rule with the same name exists, it is
* replaced. This autoscale rule will be used the next time the scheduler invokes its autoscale action.
*
* @param rule the autoscale rule to add
* @see <a href="https://github.com/Netflix/Fenzo/wiki/Autoscaling">Autoscaling</a>
*/
public void addOrReplaceAutoScaleRule(AutoScaleRule rule) {
autoScaler.replaceRule(rule);
}
/**
* Remove the autoscale rule associated with the given name from those used by the scheduler.
*
* @param ruleName name of the autoscale rule to remove
* @see <a href="https://github.com/Netflix/Fenzo/wiki/Autoscaling">Autoscaling</a>
*/
public void removeAutoScaleRule(String ruleName) {
autoScaler.removeRule(ruleName);
}
/* package */ void setUsingSchedulingService(boolean b) {
usingSchedulingService = b;
}
/* package */ void setTaskToClusterAutoScalerMapGetter(Func1<QueuableTask, List<String>> getter) {
if (autoScaler != null) {
autoScaler.setTaskToClustersGetter(getter);
}
}
/* package */ AutoScaler getAutoScaler() {
return autoScaler;
}
/**
* Schedule a list of task requests by using any newly-added resource leases in addition to any
* previously-unused leases. This is the main scheduling method that attempts to assign resources to task
* requests. Resource leases are associated with a host name. A host can have zero or more leases. Leases
* that the scheduler does not use in this scheduling run it stores for later use until they expire.
* <p>
* You cannot add a lease object with an Id equal to that of a stored lease object; {@code scheduleOnce()}
* will throw an {@code IllegalStateException}. Upon throwing this exception, if you provided multiple
* leases in the {@code newLeases} argument, the state of internally maintained list of unused leases will
* be in an indeterminate state - some of the leases may have been successfully added.
* <p>
* The task scheduler rejects any expired leases before scheduling begins. Then, it combines all leases of a
* host to determine the total available resources on the host. The scheduler then tries each task request,
* in the order that they appear in the given list, for assignment against the available hosts until
* successful. For each task the scheduler returns either a successful assignment result, or, a set of
* assignment failures.
* <p>
* After the scheduler evaluates all assignments, it will reject remaining leases if they are unused and
* their offer time is further in the past than lease expiration interval. This prevents the scheduler from
* hoarding leases. If you provided an autoscaler, the scheduler then launches autoscale evaluation to run
* asynchronously, which runs each registered autoscale rule based on its policy.
* <p>
* The successful assignments contain hosts to which tasks have been successfully assigned and the offers for that
* host that were used for the assignments. Fenzo removes those offers from its internal state. Normally, you
* would use those offers to launch the tasks. For any reason if you do not launch those tasks, you must either
* reject the offers to Mesos, or, re-add them to Fenzo with the next call to {@link #scheduleOnce(List, List)}.
* Otherwise, those offers would be "leaked out".
* <p>
* Unexpected exceptions may arise during scheduling, for example, due to uncaught exceptions in user provided
* plugins. The scheduling routine stops upon catching any unexpected exceptions. These exceptions are surfaced to
* you in one or both of two ways.
* <UL>
* <li>The returned result object will contain the exceptions encountered in
* {@link SchedulingResult#getExceptions()}. In this case, no assignments would have been made.</li>
* <li>This method may throw {@code IllegalStateException} with its cause set to the uncaught exception. In this
* case the internal state of Fenzo will be undefined.</li>
* </UL>
* If there are exceptions, the internal state of Fenzo may be corrupt with no way to undo any partial effects.
*
* @param requests a list of task requests to match with resources, in their given order
* @param newLeases new resource leases from hosts that the scheduler can use along with any previously
* ununsed leases
* @return a {@link SchedulingResult} object that contains a task assignment results map and other summaries
* @throws IllegalStateException if you call this method concurrently, or, if you try to add an existing lease
* again, or, if there was unexpected exception during the scheduling iteration, or, if using
* {@link TaskSchedulingService}, which will instead invoke scheduling from within. Unexpected exceptions
* can arise from uncaught exceptions in user defined plugins. It is also thrown if the scheduler has been shutdown
* via the {@link #shutdown()} method.
*/
public SchedulingResult scheduleOnce(
List<? extends TaskRequest> requests,
List<VirtualMachineLease> newLeases) throws IllegalStateException {
if (usingSchedulingService) {
throw new IllegalStateException(usingSchedSvcMesg);
}
final Iterator<? extends TaskRequest> iterator =
requests != null ?
requests.iterator() :
Collections.<TaskRequest>emptyIterator();
TaskIterator taskIterator = () -> {
if (iterator.hasNext()) {
return Assignable.success(iterator.next());
}
return null;
};
return scheduleOnce(taskIterator, newLeases);
}
/**
* Variant of {@link #scheduleOnce(List, List)} that takes a task iterator instead of task list.
*
* @param taskIterator Iterator for tasks to assign resources to.
* @param newLeases new resource leases from hosts that the scheduler can use along with any previously
* ununsed leases
* @return a {@link SchedulingResult} object that contains a task assignment results map and other summaries
* @throws IllegalStateException if you call this method concurrently, or, if you try to add an existing lease
* again, or, if there was unexpected exception during the scheduling iteration. For example, unexpected exceptions
* can arise from uncaught exceptions in user defined plugins. It is also thrown if the scheduler has been shutdown
* via the {@link #shutdown()} method.
*/
/* package */ SchedulingResult scheduleOnce(
TaskIterator taskIterator,
List<VirtualMachineLease> newLeases) throws IllegalStateException {
checkIfShutdown();
try (AutoCloseable ignored = stateMonitor.enter()) {
return doScheduling(taskIterator, newLeases);
} catch (Exception e) {
logger.error("Error with scheduling run: " + e.getMessage(), e);
if (e instanceof IllegalStateException) {
throw (IllegalStateException) e;
} else {
logger.warn("Unexpected exception: " + e.getMessage());
throw new IllegalStateException("Unexpected exception during scheduling run: " + e.getMessage(), e);
}
}
}
/**
* Variant of {@link #scheduleOnce(List, List)} that should be only used to schedule a pseudo iteration as it
* ignores the StateMonitor lock.
*
* @param taskIterator Iterator for tasks to assign resources to.
* @return a {@link SchedulingResult} object that contains a task assignment results map and other summaries
*/
/* package */ SchedulingResult pseudoScheduleOnce(TaskIterator taskIterator) throws Exception {
return doScheduling(taskIterator, Collections.emptyList());
}
private SchedulingResult doScheduling(TaskIterator taskIterator,
List<VirtualMachineLease> newLeases) throws Exception {
long start = System.currentTimeMillis();
final SchedulingResult schedulingResult = doSchedule(taskIterator, newLeases);
if ((lastVMPurgeAt + purgeVMsIntervalSecs * 1000) < System.currentTimeMillis()) {
lastVMPurgeAt = System.currentTimeMillis();
logger.debug("Purging inactive VMs");
assignableVMs.purgeInactiveVMs( // explicitly exclude VMs that have assignments
schedulingResult.getResultMap() == null ?
Collections.emptySet() :
new HashSet<>(schedulingResult.getResultMap().keySet())
);
}
schedulingResult.setRuntime(System.currentTimeMillis() - start);
return schedulingResult;
}
private SchedulingResult doSchedule(
TaskIterator taskIterator,
List<VirtualMachineLease> newLeases) throws Exception {
AtomicInteger rejectedCount = new AtomicInteger();
List<AssignableVirtualMachine> originalVms = assignableVMs.prepareAndGetOrderedVMs(newLeases, rejectedCount);
List<AssignableVirtualMachine> avms = assignableVMsEvaluator.call(originalVms);
if (logger.isDebugEnabled()) {
logger.debug("Original VMs: {}", originalVms);
logger.debug("VMs: {}", avms);
}
List<AssignableVirtualMachine> inactiveAVMs = assignableVMs.getInactiveVMs();
final boolean hasResAllocs = resAllocsEvaluator.prepare();
//logger.info("Got " + avms.size() + " AVMs to schedule on");
int totalNumAllocations = 0;
Set<TaskRequest> failedTasksForAutoScaler = new HashSet<>();
Map<String, VMAssignmentResult> resultMap = new HashMap<>(avms.size());
final SchedulingResult schedulingResult = new SchedulingResult(resultMap);
long taskBatchSize = builder.taskBatchSizeSupplier.get();
long tasksIterationCount = 0;
if (avms.isEmpty()) {
while (true) {
final Assignable<? extends TaskRequest> taskOrFailure = taskIterator.next();
if (taskOrFailure == null) {
break;
}
failedTasksForAutoScaler.add(taskOrFailure.getTask());
}
} else {
schedulingEventListener.onScheduleStart();
try {
while (true) {
if (tasksIterationCount >= taskBatchSize) {
break;
}
final Assignable<? extends TaskRequest> taskOrFailure = taskIterator.next();
if (logger.isDebugEnabled()) {
logger.debug("TaskSched: task=" + (taskOrFailure == null ? "null" : taskOrFailure.getTask().getId()));
}
if (taskOrFailure == null) {
break;
}
if (taskOrFailure.hasFailure()) {
schedulingResult.addFailures(
taskOrFailure.getTask(),
Collections.singletonList(new TaskAssignmentResult(
assignableVMs.getDummyVM(),
taskOrFailure.getTask(),
false,
Collections.singletonList(taskOrFailure.getAssignmentFailure()),
null,
0
)
));
continue;
}
TaskRequest task = taskOrFailure.getTask();
failedTasksForAutoScaler.add(task);
if (hasResAllocs) {
if (resAllocsEvaluator.taskGroupFailed(task.taskGroupName())) {
if (logger.isDebugEnabled()) {
logger.debug("Resource allocation limits reached for task: " + task.getId());
}
continue;
}
final AssignmentFailure resAllocsFailure = resAllocsEvaluator.hasResAllocs(task);
if (resAllocsFailure != null) {
final List<TaskAssignmentResult> failures = Collections.singletonList(new TaskAssignmentResult(assignableVMs.getDummyVM(),
task, false, Collections.singletonList(resAllocsFailure), null, 0.0));
schedulingResult.addFailures(task, failures);
failedTasksForAutoScaler.remove(task); // don't scale up for resAllocs failures
if (logger.isDebugEnabled()) {
logger.debug("Resource allocation limit reached for task " + task.getId() + ": " + resAllocsFailure);
}
continue;
}
}
final AssignmentFailure maxResourceFailure = assignableVMs.getFailedMaxResource(null, task);
if (maxResourceFailure != null) {
final List<TaskAssignmentResult> failures = Collections.singletonList(new TaskAssignmentResult(assignableVMs.getDummyVM(), task, false,
Collections.singletonList(maxResourceFailure), null, 0.0));
schedulingResult.addFailures(task, failures);
if (logger.isDebugEnabled()) {
logger.debug("Task {}: maxResource failure: {}", task.getId(), maxResourceFailure);
}
continue;
}
// create batches of VMs to evaluate assignments concurrently across the batches
final BlockingQueue<AssignableVirtualMachine> virtualMachines = new ArrayBlockingQueue<>(avms.size(), false, avms);
int nThreads = (int) Math.ceil((double) avms.size() / PARALLEL_SCHED_EVAL_MIN_BATCH_SIZE);
List<Future<EvalResult>> futures = new ArrayList<>();
if (logger.isDebugEnabled()) {
logger.debug("Launching {} threads for evaluating assignments for task {}", nThreads, task.getId());
}
for (int b = 0; b < nThreads && b < maxConcurrent; b++) {
futures.add(executorService.submit(() -> evalAssignments(task, virtualMachines)));
}
List<EvalResult> results = new ArrayList<>();
List<TaskAssignmentResult> bestResults = new ArrayList<>();
for (Future<EvalResult> f : futures) {
try {
EvalResult evalResult = f.get();
if (evalResult.exception != null) {
logger.warn("Error during concurrent task assignment eval - " + evalResult.exception.getMessage(),
evalResult.exception);
schedulingResult.addException(evalResult.exception);
} else {
results.add(evalResult);
bestResults.add(evalResult.result);
if (logger.isDebugEnabled()) {
logger.debug("Task {}: best result so far: {}", task.getId(), evalResult.result);
}
totalNumAllocations += evalResult.numAllocationTrials;
}
} catch (InterruptedException | ExecutionException e) {
logger.error("Unexpected during concurrent task assignment eval - " + e.getMessage(), e);
}
}
if (!schedulingResult.getExceptions().isEmpty()) {
break;
}
TaskAssignmentResult successfulResult = getSuccessfulResult(bestResults);
List<TaskAssignmentResult> failures = new ArrayList<>();
if (successfulResult == null) {
if (logger.isDebugEnabled()) {
logger.debug("Task {}: no successful results", task.getId());
}
for (EvalResult er : results) {
failures.addAll(er.assignmentResults);
}
schedulingResult.addFailures(task, failures);
} else {
if (logger.isDebugEnabled()) {
logger.debug("Task {}: found successful assignment on host {}", task.getId(),
successfulResult.getHostname());
}
successfulResult.assignResult();
tasksIterationCount++;
failedTasksForAutoScaler.remove(task);
schedulingEventListener.onAssignment(successfulResult);
}
}
} finally {
schedulingEventListener.onScheduleFinish();
}
}
List<VirtualMachineLease> idleResourcesList = new ArrayList<>();
if (schedulingResult.getExceptions().isEmpty()) {
List<VirtualMachineLease> expirableLeases = new ArrayList<>();
for (AssignableVirtualMachine avm : avms) {
VMAssignmentResult assignmentResult = avm.resetAndGetSuccessfullyAssignedRequests();
if (assignmentResult == null) {
if (!avm.hasPreviouslyAssignedTasks()) {
idleResourcesList.add(avm.getCurrTotalLease());
}
expirableLeases.add(avm.getCurrTotalLease());
} else {
resultMap.put(avm.getHostname(), assignmentResult);
}
}
// Process inactive VMs
List<VirtualMachineLease> idleInactiveAVMs = inactiveAVMs.stream()
.filter(vm -> vm.getCurrTotalLease() != null && !vm.hasPreviouslyAssignedTasks())
.map(AssignableVirtualMachine::getCurrTotalLease)
.collect(Collectors.toList());
rejectedCount.addAndGet(assignableVMs.removeLimitedLeases(expirableLeases));
if (autoScaler != null) {
AutoScalerInput autoScalerInput = new AutoScalerInput(idleResourcesList, idleInactiveAVMs, failedTasksForAutoScaler);
autoScaler.doAutoscale(autoScalerInput);
}
}
schedulingResult.setLeasesAdded(newLeases.size());
schedulingResult.setLeasesRejected(rejectedCount.get());
schedulingResult.setNumAllocations(totalNumAllocations);
schedulingResult.setTotalVMsCount(assignableVMs.getTotalNumVMs());
schedulingResult.setIdleVMsCount(idleResourcesList.size());
return schedulingResult;
}
/* package */ Map<String, List<String>> createPseudoHosts(Map<String, Integer> groupCounts) {
return assignableVMs.createPseudoHosts(groupCounts, autoScaler == null ? name -> null : autoScaler::getRule);
}
/* package */ void removePseudoHosts(Map<String, List<String>> hostsMap) {
assignableVMs.removePseudoHosts(hostsMap);
}
/* package */ void removePseudoAssignments() {
taskTracker.clearAssignedTasks(); // this should suffice for pseudo assignments
}
/**
* Returns the state of resources on all known hosts. You can use this for debugging or informational
* purposes (occasionally). This method obtains and holds a lock for the duration of creating the state
* information. Scheduling runs are blocked around the lock.
*
* @return a Map of state information with the hostname as the key and a Map of resource state as the value.
* The resource state Map contains a resource as the key and a two element Double array - the first
* element of which contains the amount of the resource used and the second element contains the
* amount still available (available does not include used).
* @throws IllegalStateException if called concurrently with {@link #scheduleOnce(List, List)} or if called when
* using a {@link TaskSchedulingService}.
* @see <a href="https://github.com/Netflix/Fenzo/wiki/Insights#how-to-learn-which-resources-are-available-on-which-hosts">How to Learn Which Resources Are Available on Which Hosts</a>
*/
public Map<String, Map<VMResource, Double[]>> getResourceStatus() throws IllegalStateException {
if (usingSchedulingService) {
throw new IllegalStateException(usingSchedSvcMesg);
}
return getResourceStatusIntl();
}
/* package */ Map<String, Map<VMResource, Double[]>> getResourceStatusIntl() {
try (AutoCloseable ignored = stateMonitor.enter()) {
return assignableVMs.getResourceStatus();
} catch (Exception e) {
logger.error("Unexpected error from state monitor: " + e.getMessage());
throw new RuntimeException(e);
}
}
/**
* Returns the current state of all known hosts. You might occasionally use this for debugging or
* informational purposes. If you call this method, it will obtain and hold a lock for as long as it takes
* to create the state information. Scheduling runs are blocked around the lock.
*
* @return a list containing the current state of all known VMs
* @throws IllegalStateException if called concurrently with {@link #scheduleOnce(List, List)} or if called when
* using a {@link TaskSchedulingService}.
* @see <a href="https://github.com/Netflix/Fenzo/wiki/Insights#how-to-learn-the-amount-of-resources-currently-available-on-particular-hosts">How to Learn the Amount of Resources Currently Available on Particular Hosts</a>
*/
public List<VirtualMachineCurrentState> getVmCurrentStates() throws IllegalStateException {
if (usingSchedulingService) {
throw new IllegalStateException(usingSchedSvcMesg);
}
return getVmCurrentStatesIntl();
}
/* package */ List<VirtualMachineCurrentState> getVmCurrentStatesIntl() throws IllegalStateException {
try (AutoCloseable ignored = stateMonitor.enter()) {
return assignableVMs.getVmCurrentStates();
} catch (Exception e) {
logger.error("Unexpected error from state monitor: " + e.getMessage(), e);
throw new IllegalStateException(e);
}
}
private EvalResult evalAssignments(TaskRequest task, BlockingQueue<AssignableVirtualMachine> virtualMachines) {
// This number below sort of controls minimum machines to eval, choose carefully.
// Having it too small increases overhead of getting next machine to evaluate on.
// Having it too high increases latency of thread before it returns when done
try {
int N = 10;
List<AssignableVirtualMachine> buf = new ArrayList<>(N);
List<TaskAssignmentResult> results = new ArrayList<>();
while (true) {
buf.clear();
int n = virtualMachines.drainTo(buf, N);
if (n == 0) {
return new EvalResult(results, getSuccessfulResult(results), results.size(), null);
}
for (int m = 0; m < n; m++) {
final AssignableVirtualMachine avm = buf.get(m);
if (logger.isDebugEnabled()) {
logger.debug("Evaluating task assignment on host " + avm.getHostname());
logger.debug("CurrTotalRes on host {}: {}", avm.getHostname(), avm.getCurrTotalLease());
}
TaskAssignmentResult result = avm.tryRequest(task, builder.fitnessCalculator);
results.add(result);
if (result.isSuccessful() && builder.isFitnessGoodEnoughFunction.call(result.getFitness())) {
// drain rest of the queue, nobody needs to do more work.
virtualMachines.clear();
// Instead of returning here, we finish computing on rest of the machines in buf
}
}
}
} catch (Exception e) {
return new EvalResult(null, null, 0, e);
}
}
/**
* Call this method to instruct the task scheduler to reject a particular resource offer.
*
* @param leaseId the lease ID of the lease to expire
* @throws IllegalStateException if the scheduler is shutdown via the {@link #isShutdown} method.
*/
public void expireLease(String leaseId) throws IllegalStateException {
assignableVMs.expireLease(leaseId);
}
/**
* Call this method to instruct the task scheduler to reject all of the unused offers it is currently
* holding that concern resources offered by the host with the name {@code hostname}.
*
* @param hostname the name of the host whose leases you want to expire
* @throws IllegalStateException if the scheduler is shutdown via the {@link #isShutdown} method.
*/
public void expireAllLeases(String hostname) throws IllegalStateException {
assignableVMs.expireAllLeases(hostname);
}
/**
* Call this method to instruct the task scheduler to reject all of the unused offers it is currently
* holding that concern resources offered by the host with the ID, {@code vmId}.
*
* @param vmId the ID of the host whose leases you want to expire
* @return {@code true} if the given ID matches a known host, {@code false} otherwise.
* @throws IllegalStateException if the scheduler is shutdown via the {@link #isShutdown} method.
*/
public boolean expireAllLeasesByVMId(String vmId) throws IllegalStateException {
final String hostname = assignableVMs.getHostnameFromVMId(vmId);
if (hostname == null) {
return false;
}
expireAllLeases(hostname);
return true;
}
/**
* Call this method to instruct the task scheduler to reject all of the unused offers it is currently
* holding.
*
* @throws IllegalStateException if the scheduler is shutdown via the {@link #isShutdown} method.
*/
public void expireAllLeases() throws IllegalStateException {
logger.debug("Expiring all leases");
assignableVMs.expireAllLeases();
}
/**
* Get the task assigner action. For each task you assign and launch, you must call your task scheduler's
* {@code getTaskAssigner().call()} method in order to notify Fenzo that the task has actually been deployed
* on a host. Pass two arguments to this call method: the {@link TaskRequest} object for the task assigned and
* the hostname.
*
* <p>
* In addition, in your framework's task completion callback that you supply to Mesos, you must call your
* task scheduler's {@link #getTaskUnAssigner() getTaskUnassigner().call()} method to notify Fenzo that the
* task is no longer assigned.
* <p>
* Some scheduling optimizers need to know not only which tasks are waiting to be scheduled and which hosts
* have resource offers available, but also which tasks have previously been assigned and are currently
* running on hosts. These two methods help Fenzo provide this information to these scheduling optimizers.
* <p>
* Note that you may not call the task assigner action concurrently with
* {@link #scheduleOnce(java.util.List, java.util.List) scheduleOnce()}. If you do so, the task assigner
* action will throw an {@code IllegalStateException}.
*
* @return a task assigner action
* @throws IllegalStateException if the scheduler is shutdown via the {@link #isShutdown} method.
*/
public Action2<TaskRequest, String> getTaskAssigner() throws IllegalStateException {
if (usingSchedulingService) {
throw new IllegalStateException(usingSchedSvcMesg);
}
return getTaskAssignerIntl();
}
/* package */Action2<TaskRequest, String> getTaskAssignerIntl() throws IllegalStateException {
return (request, hostname) -> {
try (AutoCloseable ignored = stateMonitor.enter()) {
assignableVMs.setTaskAssigned(request, hostname);
} catch (Exception e) {
logger.error("Unexpected error from state monitor: " + e.getMessage(), e);
throw new IllegalStateException(e);
}
};
}
/**
* Get the task unassigner action. Call this object's {@code call()} method to unassign an assignment you
* have previously set for each task that completes so that internal state is maintained correctly. Pass two
* String arguments to this call method: the taskId and the hostname.
* <p>
* For each task you assign and launch, you must call your task scheduler's
* {@link #getTaskAssigner() getTaskAssigner().call()} method in order to notify Fenzo that the task has
* actually been deployed on a host.
* <p>
* In addition, in your framework's task completion callback that you supply to Mesos, you must call your
* task scheduler's {@code getTaskUnassigner().call()} method to notify Fenzo that the
* task is no longer assigned.
* <p>
* Some scheduling optimizers need to know not only which tasks are waiting to be scheduled and which hosts
* have resource offers available, but also which tasks have previously been assigned and are currently
* running on hosts. These two methods help Fenzo provide this information to these scheduling optimizers.
* <p>
* This method is safe to be called concurrently with other calls to {@code TaskScheduler}. The tasks to be
* unassigned are stored internally and actually unassigned at the beginning of the next scheduling iteration,
* that is, the next time {@link #scheduleOnce(List, List)} is called.
*
* @return the task un-assigner action
* @throws IllegalStateException if the scheduler is shutdown via the {@link #isShutdown} method.
*/
public Action2<String, String> getTaskUnAssigner() throws IllegalStateException {
return assignableVMs::unAssignTask;
}
/**
* Disable the virtual machine with the specified hostname. The scheduler will not use disabled hosts for
* allocating resources to tasks.
*
* @param hostname the name of the host to disable
* @param durationMillis the length of time, starting from now, in milliseconds, during which the host will
* be disabled
* @throws IllegalStateException if the scheduler is shutdown via the {@link #isShutdown} method.
*/
public void disableVM(String hostname, long durationMillis) throws IllegalStateException {
logger.debug("Disable VM " + hostname + " for " + durationMillis + " millis");
assignableVMs.disableUntil(hostname, System.currentTimeMillis() + durationMillis);
}
/**
* Disable the virtual machine with the specified ID. The scheduler will not use disabled hosts for allocating
* resources to tasks.
*
* @param vmID the ID of the host to disable
* @param durationMillis the length of time, starting from now, in milliseconds, during which the host will
* be disabled
* @return {@code true} if the ID matches a known VM, {@code false} otherwise.
* @throws IllegalStateException if the scheduler is shutdown via the {@link #isShutdown} method.
*/
public boolean disableVMByVMId(String vmID, long durationMillis) throws IllegalStateException {
final String hostname = assignableVMs.getHostnameFromVMId(vmID);
if (hostname == null) {
return false;
}
disableVM(hostname, durationMillis);
return true;
}
/**
* Enable the VM with the specified host name. Hosts start in an enabled state, so you only need to call
* this method if you have previously explicitly disabled the host.
*
* @param hostname the name of the host to enable
* @throws IllegalStateException if the scheduler is shutdown via the {@link #isShutdown} method.
*/
public void enableVM(String hostname) throws IllegalStateException {
logger.debug("Enabling VM " + hostname);
assignableVMs.enableVM(hostname);
}
/**
* Set how the scheduler determines to which group the VM (host) belongs. You can group hosts. Which group a
* host belongs to is determined by the value of a particular attribute in its offers. You can set which
* attribute defines group membership by naming it in this method.
*
* @param attributeName the name of the attribute that determines a VM's group
*/
public void setActiveVmGroupAttributeName(String attributeName) {
assignableVMs.setActiveVmGroupAttributeName(attributeName);
}
/**
* Set the list of VM group names that are active. VMs (hosts) that belong to groups that you do not include
* in this list are said to be disabled. The scheduler does not use the resources of disabled hosts when it
* allocates tasks. If you pass in a null list, this indicates that the scheduler should consider all groups
* to be enabled.
*
* @param vmGroups a list of VM group names that the scheduler is to consider to be enabled, or {@code null}
* if the scheduler is to consider every group to be enabled
*/
public void setActiveVmGroups(List<String> vmGroups) {
assignableVMs.setActiveVmGroups(vmGroups);
}
/**
* Mark task scheduler as shutdown and shutdown any thread pool executors created.
*/
public void shutdown() {
if (isShutdown.compareAndSet(false, true)) {
executorService.shutdown();
if (autoScaler != null) {
autoScaler.shutdown();
}
}
}
}
| 9,137 |
0 | Create_ds/Fenzo/fenzo-core/src/main/java/com/netflix | Create_ds/Fenzo/fenzo-core/src/main/java/com/netflix/fenzo/PreferentialNamedConsumableResourceEvaluator.java | package com.netflix.fenzo;
import com.netflix.fenzo.PreferentialNamedConsumableResourceSet.PreferentialNamedConsumableResource;
/**
* Evaluator for {@link PreferentialNamedConsumableResource} selection process. Given an agent with matching
* ENI slot (either empty or with a matching name), this evaluator computes the fitness score.
* A custom implementation can provide fitness calculators augmented with additional information not available to
* Fenzo for making best placement decision.
*
* <h1>Example</h1>
* {@link PreferentialNamedConsumableResource} can be used to model AWS ENI interfaces together with IP and security
* group assignments. To minimize number of AWS API calls and to improve efficiency, it is beneficial to place a task
* on an agent which has ENI profile with matching security group profile so the ENI can be reused. Or if a task
* is terminated, but agent releases its resources lazily, they can be reused by another task with a matching profile.
*/
public interface PreferentialNamedConsumableResourceEvaluator {
/**
* Provide fitness score for an idle consumable resource.
*
* @param hostname hostname of an agent
* @param resourceName name to be associated with a resource with the given index
* @param index a consumable resource index
* @param subResourcesNeeded an amount of sub-resources required by a scheduled task
* @param subResourcesLimit a total amount of sub-resources available
* @return fitness score
*/
double evaluateIdle(String hostname, String resourceName, int index, double subResourcesNeeded, double subResourcesLimit);
/**
* Provide fitness score for a consumable resource that is already associated with some tasks. These tasks and
* the current one having profiles so can share the resource.
*
* @param hostname hostname of an agent
* @param resourceName name associated with a resource with the given index
* @param index a consumable resource index
* @param subResourcesNeeded an amount of sub-resources required by a scheduled task
* @param subResourcesUsed an amount of sub-resources already used by other tasks
* @param subResourcesLimit a total amount of sub-resources available
* @return fitness score
*/
double evaluate(String hostname, String resourceName, int index, double subResourcesNeeded, double subResourcesUsed, double subResourcesLimit);
}
| 9,138 |
0 | Create_ds/Fenzo/fenzo-core/src/main/java/com/netflix | Create_ds/Fenzo/fenzo-core/src/main/java/com/netflix/fenzo/ScaleDownOrderEvaluator.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.fenzo;
import java.util.Collection;
import java.util.List;
import java.util.Set;
/**
* A constraint evaluator that examines if VMs can be terminated, and in which order. It groups VMs into equivalence
* classes, and orders them according to their scale down priority. If a VM instance is missing in the returned list
* it means that it should not be terminated.
* The scale down order within an equivalence class is determined by {@link ScaleDownConstraintExecutor}.
*/
public interface ScaleDownOrderEvaluator {
/**
* Returns VMs grouped into equivalence classes ordered according to their scale down priority.
*
* @param candidates VMs to be terminated
* @return VMs in scale down order
*/
List<Set<VirtualMachineLease>> evaluate(Collection<VirtualMachineLease> candidates);
}
| 9,139 |
0 | Create_ds/Fenzo/fenzo-core/src/main/java/com/netflix | Create_ds/Fenzo/fenzo-core/src/main/java/com/netflix/fenzo/AsSoftConstraint.java | /*
* Copyright 2015 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.fenzo;
import com.netflix.fenzo.ConstraintEvaluator;
import com.netflix.fenzo.TaskRequest;
import com.netflix.fenzo.TaskTrackerState;
import com.netflix.fenzo.VMTaskFitnessCalculator;
import com.netflix.fenzo.VirtualMachineCurrentState;
/**
* Converts a hard constraint into a soft constraint. A {@link ConstraintEvaluator} is by default a "hard," or
* mandatory constraint. Fenzo will not place a task with a target that fails such a constraint, and will not
* place the task at all if no target passes the constraint. You can convert such a "hard" constraint into a
* "soft" constraint by passing it into the {@link #get} method of this class. That method returns a
* {@link VMTaskFitnessCalculator} that implements a "soft" constraint. When Fenzo uses such a constraint, it
* will attempt to place a task with a target that satisfies the constraint, but will place the task with a
* target that fails the constraint if no other target can be found.
* <p>
* The resulting "soft" constraint will return evaluate a host/task combination as 0.0 if the underlying hard
* constraint would be violated, or 1.0 if the underlying hard constraint would be satisfied.
* <p>
* Note that some hard constraints may implement their own hard-to-soft conversion methods and that these
* methods may return a soft constraint that is more nuanced, returning values between 0.0 and 1.0 and not just
* those two values at either extreme (see, for example,
* {@link com.netflix.fenzo.plugins.BalancedHostAttrConstraint BalancedHostAttrConstraint}).
*/
public class AsSoftConstraint {
/**
* Returns a "soft" constraint, in the form of a {@link VMTaskFitnessCalculator}, based on a specified "hard"
* constraint, in the form of a {@link ConstraintEvaluator}.
*
* @param c the "hard" constraint to convert
* @return a "soft" constraint version of {@code c}
*/
public static VMTaskFitnessCalculator get(final ConstraintEvaluator c) {
// This fitness calculator return 0 or 1. This can possibly be improved upon by the ConstraintEvaluator using its
// own logic.
return new VMTaskFitnessCalculator() {
@Override
public String getName() {
return c.getName();
}
@Override
public double calculateFitness(TaskRequest taskRequest, VirtualMachineCurrentState targetVM, TaskTrackerState taskTrackerState) {
return c.evaluate(taskRequest, targetVM, taskTrackerState).isSuccessful()? 1.0 : 0.0;
}
};
}
}
| 9,140 |
0 | Create_ds/Fenzo/fenzo-core/src/main/java/com/netflix | Create_ds/Fenzo/fenzo-core/src/main/java/com/netflix/fenzo/TaskIterator.java | /*
* Copyright 2016 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.fenzo;
import com.netflix.fenzo.queues.Assignable;
import com.netflix.fenzo.queues.TaskQueueException;
public interface TaskIterator {
/**
* Get the next task from queue, or {@code null} if no more tasks exist.
* @return The next task or a task with an assignment failure, if the task cannot be scheduled due to some
* internal constraints (for example exceeds allowed resource usage for a queue).
* Returns {@code null} if there are no tasks left to assign resources to.
* @throws TaskQueueException if there were errors retrieving the next task from the queue.
*/
Assignable<? extends TaskRequest> next() throws TaskQueueException;
}
| 9,141 |
0 | Create_ds/Fenzo/fenzo-core/src/main/java/com/netflix | Create_ds/Fenzo/fenzo-core/src/main/java/com/netflix/fenzo/AutoScalerInput.java | /*
* Copyright 2015 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.fenzo;
import java.util.List;
import java.util.Set;
class AutoScalerInput {
private final List<VirtualMachineLease> idleResourcesList;
private final List<VirtualMachineLease> idleInactiveResources;
private final Set<TaskRequest> failedTasks;
AutoScalerInput(List<VirtualMachineLease> idleResources, List<VirtualMachineLease> idleInactiveResources, Set<TaskRequest> failedTasks) {
this.idleResourcesList= idleResources;
this.idleInactiveResources = idleInactiveResources;
this.failedTasks = failedTasks;
}
public List<VirtualMachineLease> getIdleResourcesList() {
return idleResourcesList;
}
public List<VirtualMachineLease> getIdleInactiveResourceList() {
return idleInactiveResources;
}
public Set<TaskRequest> getFailures() {
return failedTasks;
}
}
| 9,142 |
0 | Create_ds/Fenzo/fenzo-core/src/main/java/com/netflix | Create_ds/Fenzo/fenzo-core/src/main/java/com/netflix/fenzo/CompositeSchedulingEventListener.java | package com.netflix.fenzo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.function.Consumer;
class CompositeSchedulingEventListener implements SchedulingEventListener {
private static final Logger logger = LoggerFactory.getLogger(CompositeSchedulingEventListener.class);
private final List<SchedulingEventListener> listeners;
private CompositeSchedulingEventListener(Collection<SchedulingEventListener> listeners) {
this.listeners = new ArrayList<>(listeners);
}
@Override
public void onScheduleStart() {
safely(SchedulingEventListener::onScheduleStart);
}
@Override
public void onAssignment(TaskAssignmentResult taskAssignmentResult) {
safely(listener -> listener.onAssignment(taskAssignmentResult));
}
@Override
public void onScheduleFinish() {
safely(SchedulingEventListener::onScheduleFinish);
}
private void safely(Consumer<SchedulingEventListener> action) {
listeners.forEach(listener -> {
try {
action.accept(listener);
} catch (Exception e) {
logger.warn("Scheduling event dispatching error: {} -> {}", listener.getClass().getSimpleName(), e.getMessage());
if (logger.isDebugEnabled()) {
logger.debug("Details", e);
}
}
});
}
static SchedulingEventListener of(Collection<SchedulingEventListener> listeners) {
if (listeners.isEmpty()) {
return NoOpSchedulingEventListener.INSTANCE;
}
return new CompositeSchedulingEventListener(listeners);
}
}
| 9,143 |
0 | Create_ds/Fenzo/fenzo-core/src/main/java/com/netflix | Create_ds/Fenzo/fenzo-core/src/main/java/com/netflix/fenzo/AutoScaleRule.java | /*
* Copyright 2015 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.fenzo;
/**
* A rule that defines when to scale the number of hosts of a certain type. You define one rule for each unique
* value of the host attribute that you have designated to differentiate autoscale groups (see the
* {@link com.netflix.fenzo.TaskScheduler.Builder#withAutoScaleByAttributeName(String) withAutoScaleByAttributeName()}
* task scheduler builder method).
*/
public interface AutoScaleRule {
/**
* Returns the value, for the group of hosts that this rule applies to, of the host attribute that you have
* designated to differentiate autoscale groups. This acts as the name of the autoscaling group.
*
* @return the value of the designated host attribute, which is the name of the autoscaling group this rule
* applies to
*/
String getRuleName();
/**
* Returns the minimum number of hosts, in the autoscale group this rule applies to, that Fenzo is to keep
* in idle readiness. Keeping idle hosts in a standby state like this allows Fenzo to rapidly launch new
* jobs without waiting for new instances to spin up.
*
* @return the minimum number of idle hosts to maintain in this autoscale group
*/
int getMinIdleHostsToKeep();
/**
* Returns the minimum number of hosts to expect in the autoscale group for this rule. Fenzo will not invoke
* scale down actions that will make the group size to go below this minimum size. A value of {@code 0} effectively
* disables this function.
* @return The minimum number of hosts to expect in the group, even if idle.
*/
default int getMinSize() {
return 0;
}
/**
* Returns the maximum number of hosts, in the autoscale group this rule applies to, that Fenzo is to keep
* in idle readiness. Keeping idle hosts in a standby state like this allows Fenzo to rapidly launch new
* jobs without waiting for new instances to spin up.
*
* @return the maximum number of idle hosts to maintain in this autoscale group
*/
int getMaxIdleHostsToKeep();
/**
* Returns the maximum number of hosts to expect in the autoscale group for this rule. Fenzo will not invoke
* scale up actions that could make the group size higher than this value. A value of {@link Integer#MAX_VALUE}
* effectively disables this function.
* @return The maximum number of hosts to expect in this group, even if no idle hosts remain.
*/
default int getMaxSize() {
return Integer.MAX_VALUE;
}
/**
* Returns adjusted number of agents. By default the same amount as passed in the constructor is returned.
* During shortfall analysis, it is assumed that one tasks fits into one agent. This may result in too
* excessive scale-up, especially if the upper bound on the task size is known in advance, and it requires
* far less resources than a whole server.
*/
default int getShortfallAdjustedAgents(int numberOfAgents) {
return numberOfAgents;
}
/**
* Returns the amount of time to wait from the beginning of a scale up or scale down operation before
* initiating another autoscale operation (a.k.a the "cool down" time). Suppress autoscale actions for this
* many seconds after a previous autoscale action.
*
* @return the cool down time, in seconds
*/
long getCoolDownSecs();
/**
* Determines whether a host has too few resources to be considered an idle but potentially useful host.
* This is used to filter out hosts with too few resources before considering them to be excess resources.
* If they are not filtered out, they could prevent a much-needed scale up action.
*
* @param lease the lease object that representes the host
* @return {@code true} if the idle machine has too few resources to count as idle, {@code false} otherwise
*/
boolean idleMachineTooSmall(VirtualMachineLease lease);
}
| 9,144 |
0 | Create_ds/Fenzo/fenzo-core/src/main/java/com/netflix | Create_ds/Fenzo/fenzo-core/src/main/java/com/netflix/fenzo/VirtualMachineCurrentState.java | /*
* Copyright 2015 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.fenzo;
import org.apache.mesos.Protos;
import java.util.Collection;
import java.util.Map;
/**
* Represents the current state of the host (virtual machine) that Fenzo is considering for a task assignment.
* A fitness calculator plugin may use the information from this state object to influence how it optimizes task
* placement decisions.
*/
public interface VirtualMachineCurrentState {
/**
* Get the name of the host on which the virtual machine is running.
*
* @return the hostname
*/
String getHostname();
/**
* Get the virtual machine id provided by the last seen {@link VirtualMachineLease lease} of this host.
*
* @return an identifier provided by the last {@link VirtualMachineLease}. It can be <tt>null</tt> when no leases
* were seen yet, or when leases do not include a VM id.
*/
String getVMId();
/**
* Get a map of resource sets of the virtual machine.
*
* @return The map of resource sets
*/
Map<String, PreferentialNamedConsumableResourceSet> getResourceSets();
/**
* Returns a VM lease object representing totals of resources from all available leases on this host for the
* current scheduling run.
*
* @return a lease object that represents resources that are currently available on the host
*/
VirtualMachineLease getCurrAvailableResources();
/**
* Get all offers for the VM that represent the available resources. There may be more than one offer over time
* if Mesos master offered partial resources for the VM multiple times.
*
* @return A collection of Mesos resource offers.
*/
Collection<Protos.Offer> getAllCurrentOffers();
/**
* Get list of task assignment results for this host so far in the current scheduling run.
*
* @return a collection of tasks that the current scheduling iteration assigned to this host but that are
* not launched/executing yet
*/
Collection<TaskAssignmentResult> getTasksCurrentlyAssigned();
/**
* Get a list of those tasks that had already been assigned to this host before the current scheduling run
* started.
*
* @return a collection of the tasks running on this host
*/
Collection<TaskRequest> getRunningTasks();
/**
* Returns the time until which the given host remains disabled.
*
* @return time until which the host will remain disabled or 0 if the host is enabled
*/
long getDisabledUntil();
}
| 9,145 |
0 | Create_ds/Fenzo/fenzo-core/src/main/java/com/netflix | Create_ds/Fenzo/fenzo-core/src/main/java/com/netflix/fenzo/ActiveVmGroups.java | /*
* Copyright 2015 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.fenzo;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.CopyOnWriteArraySet;
/**
* Manage set of active VM groups.
* A VM belongs to a VM group indicated by its value for the attribute name set via
* {@link TaskScheduler#setActiveVmGroupAttributeName(String)}.
*/
class ActiveVmGroups {
private static class VmGroup {
private final long activatedAt;
private final String name;
private VmGroup(String name) {
activatedAt = System.currentTimeMillis();
this.name = name;
}
private long getActivatedAt() {
return activatedAt;
}
private String getName() {
return name;
}
}
private final ConcurrentMap<Integer, List<VmGroup>> activeVmGroupsMap;
private volatile long lastSetAt=0L;
ActiveVmGroups() {
activeVmGroupsMap = new ConcurrentHashMap<>();
activeVmGroupsMap.put(0, new ArrayList<VmGroup>());
}
private VmGroup isIn(String vmg, List<VmGroup> list) {
for(VmGroup g: list)
if(g.getName().equals(vmg))
return g;
return null;
}
void setActiveVmGroups(List<String> vmGroups) {
List<VmGroup> oldList = activeVmGroupsMap.get(0);
List<VmGroup> vmGroupsList = new ArrayList<>();
for(String vmg: vmGroups) {
final VmGroup in = isIn(vmg, oldList);
if(in == null)
vmGroupsList.add(new VmGroup(vmg));
else
vmGroupsList.add(in);
}
lastSetAt = System.currentTimeMillis();
activeVmGroupsMap.put(0, vmGroupsList);
}
long getLastSetAt() {
return lastSetAt;
}
boolean isActiveVmGroup(String vmGroupName, boolean strict) {
final List<VmGroup> vmGroupList = activeVmGroupsMap.get(0);
if(vmGroupList.isEmpty())
return true;
if(strict && vmGroupName==null)
return false;
for(VmGroup group: vmGroupList) {
if(group.getName().equals(vmGroupName))
return true;
}
return false;
}
long getActivatedAt(String vmGroupName) {
final List<VmGroup> vmGroupList = activeVmGroupsMap.get(0);
for(VmGroup group: vmGroupList) {
if(group.getName().equals(vmGroupName))
return group.getActivatedAt();
}
return -1L;
}
}
| 9,146 |
0 | Create_ds/Fenzo/fenzo-core/src/main/java/com/netflix | Create_ds/Fenzo/fenzo-core/src/main/java/com/netflix/fenzo/VMResource.java | /*
* Copyright 2015 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.fenzo;
/**
* Enumeration of resources avaialble on hosts (VMs)
*/
public enum VMResource {
ResAllocs,
VirtualMachine,
CPU,
Memory,
Network,
Ports,
Disk,
ResourceSet,
Fitness,
Other
}
| 9,147 |
0 | Create_ds/Fenzo/fenzo-core/src/main/java/com/netflix | Create_ds/Fenzo/fenzo-core/src/main/java/com/netflix/fenzo/AutoScaler.java | /*
* Copyright 2015 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.fenzo;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.SynchronousQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.stream.Collectors;
import com.netflix.fenzo.functions.Action1;
import com.netflix.fenzo.functions.Func1;
import com.netflix.fenzo.queues.QueuableTask;
import org.apache.mesos.Protos;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
class AutoScaler {
private static final Logger logger = LoggerFactory.getLogger(AutoScaler.class);
final VMCollection vmCollection;
private final String mapHostnameAttributeName;
private final String scaleDownBalancedByAttributeName;
private final ActiveVmGroups activeVmGroups;
private final AutoScaleRules autoScaleRules;
private final boolean disableShortfallEvaluation;
private final String attributeName;
private final AssignableVMs assignableVMs;
private final ExecutorService executor =
new ThreadPoolExecutor(1, 1, Long.MAX_VALUE, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<>(10),
new ThreadPoolExecutor.DiscardPolicy());
private final AtomicBoolean isShutdown = new AtomicBoolean();
private final ConcurrentMap<String, ScalingActivity> scalingActivityMap = new ConcurrentHashMap<>();
private final ScaleDownConstraintExecutor scaleDownConstraintExecutor;
private volatile Action1<AutoScaleAction> callback = null;
private ShortfallEvaluator shortfallEvaluator;
private long delayScaleUpBySecs = 0L;
private long delayScaleDownBySecs = 0L;
private long disabledVmDurationInSecs = 0L;
private volatile Func1<QueuableTask, List<String>> taskToClustersGetter = null;
AutoScaler(final String attributeName, String mapHostnameAttributeName, String scaleDownBalancedByAttributeName,
final List<AutoScaleRule> autoScaleRules, final AssignableVMs assignableVMs,
final boolean disableShortfallEvaluation, ActiveVmGroups activeVmGroups, VMCollection vmCollection,
ScaleDownConstraintExecutor scaleDownConstraintExecutor) {
this.mapHostnameAttributeName = mapHostnameAttributeName;
this.scaleDownBalancedByAttributeName = scaleDownBalancedByAttributeName;
this.shortfallEvaluator = new NaiveShortfallEvaluator();
this.attributeName = attributeName;
this.autoScaleRules = new AutoScaleRules(autoScaleRules);
this.assignableVMs = assignableVMs;
this.disableShortfallEvaluation = disableShortfallEvaluation;
this.activeVmGroups = activeVmGroups;
this.vmCollection = vmCollection;
this.scaleDownConstraintExecutor = scaleDownConstraintExecutor;
}
/* package */ void useOptimizingShortfallAnalyzer() {
shortfallEvaluator = new OptimizingShortfallEvaluator();
}
/* package */ void setSchedulingService(TaskSchedulingService service) {
shortfallEvaluator.setTaskSchedulingService(service);
}
Collection<AutoScaleRule> getRules() {
return Collections.unmodifiableCollection(autoScaleRules.getRules());
}
void replaceRule(AutoScaleRule rule) {
if (rule == null)
throw new NullPointerException("Can't add null rule");
autoScaleRules.replaceRule(rule);
}
AutoScaleRule getRule(String name) {
return autoScaleRules.get(name);
}
void removeRule(String ruleName) {
if (ruleName != null)
autoScaleRules.remRule(ruleName);
}
void setDelayScaleUpBySecs(long secs) {
delayScaleUpBySecs = secs;
}
void setDelayScaleDownBySecs(long secs) {
delayScaleDownBySecs = secs;
}
void setDisabledVmDurationInSecs(long disabledVmDurationInSecs) {
this.disabledVmDurationInSecs = disabledVmDurationInSecs;
}
void setTaskToClustersGetter(Func1<QueuableTask, List<String>> getter) {
this.taskToClustersGetter = getter;
}
void doAutoscale(final AutoScalerInput autoScalerInput) {
if (isShutdown.get()) {
return;
}
try {
shortfallEvaluator.setTaskToClustersGetter(taskToClustersGetter);
autoScaleRules.prepare();
Map<String, HostAttributeGroup> hostAttributeGroupMap = setupHostAttributeGroupMap(autoScaleRules, scalingActivityMap);
if (!disableShortfallEvaluation) {
Map<String, Integer> shortfall = shortfallEvaluator.getShortfall(hostAttributeGroupMap.keySet(), autoScalerInput.getFailures(), autoScaleRules);
for (Map.Entry<String, Integer> entry : shortfall.entrySet()) {
hostAttributeGroupMap.get(entry.getKey()).shortFall = entry.getValue() == null ? 0 : entry.getValue();
}
}
populateIdleResources(autoScalerInput.getIdleResourcesList(), autoScalerInput.getIdleInactiveResourceList(), hostAttributeGroupMap);
List<Runnable> callbacks = new ArrayList<>();
for (HostAttributeGroup hostAttributeGroup : hostAttributeGroupMap.values()) {
callbacks.addAll(processScalingNeeds(hostAttributeGroup, scalingActivityMap, assignableVMs));
}
executor.submit(() -> {
if (isShutdown.get()) {
return;
}
//Since the agents are disabled synchronously for each attribute group, the agents will become enabled again
//if the sum duration of all callback calls takes longer than the cooldown period
for (Runnable callback : callbacks) {
callback.run();
}
});
} catch (Exception e) {
logger.error("Autoscaler failure: ", e);
}
}
private boolean shouldScaleNow(boolean scaleUp, long now, ScalingActivity prevScalingActivity, AutoScaleRule rule) {
return scaleUp ?
now > (Math.max(activeVmGroups.getLastSetAt(), prevScalingActivity.scaleUpAt) + rule.getCoolDownSecs() * 1000) :
now > (Math.max(activeVmGroups.getLastSetAt(), Math.max(prevScalingActivity.scaleDownAt, prevScalingActivity.scaleUpAt))
+ rule.getCoolDownSecs() * 1000);
}
private boolean shouldScaleUp(long now, ScalingActivity prevScalingActivity, AutoScaleRule rule) {
return shouldScaleNow(true, now, prevScalingActivity, rule);
}
private boolean shouldScaleDown(long now, ScalingActivity prevScalingActivity, AutoScaleRule rule) {
return shouldScaleNow(false, now, prevScalingActivity, rule);
}
private boolean shouldScaleDownInactive(long now, ScalingActivity prevScalingActivity, AutoScaleRule rule) {
return now > (Math.max(activeVmGroups.getLastSetAt(), prevScalingActivity.inactiveScaleDownAt) + rule.getCoolDownSecs() * 1000);
}
private List<Runnable> processScalingNeeds(HostAttributeGroup hostAttributeGroup, ConcurrentMap<String, ScalingActivity> scalingActivityMap, AssignableVMs assignableVMs) {
List<Runnable> callbacks = new ArrayList<>();
AutoScaleRule rule = hostAttributeGroup.rule;
long now = System.currentTimeMillis();
ScalingActivity prevScalingActivity = scalingActivityMap.get(rule.getRuleName());
int excess = hostAttributeGroup.shortFall > 0 ? 0 : hostAttributeGroup.idleHosts.size() - rule.getMaxIdleHostsToKeep();
int inactiveIdleCount = hostAttributeGroup.idleInactiveHosts.size();
List<String> allHostsToTerminate = new ArrayList<>();
if (inactiveIdleCount > 0 && shouldScaleDownInactive(now, prevScalingActivity, rule)) {
ScalingActivity scalingActivity = scalingActivityMap.get(rule.getRuleName());
long lastReqstAge = (now - scalingActivity.inactiveScaleDownRequestedAt) / 1000L;
if (delayScaleDownBySecs > 0L && lastReqstAge > 2 * delayScaleDownBySecs) { // reset the request at time
scalingActivity.inactiveScaleDownRequestedAt = now;
} else if (delayScaleDownBySecs == 0L || lastReqstAge > delayScaleDownBySecs) {
scalingActivity.inactiveScaleDownRequestedAt = 0L;
scalingActivity.inactiveScaleDownAt = now;
Map<String, String> hostsToTerminate = getInactiveHostsToTerminate(hostAttributeGroup.idleInactiveHosts);
if (logger.isDebugEnabled()) {
logger.debug("{} has an excess of {} inactive hosts ({})", rule.getRuleName(), hostsToTerminate.size(),
String.join(", ", hostsToTerminate.keySet()));
}
allHostsToTerminate.addAll(hostsToTerminate.values());
}
}
if (excess > 0 && shouldScaleDown(now, prevScalingActivity, rule)) {
ScalingActivity scalingActivity = scalingActivityMap.get(rule.getRuleName());
long lastReqstAge = (now - scalingActivity.scaleDownRequestedAt) / 1000L;
if (delayScaleDownBySecs > 0L && lastReqstAge > 2 * delayScaleDownBySecs) { // reset the request at time
scalingActivity.scaleDownRequestedAt = now;
} else if (delayScaleDownBySecs == 0L || lastReqstAge > delayScaleDownBySecs) {
final int size = vmCollection.size(rule.getRuleName());
if (rule.getMinSize() > (size - excess))
excess = Math.max(0, size - rule.getMinSize());
if (excess > 0) {
scalingActivity.scaleDownRequestedAt = 0L;
scalingActivity.scaleDownAt = now;
scalingActivity.shortfall = hostAttributeGroup.shortFall;
Map<String, String> hostsToTerminate = getHostsToTerminate(hostAttributeGroup.idleHosts, excess);
scalingActivity.scaledNumInstances = hostsToTerminate.size();
scalingActivity.type = AutoScaleAction.Type.Down;
for (String host : hostsToTerminate.keySet()) {
long disabledDurationInSecs = Math.max(disabledVmDurationInSecs, rule.getCoolDownSecs());
assignableVMs.disableUntil(host, now + disabledDurationInSecs * 1000);
}
if (logger.isDebugEnabled()) {
logger.debug("{} has an excess of {} hosts ({})", rule.getRuleName(), hostsToTerminate.size(),
String.join(", ", hostsToTerminate.keySet()));
}
allHostsToTerminate.addAll(hostsToTerminate.values());
}
}
} else if (hostAttributeGroup.shortFall > 0 || (excess <= 0 && shouldScaleUp(now, prevScalingActivity, rule))) {
if (hostAttributeGroup.shortFall > 0 || rule.getMinIdleHostsToKeep() > hostAttributeGroup.idleHosts.size()) {
// scale up to rule.getMaxIdleHostsToKeep() instead of just until rule.getMinIdleHostsToKeep()
// but, if not shouldScaleUp(), then, scale up due to shortfall
ScalingActivity scalingActivity = scalingActivityMap.get(rule.getRuleName());
long lastReqstAge = (now - scalingActivity.scaleUpRequestedAt) / 1000L;
if (delayScaleUpBySecs > 0L && lastReqstAge > 2 * delayScaleUpBySecs) { // reset the request at time
scalingActivity.scaleUpRequestedAt = now;
} else if (delayScaleUpBySecs == 0L || lastReqstAge > delayScaleUpBySecs) {
int shortage = (excess <= 0 && shouldScaleUp(now, prevScalingActivity, rule)) ?
rule.getMaxIdleHostsToKeep() - hostAttributeGroup.idleHosts.size() : 0;
shortage = Math.max(shortage, hostAttributeGroup.shortFall);
final int size = vmCollection.size(rule.getRuleName());
if (shortage + size > rule.getMaxSize())
shortage = Math.max(0, rule.getMaxSize() - size);
if (shortage > 0) {
scalingActivity.scaleUpRequestedAt = 0L;
scalingActivity.scaleUpAt = now;
scalingActivity.shortfall = hostAttributeGroup.shortFall;
scalingActivity.scaledNumInstances = shortage;
scalingActivity.type = AutoScaleAction.Type.Up;
int finalShortage = shortage;
logger.debug("{} has a shortage of {} hosts", rule.getRuleName(), finalShortage);
callbacks.add(() -> {
logger.debug("Executing callback to scale up {} by {} hosts", rule.getRuleName(), finalShortage);
callback.call(new ScaleUpAction(rule.getRuleName(), finalShortage));
});
}
}
}
}
if (!allHostsToTerminate.isEmpty()) {
callbacks.add(() -> {
if (logger.isDebugEnabled()) {
logger.debug("Executing callback to scale down {} by {} hosts ({})", rule.getRuleName(), allHostsToTerminate.size(),
String.join(", ", allHostsToTerminate));
}
callback.call(new ScaleDownAction(rule.getRuleName(), allHostsToTerminate));
});
}
return callbacks;
}
private void populateIdleResources(List<VirtualMachineLease> idleResources,
List<VirtualMachineLease> idleInactiveResources,
Map<String, HostAttributeGroup> leasesMap) {
// Leases from active clusters
for (VirtualMachineLease l : idleResources) {
getAttribute(l).ifPresent(attrValue -> {
if (leasesMap.containsKey(attrValue)) {
if (!leasesMap.get(attrValue).rule.idleMachineTooSmall(l))
leasesMap.get(attrValue).idleHosts.add(l);
}
});
}
// Leases from inactive clusters
for (VirtualMachineLease l : idleInactiveResources) {
getAttribute(l).ifPresent(attrValue -> {
if (leasesMap.containsKey(attrValue)) {
leasesMap.get(attrValue).idleInactiveHosts.add(l);
}
});
}
}
private Optional<String> getAttribute(VirtualMachineLease lease) {
boolean hasValue = lease.getAttributeMap() != null
&& lease.getAttributeMap().get(attributeName) != null
&& lease.getAttributeMap().get(attributeName).getText().hasValue();
return hasValue ? Optional.of(lease.getAttributeMap().get(attributeName).getText().getValue()) : Optional.empty();
}
private Map<String, HostAttributeGroup> setupHostAttributeGroupMap(AutoScaleRules autoScaleRules, ConcurrentMap<String, ScalingActivity> lastScalingAt) {
Map<String, HostAttributeGroup> leasesMap = new HashMap<>();
for (AutoScaleRule rule : autoScaleRules.getRules()) {
leasesMap.put(rule.getRuleName(),
new HostAttributeGroup(rule.getRuleName(), rule));
long initialCoolDown = getInitialCoolDown(rule.getCoolDownSecs());
lastScalingAt.putIfAbsent(rule.getRuleName(), new ScalingActivity(initialCoolDown, initialCoolDown, 0, 0, null));
}
return leasesMap;
}
// make scaling activity happen after a fixed delayed time for the first time encountered (e.g., server start)
private long getInitialCoolDown(long coolDownSecs) {
long initialCoolDownInPastSecs = 120;
initialCoolDownInPastSecs = Math.min(coolDownSecs, initialCoolDownInPastSecs);
return System.currentTimeMillis() - coolDownSecs * 1000 + initialCoolDownInPastSecs * 1000;
}
private Map<String, String> getHostsToTerminate(List<VirtualMachineLease> idleHosts, int excess) {
if (scaleDownConstraintExecutor == null) {
return idleHosts.isEmpty() ? Collections.emptyMap() : getHostsToTerminateLegacy(idleHosts, excess);
} else {
return getHostsToTerminateUsingCriteria(idleHosts, excess);
}
}
private Map<String, String> getInactiveHostsToTerminate(List<VirtualMachineLease> inactiveIdleHosts) {
if (scaleDownConstraintExecutor == null) {
return Collections.emptyMap();
} else {
Map<String, String> hostsMap = new HashMap<>();
List<VirtualMachineLease> result = scaleDownConstraintExecutor.evaluate(inactiveIdleHosts);
result.forEach(lease -> hostsMap.put(lease.hostname(), getMappedHostname(lease)));
return hostsMap;
}
}
private Map<String, String> getHostsToTerminateUsingCriteria(List<VirtualMachineLease> idleHosts, int excess) {
Map<String, String> hostsMap = new HashMap<>();
List<VirtualMachineLease> allIdle = new ArrayList<>(idleHosts);
List<VirtualMachineLease> result = scaleDownConstraintExecutor.evaluate(allIdle);
// The final result should contain only excess number of active hosts. Enforce this invariant.
Set<String> activeIds = idleHosts.stream().map(VirtualMachineLease::hostname).collect(Collectors.toSet());
int activeCounter = 0;
Iterator<VirtualMachineLease> it = result.iterator();
while (it.hasNext()) {
VirtualMachineLease leaseToRemove = it.next();
if (activeIds.contains(leaseToRemove.hostname())) {
if (activeCounter < excess) {
activeCounter++;
} else {
it.remove();
}
}
}
result.forEach(lease -> hostsMap.put(lease.hostname(), getMappedHostname(lease)));
return hostsMap;
}
private Map<String, String> getHostsToTerminateLegacy(List<VirtualMachineLease> hosts, int excess) {
Map<String, String> result = new HashMap<>();
final Map<String, List<VirtualMachineLease>> hostsMap = new HashMap<>();
final String defaultAttributeName = "default";
for (VirtualMachineLease host : hosts) {
final Protos.Attribute attribute = host.getAttributeMap().get(scaleDownBalancedByAttributeName);
String val = (attribute != null && attribute.hasText()) ? attribute.getText().getValue() : defaultAttributeName;
if (hostsMap.get(val) == null)
hostsMap.put(val, new ArrayList<VirtualMachineLease>());
hostsMap.get(val).add(host);
}
final List<List<VirtualMachineLease>> lists = new ArrayList<>();
for (List<VirtualMachineLease> l : hostsMap.values())
lists.add(l);
int taken = 0;
while (taken < excess) {
List<VirtualMachineLease> takeFrom = null;
int max = 0;
for (List<VirtualMachineLease> l : lists) {
if (l.size() > max) {
max = l.size();
takeFrom = l;
}
}
final VirtualMachineLease removed = takeFrom.remove(0);
result.put(removed.hostname(), getMappedHostname(removed));
taken++;
}
return result;
}
private String getMappedHostname(VirtualMachineLease lease) {
if (mapHostnameAttributeName == null || mapHostnameAttributeName.isEmpty())
return lease.hostname();
Protos.Attribute attribute = lease.getAttributeMap().get(mapHostnameAttributeName);
if (attribute == null) {
logger.error("Didn't find attribute " + mapHostnameAttributeName + " for host " + lease.hostname());
return lease.hostname();
}
return attribute.getText().getValue();
}
public void setCallback(Action1<AutoScaleAction> callback) {
this.callback = callback;
}
void shutdown() {
if (isShutdown.compareAndSet(false, true))
executor.shutdown();
}
private static class HostAttributeGroup {
String name;
List<VirtualMachineLease> idleHosts;
List<VirtualMachineLease> idleInactiveHosts;
int shortFall;
AutoScaleRule rule;
private HostAttributeGroup(String name, AutoScaleRule rule) {
this.name = name;
this.rule = rule;
this.idleHosts = new ArrayList<>();
this.idleInactiveHosts = new ArrayList<>();
this.shortFall = 0;
}
}
private static class ScalingActivity {
private long scaleUpAt;
private long scaleUpRequestedAt;
private long scaleDownAt;
private long scaleDownRequestedAt;
private long inactiveScaleDownAt;
private long inactiveScaleDownRequestedAt;
private int shortfall;
private int scaledNumInstances;
private AutoScaleAction.Type type;
private ScalingActivity(long scaleUpAt, long scaleDownAt, int shortfall, int scaledNumInstances, AutoScaleAction.Type type) {
this.scaleUpAt = scaleUpAt;
scaleUpRequestedAt = 0L;
this.scaleDownAt = scaleDownAt;
scaleDownRequestedAt = 0L;
this.shortfall = shortfall;
this.scaledNumInstances = scaledNumInstances;
this.type = type;
}
}
} | 9,148 |
0 | Create_ds/Fenzo/fenzo-core/src/main/java/com/netflix | Create_ds/Fenzo/fenzo-core/src/main/java/com/netflix/fenzo/PreferentialNamedConsumableResourceSet.java | /*
* Copyright 2015 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.fenzo;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* This encapsulates preferential resource sets available on a VM. Resource sets are two level resources that can
* be assigned to tasks that specify a name to reserve for an available resource set, and the number of sub-resources
* (second level of the two level resource) it needs.
* <P>A {@link PreferentialNamedConsumableResourceSet} contains 1 or more resource sets,
* {@link com.netflix.fenzo.PreferentialNamedConsumableResourceSet.PreferentialNamedConsumableResource}, each of which
* can be assigned (or reserved to) a name requested by tasks, if currently unassigned. Each resource set contains one
* or more count of resources available for assignment to tasks.
* <P>A task can be assigned to one of the resource sets if it either has no tasks assigned to it, or the name assigned
* to the resource set matches what the task being assigned is requesting. The number of sub-resources requested by task
* is also checked. Tasks may request 0 or more sub-resources. The assignment attempts to use as few resource sets as
* possible and returns a fitness score that helps scheduler pick between multiple VMs that can potentially fit the task.
* The resulting assignment contains the index of the resource set assigned. The resource sets are assigned indexes
* starting with 0.
*/
public class PreferentialNamedConsumableResourceSet {
final static String attributeName = "ResourceSet";
private static String getResNameVal(String name, TaskRequest request) {
final Map<String, TaskRequest.NamedResourceSetRequest> customNamedResources = request.getCustomNamedResources();
if(customNamedResources!=null) {
final TaskRequest.NamedResourceSetRequest setRequest = customNamedResources.get(name);
return setRequest==null? CustomResAbsentKey : setRequest.getResValue();
}
return CustomResAbsentKey;
}
public static class ConsumeResult {
private final int index;
private final String attrName;
private final String resName;
private final double fitness;
@JsonCreator
@JsonIgnoreProperties(ignoreUnknown=true)
public ConsumeResult(@JsonProperty("index") int index,
@JsonProperty("attrName") String attrName,
@JsonProperty("resName") String resName,
@JsonProperty("fitness") double fitness) {
this.index = index;
this.attrName = attrName;
this.resName = resName;
this.fitness = fitness;
}
public int getIndex() {
return index;
}
public String getAttrName() {
return attrName;
}
public String getResName() {
return resName;
}
public double getFitness() {
return fitness;
}
}
public static class PreferentialNamedConsumableResource {
private final String hostname;
private final int index;
private final String attrName;
private String resName=null;
private final int limit;
private final Map<String, TaskRequest.NamedResourceSetRequest> usageBy;
private int usedSubResources=0;
PreferentialNamedConsumableResource(String hostname, int i, String attrName, int limit) {
this.hostname = hostname;
this.index = i;
this.attrName = attrName;
this.limit = limit;
usageBy = new HashMap<>();
}
public int getIndex() {
return index;
}
public String getResName() {
return resName;
}
public int getLimit() {
return limit;
}
public Map<String, TaskRequest.NamedResourceSetRequest> getUsageBy() {
return usageBy;
}
public int getUsedCount() {
if(resName == null) {
return -1;
}
return usedSubResources;
}
double getFitness(TaskRequest request, PreferentialNamedConsumableResourceEvaluator evaluator) {
TaskRequest.NamedResourceSetRequest setRequest = request.getCustomNamedResources()==null
? null
: request.getCustomNamedResources().get(attrName);
// This particular resource type is not requested. We assign to it virtual resource name 'CustomResAbsentKey',
// and request 0 sub-resources.
if(setRequest == null) {
if(resName == null) {
return evaluator.evaluateIdle(hostname, CustomResAbsentKey, index, 0, limit);
}
if(resName.equals(CustomResAbsentKey)) {
return evaluator.evaluate(hostname, CustomResAbsentKey, index, 0, usedSubResources, limit);
}
return 0.0;
}
double subResNeed = setRequest.getNumSubResources();
// Resource not assigned yet to any task
if(resName == null) {
if(subResNeed > limit) {
return 0.0;
}
return evaluator.evaluateIdle(hostname, setRequest.getResValue(), index, subResNeed, limit);
}
// Resource assigned different name than requested
if(!resName.equals(setRequest.getResValue())) {
return 0.0;
}
if(usedSubResources + subResNeed > limit) {
return 0.0;
}
return evaluator.evaluate(hostname, setRequest.getResValue(), index, subResNeed, usedSubResources, limit);
}
void consume(TaskRequest request) {
String r = getResNameVal(attrName, request);
consume(r, request);
}
void consume(String assignedResName, TaskRequest request) {
if(usageBy.get(request.getId()) != null)
return; // already consumed
if(resName!=null && !resName.equals(assignedResName))
throw new IllegalStateException(this.getClass().getName() + " already consumed by " + resName +
", can't consume for " + assignedResName);
if(resName == null) {
resName = assignedResName;
usageBy.clear();
}
final TaskRequest.NamedResourceSetRequest setRequest = request.getCustomNamedResources()==null?
null : request.getCustomNamedResources().get(attrName);
double subResNeed = setRequest==null? 0.0 : setRequest.getNumSubResources();
if(usedSubResources + subResNeed > limit)
throw new RuntimeException(this.getClass().getName() + " already consumed for " + resName +
" up to the limit of " + limit);
usageBy.put(request.getId(), setRequest);
usedSubResources += subResNeed;
}
boolean release(TaskRequest request) {
String r = getResNameVal(attrName, request);
if(resName != null && !resName.equals(r)) {
return false;
}
final TaskRequest.NamedResourceSetRequest removed = usageBy.remove(request.getId());
if(removed == null)
return false;
usedSubResources -= removed.getNumSubResources();
if(usageBy.isEmpty())
resName = null;
return true;
}
}
public static final String CustomResAbsentKey = "CustomResAbsent";
private final String name;
private final List<PreferentialNamedConsumableResource> usageBy;
public PreferentialNamedConsumableResourceSet(String hostname, String name, int val0, int val1) {
this.name = name;
usageBy = new ArrayList<>(val0);
for(int i=0; i<val0; i++)
usageBy.add(new PreferentialNamedConsumableResource(hostname, i, name, val1));
}
public String getName() {
return name;
}
public List<PreferentialNamedConsumableResource> getUsageBy() {
return Collections.unmodifiableList(usageBy);
}
// boolean hasAvailability(TaskRequest request) {
// for(PreferentialNamedConsumableResource r: usageBy) {
// if(r.hasAvailability(request))
// return true;
// }
// return false;
// }
ConsumeResult consume(TaskRequest request, PreferentialNamedConsumableResourceEvaluator evaluator) {
return consumeIntl(request, false, evaluator);
}
void assign(TaskRequest request) {
final TaskRequest.AssignedResources assignedResources = request.getAssignedResources();
if(assignedResources != null) {
final List<ConsumeResult> consumedNamedResources = assignedResources.getConsumedNamedResources();
if(consumedNamedResources!=null && !consumedNamedResources.isEmpty()) {
for(PreferentialNamedConsumableResourceSet.ConsumeResult consumeResult: consumedNamedResources) {
if(name.equals(consumeResult.getAttrName())) {
final int index = consumeResult.getIndex();
if(index < 0 || index > usageBy.size())
throw new IllegalStateException("Illegal assignment of namedResource " + name +
": has " + usageBy.size() + " resource sets, can't assign to index " + index
);
usageBy.get(index).consume(consumeResult.getResName(), request);
}
}
}
}
}
// returns 0.0 for no fitness at all, or <=1.0 for fitness
double getFitness(TaskRequest request, PreferentialNamedConsumableResourceEvaluator evaluator) {
return consumeIntl(request, true, evaluator).fitness;
}
private ConsumeResult consumeIntl(TaskRequest request, boolean skipConsume, PreferentialNamedConsumableResourceEvaluator evaluator) {
PreferentialNamedConsumableResource best = null;
double bestFitness=0.0;
for(PreferentialNamedConsumableResource r: usageBy) {
double f = r.getFitness(request, evaluator);
if(f == 0.0)
continue;
if(bestFitness < f) {
best = r;
bestFitness = f;
}
}
if(!skipConsume) {
if (best == null)
throw new RuntimeException("Unexpected to have no availability for job " + request.getId() + " for consumable resource " + name);
best.consume(request);
}
return new ConsumeResult(
best==null? -1 : best.index,
best==null? null : best.attrName,
best==null? null : best.resName,
bestFitness
);
}
boolean release(TaskRequest request) {
for(PreferentialNamedConsumableResource r: usageBy)
if(r.release(request))
return true;
return false;
}
int getNumSubResources() {
return usageBy.get(0).getLimit()-1;
}
List<Double> getUsedCounts() {
List<Double> counts = new ArrayList<>(usageBy.size());
for(PreferentialNamedConsumableResource r: usageBy)
counts.add((double) r.getUsedCount());
return counts;
}
}
| 9,149 |
0 | Create_ds/Fenzo/fenzo-core/src/main/java/com/netflix | Create_ds/Fenzo/fenzo-core/src/main/java/com/netflix/fenzo/NoOpSchedulingEventListener.java | package com.netflix.fenzo;
class NoOpSchedulingEventListener implements SchedulingEventListener {
static final SchedulingEventListener INSTANCE = new NoOpSchedulingEventListener();
@Override
public void onScheduleStart() {
}
@Override
public void onAssignment(TaskAssignmentResult taskAssignmentResult) {
}
@Override
public void onScheduleFinish() {
}
}
| 9,150 |
0 | Create_ds/Fenzo/fenzo-core/src/main/java/com/netflix | Create_ds/Fenzo/fenzo-core/src/main/java/com/netflix/fenzo/TaskTrackerState.java | /*
* Copyright 2015 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.fenzo;
import java.util.Map;
/**
* The state of the tasks that are tracked by the task scheduler. The task scheduler passes an object that
* implements this interface into {@link ConstraintEvaluator}s to enable them to have a bird's-eye view of the
* state of tasks that are assigned and running in the system at large.
*/
public interface TaskTrackerState {
/**
* Get a map of all running tasks. The map keys are the task IDs of active tasks. The map values are the
* corresponding active task objects containing information on the active task.
*
* @return a Map of all known running tasks
*/
public Map<String, TaskTracker.ActiveTask> getAllRunningTasks();
/**
* Get a map of all tasks currently assigned during a scheduling trial, but not running yet. The map keys
* are the task IDs of the assigned tasks. The map values are the corresponding active task objects
* containing information on the assigned tasks.
*
* @return a Map of all assigned tasks
*/
public Map<String, TaskTracker.ActiveTask> getAllCurrentlyAssignedTasks();
}
| 9,151 |
0 | Create_ds/Fenzo/fenzo-core/src/main/java/com/netflix | Create_ds/Fenzo/fenzo-core/src/main/java/com/netflix/fenzo/VMAssignmentResult.java | /*
* Copyright 2015 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.fenzo;
import java.util.List;
import java.util.Set;
/**
* Result of resource assignments for a host (VM). When you call your task scheduler's
* {@link TaskScheduler#scheduleOnce(java.util.List,java.util.List) scheduleOnce()} method to schedule a set of
* tasks, that method returns a {@link SchedulingResult}. That object includes the method
* {@link SchedulingResult#getResultMap() getResultMap()} which returns a map of host names to
* {@code VMAssignmentResult} objects. Those objects in turn have the {@link #getLeasesUsed()} and
* {@link #getTasksAssigned()} methods, which return information about the resource offers that participated in
* the assignments and which tasks were assigned on those hosts, in the form of {@link VirtualMachineLease}
* objects and {@link TaskAssignmentResult} objects respectively. This approach will give you insight into which
* tasks have been assigned to which hosts in the current scheduling round (but not about which tasks are
* already running on those hosts).
*/
public class VMAssignmentResult {
private final String hostname;
private final List<VirtualMachineLease> leasesUsed;
private final Set<TaskAssignmentResult> tasksAssigned;
public VMAssignmentResult(String hostname, List<VirtualMachineLease> leasesUsed, Set<TaskAssignmentResult> tasksAssigned) {
this.hostname = hostname;
this.leasesUsed = leasesUsed;
this.tasksAssigned = tasksAssigned;
}
/**
* Get the name of the host whose assignment results are available.
*
* @return the name of the host
*/
public String getHostname() {
return hostname;
}
/**
* Get the list of leases (resource offers) used in creating the resource assignments for tasks.
*
* @return a List of leases
*/
public List<VirtualMachineLease> getLeasesUsed() {
return leasesUsed;
}
/**
* Get the set of tasks that are assigned resources from this host.
*
* @return a Set of task assignment results
*/
public Set<TaskAssignmentResult> getTasksAssigned() {
return tasksAssigned;
}
@Override
public String toString() {
return "VMAssignmentResult{" +
"hostname='" + hostname + '\'' +
", leasesUsed=" + leasesUsed +
", tasksAssigned=" + tasksAssigned +
'}';
}
}
| 9,152 |
0 | Create_ds/Fenzo/fenzo-core/src/main/java/com/netflix | Create_ds/Fenzo/fenzo-core/src/main/java/com/netflix/fenzo/ConstraintEvaluator.java | /*
* Copyright 2015 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.fenzo;
/**
* A constraint evaluator inspects a target to decide whether or not its attributes are satisfactory according
* to some standard given the current state of task assignments in the system at large. Different constraint
* evaluators look at different attributes and have different standards for how they make this decision.
*/
public interface ConstraintEvaluator {
/**
* The result of the evaluation of a {@link ConstraintEvaluator}. This combines a boolean that indicates
* whether or not the target satisfied the constraint, and, if it did not, a string that includes the reason
* why.
*/
public static class Result {
private final boolean isSuccessful;
private final String failureReason;
public Result(boolean successful, String failureReason) {
isSuccessful = successful;
this.failureReason = isSuccessful? "" : failureReason;
}
/**
* Indicates whether the constraint evaluator found the target to satisfy the constraint.
*
* @return {@code true} if the target satisfies the constraint, {@code false} otherwise
*/
public boolean isSuccessful() {
return isSuccessful;
}
/**
* Returns the reason why the target did not satisfy the constraint.
*
* @return the reason why the constraint was not satisfied, or an empty string if it was met
*/
public String getFailureReason() {
return failureReason;
}
}
/**
* Returns the name of the constraint evaluator.
*
* @return the name of the constraint evaluator
*/
public String getName();
/**
* Inspects a target to decide whether or not it meets the constraints appropriate to a particular task.
*
* @param taskRequest a description of the task to be assigned
* @param targetVM a description of the host that is a potential match for the task
* @param taskTrackerState the current status of tasks and task assignments in the system at large
* @return a successful Result if the target meets the constraints enforced by this constraint evaluator, or
* an unsuccessful Result otherwise
*/
public Result evaluate(TaskRequest taskRequest, VirtualMachineCurrentState targetVM,
TaskTrackerState taskTrackerState);
}
| 9,153 |
0 | Create_ds/Fenzo/fenzo-core/src/main/java/com/netflix | Create_ds/Fenzo/fenzo-core/src/main/java/com/netflix/fenzo/AutoScaleRules.java | /*
* Copyright 2015 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.fenzo;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
/**
* This class maintains the set of autoscaling rules. You may define different autoscaling rules for different
* sets of hosts. For example, you may create an autoscaling group for a certain sort of workload and populate it
* with machines with a certain set of capabilities specific to that workload, and a second autoscaling group for
* a more varied set of tasks that requires a more varied or flexible set of machines.
*/
class AutoScaleRules {
private final Map<String, AutoScaleRule> ruleMap;
private final BlockingQueue<AutoScaleRule> addQ = new LinkedBlockingQueue<>();
private final List<AutoScaleRule> addList = new LinkedList<>();
private final BlockingQueue<String> remQ = new LinkedBlockingQueue<>();
private final List<String> remList = new LinkedList<>();
AutoScaleRules(List<AutoScaleRule> autoScaleRules) {
ruleMap = new HashMap<>();
if(autoScaleRules!=null && !autoScaleRules.isEmpty())
for(AutoScaleRule r: autoScaleRules)
ruleMap.put(r.getRuleName(), r);
}
/**
* Adds or modifies an autoscale rule in the set of active rules. Pass in the {@link AutoScaleRule} you want
* to add or modify. If another {@code AutoScaleRule} with the same rule name already exists, it will be
* overwritten by {@code rule}. Otherwise, {@code rule} will be added to the active set of autoscale rules.
*
* @param rule the autoscale rule you want to add or modify
*/
void replaceRule(AutoScaleRule rule) {
if(rule != null)
addQ.offer(rule);
}
/**
* Removes an autoscale rule from the set of active rules. Pass in the name of the autoscale rule you want to
* unqueueTask (this is the same name that would be returned by its
* {@link AutoScaleRule#getRuleName getRuleName()} method).
*
* @param ruleName the rule name of the autoscale rule you want to unqueueTask from the set of active rules
*/
void remRule(String ruleName) {
if(ruleName != null)
remQ.offer(ruleName);
}
void prepare() {
addQ.drainTo(addList);
if(!addList.isEmpty()) {
final Iterator<AutoScaleRule> iterator = addList.iterator();
while(iterator.hasNext()) {
final AutoScaleRule r = iterator.next();
if(r != null && r.getRuleName()!=null)
ruleMap.put(r.getRuleName(), r);
iterator.remove();
}
}
remQ.drainTo(remList);
if(!remList.isEmpty()) {
final Iterator<String> iterator = remList.iterator();
while(iterator.hasNext()) {
final String name = iterator.next();
if(name != null)
ruleMap.remove(name);
iterator.remove();
}
}
}
/**
* Returns the autoscale rule whose name is equal to a specified String. The name of an autoscale rule is the
* value of the attribute that defines the type of host the rule applies to (for instance, the name of the
* autoscaling group).
*
* @param attrValue the name of the autoscale rule you want to retrieve
* @return the autoscale rule whose name is equal to {@code attrValue}
*/
public AutoScaleRule get(String attrValue) {
return ruleMap.get(attrValue);
}
Collection<AutoScaleRule> getRules() {
return ruleMap.values();
}
}
| 9,154 |
0 | Create_ds/Fenzo/fenzo-core/src/main/java/com/netflix | Create_ds/Fenzo/fenzo-core/src/main/java/com/netflix/fenzo/ShortfallEvaluator.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.fenzo;
import com.netflix.fenzo.functions.Func1;
import com.netflix.fenzo.queues.QueuableTask;
import java.util.List;
import java.util.Map;
import java.util.Set;
/* package */ interface ShortfallEvaluator {
void setTaskToClustersGetter(Func1<QueuableTask, List<String>> getter);
/**
* Get number of VMs of shortfall for each VM Group for the given VM Group names and set of failed tasks.
* @param vmGroupNames VM Group names for which autoscale rules are setup, same as the autoscale rule name.
* @param failures The tasks that failed assignment due to which VM shortfall must be evaluated.
* @param autoScaleRules The current set of autoscale rules.
* @return A map with keys containing VM group names (same as autoscale rule names) and values containing the
* number of VMs that may be added to address the shortfall.
*/
Map<String, Integer> getShortfall(Set<String> vmGroupNames, Set<TaskRequest> failures, AutoScaleRules autoScaleRules);
void setTaskSchedulingService(TaskSchedulingService schedulingService);
}
| 9,155 |
0 | Create_ds/Fenzo/fenzo-core/src/main/java/com/netflix | Create_ds/Fenzo/fenzo-core/src/main/java/com/netflix/fenzo/StateMonitor.java | /*
* Copyright 2015 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.fenzo;
import java.util.concurrent.atomic.AtomicBoolean;
/**
* A monitor to ensure scheduler state is not compromised by concurrent calls that are disallowed.
*/
class StateMonitor {
private final AtomicBoolean lock;
StateMonitor() {
lock = new AtomicBoolean(false);
}
AutoCloseable enter() {
if(!lock.compareAndSet(false, true))
throw new IllegalStateException();
return new AutoCloseable() {
@Override
public void close() throws Exception {
if(!lock.compareAndSet(true, false))
throw new IllegalStateException();
}
};
}
}
| 9,156 |
0 | Create_ds/Fenzo/fenzo-core/src/main/java/com/netflix | Create_ds/Fenzo/fenzo-core/src/main/java/com/netflix/fenzo/ResAllocsEvaluater.java | /*
* Copyright 2015 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.fenzo;
import com.netflix.fenzo.AssignmentFailure;
import com.netflix.fenzo.TaskRequest;
import com.netflix.fenzo.TaskTracker;
import com.netflix.fenzo.VMResource;
import com.netflix.fenzo.sla.ResAllocs;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
/**
* Evaluator for resource allocation limits.
*/
class ResAllocsEvaluater {
private final Map<String, ResAllocs> resAllocs;
private final TaskTracker taskTracker;
private final Set<String> failedTaskGroups = new HashSet<>();
private final BlockingQueue<ResAllocs> addQ = new LinkedBlockingQueue<>();
private final BlockingQueue<String> remQ = new LinkedBlockingQueue<>();
@SuppressWarnings("MismatchedQueryAndUpdateOfCollection")
private final List<ResAllocs> addList = new LinkedList<>();
@SuppressWarnings("MismatchedQueryAndUpdateOfCollection")
private final List<String> remList = new LinkedList<>();
ResAllocsEvaluater(TaskTracker taskTracker, Map<String, ResAllocs> initialResAllocs) {
this.taskTracker = taskTracker;
this.resAllocs = initialResAllocs==null? new HashMap<String, ResAllocs>() : new HashMap<>(initialResAllocs);
}
void replaceResAllocs(ResAllocs r) {
if(r != null)
addQ.offer(r);
}
void remResAllocs(String groupName) {
if(groupName != null && !groupName.isEmpty())
remQ.offer(groupName);
}
boolean prepare() {
failedTaskGroups.clear();
updateResAllocs();
return !resAllocs.isEmpty();
}
private void updateResAllocs() {
addQ.drainTo(addList);
if(!addList.isEmpty()) {
Iterator<ResAllocs> iter = addList.iterator();
while(iter.hasNext()) {
final ResAllocs r = iter.next();
resAllocs.put(r.getTaskGroupName(), r);
iter.remove();
}
}
remQ.drainTo(remList);
if(!remList.isEmpty()) {
Iterator<String> iter = remList.iterator();
while(iter.hasNext()) {
resAllocs.remove(iter.next());
iter.remove();
}
}
}
boolean taskGroupFailed(String taskGroupName) {
return failedTaskGroups.contains(taskGroupName);
}
AssignmentFailure hasResAllocs(TaskRequest task) {
if(resAllocs.isEmpty())
return null;
if(failedTaskGroups.contains(task.taskGroupName()))
return new AssignmentFailure(VMResource.ResAllocs, 1.0, 0.0, 0.0, "");
final TaskTracker.TaskGroupUsage usage = taskTracker.getUsage(task.taskGroupName());
final ResAllocs resAllocs = this.resAllocs.get(task.taskGroupName());
if(resAllocs == null)
return new AssignmentFailure(VMResource.ResAllocs, 1.0, 0.0, 0.0, "");
if(usage==null) {
final boolean success = hasZeroUsageAllowance(resAllocs);
if(!success)
failedTaskGroups.add(task.taskGroupName());
return success? null : new AssignmentFailure(VMResource.ResAllocs, 1.0, 0.0, 0.0, "");
}
// currently, no way to indicate which of resAllocs's resources limited us
if((usage.getCores()+task.getCPUs()) > resAllocs.getCores())
return new AssignmentFailure(VMResource.ResAllocs, task.getCPUs(), usage.getCores(), resAllocs.getCores(),
"");
if((usage.getMemory() + task.getMemory()) > resAllocs.getMemory())
return new AssignmentFailure(VMResource.ResAllocs, task.getMemory(), usage.getMemory(), resAllocs.getMemory(),
"");
if((usage.getNetworkMbps()+task.getNetworkMbps()) > resAllocs.getNetworkMbps())
return new AssignmentFailure(
VMResource.ResAllocs, task.getNetworkMbps(), usage.getNetworkMbps(), resAllocs.getNetworkMbps(), "");
if((usage.getDisk()+task.getDisk()) > resAllocs.getDisk())
return new AssignmentFailure(VMResource.ResAllocs, task.getDisk(), usage.getDisk(), resAllocs.getDisk(), "");
return null;
}
private boolean hasZeroUsageAllowance(ResAllocs resAllocs) {
return resAllocs != null &&
(resAllocs.getCores() > 0.0 || resAllocs.getMemory() > 0.0 ||
resAllocs.getNetworkMbps() > 0.0 || resAllocs.getDisk() > 0.0);
}
public Map<String, ResAllocs> getResAllocs() {
return Collections.unmodifiableMap(resAllocs);
}
}
| 9,157 |
0 | Create_ds/Fenzo/fenzo-core/src/main/java/com/netflix | Create_ds/Fenzo/fenzo-core/src/main/java/com/netflix/fenzo/SchedulingResult.java | /*
* Copyright 2015 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.fenzo;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* The result of a scheduling trial, as returned by
* {@link TaskScheduler#scheduleOnce(List, List) scheduleOnce()}.
* <p>
* You can use this object to get a map of which tasks the task scheduler assigned to which virtual machines,
* and then you can use this assignment map to launch the assigned tasks via Mesos.
* <p>
* You can also use the list of task assignment failures that is available through this object to make an
* additional attempt to launch those tasks on your next scheduling loop or to modify the state of the system
* to make it more amenable to the failed tasks.
*/
public class SchedulingResult {
private final Map<String, VMAssignmentResult> resultMap;
private final Map<TaskRequest, List<TaskAssignmentResult>> failures;
private final List<Exception> exceptions;
private int leasesAdded;
private int leasesRejected;
private long runtime;
private int numAllocations;
private int totalVMsCount;
private int idleVMsCount;
public SchedulingResult(Map<String, VMAssignmentResult> resultMap) {
this.resultMap = resultMap;
failures = new HashMap<>();
exceptions = new ArrayList<>();
}
/**
* Get the successful task assignment result map. The map keys are host names on which at least one task has
* been assigned resources during the current scheduling round. The map values are the assignment results
* that contain the offers used and assigned tasks.
* <p>
* Fenzo removes these offers from its internal state when you get this result. Normally, you would use these offers
* immediately to launch the tasks. For any reason if you do not use the offers to launch those tasks, you must either
* reject the offers to Mesos, or, re-add them to Fenzo with the next call to
* {@link TaskScheduler#scheduleOnce(List, List)}. Otherwise, those offers would be "leaked out".
*
* @return a Map of the successful task assignments the task scheduler made in this scheduling round
*/
public Map<String, VMAssignmentResult> getResultMap() {
return resultMap;
}
void addFailures(TaskRequest request, List<TaskAssignmentResult> f) {
failures.put(request, f);
}
public void addException(Exception e) {
exceptions.add(e);
}
public List<Exception> getExceptions() {
return exceptions;
}
/**
* Get the unsuccessful task assignment result map. The map keys are the task requests that the task
* scheduler was unable to assign. The map values are a List of all of the failures that prevented the
* task scheduler from assigning the task.
*
* @return a Map of the tasks the task scheduler failed to assign in this scheduling round
*/
public Map<TaskRequest, List<TaskAssignmentResult>> getFailures() {
return failures;
}
/**
* Get the number of leases (resource offers) added during this scheduling trial.
*
* @return the number of leases added
*/
public int getLeasesAdded() {
return leasesAdded;
}
void setLeasesAdded(int leasesAdded) {
this.leasesAdded = leasesAdded;
}
/**
* Get the number of leases (resource offers) rejected during this scheduling trial.
*
* @return the number of leases rejected
*/
public int getLeasesRejected() {
return leasesRejected;
}
void setLeasesRejected(int leasesRejected) {
this.leasesRejected = leasesRejected;
}
/**
* Get the time elapsed, in milliseconds, during this scheduling trial.
*
* @return the time taken to complete this scheduling trial, in milliseconds
*/
public long getRuntime() {
return runtime;
}
void setRuntime(long runtime) {
this.runtime = runtime;
}
/**
* Get the number of resource allocations performed during this scheduling trial.
*
* @return the number of resource allocations during this scheduling trial
*/
public int getNumAllocations() {
return numAllocations;
}
void setNumAllocations(int numAllocations) {
this.numAllocations = numAllocations;
}
/**
* Get the total number of hosts (virtual machines) known during this scheduling trial.
*
* @return the number of known hosts (VMs)
*/
public int getTotalVMsCount() {
return totalVMsCount;
}
void setTotalVMsCount(int totalVMsCount) {
this.totalVMsCount = totalVMsCount;
}
/**
* Get the number of hosts (virtual machines) that are idle at the end of this scheduling trial. This is the
* number before any scale down action is triggered.
*
* @return the number of idle hosts
*/
public int getIdleVMsCount() {
return idleVMsCount;
}
void setIdleVMsCount(int idleVMsCount) {
this.idleVMsCount = idleVMsCount;
}
@Override
public String toString() {
return "SchedulingResult{" +
"resultMap=" + resultMap +
", failures=" + failures +
", leasesAdded=" + leasesAdded +
", leasesRejected=" + leasesRejected +
", runtime=" + runtime +
", numAllocations=" + numAllocations +
", totalVMsCount=" + totalVMsCount +
", idleVMsCount=" + idleVMsCount +
'}';
}
}
| 9,158 |
0 | Create_ds/Fenzo/fenzo-core/src/main/java/com/netflix | Create_ds/Fenzo/fenzo-core/src/main/java/com/netflix/fenzo/InternalVMCloner.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.fenzo;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import org.apache.mesos.Protos;
/* package */ class InternalVMCloner {
/**
* Creates a VM lease object representing the max of resources from the given collection of VMs. Attributes
* are created by adding all unique attributes across the collection.
*
* @param avms Collection of VMs to create the new lease object from.
* @return VM lease object representing the max of resources from the given collection of VMs
*/
/* package */ VirtualMachineLease getClonedMaxResourcesLease(Collection<AssignableVirtualMachine> avms) {
double cpus = 0.0;
double mem = 0.0;
double disk = 0.0;
double network = 0.0;
double ports = 0.0;
final Map<String, Double> scalars = new HashMap<>();
final Map<String, Protos.Attribute> attributeMap = new HashMap<>();
if (avms != null) {
for (AssignableVirtualMachine avm : avms) {
Map<VMResource, Double> maxResources = avm.getMaxResources();
Double value = maxResources.get(VMResource.CPU);
if (value != null) {
cpus = Math.max(cpus, value);
}
value = maxResources.get(VMResource.Memory);
if (value != null) {
mem = Math.max(mem, value);
}
value = maxResources.get(VMResource.Disk);
if (value != null) {
disk = Math.max(disk, value);
}
value = maxResources.get(VMResource.Network);
if (value != null) {
network = Math.max(network, value);
}
value = maxResources.get(VMResource.Ports);
if (value != null) {
ports = Math.max(ports, value);
}
final Map<String, Double> maxScalars = avm.getMaxScalars();
if (maxScalars != null && !maxScalars.isEmpty()) {
for (String k : maxScalars.keySet())
scalars.compute(k, (s, oldVal) -> {
if (oldVal == null) {
oldVal = 0.0;
}
Double aDouble = maxScalars.get(k);
if (aDouble == null) {
aDouble = 0.0;
}
return oldVal + aDouble;
});
}
final Map<String, Protos.Attribute> attrs = avm.getCurrTotalLease().getAttributeMap();
if (attrs != null && !attrs.isEmpty()) {
for (Map.Entry<String, Protos.Attribute> e : attrs.entrySet())
attributeMap.putIfAbsent(e.getKey(), e.getValue());
}
}
}
final double fcpus = cpus;
final double fmem = mem;
final double fdisk = disk;
final double fnetwork = network;
final List<VirtualMachineLease.Range> fports = Collections.singletonList(
new VirtualMachineLease.Range(100, 100 + (int) ports));
return new VirtualMachineLease() {
@Override
public String getId() {
return "NoID";
}
@Override
public long getOfferedTime() {
return 0;
}
@Override
public String hostname() {
return "NoHostname";
}
@Override
public String getVMID() {
return "NoID";
}
@Override
public double cpuCores() {
return fcpus;
}
@Override
public double memoryMB() {
return fmem;
}
@Override
public double networkMbps() {
return fnetwork;
}
@Override
public double diskMB() {
return fdisk;
}
@Override
public List<Range> portRanges() {
return fports;
}
@Override
public Protos.Offer getOffer() {
return null;
}
@Override
public Map<String, Protos.Attribute> getAttributeMap() {
return attributeMap;
}
@Override
public Double getScalarValue(String name) {
return scalars.get(name);
}
@Override
public Map<String, Double> getScalarValues() {
return scalars;
}
};
}
/* package */ VirtualMachineLease cloneLease(VirtualMachineLease lease, final String hostname, long now) {
final List<VirtualMachineLease.Range> ports = new LinkedList<>();
final List<VirtualMachineLease.Range> ranges = lease.portRanges();
if (ranges != null && !ranges.isEmpty()) {
for (VirtualMachineLease.Range r : ranges)
ports.add(new VirtualMachineLease.Range(r.getBeg(), r.getEnd()));
}
final double cpus = lease.cpuCores();
final double memory = lease.memoryMB();
final double network = lease.networkMbps();
final double disk = lease.diskMB();
final Map<String, Protos.Attribute> attributes = new HashMap<>(lease.getAttributeMap());
final Map<String, Double> scalarValues = new HashMap<>(lease.getScalarValues());
return new VirtualMachineLease() {
@Override
public String getId() {
return hostname;
}
@Override
public long getOfferedTime() {
return now;
}
@Override
public String hostname() {
return hostname;
}
@Override
public String getVMID() {
return hostname;
}
@Override
public double cpuCores() {
return cpus;
}
@Override
public double memoryMB() {
return memory;
}
@Override
public double networkMbps() {
return network;
}
@Override
public double diskMB() {
return disk;
}
@Override
public List<Range> portRanges() {
return ports;
}
@Override
public Protos.Offer getOffer() {
return null;
}
@Override
public Map<String, Protos.Attribute> getAttributeMap() {
return attributes;
}
@Override
public Double getScalarValue(String name) {
return scalarValues.get(name);
}
@Override
public Map<String, Double> getScalarValues() {
return scalarValues;
}
};
}
}
| 9,159 |
0 | Create_ds/Fenzo/fenzo-core/src/main/java/com/netflix | Create_ds/Fenzo/fenzo-core/src/main/java/com/netflix/fenzo/TaskRequest.java | /*
* Copyright 2015 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.fenzo;
import java.util.List;
import java.util.Map;
/**
* Describes a task to be assigned to a host and its requirements.
*/
public interface TaskRequest {
class NamedResourceSetRequest {
private final String resName;
private final String resValue;
private final int numSets;
private final int numSubResources;
public NamedResourceSetRequest(String resName, String resValue, int numSets, int numSubResources) {
this.resName = resName;
this.resValue = resValue;
this.numSets = numSets;
this.numSubResources = numSubResources;
}
public String getResName() {
return resName;
}
public String getResValue() {
return resValue;
}
public int getNumSets() {
return numSets;
}
public int getNumSubResources() {
return numSubResources;
}
}
class AssignedResources {
private List<PreferentialNamedConsumableResourceSet.ConsumeResult> consumedNamedResources;
public List<PreferentialNamedConsumableResourceSet.ConsumeResult> getConsumedNamedResources() {
return consumedNamedResources;
}
public void setConsumedNamedResources(List<PreferentialNamedConsumableResourceSet.ConsumeResult> consumedNamedResources) {
this.consumedNamedResources = consumedNamedResources;
}
}
/**
* Get an identifier for this task request.
*
* @return a task identifier
*/
String getId();
/**
* Get the name of the task group that this task request belongs to.
*
* @return the name of the group
*/
String taskGroupName();
/**
* Get the number of CPUs requested by the task.
*
* @return how many CPUs the task is requesting
*/
double getCPUs();
/**
* Get the amount of memory in MBs requested by the task.
*
* @return how many MBs of memory the task is requesting
*/
double getMemory();
/**
* Get the network bandwidth in Mbps requested by the task.
*
* @return how many Mbps of network bandwidth the task is requesting
*/
double getNetworkMbps();
/**
* Get the disk space in MBs requested by the task.
*
* @return how much disk space in MBs the task is requesting
*/
double getDisk();
/**
* Get the number of ports requested by the task.
*
* @return how many ports the task is requesting
*/
int getPorts();
/**
* Get the scalar resources being requested by the task.
* Although the cpus, memory, networkMbps, and disk are scalar resources, Fenzo currently treats the separately. Use
* this scalar requests collection to specify scalar resources other than those four.
* @return A {@link Map} of scalar resources requested, with resource name as the key and amount requested as the value.
*/
Map<String, Double> getScalarRequests();
/**
* Get the list of custom named resource sets requested by the task.
*
* @return List of named resource set requests, or null.
*/
Map<String, NamedResourceSetRequest> getCustomNamedResources();
/**
* Get a list of the hard constraints the task requires. All of these hard constraints must be satisfied by
* a host for the task scheduler to assign this task to that host.
*
* @return a List of hard constraints
*/
List<? extends ConstraintEvaluator> getHardConstraints();
/**
* Get a list of the soft constraints the task requests. Soft constraints need not be satisfied by a host
* for the task scheduler to assign this task to that host, but hosts that satisfy the soft constraints are
* preferred by the task scheduler over those that do not.
*
* @return a List of soft constraints
*/
List<? extends VMTaskFitnessCalculator> getSoftConstraints();
/**
* Set the assigned resources for this task. These are resources other than the supported resources such as
* CPUs, Memory, etc., and any scalar resources. This will specifically need to be set for tasks that are being
* added into Fenzo as running from a prior instance of the scheduler running, for example, after the framework
* hosting this instance of Fenzo restarts. That is, they were not assigned by this instance of Fenzo.
* @param assignedResources The assigned resources to set for this task.
* @see {@link AssignedResources}
*/
void setAssignedResources(AssignedResources assignedResources);
AssignedResources getAssignedResources();
}
| 9,160 |
0 | Create_ds/Fenzo/fenzo-core/src/main/java/com/netflix | Create_ds/Fenzo/fenzo-core/src/main/java/com/netflix/fenzo/VirtualMachineLease.java | /*
* Copyright 2015 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.fenzo;
import org.apache.mesos.Protos;
import java.util.List;
import java.util.Map;
/**
* A representation of a lease (resource offer). You describe each Mesos resource offer by means of an object
* that implements the {@code VirtualMachineLease} interface. You can get such an object by passing the
* {@link org.apache.mesos.Protos.Offer Offer} object that represents that Mesos offer (and that you received
* from Mesos) into the {@link com.netflix.fenzo.plugins.VMLeaseObject VMLeaseObject} constructor.
*/
public interface VirtualMachineLease {
/**
* Describes a [beginning, end] range.
*/
public static class Range {
private final int beg;
private final int end;
public Range(int beg, int end) {
this.beg = beg;
this.end = end;
}
/**
* Get the beginning value of the range.
*
* @return the beginning value of the range
*/
public int getBeg() {
return beg;
}
/**
* Get the end value of the range.
*
* @return the end value of the range
*/
public int getEnd() {
return end;
}
}
/**
* Get the ID of the lease (offer ID).
*
* @return the lease ID
*/
public String getId();
/**
* Get the time that this lease (offer) was obtained.
*
* @return the time when this lease was obtained, in mSecs since epoch
*/
public long getOfferedTime();
/**
* Get the name of the host offered in this lease.
*
* @return the host name
*/
public String hostname();
/**
* Get the ID of the host (mesos slave ID).
*
* @return the host ID
*/
public String getVMID();
/**
* Get the number of cores (CPUs) on this host that are available for assigning.
*
* @return the number of CPUs
*/
public double cpuCores();
/**
* Get the amount of memory, in MBs, on this host that is available for assigning.
*
* @return the amount of memory, in MB
*/
public double memoryMB();
/**
* Get the amount of network bandwidth, in Mbps, on this host that is available for assigning.
*
* @return the network bandwidth, in Mbps
*/
public double networkMbps();
/**
* Get the amount of disk space, in MB, on this host that is avaialble for assigning.
*
* @return the amount of available disk space, in MB
*/
public double diskMB();
/**
* Get the list of port ranges on this host that are available for assigning.
*
* @return a List of port ranges
*/
public List<Range> portRanges();
/**
* Get the Mesos resource offer associated with this lease.
*
* @return the Mesos resource offer
*/
public Protos.Offer getOffer();
/**
* Get the map of Mesos attributes associated with this lease (offer).
*
* @return a Map of attribute names to attribute values
*/
public Map<String, Protos.Attribute> getAttributeMap();
/**
* Get the value of the scalar resource for the given <code>name</code>.
* @param name Name of the scalar resource.
* @return Value of the requested scalar resource if available, <code>null</code> otherwise.
*/
Double getScalarValue(String name);
/**
* Get a map of all of the scalar resources with resource names as the key and resource value as the value.
* Although cpus, memory, networkMbps, and disk are scalar resources, Fenzo currently treats them separately. Use
* this scalar values collection to specify scalar resources other than those four.
* @return All of the scalar resources available.
*/
Map<String, Double> getScalarValues();
}
| 9,161 |
0 | Create_ds/Fenzo/fenzo-core/src/main/java/com/netflix | Create_ds/Fenzo/fenzo-core/src/main/java/com/netflix/fenzo/AutoScaleAction.java | /*
* Copyright 2015 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.fenzo;
/**
* Describes an autoscaling action, either the scaling up or down of an autoscaling group.
*/
public interface AutoScaleAction {
/**
* Indicates whether the autoscale action is to scale up or to scale down.
*/
public enum Type {Up, Down};
/**
* Get the name of the auto scale rule that is triggering the autoscale action.
*
* @return name of the autoscale rule
*/
public String getRuleName();
/**
* Returns an indication of whether the autoscale action is to scale up or to scale down.
*
* @return an enum indicating whether the autoscale action is {@link Type#Up} or {@link Type#Down}
*/
public Type getType();
}
| 9,162 |
0 | Create_ds/Fenzo/fenzo-core/src/main/java/com/netflix | Create_ds/Fenzo/fenzo-core/src/main/java/com/netflix/fenzo/DefaultPreferentialNamedConsumableResourceEvaluator.java | package com.netflix.fenzo;
/**
* Default {@link PreferentialNamedConsumableResourceEvaluator} implementation.
*/
public class DefaultPreferentialNamedConsumableResourceEvaluator implements PreferentialNamedConsumableResourceEvaluator {
public static final PreferentialNamedConsumableResourceEvaluator INSTANCE = new DefaultPreferentialNamedConsumableResourceEvaluator();
@Override
public double evaluateIdle(String hostname, String resourceName, int index, double subResourcesNeeded, double subResourcesLimit) {
// unassigned: 0.0 indicates no fitness, so return 0.5, which is less than the case of assigned with 0 sub-resources
return 0.5 / (subResourcesLimit + 1);
}
@Override
public double evaluate(String hostname, String resourceName, int index, double subResourcesNeeded, double subResourcesUsed, double subResourcesLimit) {
return Math.min(1.0, (subResourcesUsed + subResourcesNeeded + 1.0) / (subResourcesLimit + 1));
}
}
| 9,163 |
0 | Create_ds/Fenzo/fenzo-core/src/main/java/com/netflix | Create_ds/Fenzo/fenzo-core/src/main/java/com/netflix/fenzo/BaseShortfallEvaluator.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.fenzo;
import com.netflix.fenzo.functions.Func1;
import com.netflix.fenzo.queues.QueuableTask;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;
abstract class BaseShortfallEvaluator implements ShortfallEvaluator {
private static final long TOO_OLD_THRESHOLD_MILLIS = 10 * 60000; // should this be configurable?
private volatile Func1<QueuableTask, List<String>> taskToClustersGetter = null;
private final Map<String, Long> requestedForTasksSet = new HashMap<>();
protected TaskSchedulingService schedulingService = null;
@Override
public void setTaskToClustersGetter(Func1<QueuableTask, List<String>> getter) {
this.taskToClustersGetter = getter;
}
@Override
public abstract Map<String, Integer> getShortfall(Set<String> vmGroupNames, Set<TaskRequest> failures, AutoScaleRules autoScaleRules);
@Override
public void setTaskSchedulingService(TaskSchedulingService schedulingService) {
this.schedulingService = schedulingService;
}
protected void reset() {
long tooOld = System.currentTimeMillis() - TOO_OLD_THRESHOLD_MILLIS;
Set<String> tasks = new HashSet<>(requestedForTasksSet.keySet());
for (String t : tasks) {
if (requestedForTasksSet.get(t) < tooOld)
requestedForTasksSet.remove(t);
}
}
protected List<TaskRequest> filterFailedTasks(Collection<TaskRequest> original) {
if (original == null || original.isEmpty())
return Collections.emptyList();
long now = System.currentTimeMillis();
return original.stream()
.filter(t -> requestedForTasksSet.putIfAbsent(t.getId(), now) == null)
.collect(Collectors.toList());
}
protected Map<String, Integer> fillShortfallMap(Set<String> attrKeys, Collection<TaskRequest> requests) {
Map<String, Integer> shortfallMap = new HashMap<>();
if (requests != null && !requests.isEmpty()) {
for (TaskRequest r: requests) {
for (String k : attrKeys) {
if (matchesTask(r, k)) {
if (shortfallMap.get(k) == null)
shortfallMap.put(k, 1);
else
shortfallMap.put(k, shortfallMap.get(k) + 1);
}
}
}
}
return shortfallMap;
}
private boolean matchesTask(TaskRequest r, String k) {
if (!(r instanceof QueuableTask) || taskToClustersGetter == null)
return true;
final List<String> strings = taskToClustersGetter.call((QueuableTask) r);
if (strings != null && !strings.isEmpty()) {
for (String s : strings)
if (k.equals(s))
return true;
return false; // doesn't match
}
// matches anything
return true;
}
}
| 9,164 |
0 | Create_ds/Fenzo/fenzo-core/src/main/java/com/netflix | Create_ds/Fenzo/fenzo-core/src/main/java/com/netflix/fenzo/NaiveShortfallEvaluator.java | /*
* Copyright 2015 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.fenzo;
import com.netflix.fenzo.functions.Func1;
import com.netflix.fenzo.queues.QueuableTask;
import java.util.*;
/**
* Determines by how many hosts the system is currently undershooting its needs, based on task assignment
* failures. This is used in autoscaling.
*/
class NaiveShortfallEvaluator extends BaseShortfallEvaluator {
@Override
public Map<String, Integer> getShortfall(Set<String> vmGroupNames, Set<TaskRequest> failures, AutoScaleRules autoScaleRules) {
// A naive approach to figuring out shortfall of hosts to satisfy the tasks that failed assignments is,
// strictly speaking, not possible by just attempting to add up required resources for the tasks and then mapping
// that to the number of hosts required to satisfy that many resources. Several things can make that evaluation
// wrong, including:
// - tasks may have a choice to be satisfied by multiple types of hosts
// - tasks may have constraints (hard and soft) that alter scheduling decisions
//
// One approach that would work very well is by trying to schedule them all by mirroring the scheduler's logic,
// by giving it numerous "free" resources of each type defined in the autoscale rules. Scheduling the failed tasks
// on sufficient free resources should tell us how many resources are needed. However, we need to make sure this
// process does not step on the original scheduler's state information. Or, if it does, it can be reliably undone.
//
// However, setting up the free resources is not defined yet since it involves setting up the appropriate
// VM attributes that we have no knowledge of.
//
// Therefore, we fall back to a naive approach in this implementation that can work conservatively.
// We assume that each task may need an entire new VM. This has the effect of aggressively scaling up. This
// is better than falling short of resources, so we will go with it. The scale down will take care of things when
// shortfall is taken care of.
// We need to ensure, though, that we don't ask for resources for the same tasks multiple times. Therefore, we
// maintain the list of tasks for which we have already requested resources. So, we ask again only if we notice
// new tasks. There can be some scenarios where a resource that we asked got used up for a task other than the one
// we asked for. Although this is unlikely in FIFO queuing of tasks, it can happen with certain task queue
// implementations that have ordering semantics other than FIFO. So, we maintain the list of tasks with a
// timeout and remove it from there so we catch this scenario and ask for the resources again for that task.
if (vmGroupNames != null && failures != null && !failures.isEmpty()) {
reset();
return adjustAgentScaleUp(fillShortfallMap(vmGroupNames, filterFailedTasks(failures)), autoScaleRules);
}
else
return Collections.emptyMap();
}
private Map<String, Integer> adjustAgentScaleUp(Map<String, Integer> shortfallMap, AutoScaleRules autoScaleRules) {
Map<String, Integer> corrected = new HashMap<>(shortfallMap);
for (Map.Entry<String, Integer> entry : shortfallMap.entrySet()) {
AutoScaleRule rule = autoScaleRules.get(entry.getKey());
if (rule != null) {
int adjustedValue = rule.getShortfallAdjustedAgents(entry.getValue());
if (adjustedValue > 0) {
corrected.put(entry.getKey(), adjustedValue);
}
}
}
return corrected;
}
}
| 9,165 |
0 | Create_ds/Fenzo/fenzo-core/src/main/java/com/netflix | Create_ds/Fenzo/fenzo-core/src/main/java/com/netflix/fenzo/ScaleDownAction.java | /*
* Copyright 2015 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.fenzo;
import java.util.Collection;
/**
* An autoscale action that indicates an autoscale group is to be scaled down.
*/
public class ScaleDownAction implements AutoScaleAction {
private final String ruleName;
private final Collection<String> hosts;
ScaleDownAction(String ruleName, Collection<String> hosts) {
this.ruleName = ruleName;
this.hosts = hosts;
// ToDo need to ensure those hosts' offers don't get used
}
/**
* Get the name of the autoscale rule that triggered the scale down action.
*
* @return the name of the autoscale rule.
*/
@Override
public String getRuleName() {
return ruleName;
}
/**
* Returns an indication of whether the autoscale action is to scale up or to scale down - in this case,
* down.
*
* @return {@link AutoScaleAction.Type#Down Down}
*/
@Override
public Type getType() {
return Type.Down;
}
/**
* Get the hostnames to unqueueTask from the cluster during the scale down action.
*
* @return a Collection of host names.
*/
public Collection<String> getHosts() {
return hosts;
}
}
| 9,166 |
0 | Create_ds/Fenzo/fenzo-core/src/main/java/com/netflix | Create_ds/Fenzo/fenzo-core/src/main/java/com/netflix/fenzo/AssignableVirtualMachine.java | /*
* Copyright 2015 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.fenzo;
import com.netflix.fenzo.functions.Action1;
import com.netflix.fenzo.plugins.ExclusiveHostConstraint;
import org.apache.mesos.Protos;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.*;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.atomic.AtomicBoolean;
/**
* This class represents a VM that contains resources that can be assigned to tasks.
*/
public class AssignableVirtualMachine implements Comparable<AssignableVirtualMachine>{
/* package */ static final String PseuoHostNamePrefix = "FenzoPsueodHost-";
private static class PortRange {
private final VirtualMachineLease.Range range;
private PortRange(VirtualMachineLease.Range range) {
this.range = range;
}
int size() {
return range.getEnd()-range.getBeg()+1;
}
}
private static class PortRanges {
private List<VirtualMachineLease.Range> ranges = new ArrayList<>();
private List<PortRange> portRanges = new ArrayList<>();
private int totalPorts=0;
private int currUsedPorts=0;
void addRanges(List<VirtualMachineLease.Range> ranges) {
if(ranges!=null) {
this.ranges.addAll(ranges);
for(VirtualMachineLease.Range range: ranges) {
PortRange pRange = new PortRange(range);
portRanges.add(pRange);
totalPorts += pRange.size();
}
}
}
void clear() {
ranges.clear();
portRanges.clear();
currUsedPorts=0;
totalPorts=0;
}
private List<VirtualMachineLease.Range> getRanges() {
return ranges;
}
boolean hasPorts(int num) {
return num + currUsedPorts <= totalPorts;
}
private int consumeNextPort() {
int forward=0;
for(PortRange range: portRanges) {
if(forward+range.size()>currUsedPorts) {
// consume in this range
return range.range.getBeg() + (currUsedPorts++ - forward);
}
else {
forward += range.size();
}
}
throw new IllegalStateException("All ports (" + totalPorts + ") already used up");
}
}
private static class ResAsgmntResult {
private final List<AssignmentFailure> failures;
private final double fitness;
public ResAsgmntResult(List<AssignmentFailure> failures, double fitness) {
this.failures = failures;
this.fitness = fitness;
}
}
private final PreferentialNamedConsumableResourceEvaluator preferentialNamedConsumableResourceEvaluator;
private final Map<String, VirtualMachineLease> leasesMap;
private final BlockingQueue<String> workersToUnAssign;
private final BlockingQueue<String> leasesToExpire;
private final AtomicBoolean expireAllLeasesNow;
private final Action1<VirtualMachineLease> leaseRejectAction;
private final long leaseOfferExpirySecs;
private final String hostname;
private final Map<String, Double> currTotalScalars = new HashMap<>();
private final Map<String, Double> currUsedScalars = new HashMap<>();
private double currTotalCpus=0.0;
private double currUsedCpus=0.0;
private double currTotalMemory=0.0;
private double currUsedMemory=0.0;
private double currTotalNetworkMbps=0.0;
private double currUsedNetworkMbps=0.0;
private double currTotalDisk=0.0;
private double currUsedDisk=0.0;
private VirtualMachineLease currTotalLease=null;
private PortRanges currPortRanges = new PortRanges();
private volatile Map<String, Protos.Attribute> currAttributesMap = Collections.emptyMap();
private final Map<String, PreferentialNamedConsumableResourceSet> resourceSets = new HashMap<>();
// previouslyAssignedTasksMap contains tasks on this VM before current scheduling iteration started. This is
// available for optimization of scheduling assignments for such things as locality with other similar tasks, etc.
private final Map<String, TaskRequest> previouslyAssignedTasksMap;
// assignmentResults contains results of assignments on this VM from the current scheduling iteration; they
// haven't been launched yet
private final Map<TaskRequest, TaskAssignmentResult> assignmentResults;
private static final Logger logger = LoggerFactory.getLogger(AssignableVirtualMachine.class);
private final ConcurrentMap<String, String> leaseIdToHostnameMap;
private final ConcurrentMap<String, String> vmIdToHostnameMap;
private volatile String currVMId =null;
private final TaskTracker taskTracker;
private volatile long disabledUntil=0L;
// This may have to be configurable, but, for now weight the job's soft constraints more than system wide fitness calculators
private static double softConstraintFitnessWeightPercentage =50.0;
private static double rSetsFitnessWeightPercentage=15.0;
private String exclusiveTaskId =null;
private final boolean singleLeaseMode;
private boolean firstLeaseAdded=false;
private final List<TaskRequest> consumedResourcesToAssign = new ArrayList<>();
public AssignableVirtualMachine(PreferentialNamedConsumableResourceEvaluator preferentialNamedConsumableResourceEvaluator,
ConcurrentMap<String, String> vmIdToHostnameMap,
ConcurrentMap<String, String> leaseIdToHostnameMap,
String hostname, Action1<VirtualMachineLease> leaseRejectAction,
long leaseOfferExpirySecs, TaskTracker taskTracker) {
this(preferentialNamedConsumableResourceEvaluator, vmIdToHostnameMap, leaseIdToHostnameMap, hostname, leaseRejectAction, leaseOfferExpirySecs, taskTracker, false);
}
public AssignableVirtualMachine(PreferentialNamedConsumableResourceEvaluator preferentialNamedConsumableResourceEvaluator,
ConcurrentMap<String, String> vmIdToHostnameMap,
ConcurrentMap<String, String> leaseIdToHostnameMap,
String hostname, Action1<VirtualMachineLease> leaseRejectAction,
long leaseOfferExpirySecs, TaskTracker taskTracker, boolean singleLeaseMode) {
this.preferentialNamedConsumableResourceEvaluator = preferentialNamedConsumableResourceEvaluator;
this.vmIdToHostnameMap = vmIdToHostnameMap;
this.leaseIdToHostnameMap = leaseIdToHostnameMap;
this.hostname = hostname;
this.leaseRejectAction = getWrappedLeaseRejectAction(leaseRejectAction);
this.leaseOfferExpirySecs = leaseOfferExpirySecs;
this.taskTracker = taskTracker;
this.leasesMap = new HashMap<>();
this.leasesToExpire = new LinkedBlockingQueue<>();
expireAllLeasesNow = new AtomicBoolean(false);
this.workersToUnAssign = new LinkedBlockingQueue<>();
this.previouslyAssignedTasksMap = new HashMap<>();
this.assignmentResults = new HashMap<>();
this.singleLeaseMode = singleLeaseMode;
}
private Action1<VirtualMachineLease> getWrappedLeaseRejectAction(final Action1<VirtualMachineLease> leaseRejectAction) {
return leaseRejectAction==null?
lease -> logger.warn("No lease reject action registered to reject lease id " + lease.getId() +
" on host " + lease.hostname()) :
lease -> {
if (isRejectable(lease))
leaseRejectAction.call(lease);
};
}
private boolean isRejectable(VirtualMachineLease l) {
return l != null && l.getOffer() != null;
}
private void addToAvailableResources(VirtualMachineLease l) {
if(singleLeaseMode && firstLeaseAdded)
return; // ToDo should this be illegal state exception?
firstLeaseAdded = true;
final Map<String, Double> scalars = l.getScalarValues();
if(scalars != null && !scalars.isEmpty()) {
for(Map.Entry<String, Double> entry: scalars.entrySet()) {
Double currVal = currTotalScalars.get(entry.getKey());
if(currVal == null)
currVal = 0.0;
currTotalScalars.put(entry.getKey(), currVal + entry.getValue());
}
}
currTotalCpus += l.cpuCores();
currTotalMemory += l.memoryMB();
currTotalNetworkMbps += l.networkMbps();
currTotalDisk += l.diskMB();
if (l.portRanges() != null)
currPortRanges.addRanges(l.portRanges());
if (l.getAttributeMap() != null) {
// always replace attributes map with the latest
currAttributesMap = Collections.unmodifiableMap(new HashMap<>(l.getAttributeMap()));
}
for(Map.Entry<String, Protos.Attribute> entry: currAttributesMap.entrySet()) {
switch (entry.getKey()) {
case "res":
String val = entry.getValue().getText().getValue();
if(val!=null) {
StringTokenizer tokenizer = new StringTokenizer(val, "-");
String resName = tokenizer.nextToken();
switch (resName) {
case PreferentialNamedConsumableResourceSet.attributeName:
if(tokenizer.countTokens() == 3) {
String name = tokenizer.nextToken();
String val0Str = tokenizer.nextToken();
String val1Str = tokenizer.nextToken();
if(!resourceSets.containsKey(name)) {
try {
int val0 = Integer.parseInt(val0Str);
int val1 = Integer.parseInt(val1Str);
final PreferentialNamedConsumableResourceSet crs =
new PreferentialNamedConsumableResourceSet(hostname, name, val0, val1);
final Iterator<TaskRequest> iterator = consumedResourcesToAssign.iterator();
while(iterator.hasNext()) {
TaskRequest request = iterator.next();
crs.assign(request);
iterator.remove();
}
resourceSets.put(name, crs);
}
catch (NumberFormatException e) {
logger.warn(hostname + ": invalid resource spec (" + val + ") in attributes, ignoring: " + e.getMessage());
}
}
}
else
logger.warn("Invalid res spec (expected 4 tokens with delimiter '-', ignoring: " + val);
break;
default:
logger.warn("Unknown resource in attributes, ignoring: " + val);
}
}
break;
}
}
if(!consumedResourcesToAssign.isEmpty()) {
throw new IllegalStateException(hostname + ": Some assigned tasks have no resource sets in offers: " +
consumedResourcesToAssign);
}
}
void updateCurrTotalLease() {
currTotalLease = createTotaledLease();
}
void resetResources() {
if(!singleLeaseMode) {
currTotalCpus=0.0;
currTotalMemory=0.0;
currTotalNetworkMbps=0.0;
currTotalDisk=0.0;
currPortRanges.clear();
currTotalScalars.clear();
}
currUsedCpus=0.0;
currUsedMemory=0.0;
currUsedNetworkMbps=0.0;
currUsedDisk=0.0;
currUsedScalars.clear();
// ToDo: in single offer mode, need to resolve used ports somehow
// don't clear attribute map
for(VirtualMachineLease l: leasesMap.values())
addToAvailableResources(l);
}
VirtualMachineLease getCurrTotalLease() {
return currTotalLease;
}
private VirtualMachineLease createTotaledLease() {
return new VirtualMachineLease() {
@Override
public String getId() {
return "InternalVMLeaseObject";
}
@Override
public long getOfferedTime() {
return System.currentTimeMillis();
}
@Override
public String hostname() {
return hostname;
}
@Override
public String getVMID() {
return "NoVMID-InternalVMLease";
}
@Override
public double cpuCores() {
return currTotalCpus;
}
@Override
public double memoryMB() {
return currTotalMemory;
}
@Override
public double networkMbps() {
return currTotalNetworkMbps;
}
@Override
public double diskMB() {
return currTotalDisk;
}
@Override
public List<Range> portRanges() {
return Collections.unmodifiableList(currPortRanges.getRanges());
}
@Override
public Protos.Offer getOffer() {
return null;
}
@Override
public Map<String, Protos.Attribute> getAttributeMap() {
return currAttributesMap;
}
@Override
public Double getScalarValue(String name) {
return currTotalScalars.get(name);
}
@Override
public Map<String, Double> getScalarValues() {
return Collections.unmodifiableMap(currTotalScalars);
}
};
}
void removeExpiredLeases(boolean all) {
removeExpiredLeases(all, true);
}
void removeExpiredLeases(boolean all, boolean doRejectCallback) {
@SuppressWarnings("MismatchedQueryAndUpdateOfCollection") Set<String> leasesToExpireIds = new HashSet<>();
leasesToExpire.drainTo(leasesToExpireIds);
Iterator<Map.Entry<String,VirtualMachineLease>> iterator = leasesMap.entrySet().iterator();
boolean expireAll = expireAllLeasesNow.getAndSet(false) || all;
while(iterator.hasNext()) {
VirtualMachineLease l = iterator.next().getValue();
if(expireAll || leasesToExpireIds.contains(l.getId())) {
leaseIdToHostnameMap.remove(l.getId());
if(expireAll) {
if(logger.isDebugEnabled())
logger.debug(hostname + ": expiring lease offer id " + l.getId());
if (doRejectCallback)
leaseRejectAction.call(l);
}
iterator.remove();
if (logger.isDebugEnabled())
logger.debug("Removed lease on {}, all={}", hostname, all);
}
}
if(expireAll && !hasPreviouslyAssignedTasks())
resourceSets.clear();
}
int expireLimitedLeases(AssignableVMs.VMRejectLimiter vmRejectLimiter) {
if(singleLeaseMode)
return 0;
long now = System.currentTimeMillis();
for (VirtualMachineLease l: leasesMap.values()) {
if (isRejectable(l) && l.getOfferedTime() < (now - leaseOfferExpirySecs * 1000) && vmRejectLimiter.reject()) {
for (VirtualMachineLease vml: leasesMap.values()) {
leaseIdToHostnameMap.remove(vml.getId());
if(logger.isDebugEnabled())
logger.debug(getHostname() + ": expiring lease offer id " + l.getId());
leaseRejectAction.call(vml);
}
int size = leasesMap.values().size();
leasesMap.clear();
if (logger.isDebugEnabled())
logger.debug(hostname + ": cleared leases");
return size;
}
}
return 0;
}
String getCurrVMId() {
return currVMId;
}
boolean addLease(VirtualMachineLease lease) {
if (logger.isDebugEnabled())
logger.debug("{}: adding lease id {}", hostname, lease.getId());
if(singleLeaseMode && firstLeaseAdded) {
if (leasesMap.isEmpty()) {
leasesMap.put(lease.getId(), lease);
return true;
} else {
return false;
}
}
if(!Objects.equals(currVMId, lease.getVMID())) {
currVMId = lease.getVMID();
vmIdToHostnameMap.put(lease.getVMID(), hostname);
}
if(System.currentTimeMillis()<disabledUntil) {
leaseRejectAction.call(lease);
return false;
}
if (logger.isDebugEnabled())
logger.debug(hostname + ": adding to internal leases map");
if(leasesMap.get(lease.getId()) != null)
throw new IllegalStateException("Attempt to add duplicate lease with id=" + lease.getId());
if(leaseIdToHostnameMap.putIfAbsent(lease.getId(), hostname) != null)
logger.warn("Unexpected to add a lease that already exists for host " + hostname + ", lease ID: " + lease.getId());
if(logger.isDebugEnabled())
logger.debug(getHostname() + ": adding lease offer id " + lease.getId());
leasesMap.put(lease.getId(), lease);
addToAvailableResources(lease);
return true;
}
void setDisabledUntil(long disabledUntil) {
this.disabledUntil = disabledUntil;
if(logger.isDebugEnabled())
logger.debug("{}: disabling for {} mSecs", hostname, (disabledUntil - System.currentTimeMillis()));
Iterator<Map.Entry<String, VirtualMachineLease>> entriesIterator = leasesMap.entrySet().iterator();
while(entriesIterator.hasNext()) {
Map.Entry<String, VirtualMachineLease> entry = entriesIterator.next();
leaseIdToHostnameMap.remove(entry.getValue().getId());
leaseRejectAction.call(entry.getValue());
entriesIterator.remove();
if (logger.isDebugEnabled())
logger.debug("Removed lease on " + hostname + " due to being disabled");
}
}
public void enable() {
disabledUntil = 0;
}
long getDisabledUntil() {
return disabledUntil;
}
boolean isActive() {
return !leasesMap.isEmpty() ||
hasPreviouslyAssignedTasks() ||
!assignmentResults.isEmpty() ||
!leasesToExpire.isEmpty() ||
!workersToUnAssign.isEmpty() ||
System.currentTimeMillis() < disabledUntil;
}
boolean isAssignableNow() {
return !isDisabled() && !leasesMap.isEmpty();
}
boolean isDisabled() {
return System.currentTimeMillis() < disabledUntil;
}
void setAssignedTask(TaskRequest request) {
if(logger.isDebugEnabled())
logger.debug("{}: setting assigned task {}", hostname, request.getId());
boolean added = taskTracker.addRunningTask(request, this);
if(added) {
assignResourceSets(request);
}
else
logger.error("Unexpected to add duplicate task id=" + request.getId());
previouslyAssignedTasksMap.put(request.getId(), request);
setIfExclusive(request);
if(singleLeaseMode && added) {
removeResourcesOf(request);
}
}
private void assignResourceSets(TaskRequest request) {
if(request.getAssignedResources() != null) {
final List<PreferentialNamedConsumableResourceSet.ConsumeResult> consumedNamedResources =
request.getAssignedResources().getConsumedNamedResources();
if(consumedNamedResources != null && !consumedNamedResources.isEmpty()) {
for(PreferentialNamedConsumableResourceSet.ConsumeResult cr: consumedNamedResources) {
if(resourceSets.get(cr.getAttrName()) == null)
consumedResourcesToAssign.add(request); // resource set not available yet
else
resourceSets.get(cr.getAttrName()).assign(request);
}
}
}
}
void expireLease(String leaseId) {
logger.debug("Got request to expire lease on " + hostname);
leasesToExpire.offer(leaseId);
}
void expireAllLeases() {
expireAllLeasesNow.set(true);
}
void markTaskForUnassigning(String taskId) {
workersToUnAssign.offer(taskId);
}
private void setIfExclusive(TaskRequest request) {
if(request.getHardConstraints()!=null) {
for(ConstraintEvaluator evaluator: request.getHardConstraints()) {
if(evaluator instanceof ExclusiveHostConstraint) {
exclusiveTaskId = request.getId();
return;
}
}
}
}
private void clearIfExclusive(String taskId) {
if(taskId.equals(exclusiveTaskId))
exclusiveTaskId = null;
}
void prepareForScheduling() {
@SuppressWarnings("MismatchedQueryAndUpdateOfCollection") List<String> tasks = new ArrayList<>();
workersToUnAssign.drainTo(tasks);
for(String t: tasks) {
if(logger.isDebugEnabled())
logger.debug("{}: removing previously assigned task {}", hostname, t);
taskTracker.removeRunningTask(t);
TaskRequest r = previouslyAssignedTasksMap.remove(t);
if(singleLeaseMode && r!=null)
addBackResourcesOf(r);
releaseResourceSets(r);
clearIfExclusive(t);
}
assignmentResults.clear();
}
private void releaseResourceSets(TaskRequest r) {
if(r==null) {
logger.warn("Can't release resource sets for null task");
return;
}
// unassign resource sets if any
final Map<String, TaskRequest.NamedResourceSetRequest> customNamedResources = r.getCustomNamedResources();
for (Map.Entry<String, PreferentialNamedConsumableResourceSet> entry : resourceSets.entrySet()) {
entry.getValue().release(r);
}
}
private void removeResourcesOf(TaskRequest request) {
currTotalCpus -= request.getCPUs();
currTotalMemory -= request.getMemory();
currTotalDisk -= request.getDisk();
currTotalNetworkMbps -= request.getNetworkMbps();
final Map<String, Double> scalarRequests = request.getScalarRequests();
if(scalarRequests != null && !scalarRequests.isEmpty()) {
for (Map.Entry<String, Double> entry : scalarRequests.entrySet()) {
Double oldVal = currTotalScalars.get(entry.getKey());
if (singleLeaseMode) {
// resources must be able to be negative in single lease mode
if (oldVal == null) {
oldVal = 0.0;
}
currTotalScalars.put(entry.getKey(), oldVal - entry.getValue());
} else {
if (oldVal != null) {
double newVal = oldVal - entry.getValue();
if (newVal < 0.0) {
logger.warn(hostname + ": Scalar resource " + entry.getKey() + " is " + newVal + " after removing " +
entry.getValue() + " from task " + request.getId());
currTotalScalars.put(entry.getKey(), 0.0);
} else {
currTotalScalars.put(entry.getKey(), newVal);
}
}
}
}
}
// ToDo need to figure out ports as well
}
private void addBackResourcesOf(TaskRequest r) {
currTotalCpus += r.getCPUs();
currTotalMemory += r.getMemory();
currTotalNetworkMbps += r.getNetworkMbps();
currTotalDisk += r.getDisk();
final Map<String, Double> scalarRequests = r.getScalarRequests();
if(scalarRequests != null && !scalarRequests.isEmpty()) {
for(Map.Entry<String, Double> entry: scalarRequests.entrySet()) {
Double oldVal = currTotalScalars.get(entry.getKey());
if(oldVal == null)
oldVal = 0.0;
currTotalScalars.put(entry.getKey(), oldVal + entry.getValue());
}
}
// ToDo queueTask back ports
}
String getAttrValue(String attrName) {
if(getCurrTotalLease()==null)
return null;
Protos.Attribute attribute = getCurrTotalLease().getAttributeMap().get(attrName);
if(attribute==null)
return null;
return attribute.getText().getValue();
}
Map<String, Double> getMaxScalars() {
Map<String, Double> result = new HashMap<>();
if (currTotalScalars != null) {
for (Map.Entry<String, Double> e : currTotalScalars.entrySet()) {
result.put(e.getKey(), e.getValue());
}
}
if (hasPreviouslyAssignedTasks()) {
for (TaskRequest t: previouslyAssignedTasksMap.values()) {
final Map<String, Double> scalarRequests = t.getScalarRequests();
if (scalarRequests != null && !scalarRequests.isEmpty()) {
for (Map.Entry<String, Double> e: scalarRequests.entrySet()) {
if (result.get(e.getKey()) == null)
result.put(e.getKey(), e.getValue());
else
result.put(e.getKey(), e.getValue() + result.get(e.getKey()));
}
}
}
}
return result;
}
Map<VMResource, Double> getMaxResources() {
double cpus=0.0;
double memory=0.0;
double network=0.0;
double ports=0.0;
double disk=0.0;
for(TaskRequest r: previouslyAssignedTasksMap.values()) {
cpus += r.getCPUs();
memory += r.getMemory();
network += r.getNetworkMbps();
ports += r.getPorts();
disk += r.getDisk();
}
cpus += getCurrTotalLease().cpuCores();
memory += getCurrTotalLease().memoryMB();
network += getCurrTotalLease().networkMbps();
List<VirtualMachineLease.Range> ranges = getCurrTotalLease().portRanges();
for(VirtualMachineLease.Range r: ranges)
ports += r.getEnd()-r.getBeg();
disk += getCurrTotalLease().diskMB();
Map<VMResource, Double> result = new HashMap<>();
result.put(VMResource.CPU, cpus);
result.put(VMResource.Memory, memory);
result.put(VMResource.Network, network);
result.put(VMResource.Ports, ports);
result.put(VMResource.Disk, disk);
return result;
}
/**
* Try assigning resources for a given task.
* This is the main allocation method to allocate resources from this VM to a given task. This method evaluates
* hard constraints first. Then, it tries to assign resources. If either of these results in failures, it returns a
* failure result. If successful, it invokes the fitness calculator to determine the fitness value. Then, it
* evaluates soft constraints to get its fitness value. The resulting fitness value is reduced as a
* weighted average of the two fitness values.
*
* @param request The task request to assign resources to.
* @param fitnessCalculator The fitness calculator to use for resource assignment.
* @return Assignment result.
*/
TaskAssignmentResult tryRequest(TaskRequest request, VMTaskFitnessCalculator fitnessCalculator) {
if(logger.isDebugEnabled())
logger.debug("Host {} task {}: #leases: {}", getHostname(), request.getId(), leasesMap.size());
if(leasesMap.isEmpty())
return null;
if(exclusiveTaskId!=null) {
if(logger.isDebugEnabled())
logger.debug("Host {}: can't assign task {}, already have task {} assigned with exclusive host constraint",
hostname, request.getId(), exclusiveTaskId);
ConstraintFailure failure = new ConstraintFailure(ExclusiveHostConstraint.class.getName(),
"Already has task " + exclusiveTaskId + " with exclusive host constraint");
return new TaskAssignmentResult(this, request, false, null, failure, 0.0);
}
VirtualMachineCurrentState vmCurrentState = vmCurrentState();
TaskTrackerState taskTrackerState = taskTrackerState();
ConstraintFailure failedHardConstraint = findFailedHardConstraints(request, vmCurrentState, taskTrackerState);
if(failedHardConstraint!=null) {
if(logger.isDebugEnabled())
logger.debug("Host {}: task {} failed hard constraint: ", hostname, request.getId(), failedHardConstraint);
return new TaskAssignmentResult(this, request, false, null, failedHardConstraint, 0.0);
}
final ResAsgmntResult resAsgmntResult = evalAndGetResourceAssignmentFailures(request);
if(!resAsgmntResult.failures.isEmpty()) {
if(logger.isDebugEnabled()) {
StringBuilder b = new StringBuilder();
for(AssignmentFailure f: resAsgmntResult.failures)
b.append(f.toString()).append(" ; ");
logger.debug("{}: task {} failed assignment: {}", hostname, request.getId(), b.toString());
}
return new TaskAssignmentResult(this, request, false, resAsgmntResult.failures, null, 0.0);
}
final double resAsgmntFitness = resAsgmntResult.fitness;
double fitness = fitnessCalculator.calculateFitness(request, vmCurrentState, taskTrackerState);
if(fitness == 0.0) {
if(logger.isDebugEnabled())
logger.debug("{}: task {} fitness calculator returned 0.0", hostname, request.getId());
List<AssignmentFailure> failures = Collections.singletonList(
new AssignmentFailure(VMResource.Fitness, 0.0, 0.0, 0.0, "fitnessCalculator: 0.0"));
return new TaskAssignmentResult(this, request, false, failures, null, fitness);
}
List<? extends VMTaskFitnessCalculator> softConstraints = request.getSoftConstraints();
// we don't fail on soft constraints
double softConstraintFitness=1.0;
if(softConstraints!=null && !softConstraints.isEmpty()) {
softConstraintFitness = getSoftConstraintsFitness(request, vmCurrentState, taskTrackerState);
}
fitness = combineFitnessValues(resAsgmntFitness, fitness, softConstraintFitness);
return new TaskAssignmentResult(this, request, true, null, null, fitness);
}
private double combineFitnessValues(double resAsgmntFitness, double fitness, double softConstraintFitness) {
return ( resAsgmntFitness * rSetsFitnessWeightPercentage +
softConstraintFitness * softConstraintFitnessWeightPercentage +
fitness * (100.0 - rSetsFitnessWeightPercentage - softConstraintFitnessWeightPercentage) )
/ 100.0;
}
private double getSoftConstraintsFitness(TaskRequest request, VirtualMachineCurrentState vmCurrentState, TaskTrackerState taskTrackerState) {
List<? extends VMTaskFitnessCalculator> softConstraints = request.getSoftConstraints();
int n=0;
double sum=0.0;
for(VMTaskFitnessCalculator s: softConstraints) {
n++;
sum += s.calculateFitness(request, vmCurrentState, taskTrackerState);
}
return sum/n;
}
private ResAsgmntResult evalAndGetResourceAssignmentFailures(TaskRequest request) {
List<AssignmentFailure> failures = new ArrayList<>();
final Map<String, Double> scalarRequests = request.getScalarRequests();
if(scalarRequests != null && !scalarRequests.isEmpty()) {
for(Map.Entry<String, Double> entry: scalarRequests.entrySet()) {
if(entry.getValue() == null)
continue;
Double u = currUsedScalars.get(entry.getKey());
if(u == null) u = 0.0;
Double t = currTotalScalars.get(entry.getKey());
if(t == null) t=0.0;
if(u + entry.getValue() > t) {
failures.add(new AssignmentFailure(
VMResource.Other, entry.getValue(), u, t, entry.getKey()
));
}
}
}
if((currUsedCpus+request.getCPUs()) > currTotalCpus) {
AssignmentFailure failure = new AssignmentFailure(
VMResource.CPU, request.getCPUs(), currUsedCpus,
currTotalCpus, "");
//logger.info(hostname+":"+request.getId()+" Insufficient cpus: " + failure.toString());
failures.add(failure);
}
if((currUsedMemory+request.getMemory()) > currTotalMemory) {
AssignmentFailure failure = new AssignmentFailure(
VMResource.Memory, request.getMemory(), currUsedMemory,
currTotalMemory, "");
//logger.info(hostname+":"+request.getId()+" Insufficient memory: " + failure.toString());
failures.add(failure);
}
if((currUsedNetworkMbps+request.getNetworkMbps()) > currTotalNetworkMbps) {
AssignmentFailure failure = new AssignmentFailure(
VMResource.Network, request.getNetworkMbps(), currUsedNetworkMbps, currTotalNetworkMbps, "");
//logger.info(hostname+":"+request.getId()+" Insufficient network: " + failure.toString());
failures.add(failure);
}
if((currUsedDisk+request.getDisk()) > currTotalDisk) {
AssignmentFailure failure =
new AssignmentFailure(VMResource.Disk, request.getDisk(), currUsedDisk, currTotalDisk, "");
//logger.info(hostname+":"+request.getId()+" Insufficient disk: " + failure.toString());
failures.add(failure);
}
if(!currPortRanges.hasPorts(request.getPorts())) {
AssignmentFailure failure = new AssignmentFailure(
VMResource.Ports, request.getPorts(), currPortRanges.currUsedPorts,
currPortRanges.totalPorts, "");
//logger.info(hostname+":"+request.getId()+" Insufficient ports: " + failure.toString());
failures.add(failure);
}
double rSetFitness=0.0;
int numRSets=0;
final Set<String> requestedNamedResNames = new HashSet<>(request.getCustomNamedResources()==null? Collections.<String>emptySet() :
request.getCustomNamedResources().keySet());
if(failures.isEmpty()) {
// perform resource set checks only if no other assignment failures so far
for (Map.Entry<String, PreferentialNamedConsumableResourceSet> entry : resourceSets.entrySet()) {
if (!requestedNamedResNames.isEmpty())
requestedNamedResNames.remove(entry.getKey());
final double fitness = entry.getValue().getFitness(request, preferentialNamedConsumableResourceEvaluator);
if (fitness == 0.0) {
AssignmentFailure failure = new AssignmentFailure(VMResource.ResourceSet, 0.0, 0.0, 0.0,
"ResourceSet " + entry.getValue().getName() + " unavailable"
);
failures.add(failure);
} else {
rSetFitness += fitness;
numRSets++;
}
}
if (!requestedNamedResNames.isEmpty()) {
// task requested resourceSets that aren't available on this host
AssignmentFailure failure = new AssignmentFailure(VMResource.ResourceSet, 0.0, 0.0, 0.0,
"UnavailableResourceSets: " + requestedNamedResNames
);
failures.add(failure);
} else {
if (!failures.isEmpty()) {
rSetFitness = 0.0;
} else if (numRSets > 1)
rSetFitness /= numRSets;
}
}
return new ResAsgmntResult(failures, rSetFitness);
}
private TaskTrackerState taskTrackerState() {
return new TaskTrackerState() {
@Override
public Map<String, TaskTracker.ActiveTask> getAllRunningTasks() {
return taskTracker.getAllRunningTasks();
}
@Override
public Map<String, TaskTracker.ActiveTask> getAllCurrentlyAssignedTasks() {
return taskTracker.getAllAssignedTasks();
}
};
}
public VirtualMachineCurrentState getVmCurrentState() {
final List<Protos.Offer> offers = new LinkedList<>();
for (VirtualMachineLease l: leasesMap.values()) {
offers.add(l.getOffer());
}
return new VirtualMachineCurrentState() {
@Override
public String getHostname() {
return hostname;
}
@Override
public String getVMId() {
return currVMId;
}
@Override
public Map<String, PreferentialNamedConsumableResourceSet> getResourceSets() {
return resourceSets;
}
@Override
public VirtualMachineLease getCurrAvailableResources() {
return currTotalLease;
}
@Override
public Collection<Protos.Offer> getAllCurrentOffers() {
return offers;
}
@Override
public Collection<TaskAssignmentResult> getTasksCurrentlyAssigned() {
return Collections.emptyList();
}
@Override
public Collection<TaskRequest> getRunningTasks() {
return Collections.unmodifiableCollection(previouslyAssignedTasksMap.values());
}
@Override
public long getDisabledUntil() {
return disabledUntil;
}
};
}
private VirtualMachineCurrentState vmCurrentState() {
final List<Protos.Offer> offers = new LinkedList<>();
for (VirtualMachineLease l: leasesMap.values()) {
offers.add(l.getOffer());
}
return new VirtualMachineCurrentState() {
@Override
public String getHostname() {
return hostname;
}
@Override
public String getVMId() {
return currVMId;
}
@Override
public Map<String, PreferentialNamedConsumableResourceSet> getResourceSets() {
return resourceSets;
}
@Override
public VirtualMachineLease getCurrAvailableResources() {
return currTotalLease;
}
@Override
public Collection<Protos.Offer> getAllCurrentOffers() {
return offers;
}
@Override
public Collection<TaskAssignmentResult> getTasksCurrentlyAssigned() {
return Collections.unmodifiableCollection(assignmentResults.values());
}
@Override
public Collection<TaskRequest> getRunningTasks() {
return Collections.unmodifiableCollection(previouslyAssignedTasksMap.values());
}
@Override
public long getDisabledUntil() {
return disabledUntil;
}
};
}
private ConstraintFailure findFailedHardConstraints(TaskRequest request, VirtualMachineCurrentState vmCurrentState, TaskTrackerState taskTrackerState) {
List<? extends ConstraintEvaluator> hardConstraints = request.getHardConstraints();
if(hardConstraints==null || hardConstraints.isEmpty())
return null;
for(ConstraintEvaluator c: hardConstraints) {
ConstraintEvaluator.Result r = c.evaluate(request, vmCurrentState, taskTrackerState);
if(!r.isSuccessful())
return new ConstraintFailure(c.getName(), r.getFailureReason());
}
return null;
}
String getHostname() {
return hostname;
}
boolean hasPreviouslyAssignedTasks() {
return !previouslyAssignedTasksMap.isEmpty();
}
/**
* Assign the given result and update internal counters for used resources. Use this to assign an individual
* assignment result within a scheduling iteration.
*
* @param result The assignment result to assign.
*/
void assignResult(TaskAssignmentResult result) {
final Map<String, Double> scalarRequests = result.getRequest().getScalarRequests();
if(scalarRequests != null && !scalarRequests.isEmpty()) {
for(Map.Entry<String, Double> entry: scalarRequests.entrySet()) {
if(entry.getValue() == null)
continue;
Double u = currUsedScalars.get(entry.getKey());
if(u == null) u = 0.0;
currUsedScalars.put(entry.getKey(), u + entry.getValue());
}
}
currUsedCpus += result.getRequest().getCPUs();
currUsedMemory += result.getRequest().getMemory();
currUsedNetworkMbps += result.getRequest().getNetworkMbps();
currUsedDisk += result.getRequest().getDisk();
for(int p=0; p<result.getRequest().getPorts(); p++){
result.addPort(currPortRanges.consumeNextPort());
}
for(Map.Entry<String, PreferentialNamedConsumableResourceSet> entry: resourceSets.entrySet()) {
result.addResourceSet(entry.getValue().consume(result.getRequest(), preferentialNamedConsumableResourceEvaluator));
}
if(!taskTracker.addAssignedTask(result.getRequest(), this))
logger.error("Unexpected to re-add task to assigned state, id=" + result.getRequest().getId());
assignmentResults.put(result.getRequest(), result);
}
/**
* Reset the assignment results of current scheduling iteration and return the total assignment result for this VM.
* Use this at the end of the scheduling iteration. Include all of the assignment results as well as all of the VM
* leases available in the result.
*
* @return Total assignment result including the tasks assigned and VM leases used.
*/
VMAssignmentResult resetAndGetSuccessfullyAssignedRequests() {
if(assignmentResults.isEmpty())
return null;
Set<TaskAssignmentResult> result = new HashSet<>();
for(Map.Entry<TaskRequest, TaskAssignmentResult> entry: assignmentResults.entrySet())
if(entry.getValue().isSuccessful())
result.add(entry.getValue());
if(result.isEmpty())
return null;
VMAssignmentResult vmar = new VMAssignmentResult(hostname, new ArrayList<>(leasesMap.values()), result);
if(!singleLeaseMode) {
for(String l: leasesMap.keySet())
leaseIdToHostnameMap.remove(l);
leasesMap.clear();
}
assignmentResults.clear();
return vmar;
}
// Only makes sense to get called after leases have been consolidated and total resources set in
// {@Code setAvailableResources()}
@Override
public int compareTo(AssignableVirtualMachine o) {
if(o == null)
return -1;
if(o.leasesMap.isEmpty())
return -1;
if(leasesMap.isEmpty())
return 1;
return Double.compare(o.currTotalCpus, currTotalCpus);
}
/**
* Get resource status, showing used and available amounts. The available amounts are in addition to the amounts used.
*
* @return Map with keys containing resources and values containing corresponding usage represented as a two number
* array, where the first represents the used amounts and the second represents additional available amounts.
*/
Map<VMResource, Double[]> getResourceStatus() {
Map<VMResource, Double[]> resourceMap = new HashMap<>();
double cpusUsed=0.0;
double memUsed=0.0;
double portsUsed=0.0;
double networkUsed=0.0;
double diskUsed=0.0;
for(TaskRequest r: previouslyAssignedTasksMap.values()) {
cpusUsed += r.getCPUs();
memUsed += r.getMemory();
portsUsed += r.getPorts();
networkUsed += r.getNetworkMbps();
diskUsed += r.getDisk();
}
double cpusAvail=0.0;
double memAvail=0.0;
double portsAvail=0;
double networkAvail=0.0;
double diskAvail=0.0;
for(VirtualMachineLease l: leasesMap.values()) {
cpusAvail += l.cpuCores();
memAvail += l.memoryMB();
for(VirtualMachineLease.Range range: l.portRanges())
portsAvail += range.getEnd()-range.getBeg();
networkAvail += l.networkMbps();
diskAvail += l.diskMB();
}
resourceMap.put(VMResource.CPU, new Double[]{cpusUsed, cpusAvail});
resourceMap.put(VMResource.Memory, new Double[]{memUsed, memAvail});
resourceMap.put(VMResource.Ports, new Double[]{portsUsed, portsAvail});
resourceMap.put(VMResource.Network, new Double[]{networkUsed, networkAvail});
resourceMap.put(VMResource.Disk, new Double[]{diskUsed, diskAvail});
// put resource sets
for(PreferentialNamedConsumableResourceSet rSet: resourceSets.values()) {
final String name = rSet.getName();
final List<Double> usedCounts = rSet.getUsedCounts();
int used=0;
for(Double c: usedCounts) {
if(c>=0)
used++;
}
resourceMap.put(VMResource.ResourceSet, new Double[]{(double)used, (double)(usedCounts.size()-used)});
}
return resourceMap;
}
}
| 9,167 |
0 | Create_ds/Fenzo/fenzo-core/src/main/java/com/netflix | Create_ds/Fenzo/fenzo-core/src/main/java/com/netflix/fenzo/TaskTracker.java | /*
* Copyright 2015 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.fenzo;
import com.netflix.fenzo.queues.QueuableTask;
import com.netflix.fenzo.queues.TaskQueueException;
import com.netflix.fenzo.queues.UsageTrackedQueue;
import com.netflix.fenzo.sla.ResAllocs;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
/**
* Class to keep track of task assignments.
*/
public class TaskTracker {
static class TaskGroupUsage implements ResAllocs {
private final String taskGroupName;
private double cores=0.0;
private double memory=0.0;
private double networkMbps=0.0;
private double disk=0.0;
private TaskGroupUsage(String taskGroupName) {
this.taskGroupName = taskGroupName;
}
@Override
public String getTaskGroupName() {
return taskGroupName;
}
@Override
public double getCores() {
return cores;
}
@Override
public double getMemory() {
return memory;
}
@Override
public double getNetworkMbps() {
return networkMbps;
}
@Override
public double getDisk() {
return disk;
}
void addUsage(TaskRequest task) {
cores += task.getCPUs();
memory += task.getMemory();
networkMbps += task.getNetworkMbps();
disk += task.getDisk();
}
void subtractUsage(TaskRequest task) {
cores -= task.getCPUs();
if(cores < 0.0) {
logger.warn("correcting cores usage <0.0");
cores=0.0;
}
memory -= task.getMemory();
if(memory<0.0) {
logger.warn("correcting memory usage<0.0");
memory=0.0;
}
networkMbps -= task.getNetworkMbps();
if(networkMbps<0.0) {
logger.warn("correcting networkMbps usage<0.0");
networkMbps=0.0;
}
disk -= task.getDisk();
if(disk<0.0) {
logger.warn("correcting disk usage<0.0");
disk=0.0;
}
}
}
// TODO move this class out into its own class instead of being an inner class
/**
* An active task in the scheduler.
*/
public static class ActiveTask {
private TaskRequest taskRequest;
private AssignableVirtualMachine avm;
public ActiveTask(TaskRequest taskRequest, AssignableVirtualMachine avm) {
this.taskRequest = taskRequest;
this.avm = avm;
}
/**
* Get the task request object associated with the active task.
*
* @return the task request object
*/
public TaskRequest getTaskRequest() {
return taskRequest;
}
/**
* Get the totals resource offers associated with the host on which the task is active.
*
* @return the total resource offers for the host
*/
public VirtualMachineLease getTotalLease() {
return avm.getCurrTotalLease();
}
}
private static final Logger logger = LoggerFactory.getLogger(TaskTracker.class);
private final Map<String, ActiveTask> runningTasks = new HashMap<>();
private final Map<String, ActiveTask> assignedTasks = new HashMap<>();
private final Map<String, TaskGroupUsage> taskGroupUsages = new HashMap<>();
private UsageTrackedQueue usageTrackedQueue = null;
// package scoped
TaskTracker() {
}
/* package */ void setUsageTrackedQueue(UsageTrackedQueue t) {
usageTrackedQueue = t;
}
boolean addRunningTask(TaskRequest request, AssignableVirtualMachine avm) {
final boolean added = runningTasks.put(request.getId(), new ActiveTask(request, avm)) == null;
if(added) {
addUsage(request);
if (usageTrackedQueue != null && request instanceof QueuableTask)
try {
usageTrackedQueue.launchTask((QueuableTask)request);
} catch (TaskQueueException e) {
// We don't expect this to happen since we call this only outside scheduling iteration
logger.warn("Unexpected: " + e.getMessage());
}
}
return added;
}
boolean removeRunningTask(String taskId) {
final ActiveTask removed = runningTasks.remove(taskId);
if(removed != null) {
final TaskRequest task = removed.getTaskRequest();
final TaskGroupUsage usage = taskGroupUsages.get(task.taskGroupName());
if(usage==null)
logger.warn("Unexpected to not find usage for task group " + task.taskGroupName() +
" to unqueueTask usage of task " + task.getId());
else
usage.subtractUsage(task);
if (usageTrackedQueue != null && removed.getTaskRequest() instanceof QueuableTask)
try {
final QueuableTask queuableTask = (QueuableTask) removed.getTaskRequest();
usageTrackedQueue.removeTask(queuableTask.getId(), queuableTask.getQAttributes());
} catch (TaskQueueException e) {
// We don't expect this to happen since we call this only outside scheduling iteration
logger.warn("Unexpected: " + e.getMessage());
}
}
return removed != null;
}
Map<String, ActiveTask> getAllRunningTasks() {
return Collections.unmodifiableMap(runningTasks);
}
boolean addAssignedTask(TaskRequest request, AssignableVirtualMachine avm) {
final boolean assigned = assignedTasks.put(request.getId(), new ActiveTask(request, avm)) == null;
if(assigned) {
addUsage(request);
if (usageTrackedQueue != null && request instanceof QueuableTask)
try {
usageTrackedQueue.assignTask((QueuableTask) request);
} catch (TaskQueueException e) {
// We don't expect this to happen since we call this only from within a scheduling iteration
logger.warn("Unexpected: " + e.getMessage());
}
}
return assigned;
}
private void addUsage(TaskRequest request) {
TaskGroupUsage usage = taskGroupUsages.get(request.taskGroupName());
if(usage==null) {
taskGroupUsages.put(request.taskGroupName(), new TaskGroupUsage(request.taskGroupName()));
usage = taskGroupUsages.get(request.taskGroupName());
}
usage.addUsage(request);
}
void clearAssignedTasks() {
for(ActiveTask t: assignedTasks.values())
taskGroupUsages.get(t.getTaskRequest().taskGroupName()).subtractUsage(t.getTaskRequest());
assignedTasks.clear();
}
Map<String, ActiveTask> getAllAssignedTasks() {
return Collections.unmodifiableMap(assignedTasks);
}
TaskGroupUsage getUsage(String taskGroupName) {
return taskGroupUsages.get(taskGroupName);
}
void setTotalResources(Map<VMResource, Double> totalResourcesMap) {
if (usageTrackedQueue != null)
usageTrackedQueue.setTotalResources(totalResourcesMap);
}
}
| 9,168 |
0 | Create_ds/Fenzo/fenzo-core/src/main/java/com/netflix | Create_ds/Fenzo/fenzo-core/src/main/java/com/netflix/fenzo/DefaultFitnessCalculator.java | /*
* Copyright 2015 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.fenzo;
/**
* A default fitness calculator that always finds any target to be perfectly fit for any task. A fitness
* calculator computes * a value between 0.0 and 1.0 to indicate the confidence with which it believes a
* particular target is suitable for a particular task, with 0.0 signifying that it is completely unconfident,
* and 1.0 signifying that it is completely confident. This default fitness calculator always computes this
* value to be 1.0, meaning that it always believes a target and a task are well matched for each other.
*/
public class DefaultFitnessCalculator implements VMTaskFitnessCalculator {
public DefaultFitnessCalculator() {
}
/**
* Returns the name of this fitness calculator (the class name).
*
* @return the name of this fitness calculator
*/
@Override
public String getName() {
return DefaultFitnessCalculator.class.getName();
}
/**
* Computes the suitability of {@code targetVM} to take on the task described by {@code taskRequest} to be
* 1.0 (fully suitable).
*
* @param taskRequest a description of the task to be assigned
* @param targetVM a description of the host to which the task may potentially be assigned
* @param taskTrackerState the state of tasks and task assignments in the system at large
* @return 1.0
*/
@Override
public double calculateFitness(TaskRequest taskRequest, VirtualMachineCurrentState targetVM, TaskTrackerState taskTrackerState) {
return 1.0;
}
}
| 9,169 |
0 | Create_ds/Fenzo/fenzo-core/src/main/java/com/netflix | Create_ds/Fenzo/fenzo-core/src/main/java/com/netflix/fenzo/ConstraintFailure.java | /*
* Copyright 2015 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.fenzo;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* An object that encapsulates the case of a target failing to satisfy a constraint mandated by a task and
* implemented by a {@link ConstraintEvaluator}.
*/
public class ConstraintFailure {
@JsonIgnore
private static final ObjectMapper objectMapper = new ObjectMapper();
@JsonIgnore
private static final Logger logger = LoggerFactory.getLogger(ConstraintFailure.class);
private final String name;
private final String reason;
@JsonCreator
@JsonIgnoreProperties(ignoreUnknown=true)
public ConstraintFailure(@JsonProperty("name") String name, @JsonProperty("reason") String reason) {
this.name = name;
this.reason = reason;
objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
}
/**
* Returns the name of the constraint that was violated by the target.
*
* @return the name of the constraint
*/
public String getName() {
return name;
}
/**
* Returns a description of how the constraint was violated by the target.
*
* @return a description of how the constraint failed
*/
public String getReason() {
return reason;
}
/**
* Returns a textual description of the constraint failure that combines the name of the constraint and
* the reason why it was violated by the target.
*
* @return a String representation of this {@code ConstraintFailure}
*/
@Override
public String toString() {
return "ConstraintFailure{" +
"name='" + name + '\'' +
", reason='" + reason + '\'' +
'}';
}
}
| 9,170 |
0 | Create_ds/Fenzo/fenzo-core/src/main/java/com/netflix | Create_ds/Fenzo/fenzo-core/src/main/java/com/netflix/fenzo/VMCollection.java | /*
* Copyright 2015 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.fenzo;
import com.netflix.fenzo.functions.Func1;
import org.apache.mesos.Protos;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.stream.Collectors;
import java.util.stream.Stream;
class VMCollection {
private static final String defaultGroupName = "DEFAULT";
private static final Logger logger = LoggerFactory.getLogger(VMCollection.class);
private final ConcurrentMap<String, ConcurrentMap<String, AssignableVirtualMachine>> vms;
private final Func1<String, AssignableVirtualMachine> newVmCreator;
private final String groupingAttrName;
VMCollection(Func1<String, AssignableVirtualMachine> func1, String groupingAttrName) {
vms = new ConcurrentHashMap<>();
this.newVmCreator = func1;
this.groupingAttrName = groupingAttrName;
}
Collection<AssignableVirtualMachine> getAllVMs() {
List<AssignableVirtualMachine> result = new LinkedList<>();
vms.values().forEach(m -> result.addAll(m.values()));
return result;
}
Collection<String> getGroups() {
return Collections.unmodifiableCollection(vms.keySet());
}
/**
* Create <code>n</code> pseudo VMs for each group by cloning a VM in each group.
* @param groupCounts Map with keys contain group names and values containing number of agents to clone
* @param ruleGetter Getter function for autoscale rules
* @return Collection of pseudo host names added.
*/
Map<String, List<String>> clonePseudoVMsForGroups(Map<String, Integer> groupCounts,
Func1<String, AutoScaleRule> ruleGetter,
Predicate<VirtualMachineLease> vmFilter
) {
if (groupCounts == null || groupCounts.isEmpty())
return Collections.emptyMap();
InternalVMCloner vmCloner = new InternalVMCloner();
Map<String, List<String>> result = new HashMap<>();
long now = System.currentTimeMillis();
for (String g: groupCounts.keySet()) {
List<String> hostnames = new LinkedList<>();
result.put(g, hostnames);
final ConcurrentMap<String, AssignableVirtualMachine> avmsMap = vms.get(g);
if (avmsMap != null) {
final List<AssignableVirtualMachine> vmsList = avmsMap.values()
.stream()
.filter(avm -> vmFilter.test(avm.getCurrTotalLease()))
.collect(Collectors.toList());
if (vmsList != null && !vmsList.isEmpty()) {
// NOTE: a shortcoming here is that the attributes of VMs across a group may not be homogeneous.
// By creating one lease object and cloning from it, we pick one combination of the attributes
// and replicate across all the newly created pseudo VMs. It may be possible to capture the
// unique set of attributes across all existing VMs in the group and replicate that mix within
// the new pseudo VMs. However, we will not do that at this time. So, it is possible that some
// task constraints that depend on the variety of such attributes may fail the task placement.
// We will live with that limitation at this time.
VirtualMachineLease lease = vmCloner.getClonedMaxResourcesLease(vmsList);
if(logger.isDebugEnabled()) {
logger.debug("Cloned lease cpu={}, mem={}, disk={}, network={}", lease.cpuCores(),
lease.memoryMB(), lease.diskMB(), lease.networkMbps());
final Map<String, Protos.Attribute> attributeMap = lease.getAttributeMap();
if (attributeMap == null || attributeMap.isEmpty())
logger.debug("Cloned maxRes lease has empty attributeMap");
else
for (Map.Entry<String, Protos.Attribute> entry : attributeMap.entrySet())
logger.debug("Cloned maxRes lease attribute: " + entry.getKey() + ": " +
(entry.getValue() == null ? "null" : entry.getValue().getText().getValue())
);
}
int n = groupCounts.get(g);
final AutoScaleRule rule = ruleGetter.call(g);
if (rule != null) {
int max = rule.getMaxSize();
if (max < Integer.MAX_VALUE && n > (max - vmsList.size()))
n = max - vmsList.size();
}
for (int i = 0; i < n; i++) {
final String hostname = createHostname(g, i);
addLease(vmCloner.cloneLease(lease, hostname, now));
if(logger.isDebugEnabled())
logger.debug("Added cloned lease for " + hostname);
hostnames.add(hostname);
// update total lease on the newly added VMs so they are available for use
getVmByName(hostname).ifPresent(AssignableVirtualMachine::updateCurrTotalLease);
}
}
}
}
return result;
}
private String createHostname(String g, int i) {
return AssignableVirtualMachine.PseuoHostNamePrefix + g + "-" + i;
}
/**
* Remove VM of given name from the given group. This is generally unsafe and intended only to be used by whoever
* uses {@link VMCollection#clonePseudoVMsForGroups(Map, Func1, Predicate)}.
* @param name
* @param group
*/
/* package */ AssignableVirtualMachine unsafeRemoveVm(String name, String group) {
final ConcurrentMap<String, AssignableVirtualMachine> vmsMap = vms.get(group);
if (vmsMap != null) {
return vmsMap.remove(name);
}
return null;
}
Optional<AssignableVirtualMachine> getVmByName(String name) {
return vms.values().stream()
.flatMap(
(Function<ConcurrentMap<String, AssignableVirtualMachine>, Stream<AssignableVirtualMachine>>) m
-> m.values().stream()
)
.filter(avm -> name.equals(avm.getHostname()))
.findFirst();
}
AssignableVirtualMachine create(String host) {
return create(host, defaultGroupName);
}
AssignableVirtualMachine create(String host, String group) {
vms.putIfAbsent(group, new ConcurrentHashMap<>());
AssignableVirtualMachine prev = null;
if (!defaultGroupName.equals(group)) {
if (vms.get(defaultGroupName) != null)
prev = vms.get(defaultGroupName).remove(host);
}
vms.get(group).putIfAbsent(host, prev == null? newVmCreator.call(host) : prev);
return vms.get(group).get(host);
}
AssignableVirtualMachine getOrCreate(String host) {
final Optional<AssignableVirtualMachine> vmByName = getVmByName(host);
if (vmByName.isPresent())
return vmByName.get();
return create(host, defaultGroupName);
}
private AssignableVirtualMachine getOrCreate(String host, String group) {
vms.putIfAbsent(group, new ConcurrentHashMap<>());
final AssignableVirtualMachine avm = vms.get(group).get(host);
if (avm != null)
return avm;
if (logger.isDebugEnabled())
logger.debug("Creating new host " + host);
return create(host, group);
}
boolean addLease(VirtualMachineLease l) {
String group = l.getAttributeMap() == null? null :
l.getAttributeMap().get(groupingAttrName) == null?
null :
l.getAttributeMap().get(groupingAttrName).getText().getValue();
if (group == null)
group = defaultGroupName;
final AssignableVirtualMachine avm = getOrCreate(l.hostname(), group);
return avm.addLease(l);
}
public int size() {
final Optional<Integer> size = vms.values().stream().map(Map::size).reduce((i1, i2) -> i1 + i2);
return size.orElse(0);
}
public int size(String group) {
final ConcurrentMap<String, AssignableVirtualMachine> m = vms.get(group);
return m == null? 0 : m.size();
}
public AssignableVirtualMachine remove(AssignableVirtualMachine avm) {
final String group = avm.getAttrValue(groupingAttrName);
AssignableVirtualMachine removed = null;
if (group != null) {
final ConcurrentMap<String, AssignableVirtualMachine> m = vms.get(group);
if (m != null) {
removed = m.remove(avm.getHostname());
}
}
if (removed != null)
return removed;
final ConcurrentMap<String, AssignableVirtualMachine> m = vms.get(defaultGroupName);
if (m != null)
m.remove(avm.getHostname());
return null;
}
}
| 9,171 |
0 | Create_ds/Fenzo/fenzo-core/src/main/java/com/netflix | Create_ds/Fenzo/fenzo-core/src/main/java/com/netflix/fenzo/SchedulingEventListener.java | package com.netflix.fenzo;
/**
* A callback API providing notification about Fenzo task placement decisions during the scheduling process.
*/
public interface SchedulingEventListener {
/**
* Called before a new scheduling iteration is started.
*/
void onScheduleStart();
/**
* Called when a new task placement decision is made (a task gets resources allocated on a server).
*
* @param taskAssignmentResult task assignment result
*/
void onAssignment(TaskAssignmentResult taskAssignmentResult);
/**
* Called when the scheduling iteration completes.
*/
void onScheduleFinish();
}
| 9,172 |
0 | Create_ds/Fenzo/fenzo-core/src/main/java/com/netflix | Create_ds/Fenzo/fenzo-core/src/main/java/com/netflix/fenzo/ScaleUpAction.java | /*
* Copyright 2015 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.fenzo;
/**
* An autoscale action indicating that the autoscale group is to be scaled up.
*/
public class ScaleUpAction implements AutoScaleAction {
private final String ruleName;
private final int scaleUpCount;
ScaleUpAction(String ruleName, int scaleUpCount) {
this.ruleName = ruleName;
this.scaleUpCount = scaleUpCount;
}
/**
* Returns an indication of whether the autoscale action is to scale up or to scale down - in this case, up.
*
* @return {@link AutoScaleAction.Type#Up Up}
*/
@Override
public Type getType() {
return Type.Up;
}
/**
* Returns the name of the autoscale rule that triggered the scale up action.
*
* @return the name of the autoscale rule
*/
@Override
public String getRuleName() {
return ruleName;
}
/**
* Returns the number of hosts to add to the cluster during this scale up action.
*
* @return the number of hosts to add
*/
public int getScaleUpCount() {
return scaleUpCount;
}
}
| 9,173 |
0 | Create_ds/Fenzo/fenzo-core/src/main/java/com/netflix | Create_ds/Fenzo/fenzo-core/src/main/java/com/netflix/fenzo/OptimizingShortfallEvaluator.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.fenzo;
import com.netflix.fenzo.queues.InternalTaskQueue;
import com.netflix.fenzo.queues.InternalTaskQueues;
import com.netflix.fenzo.queues.QueuableTask;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Set;
/**
* This class implements an optimal evaluation of the shortfall of the right VMs needed for cluster scale up.
* In a cluster with multiple VM groups, this evaluator is able to determine the minimum number of VMs of each group
* required to satisfy the resource demands from pending tasks at the end of a scheduling iteration.
* <P>
* This evaluator can only be used with {@link TaskSchedulingService}, it cannot be used when directly using
* {@link TaskScheduler}. The latter uses {@link NaiveShortfallEvaluator} for shortfall analysis.
* <P>
* This evaluator works by requesting a "pseudo" scheduling iteration from {@link TaskSchedulingService} with a
* new queue that is cloned from the original queue being used and adding to it only the tasks that failed assignments.
* {@link TaskSchedulingService} performs the pseudo scheduling run by creating the appropriate number of pseudo VMs
* for each group of VMs. For this, the autoscale rules are consulted to ensure the scale up will honor the maximum VMs
* for each group.
* <P>
* The pseudo scheduling run performs an entire scheduling iteration using the cloned queue and pseudo VMs in addition
* to any new VM leases that have been added since previous scheduling iteration. This will invoke any and all task
* constraints as well as fitness function setup in the scheduler. The scheduling result is used to determine the
* number of VMs in each group and then the results are discarded. As expected, the pseudo scheduling run has no impact
* on the real scheduling assignments made.
* <P>
* Tasks for which scale up is requested by this evaluator are remembered and not requested again until certain delay.
*/
class OptimizingShortfallEvaluator extends BaseShortfallEvaluator {
@Override
public Map<String, Integer> getShortfall(Set<String> vmGroupNames, Set<TaskRequest> failures, AutoScaleRules autoScaleRules) {
if (schedulingService == null || failures == null || failures.isEmpty())
return Collections.emptyMap();
final List<TaskRequest> filteredTasks = filterFailedTasks(failures);
final Map<String, Integer> shortfallTasksPerGroup = fillShortfallMap(vmGroupNames, filteredTasks);
if (shortfallTasksPerGroup.isEmpty())
return Collections.emptyMap();
if (schedulingService.isShutdown())
return Collections.emptyMap();
final InternalTaskQueue taskQueue = createAndFillAlternateQueue(filteredTasks);
return schedulingService.requestPseudoScheduling(taskQueue, shortfallTasksPerGroup);
}
private InternalTaskQueue createAndFillAlternateQueue(List<TaskRequest> shortfallTasks) {
final InternalTaskQueue taskQueue = InternalTaskQueues.createQueueOf(schedulingService.getQueue());
for (TaskRequest t: shortfallTasks) {
taskQueue.queueTask((QueuableTask) t);
}
return taskQueue;
}
}
| 9,174 |
0 | Create_ds/Fenzo/fenzo-core/src/main/java/com/netflix | Create_ds/Fenzo/fenzo-core/src/main/java/com/netflix/fenzo/TaskSchedulingService.java | /*
* Copyright 2016 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.fenzo;
import com.netflix.fenzo.common.ThreadFactoryBuilder;
import com.netflix.fenzo.functions.Action0;
import com.netflix.fenzo.functions.Action1;
import com.netflix.fenzo.functions.Func1;
import com.netflix.fenzo.queues.InternalTaskQueue;
import com.netflix.fenzo.queues.QAttributes;
import com.netflix.fenzo.queues.QueuableTask;
import com.netflix.fenzo.queues.TaskQueue;
import com.netflix.fenzo.queues.TaskQueueException;
import com.netflix.fenzo.queues.TaskQueueMultiException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicLong;
/**
* A task scheduling service that maintains a scheduling loop to continuously assign resources to tasks pending in
* the queue. This service maintains a scheduling loop to assign resources to tasks in the queue created when
* constructing this service. It calls {@link TaskScheduler#scheduleOnce(TaskIterator, List)} from within its
* scheduling loop. Users of this service add tasks into this service's queue, which are held until they are assigned.
* Here's a typical use of this service:
* <UL>
* <LI>
* Build a {@link TaskScheduler} using its builder, {@link TaskScheduler.Builder}.
* </LI>
* <LI>
* Build this service using its builder, {@link TaskSchedulingService.Builder}, providing a queue implementation
* from {@link com.netflix.fenzo.queues.TaskQueues}. Specify scheduling interval and other callbacks.
* </LI>
* <LI>
* Start the scheduling loop by calling {@link #start()}.
* </LI>
* <LI>
* Receive callbacks for scheduling result that provide a {@link SchedulingResult} object. Note that it is
* not allowed to call {@link TaskScheduler#getTaskAssigner()} for tasks assigned in the result, they are
* assigned from within this scheduling service. This service assigns the tasks before making the result
* available to you via the callback. The assignments also sets any resource sets requested by the task.
* To mark tasks as running for those tasks that were running from before this service was created, use
* {@link #initializeRunningTask(QueuableTask, String)}. Later, call
* {@link #removeTask(String, QAttributes, String)} when tasks complete or they no longer need resource assignments.
* </LI>
* </UL>
*/
public class TaskSchedulingService {
private static class RemoveTaskRequest {
private final String taskId;
private final QAttributes qAttributes;
private final String hostname;
public RemoveTaskRequest(String taskId, QAttributes qAttributes, String hostname) {
this.taskId = taskId;
this.qAttributes = qAttributes;
this.hostname = hostname;
}
}
private static class SetReadyTimeRequest {
private final String taskId;
private final QAttributes qAttributes;
private final long when;
private SetReadyTimeRequest(String taskId, QAttributes qAttributes, long when) {
this.taskId = taskId;
this.qAttributes = qAttributes;
this.when = when;
}
}
private static final Logger logger = LoggerFactory.getLogger(TaskSchedulingService.class);
private final TaskScheduler taskScheduler;
private final Action1<SchedulingResult> schedulingResultCallback;
private final InternalTaskQueue taskQueue;
private final ScheduledExecutorService executorService;
private final long loopIntervalMillis;
private final Action0 preHook;
private final BlockingQueue<VirtualMachineLease> leaseBlockingQueue = new LinkedBlockingQueue<>();
private final BlockingQueue<Map<String, QueuableTask>> addRunningTasksQueue = new LinkedBlockingQueue<>();
private final BlockingQueue<RemoveTaskRequest> removeTasksQueue = new LinkedBlockingQueue<>();
private final BlockingQueue<SetReadyTimeRequest> setReadyTimeQueue = new LinkedBlockingQueue<>();
private final BlockingQueue<Action1<Map<TaskQueue.TaskState, Collection<QueuableTask>>>> taskMapRequest = new LinkedBlockingQueue<>(10);
private final BlockingQueue<Action1<Map<String, Map<VMResource, Double[]>>>> resStatusRequest = new LinkedBlockingQueue<>(10);
private final BlockingQueue<Action1<List<VirtualMachineCurrentState>>> vmCurrStateRequest = new LinkedBlockingQueue<>(10);
private final AtomicLong lastSchedIterationAt = new AtomicLong();
private final long maxSchedIterDelay;
private volatile Func1<QueuableTask, List<String>> taskToClusterAutoScalerMapGetter = null;
private TaskSchedulingService(Builder builder) {
taskScheduler = builder.taskScheduler;
schedulingResultCallback = builder.schedulingResultCallback;
taskQueue = builder.taskQueue;
taskScheduler.getTaskTracker().setUsageTrackedQueue(taskQueue.getUsageTracker());
taskScheduler.setUsingSchedulingService(true);
executorService = builder.executorService;
loopIntervalMillis = builder.loopIntervalMillis;
preHook = builder.preHook;
maxSchedIterDelay = Math.max(builder.maxDelayMillis, loopIntervalMillis);
}
/**
* Start this scheduling service. Tasks are scheduled continuously in a loop with a delay between two consecutive
* iterations of at least the value specified via {@link Builder#withLoopIntervalMillis(long)}, and at most delay
* specified via {@link Builder#withMaxDelayMillis(long)}. The delay between consecutive iterations is longer if the
* service notices no change since the previous iteration. Changes include additions of new tasks and additions of
* new leases.
*/
public void start() {
executorService.scheduleWithFixedDelay(TaskSchedulingService.this::scheduleOnce, 0, loopIntervalMillis, TimeUnit.MILLISECONDS);
}
/**
* Mark this scheduler as shutdown and prevent any further scheduling iterations from starting. This may let an
* already running scheduling iteration to complete.
*/
public void shutdown() {
executorService.shutdown();
}
public boolean isShutdown() {
return executorService.isShutdown();
}
/* package */ TaskQueue getQueue() {
return taskQueue;
}
/* package */ Map<String, Integer> requestPseudoScheduling(final InternalTaskQueue pTaskQueue, Map<String, Integer> groupCounts) {
Map<String, Integer> pseudoSchedulingResult = new HashMap<>();
try {
logger.debug("Creating pseudo hosts");
final Map<String, List<String>> pseudoHosts = taskScheduler.createPseudoHosts(groupCounts);
logger.debug("Created " + pseudoHosts.size() + " pseudoHost groups");
int pHostsAdded = 0;
for(Map.Entry<String, List<String>> entry: pseudoHosts.entrySet()) {
logger.debug("Pseudo hosts for group " + entry.getKey() + ": " + entry.getValue());
pHostsAdded += entry.getValue() == null? 0 : entry.getValue().size();
}
try {
Map<String, String> hostnameToGrpMap = new HashMap<>();
for (Map.Entry<String, List<String>> entry : pseudoHosts.entrySet()) {
for (String h : entry.getValue())
hostnameToGrpMap.put(h, entry.getKey());
}
try {
pTaskQueue.reset();
} catch (TaskQueueMultiException e) {
final List<Exception> exceptions = e.getExceptions();
if (exceptions == null || exceptions.isEmpty()) {
logger.error("Error with pseudo queue, no details available");
} else {
logger.error("Error with pseudo queue, details:");
for (Exception pe : exceptions) {
logger.error("pseudo queue error detail: " + pe.getMessage());
}
}
}
// temporarily replace usage tracker in taskTracker to the pseudoQ and then put back the original one
taskScheduler.getTaskTracker().setUsageTrackedQueue(pTaskQueue.getUsageTracker());
logger.debug("Scheduling with pseudoQ");
final SchedulingResult schedulingResult = taskScheduler.pseudoScheduleOnce(pTaskQueue);
final Map<String, VMAssignmentResult> resultMap = schedulingResult.getResultMap();
Map<String, Integer> result = new HashMap<>();
if (!resultMap.isEmpty()) {
for (String h : resultMap.keySet()) {
final String grp = hostnameToGrpMap.get(h);
if (grp != null) {
Integer count = result.get(grp);
if (count == null)
result.put(grp, 1);
else
result.put(grp, count + 1);
}
}
}
else if(pHostsAdded > 0) {
logger.debug("No pseudo assignments made, looking for failures");
final Map<TaskRequest, List<TaskAssignmentResult>> failures = schedulingResult.getFailures();
if (failures == null || failures.isEmpty()) {
logger.debug("No failures found for pseudo assignments");
} else {
for (Map.Entry<TaskRequest, List<TaskAssignmentResult>> entry: failures.entrySet()) {
final List<TaskAssignmentResult> tars = entry.getValue();
if (tars == null || tars.isEmpty())
logger.debug("No pseudo assignment failures for task " + entry.getKey());
else {
StringBuilder b = new StringBuilder("Pseudo assignment failures for task ").append(entry.getKey()).append(": ");
for (TaskAssignmentResult r: tars) {
b.append("HOST: ").append(r.getHostname()).append(":");
final List<AssignmentFailure> afs = r.getFailures();
if (afs != null && !afs.isEmpty())
afs.forEach(af -> b.append(af.getMessage()).append("; "));
else
b.append("None").append(";");
}
logger.debug(b.toString());
}
}
}
}
pseudoSchedulingResult = result;
}
catch (Exception e) {
logger.error("Error in pseudo scheduling", e);
throw e;
}
finally {
taskScheduler.removePseudoHosts(pseudoHosts);
taskScheduler.removePseudoAssignments();
taskScheduler.getTaskTracker().setUsageTrackedQueue(taskQueue.getUsageTracker());
}
}
catch (Exception e) {
logger.error("Error in pseudo scheduling", e);
}
return pseudoSchedulingResult;
}
private void scheduleOnce() {
try {
taskScheduler.checkIfShutdown();
}
catch (IllegalStateException e) {
logger.warn("Shutting down due to taskScheduler being shutdown");
shutdown();
return;
}
try {
// check if next scheduling iteration is actually needed right away
final boolean qModified = taskQueue.reset();
addPendingRunningTasks();
removeTasks();
setTaskReadyTimes();
final boolean newLeaseExists = leaseBlockingQueue.peek() != null;
if (qModified || newLeaseExists || doNextIteration()) {
taskScheduler.setTaskToClusterAutoScalerMapGetter(taskToClusterAutoScalerMapGetter);
lastSchedIterationAt.set(System.currentTimeMillis());
if (preHook != null)
preHook.call();
List<VirtualMachineLease> currentLeases = new ArrayList<>();
leaseBlockingQueue.drainTo(currentLeases);
final SchedulingResult schedulingResult = taskScheduler.scheduleOnce(taskQueue, currentLeases);
// mark end of scheduling iteration before assigning tasks.
taskQueue.getUsageTracker().reset();
assignTasks(schedulingResult, taskScheduler);
schedulingResultCallback.call(schedulingResult);
doPendingActions();
}
}
catch (Exception e) {
SchedulingResult result = new SchedulingResult(null);
result.addException(e);
schedulingResultCallback.call(result);
}
}
private void addPendingRunningTasks() {
// add any pending running tasks
if (addRunningTasksQueue.peek() != null) {
List<Map<String, QueuableTask>> r = new LinkedList<>();
addRunningTasksQueue.drainTo(r);
for (Map<String, QueuableTask> m: r) {
for (Map.Entry<String, QueuableTask> entry: m.entrySet())
taskScheduler.getTaskAssignerIntl().call(entry.getValue(), entry.getKey());
}
}
}
private void removeTasks() {
if (removeTasksQueue.peek() != null) {
List<RemoveTaskRequest> l = new LinkedList<>();
removeTasksQueue.drainTo(l);
for (RemoveTaskRequest r: l) {
// remove it from the queue and call taskScheduler to unassign it if hostname is not null
try {
taskQueue.getUsageTracker().removeTask(r.taskId, r.qAttributes);
} catch (TaskQueueException e1) {
// shouldn't happen since we're calling outside of scheduling iteration
logger.warn("Unexpected to get exception outside of scheduling iteration: " + e1.getMessage(), e1);
}
if (r.hostname != null)
taskScheduler.getTaskUnAssigner().call(r.taskId, r.hostname);
}
}
}
private void setTaskReadyTimes() {
if (setReadyTimeQueue.peek() != null) {
List<SetReadyTimeRequest> l = new LinkedList<>();
setReadyTimeQueue.drainTo(l);
l.forEach(r -> {
try {
taskQueue.getUsageTracker().setTaskReadyTime(r.taskId, r.qAttributes, r.when);
} catch (TaskQueueException e) {
logger.warn("Unexpected to get exception outside of scheduling iteration: " + e.getMessage(), e);
}
});
}
}
private void doPendingActions() {
final Action1<Map<TaskQueue.TaskState, Collection<QueuableTask>>> action = taskMapRequest.poll();
try {
if (action != null)
action.call(taskQueue.getAllTasks());
} catch (TaskQueueException e) {
logger.warn("Unexpected when trying to get task list: " + e.getMessage(), e);
}
final Action1<Map<String, Map<VMResource, Double[]>>> rsAction = resStatusRequest.poll();
try {
if (rsAction != null)
rsAction.call(taskScheduler.getResourceStatusIntl());
} catch (IllegalStateException e) {
logger.warn("Unexpected when trying to get resource status: " + e.getMessage(), e);
}
final Action1<List<VirtualMachineCurrentState>> vmcAction = vmCurrStateRequest.poll();
try {
if (vmcAction != null)
vmcAction.call(taskScheduler.getVmCurrentStatesIntl());
} catch (IllegalStateException e) {
logger.warn("Unexpected when trying to get vm current states: " + e.getMessage(), e);
}
}
private boolean doNextIteration() {
return (System.currentTimeMillis() - lastSchedIterationAt.get()) > maxSchedIterDelay;
}
private void assignTasks(SchedulingResult schedulingResult, TaskScheduler taskScheduler) {
if(!schedulingResult.getResultMap().isEmpty()) {
for (VMAssignmentResult result: schedulingResult.getResultMap().values()) {
for (TaskAssignmentResult t: result.getTasksAssigned()) {
taskScheduler.getTaskAssignerIntl().call(t.getRequest(), result.getHostname());
final List<PreferentialNamedConsumableResourceSet.ConsumeResult> rSets = t.getrSets();
if (rSets != null) {
final TaskRequest.AssignedResources assignedResources = new TaskRequest.AssignedResources();
assignedResources.setConsumedNamedResources(rSets);
t.getRequest().setAssignedResources(assignedResources);
}
}
}
}
}
/**
* Add new leases to be used for next scheduling iteration. Leases with IDs previously added cannot be added
* again. If duplicates are found, the scheduling iteration throws an exception and is available via the
* scheduling result callback. See {@link TaskScheduler#scheduleOnce(List, List)} for details on behavior upon
* encountering an exception. This method can be called anytime without impacting any currently running scheduling
* iterations. The leases will be used in the next scheduling iteration.
* @param leases New leases to use for scheduling.
*/
public void addLeases(List<? extends VirtualMachineLease> leases) {
if (leases != null && !leases.isEmpty()) {
for(VirtualMachineLease l: leases)
leaseBlockingQueue.offer(l);
}
}
/**
* Get all of the tasks in the scheduling service's queue and call the given action when it is available. The
* list of queues returned is in a consistent state, that is, transitionary actions from ongoing scheduling
* iterations do not affect the returned collection of tasks. Although an ongoing scheduling iteration is
* unaffected by this call, onset of the next scheduling iteration may be delayed until the call to the given
* {@code action} returns. Therefore, it is expected that the {@code action} callback return quickly.
* @param action The action to call with task collection.
* @throws TaskQueueException if too many actions are pending to get tasks collection.
*/
public void requestAllTasks(Action1<Map<TaskQueue.TaskState, Collection<QueuableTask>>> action) throws TaskQueueException {
if (!taskMapRequest.offer(action))
throw new TaskQueueException("Too many pending actions submitted for getting tasks collection");
}
/**
* Get resource status information and call the given action when available. Although an ongoing scheduling
* iteration is unaffected by this call, onset of the next scheduling iteration may be delayed until the call to the
* given {@code action} returns. Therefore, it is expected that the {@code action} callback return quickly.
* @param action The action to call with resource status.
* @throws TaskQueueException if too many actions are pending to get resource status.
*/
public void requestResourceStatus(Action1<Map<String, Map<VMResource, Double[]>>> action) throws TaskQueueException {
if (!resStatusRequest.offer(action))
throw new TaskQueueException("Too many pending actions submitted for getting resource status");
}
/**
* Get the current states of all known VMs and call the given action when available. Although an ongoing scheduling
* iteration is unaffected by this call, onset of the next scheduling iteration may be delayed until the call to the
* given {@code action} returns. Therefore, it is expected that the {@code action} callback return quickly.
* @param action The action to call with VM states.
* @throws TaskQueueException if too many actions are pending to get VM states.
*/
public void requestVmCurrentStates(Action1<List<VirtualMachineCurrentState>> action) throws TaskQueueException {
if (!vmCurrStateRequest.offer(action))
throw new TaskQueueException("Too many pending actions submitted for getting VM current state");
}
/**
* Mark the given tasks as running. This is expected to be called for all tasks that were already running from before
* {@link com.netflix.fenzo.TaskSchedulingService} started running. For example, when the scheduling service
* is being started after a restart of the system and there were some tasks launched in the previous run of
* the system. Any tasks assigned resources during scheduling invoked by this service will be automatically marked
* as running.
* <P>
* @param task The task to mark as running
* @param hostname The name of the VM that the task is running on.
*/
public void initializeRunningTask(QueuableTask task, String hostname) {
addRunningTasksQueue.offer(Collections.singletonMap(hostname, task));
}
/**
* Mark the task to be removed. This is expected to be called for all tasks that were added to the queue, whether or
* not the task is already running. If the task is running, the <code>hostname</code> parameter must be set, otherwise,
* it can be <code>null</code>. The actual remove operation is performed before the start of the next scheduling
* iteration.
* @param taskId The Id of the task to be removed.
* @param qAttributes The queue attributes of the queue that the task belongs to
* @param hostname The name of the VM where the task was assigned resources from, or, <code>null</code> if it was
* not assigned any resources.
*/
public void removeTask(String taskId, QAttributes qAttributes, String hostname) {
removeTasksQueue.offer(new RemoveTaskRequest(taskId, qAttributes, hostname));
}
/**
* Set the wall clock time when this task is ready for consideration for resource allocation. Calling this method
* is safer than directly calling {@link QueuableTask#safeSetReadyAt(long)} since this scheduling service will
* call the latter when it is safe to do so.
* @see QueuableTask#getReadyAt()
* @param taskId The Id of the task.
* @param attributes The queue attributes of the queue that the task belongs to.
* @param when The wall clock time in millis when the task is ready for consideration for assignment.
*/
public void setTaskReadyTime(String taskId, QAttributes attributes, long when) {
setReadyTimeQueue.offer(new SetReadyTimeRequest(taskId, attributes, when));
}
/**
* Set the getter function that maps a given queuable task object to a list of names of VM groups for which
* cluster autoscaling rules have been set. This function will be called by autoscaler, if it was setup for
* the {@link TaskScheduler} using {@link TaskScheduler.Builder#withAutoScaleRule(AutoScaleRule)}, to determine if
* the autoscaling rule should be triggered for aggressive scale up. The function call is expected to return a list
* of autoscale group names to which the task can be launched, if there are resources available. If either this
* function is not set, or if the function returns no entries when called, the task is assumed to be able to run
* on any autoscale group.
* @param getter The function that takes a queuable task object and returns a list of autoscale group names
*/
public void setTaskToClusterAutoScalerMapGetter(Func1<QueuableTask, List<String>> getter) {
taskToClusterAutoScalerMapGetter = getter;
}
public final static class Builder {
private TaskScheduler taskScheduler = null;
private Action1<SchedulingResult> schedulingResultCallback = null;
private InternalTaskQueue taskQueue = null;
private long loopIntervalMillis = 50;
private final ScheduledExecutorService executorService;
private Action0 preHook = null;
private long maxDelayMillis = 5000L;
private boolean optimizingShortfallEvaluator = false;
public Builder() {
ThreadFactory threadFactory = ThreadFactoryBuilder.newBuilder().withNameFormat("fenzo-main").build();
executorService = new ScheduledThreadPoolExecutor(1, threadFactory);
}
/**
* Use the given instance of {@link TaskScheduler} for scheduling resources. A task scheduler must be provided
* before this builder can create the scheduling service.
* @param taskScheduler The task scheduler instance to use.
* @return this same {@code Builder}, suitable for further chaining or to build the {@link TaskSchedulingService}.
*/
public Builder withTaskScheduler(TaskScheduler taskScheduler) {
this.taskScheduler = taskScheduler;
return this;
}
/**
* Use the given callback to give scheduling results to at the end of each scheduling iteration. A callback must
* be provided before this builder can create the scheduling service.
* @param callback The action to call with scheduling results.
* @return this same {@code Builder}, suitable for further chaining or to build the {@link TaskSchedulingService}.
*/
public Builder withSchedulingResultCallback(Action1<SchedulingResult> callback) {
this.schedulingResultCallback = callback;
return this;
}
/**
* Use the given instance of {@link com.netflix.fenzo.queues.TaskQueue} from which to get tasks to assign
* resource to. A task queue must be provided before this builder can create the scheduling service.
* @param taskQ The task queue from which to get tasks for assignment of resoruces.
* @return this same {@code Builder}, suitable for further chaining or to build the {@link TaskSchedulingService}.
*/
public Builder withTaskQueue(TaskQueue taskQ) {
if (!(taskQ instanceof InternalTaskQueue))
throw new IllegalArgumentException("Argument is not a valid implementation of task queue");
taskQueue = (InternalTaskQueue) taskQ;
return this;
}
/**
* Use the given milli seconds as minimum delay between two consecutive scheduling iterations. Default to 50.
* @param loopIntervalMillis The delay between consecutive scheduling iterations in milli seconds.
* @return this same {@code Builder}, suitable for further chaining or to build the {@link TaskSchedulingService}.
*/
public Builder withLoopIntervalMillis(long loopIntervalMillis) {
this.loopIntervalMillis = loopIntervalMillis;
return this;
}
/**
* Use the given milli seconds as the maximum delay between two consecutive scheduling iterations. Default to
* 5000. Delay between two iterations may be longer than the minimum delay specified using
* {@link #withLoopIntervalMillis(long)} if the service notices no changes to the queue or there are no new
* VM leases input.
* @param maxDelayMillis The maximum delay between two consecutive scheduling iterations.
* @return this same {@code Builder}, suitable for further chaining or to build the {@link TaskSchedulingService}.
*/
public Builder withMaxDelayMillis(long maxDelayMillis) {
this.maxDelayMillis = maxDelayMillis;
return this;
}
/**
* Use the given action to call before starting a new scheduling iteration. This can be used, for example,
* to prepare for the next iteration by updating any state that user provided plugins may wish to use for
* constraints and fitness functions.
* @param preHook The callback to mark beginning of a new scheduling iteration.
* @return this same {@code Builder}, suitable for further chaining or to build the {@link TaskSchedulingService}.
*/
public Builder withPreSchedulingLoopHook(Action0 preHook) {
this.preHook = preHook;
return this;
}
/**
* Use an optimal evaluator of resource shortfall for tasks failing assignments to determine the right number
* of VMs needed for cluster scale up.
* In a cluster with multiple VM groups, determine the minimum number of VMs of each group required to satisfy
* the resource demands from pending tasks at the end of a scheduling iteration.
* <P>
* The default is to use a naive shortfall evaluator that may scale up more VMs than needed and later correct
* with an appropriate scale down.
* <P>
* Using this evaluator should incur an overhead of approximately one scheduling iteration, only once for
* the set of unassigned tasks.
* @return this same {@code Builder}, suitable for further chaining or to build the {@link TaskSchedulingService}.
*/
public Builder withOptimizingShortfallEvaluator() {
this.optimizingShortfallEvaluator = true;
return this;
}
/**
* Creates a {@link TaskSchedulingService} based on the various builder methods you have chained.
*
* @return a {@code TaskSchedulingService} built according to the specifications you indicated
*/
public TaskSchedulingService build() {
if (taskScheduler == null)
throw new NullPointerException("Null task scheduler not allowed");
if (schedulingResultCallback == null)
throw new NullPointerException("Null scheduling result callback not allowed");
if (taskQueue == null)
throw new NullPointerException("Null task queue not allowed");
final TaskSchedulingService schedulingService = new TaskSchedulingService(this);
if (optimizingShortfallEvaluator) {
taskScheduler.getAutoScaler().useOptimizingShortfallAnalyzer();
taskScheduler.getAutoScaler().setSchedulingService(schedulingService);
}
return schedulingService;
}
}
}
| 9,175 |
0 | Create_ds/Fenzo/fenzo-core/src/main/java/com/netflix | Create_ds/Fenzo/fenzo-core/src/main/java/com/netflix/fenzo/AssignmentFailure.java | /*
* Copyright 2015 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.fenzo;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* An assignment failure to indicate that a particular task could not be scheduled because a quantifiable
* resource was insufficient, along with the amount of the resource that was requested (asked) by the task, the
* amount already used, and the amount available on the target.
* <p>
* When you call {@link TaskScheduler#scheduleOnce(java.util.List, java.util.List) scheduleOnce()} to
* schedule tasks, that method returns a {@link SchedulingResult}. You can use that object's
* {@link SchedulingResult#getFailures() getFailures()} method to get a List of
* {@link TaskAssignmentResult} objects that represent the status of each task you attempted to assign. Each of
* those objects has a {@link TaskAssignmentResult#getFailures() getFailures()} method with which you can get
* a list of {@code AssignmentFailure} objects describing any failures of this sort that made the task
* scheduler unable to assign the task to a host.
*/
public class AssignmentFailure {
@JsonIgnore
private static final Logger logger = LoggerFactory.getLogger(AssignmentFailure.class);
private final VMResource resource;
private final double asking;
private final double used;
private final double available;
private final String message;
@JsonCreator
@JsonIgnoreProperties(ignoreUnknown=true)
public AssignmentFailure(@JsonProperty("resource") VMResource resource,
@JsonProperty("asking") double asking,
@JsonProperty("used") double used,
@JsonProperty("available") double available,
@JsonProperty("message") String message
) {
this.resource = resource;
this.asking = asking;
this.used = used;
this.available = available;
this.message = message;
}
/**
* Returns which target resource this assignment failure is referring to.
*
* @return an enum that indicates which target resource this assignment failure refers to
*/
public VMResource getResource() {
return resource;
}
/**
* Returns the quantity of this target resource the task was requesting.
*
* @return the quantity of the target resource the task requested
*/
public double getAsking() {
return asking;
}
/**
* Returns the quantity of this resource that is already assigned on the target.
*
* @return the quantity of the target resource that is already allocated
*/
public double getUsed() {
return used;
}
/**
* Returns the quantity of this resource that the target has free to be assigned to a new task or tasks.
*
* @return the quantity of the target resource that is available for allocation
*/
public double getAvailable() {
return available;
}
/**
* Returns text message associated with this assignment failure.
*
* @return a message or null if message not defined
*/
public String getMessage() {
return message;
}
/**
* Returns a String representation of this assignment failure, with details about the resource that caused
* the failure and its current level of allocation and availability on the target.
*
* @return a String representation of this assignment failure
*/
@Override
public String toString() {
return "AssignmentFailure{" +
"resource=" + resource +
", asking=" + asking +
", used=" + used +
", available=" + available +
", message=" + message +
'}';
}
}
| 9,176 |
0 | Create_ds/Fenzo/fenzo-core/src/main/java/com/netflix | Create_ds/Fenzo/fenzo-core/src/main/java/com/netflix/fenzo/TaskAssignmentResult.java | /*
* Copyright 2015 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.fenzo;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;
import java.util.ArrayList;
import java.util.List;
/**
* Encapsulates the results of attempting to assign a task to a host.
*/
public class TaskAssignmentResult {
@JsonIgnore
private final AssignableVirtualMachine avm;
@JsonIgnore
private final TaskRequest request;
private final String taskId;
private final String hostname;
private final String vmId;
private final List<Integer> assignedPorts;
private final List<PreferentialNamedConsumableResourceSet.ConsumeResult> rSets;
private final boolean successful;
private final List<AssignmentFailure> failures;
private final ConstraintFailure constraintFailure;
private final double fitness;
@JsonCreator
@JsonIgnoreProperties(ignoreUnknown = true)
TaskAssignmentResult(@JsonProperty("avm") AssignableVirtualMachine avm,
@JsonProperty("request") TaskRequest request,
@JsonProperty("successful") boolean successful,
@JsonProperty("failures") List<AssignmentFailure> failures,
@JsonProperty("constraintFailure") ConstraintFailure constraintFailure,
@JsonProperty("fitness") double fitness) {
this.avm = avm;
this.request = request;
this.taskId = request.getId();
this.hostname = avm == null ? "" : avm.getHostname();
this.vmId = avm == null ? null : avm.getCurrVMId();
this.successful = successful;
this.failures = failures;
this.constraintFailure = constraintFailure;
this.fitness = fitness;
assignedPorts = new ArrayList<>();
rSets = new ArrayList<>();
}
/**
* Returns the string identifier of the task request for the task whose assignment result this is.
*
* @return the identifier of the task request
*/
public String getTaskId() {
return taskId;
}
/**
* Returns the name of the host machine to which this task was attempted to be assigned.
*
* @return the hostname
*/
public String getHostname() {
return hostname;
}
/**
* Returns the identifier of the host machine at the time when this task was assigned to it, which can be
* <tt>null</tt> when not provided by {@link VirtualMachineLease machine leases}.
*
* @return the identifier of the machine
*/
public String getVMId() {
return vmId;
}
void assignResult() {
avm.assignResult(this);
}
void addPort(int port) {
assignedPorts.add(port);
}
void addResourceSet(PreferentialNamedConsumableResourceSet.ConsumeResult rSet) {
rSets.add(rSet);
}
/**
* Returns a list of port numbers corresponding to the ports the task was assigned on the host.
*
* @return a list of port numbers
*/
public List<Integer> getAssignedPorts() {
return assignedPorts;
}
public List<PreferentialNamedConsumableResourceSet.ConsumeResult> getrSets() {
return rSets;
}
/**
* Returns the {@link TaskRequest} corresponding to the task whose assignment result this is.
*
* @return the {@code TaskRequest} for this task
*/
@JsonIgnore
public TaskRequest getRequest() {
return request;
}
/**
* Indicates whether the assignment of this task to the host succeeded.
*
* @return {@code true} if this assignment succeeded, {@code false} otherwise
*/
public boolean isSuccessful() {
return successful;
}
/**
* Get a list of {@link AssignmentFailure}s corresponding to the reasons why the assignment of this task to
* the host did not succeed because of insufficient resources.
*
* @return a list of reasons why the task could not be assigned to the host because of insufficient
* resources
*/
public List<AssignmentFailure> getFailures() {
return failures;
}
/**
* Get the {@link ConstraintFailure} corresponding to the task constraint that the host failed to meet.
*
* @return information about the constraint that the host failed to satisfy
*/
public ConstraintFailure getConstraintFailure() {
return constraintFailure;
}
/**
* Get the result of the fitness calculation applied to this host for this task.
*
* @return a number between 0.0 (indicating that the host is completely unfit for this task) to 1.0
* (indicating that the host is a perfect fit for this task)
*/
public double getFitness() {
return fitness;
}
@Override
public String toString() {
return "TaskAssignmentResult{" +
"host=" + avm.getHostname() +
", request=" + request +
", taskId='" + taskId + '\'' +
", hostname='" + hostname + '\'' +
", assignedPorts=" + assignedPorts +
", successful=" + successful +
", failures=" + failures +
", constraintFailure=" + constraintFailure +
", fitness=" + fitness +
'}';
}
}
| 9,177 |
0 | Create_ds/Fenzo/fenzo-core/src/main/java/com/netflix | Create_ds/Fenzo/fenzo-core/src/main/java/com/netflix/fenzo/ScaleDownConstraintEvaluator.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.fenzo;
import java.util.Optional;
/**
* An evaluator that for each VM computes a score from 0.0 to 1.0, with 0.0 being the lowest, and 1.0 highest. Evaluation
* equal to 0.0, means that the VM should not be terminated at all. To allow state sharing during evaluation of a
* sequence of candidate VMs, an evaluator implementation specific context is provided on each invocation. A new
* context value is returned as part of the {@link Result}.
*/
public interface ScaleDownConstraintEvaluator<CONTEXT> {
/**
* Evaluation result.
*/
class Result<CONTEXT> {
private final double score;
private final Optional<CONTEXT> context;
private Result(double score, Optional<CONTEXT> context) {
this.score = score;
this.context = context;
}
public double getScore() {
return score;
}
public Optional<CONTEXT> getContext() {
return context;
}
public static <CONTEXT> Result<CONTEXT> of(double score) {
return new Result<>(score, Optional.empty());
}
public static <CONTEXT> Result<CONTEXT> of(double score, CONTEXT context) {
return new Result<>(score, Optional.of(context));
}
}
/**
* Returns the name of the constraint evaluator.
*
* @return the name of the constraint evaluator
*/
default String getName() {
return this.getClass().getSimpleName();
}
/**
* Return score from 0.0 to 1.0 for a candidate VM to be terminating. The higher the score, the higher priority of
* the VM to get terminated. Value 0.0 means that it should not be terminated.
*
* @param candidate candidate VM to be removed
* @param context evaluator specific data, held for single evaluation cycle. Initial value is set to Optional.empty().
* Evaluator should return new context as part of {@link Result} result. The new state will be passed
* during subsequent method invocation.
*
* @return result combining VM score, and new context state
*/
Result evaluate(VirtualMachineLease candidate, Optional<CONTEXT> context);
}
| 9,178 |
0 | Create_ds/Fenzo/fenzo-core/src/main/java/com/netflix/fenzo | Create_ds/Fenzo/fenzo-core/src/main/java/com/netflix/fenzo/plugins/VMLeaseObject.java | /*
* Copyright 2015 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.fenzo.plugins;
import com.netflix.fenzo.VirtualMachineLease;
import org.apache.mesos.Protos;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.*;
/**
* An adapter class to transform a Mesos resource offer to a Fenzo {@link VirtualMachineLease}. Pass a Mesos
* {@link org.apache.mesos.Protos.Offer Offer} to the {@code VMLeaseObject} constructor to transform it into an
* object that implements the {@link VirtualMachineLease} interface.
*/
public class VMLeaseObject implements VirtualMachineLease {
private static final Logger logger = LoggerFactory.getLogger(VMLeaseObject.class);
private final Protos.Offer offer;
private final String hostname;
private final String vmID;
private final Map<String, Protos.Attribute> attributeMap;
private final Map<String, Double> scalarResources;
private final Map<String, List<Range>> rangeResources;
private final long offeredTime;
public VMLeaseObject(Protos.Offer offer) {
this.offer = offer;
hostname = offer.getHostname();
this.vmID = offer.getSlaveId().getValue();
offeredTime = System.currentTimeMillis();
scalarResources = new HashMap<>();
rangeResources = new HashMap<>();
// parse out resources from offer
// expects network bandwidth to come in as consumable scalar resource named "network"
for (Protos.Resource resource : offer.getResourcesList()) {
switch (resource.getType()) {
case SCALAR:
scalarResources.put(resource.getName(), resource.getScalar().getValue());
break;
case RANGES:
List<Range> ranges = new ArrayList<>();
for (Protos.Value.Range range : resource.getRanges().getRangeList()) {
ranges.add(new Range((int)range.getBegin(), (int) range.getEnd()));
}
rangeResources.put(resource.getName(), ranges);
break;
default:
logger.debug("Unknown resource type " + resource.getType() + " for resource " + resource.getName() +
" in offer, hostname=" + hostname + ", offerId=" + offer.getId());
}
}
if(offer.getAttributesCount()>0) {
Map<String, Protos.Attribute> attributeMap = new HashMap<>();
for(Protos.Attribute attribute: offer.getAttributesList()) {
attributeMap.put(attribute.getName(), attribute);
}
this.attributeMap = Collections.unmodifiableMap(attributeMap);
} else {
this.attributeMap = Collections.emptyMap();
}
}
@Override
public String hostname() {
return hostname;
}
@Override
public String getVMID() {
return vmID;
}
@Override
public double cpuCores() {
return scalarResources.get("cpus")==null? 0.0 : scalarResources.get("cpus");
}
@Override
public double memoryMB() {
return scalarResources.get("mem")==null? 0.0 : scalarResources.get("mem");
}
@Override
public double networkMbps() {
return scalarResources.get("network")==null? 0.0 : scalarResources.get("network");
}
@Override
public double diskMB() {
return scalarResources.get("disk")==null? 0.0 : scalarResources.get("disk");
}
public Protos.Offer getOffer(){
return offer;
}
@Override
public String getId() {
return offer.getId().getValue();
}
@Override
public long getOfferedTime() {
return offeredTime;
}
@Override
public List<Range> portRanges() {
return rangeResources.get("ports")==null? Collections.<Range>emptyList() : rangeResources.get("ports");
}
@Override
public Map<String, Protos.Attribute> getAttributeMap() {
return attributeMap;
}
@Override
public Double getScalarValue(String name) {
return scalarResources.get(name);
}
@Override
public Map<String, Double> getScalarValues() {
return Collections.unmodifiableMap(scalarResources);
}
@Override
public String toString() {
return "VMLeaseObject{" +
"offer=" + offer +
", scalars: " + scalarResources.toString() +
", ranges: " + rangeResources.toString() +
", hostname='" + hostname + '\'' +
", vmID='" + vmID + '\'' +
", attributeMap=" + attributeMap +
", offeredTime=" + offeredTime +
'}';
}
}
| 9,179 |
0 | Create_ds/Fenzo/fenzo-core/src/main/java/com/netflix/fenzo | Create_ds/Fenzo/fenzo-core/src/main/java/com/netflix/fenzo/plugins/HostAttrValueConstraint.java | /*
* Copyright 2015 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.fenzo.plugins;
import com.netflix.fenzo.ConstraintEvaluator;
import com.netflix.fenzo.TaskRequest;
import com.netflix.fenzo.TaskTrackerState;
import com.netflix.fenzo.VirtualMachineCurrentState;
import com.netflix.fenzo.VirtualMachineLease;
import org.apache.mesos.Protos;
import com.netflix.fenzo.functions.Func1;
import java.util.Map;
/**
* A constraint that ensures that a task gets a host with an attribute of a specified value.
*/
public class HostAttrValueConstraint implements ConstraintEvaluator {
private static final String HOSTNAME="HOSTNAME";
private final String hostAttributeName;
private final Func1<String, String> hostAttributeValueGetter;
public HostAttrValueConstraint(String hostAttributeName, Func1<String, String> hostAttributeValueGetter) {
this.hostAttributeName = hostAttributeName==null? HOSTNAME:hostAttributeName;
this.hostAttributeValueGetter = hostAttributeValueGetter;
}
/**
* Returns the name of this constraint as a String, in the form of the class name followed by a dash
* followed by the value of {@code hostAttributeName} as it was set when this object was constructed.
*
* @return the name of this constraint
*/
@Override
public String getName() {
return HostAttrValueConstraint.class.getName()+"-"+hostAttributeName;
}
/**
* Tests a host to determine whether it has an attribute of the required value for this task request.
*
* @param taskRequest describes the task being evaluated for assignment to the host
* @param targetVM describes the host being evaluated as a target for the task
* @param taskTrackerState describes the state of tasks already assigned or running on hosts throughout the
* system
* @return a successful Result if the host has an attribute with the required value, or an unsuccessful
* Result otherwise
*/
@Override
public Result evaluate(TaskRequest taskRequest, VirtualMachineCurrentState targetVM, TaskTrackerState taskTrackerState) {
String targetHostAttrVal = getAttrValue(targetVM.getCurrAvailableResources());
if(targetHostAttrVal==null || targetHostAttrVal.isEmpty()) {
return new Result(false, hostAttributeName + " attribute unavailable on host " + targetVM.getCurrAvailableResources().hostname());
}
String requiredAttrVal = hostAttributeValueGetter.call(taskRequest.getId());
return targetHostAttrVal.equals(requiredAttrVal)?
new Result(true, "") :
new Result(false, "Host attribute " + hostAttributeName + ": required=" + requiredAttrVal + ", got=" + targetHostAttrVal);
}
private String getAttrValue(VirtualMachineLease lease) {
switch (hostAttributeName) {
case HOSTNAME:
return lease.hostname();
default:
Map<String,Protos.Attribute> attributeMap = lease.getAttributeMap();
if(attributeMap==null)
return null;
Protos.Attribute attribute = attributeMap.get(hostAttributeName);
if(attribute==null)
return null;
return attribute.getText().getValue();
}
}
}
| 9,180 |
0 | Create_ds/Fenzo/fenzo-core/src/main/java/com/netflix/fenzo | Create_ds/Fenzo/fenzo-core/src/main/java/com/netflix/fenzo/plugins/SpreadingFitnessCalculators.java | /*
* Copyright 2015 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.fenzo.plugins;
import com.netflix.fenzo.TaskRequest;
import com.netflix.fenzo.TaskTrackerState;
import com.netflix.fenzo.VMTaskFitnessCalculator;
import com.netflix.fenzo.VirtualMachineCurrentState;
/**
* A collection of spreading fitness calculators.
*/
public class SpreadingFitnessCalculators {
/**
* A CPU spreading fitness calculator. This fitness calculator has the effect of assigning a task to a
* host that has the most CPUs available.
*/
public final static VMTaskFitnessCalculator cpuSpreader = new VMTaskFitnessCalculator() {
@Override
public String getName() {
return "CpuSpreader";
}
@Override
public double calculateFitness(TaskRequest taskRequest, VirtualMachineCurrentState targetVM, TaskTrackerState taskTrackerState) {
VMTaskFitnessCalculator cpuBinPacker = BinPackingFitnessCalculators.cpuBinPacker;
return 1 - cpuBinPacker.calculateFitness(taskRequest, targetVM, taskTrackerState);
}
};
/**
* A memory bin packing fitness calculator. This fitness calculator has the effect of assigning a task to a
* host that has the most memory available.
*/
public final static VMTaskFitnessCalculator memorySpreader = new VMTaskFitnessCalculator() {
@Override
public String getName() {
return "MemorySpreader";
}
@Override
public double calculateFitness(TaskRequest taskRequest, VirtualMachineCurrentState targetVM, TaskTrackerState taskTrackerState) {
VMTaskFitnessCalculator memoryBinPacker = BinPackingFitnessCalculators.memoryBinPacker;
return 1 - memoryBinPacker.calculateFitness(taskRequest, targetVM, taskTrackerState);
}
};
/**
* A network bandwidth spreading fitness calculator. This fitness calculator has the effect of assigning a
* task to a host that has the most amount of available network bandwidth.
*/
public final static VMTaskFitnessCalculator networkSpreader = new VMTaskFitnessCalculator() {
@Override
public String getName() {
return "NetworkSpreader";
}
@Override
public double calculateFitness(TaskRequest taskRequest, VirtualMachineCurrentState targetVM, TaskTrackerState taskTrackerState) {
VMTaskFitnessCalculator networkBinPacker = BinPackingFitnessCalculators.networkBinPacker;
return 1 - networkBinPacker.calculateFitness(taskRequest, targetVM, taskTrackerState);
}
};
/**
* A bin packing fitness calculator that achieves both CPU and Memory spreading with equal weights to
* both goals.
*/
public final static VMTaskFitnessCalculator cpuMemSpreader = new VMTaskFitnessCalculator() {
@Override
public String getName() {
return "CpuAndMemorySpreader";
}
@Override
public double calculateFitness(TaskRequest taskRequest, VirtualMachineCurrentState targetVM, TaskTrackerState taskTrackerState) {
double cpuFitness = cpuSpreader.calculateFitness(taskRequest, targetVM, taskTrackerState);
double memoryFitness = memorySpreader.calculateFitness(taskRequest, targetVM, taskTrackerState);
return (cpuFitness + memoryFitness) / 2.0;
}
};
/**
* A fitness calculator that achieves CPU, Memory, and network bandwidth spreading with equal weights to
* each of the three goals.
*/
public final static VMTaskFitnessCalculator cpuMemNetworkSpreader = new VMTaskFitnessCalculator() {
@Override
public String getName() {
return "CPUAndMemoryAndNetworkBinPacker";
}
@Override
public double calculateFitness(TaskRequest taskRequest, VirtualMachineCurrentState targetVM, TaskTrackerState taskTrackerState) {
double cpuFitness = cpuSpreader.calculateFitness(taskRequest, targetVM, taskTrackerState);
double memFitness = memorySpreader.calculateFitness(taskRequest, targetVM, taskTrackerState);
double networkFitness = networkSpreader.calculateFitness(taskRequest, targetVM, taskTrackerState);
return (cpuFitness + memFitness + networkFitness) / 3.0;
}
};
}
| 9,181 |
0 | Create_ds/Fenzo/fenzo-core/src/main/java/com/netflix/fenzo | Create_ds/Fenzo/fenzo-core/src/main/java/com/netflix/fenzo/plugins/BalancedScaleDownConstraintEvaluator.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.fenzo.plugins;
import com.netflix.fenzo.ScaleDownConstraintEvaluator;
import com.netflix.fenzo.VirtualMachineLease;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
import java.util.function.Function;
/**
* Evaluator that tries to keep the same number of idle instances in each zone/region.
* As the number of instances may be large, and for each subsequent instance within a group we need to increase the
* score, we add exponentially increasing increments to the initial scoring.
*
* <h1>Example</h1>
* Lets assume that:
* <ul>
* <li>There are two zones Za and Zb</li>
* <li>Zone Za has five idle instances, and zone Zb three</li>
* <li>The initial score is 0.5, and the initial step is 0.1</li>
* </ul>
* The subsequent scores for a single zone will be: 0.5, 0.6, 0.65, 0.675, 0.6875, etc.
* Int the given example we will get:
* <ul>
* <li>Za(1)=0.5, Za(2)=0.6, Za(3)=0.65, Za(4)=0.675, Za(5)=0.6875</li>
* <li>Zb(1)=0.5, Zb(2)=0.6, Zb(3)=0.65</li>
* </ul>
* Assuming the zone balancing is the only evaluation criteria, the termination order (according to the highest score)
* for four instances will be: Za(5), Za(4), Za(3), Zb(3). In the end zones Za and Zb will be left with the same
* number of instances.
*/
public class BalancedScaleDownConstraintEvaluator implements ScaleDownConstraintEvaluator<Map<String, Integer>> {
// TODO Figure our failure propagation without blowing up everything
private static final String FAILURE_GROUP = "failures";
private final Function<VirtualMachineLease, String> keyExtractor;
private final double initialScore;
private final double initialStep;
public BalancedScaleDownConstraintEvaluator(Function<VirtualMachineLease, String> keyExtractor,
double initialScore,
double initialStep) {
this.keyExtractor = keyExtractor;
this.initialScore = initialScore;
this.initialStep = initialStep;
}
@Override
public String getName() {
return getClass().getSimpleName();
}
@Override
public Result<Map<String, Integer>> evaluate(VirtualMachineLease candidate, Optional<Map<String, Integer>> optionalContext) {
Map<String, Integer> context = optionalContext.orElseGet(HashMap::new);
String group = findGroup(candidate);
int groupCount = context.getOrDefault(group, 0);
context.put(group, groupCount + 1);
double score = computeScore(groupCount);
return Result.of(score, context);
}
private double computeScore(int groupCount) {
if (groupCount == 0) {
return initialScore;
}
return initialScore + initialStep * (1 - Math.pow(0.5, groupCount)) / 0.5;
}
private String findGroup(VirtualMachineLease l) {
String groupName;
try {
groupName = keyExtractor.apply(l);
} catch (Exception e) {
groupName = FAILURE_GROUP;
}
return groupName;
}
}
| 9,182 |
0 | Create_ds/Fenzo/fenzo-core/src/main/java/com/netflix/fenzo | Create_ds/Fenzo/fenzo-core/src/main/java/com/netflix/fenzo/plugins/AttributeUtilities.java | /*
* Copyright 2015 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.fenzo.plugins;
import com.netflix.fenzo.VirtualMachineLease;
import org.apache.mesos.Protos;
import java.util.Map;
class AttributeUtilities {
/* package */ final static String DEFAULT_ATTRIBUTE="HOSTNAME";
/* package */ static String getAttrValue(VirtualMachineLease lease, String hostAttributeName) {
switch (hostAttributeName) {
case DEFAULT_ATTRIBUTE:
return lease.hostname();
default:
Map<String,Protos.Attribute> attributeMap = lease.getAttributeMap();
if(attributeMap==null)
return null;
Protos.Attribute attribute = attributeMap.get(hostAttributeName);
if(attribute==null)
return null;
return attribute.getText().getValue();
}
}
}
| 9,183 |
0 | Create_ds/Fenzo/fenzo-core/src/main/java/com/netflix/fenzo | Create_ds/Fenzo/fenzo-core/src/main/java/com/netflix/fenzo/plugins/BinPackingFitnessCalculators.java | /*
* Copyright 2015 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.fenzo.plugins;
import com.netflix.fenzo.TaskAssignmentResult;
import com.netflix.fenzo.TaskRequest;
import com.netflix.fenzo.TaskTrackerState;
import com.netflix.fenzo.VMTaskFitnessCalculator;
import com.netflix.fenzo.VirtualMachineCurrentState;
import com.netflix.fenzo.VirtualMachineLease;
import com.netflix.fenzo.functions.Func1;
import java.util.Iterator;
/**
* A collection of bin packing fitness calculators.
*/
public class BinPackingFitnessCalculators {
/**
* A CPU bin packing fitness calculator. This fitness calculator has the effect of assigning a task to a
* host that has the least number of available CPUs that are sufficient to fit the task.
*/
public final static VMTaskFitnessCalculator cpuBinPacker = new VMTaskFitnessCalculator() {
@Override
public String getName() {
return "CPUBinPacker";
}
@Override
public double calculateFitness(TaskRequest taskRequest, VirtualMachineCurrentState targetVM, TaskTrackerState taskTrackerState) {
return calculateResourceFitness(taskRequest, targetVM, taskTrackerState,
new Func1<TaskRequest, Double>() {
@Override
public Double call(TaskRequest request) {
return request.getCPUs();
}
},
new Func1<VirtualMachineLease, Double>() {
@Override
public Double call(VirtualMachineLease l) {
return l.cpuCores();
}
});
}
};
/**
* A memory bin packing fitness calcualtor. This fitness calculator has the effect of assigning a task to a
* host that has the least amount of available memory that is sufficient to fit the task.
*/
public final static VMTaskFitnessCalculator memoryBinPacker = new VMTaskFitnessCalculator() {
@Override
public String getName() {
return "MemoryBinPacker";
}
@Override
public double calculateFitness(TaskRequest taskRequest, VirtualMachineCurrentState targetVM, TaskTrackerState taskTrackerState) {
return calculateResourceFitness(taskRequest, targetVM, taskTrackerState,
new Func1<TaskRequest, Double>() {
@Override
public Double call(TaskRequest request) {
return request.getMemory();
}
},
new Func1<VirtualMachineLease, Double>() {
@Override
public Double call(VirtualMachineLease l) {
return l.memoryMB();
}
});
}
};
/**
* A bin packing fitness calculator that achieves both CPU and Memory bin packing with equal weights to
* both goals.
*/
public final static VMTaskFitnessCalculator cpuMemBinPacker = new VMTaskFitnessCalculator() {
@Override
public String getName() {
return "CPUAndMemoryBinPacker";
}
@Override
public double calculateFitness(TaskRequest taskRequest, VirtualMachineCurrentState targetVM, TaskTrackerState taskTrackerState) {
double cpuFitness = cpuBinPacker.calculateFitness(taskRequest, targetVM, taskTrackerState);
double memoryFitness = memoryBinPacker.calculateFitness(taskRequest, targetVM, taskTrackerState);
return (cpuFitness + memoryFitness) / 2.0;
}
};
/**
* A network bandwidth bin packing fitness calculator. This fitness calculator has the effect of assigning a
* task to a host that has the least amount of available network bandwidth that is sufficient for the task.
*/
public final static VMTaskFitnessCalculator networkBinPacker = new VMTaskFitnessCalculator() {
@Override
public String getName() {
return "NetworkBinPacker";
}
@Override
public double calculateFitness(TaskRequest taskRequest, VirtualMachineCurrentState targetVM, TaskTrackerState taskTrackerState) {
return calculateResourceFitness(taskRequest, targetVM, taskTrackerState,
new Func1<TaskRequest, Double>() {
@Override
public Double call(TaskRequest request) {
return request.getNetworkMbps();
}
},
new Func1<VirtualMachineLease, Double>() {
@Override
public Double call(VirtualMachineLease l) {
return l.networkMbps();
}
});
}
};
/**
* A fitness calculator that achieves CPU, Memory, and network bandwidth bin packing with equal weights to
* each of the three goals.
*/
public final static VMTaskFitnessCalculator cpuMemNetworkBinPacker = new VMTaskFitnessCalculator() {
@Override
public String getName() {
return "CPUAndMemoryAndNetworkBinPacker";
}
@Override
public double calculateFitness(TaskRequest taskRequest, VirtualMachineCurrentState targetVM, TaskTrackerState taskTrackerState) {
double cpuFitness = cpuBinPacker.calculateFitness(taskRequest, targetVM, taskTrackerState);
double memFitness = memoryBinPacker.calculateFitness(taskRequest, targetVM, taskTrackerState);
double networkFitness = networkBinPacker.calculateFitness(taskRequest, targetVM, taskTrackerState);
return (cpuFitness + memFitness + networkFitness)/3.0;
}
};
private static double calculateResourceFitness(TaskRequest request, VirtualMachineCurrentState targetVM, TaskTrackerState taskTrackerState,
Func1<TaskRequest, Double> taskResourceGetter,
Func1<VirtualMachineLease, Double> leaseResourceGetter) {
double totalRes = leaseResourceGetter.call(targetVM.getCurrAvailableResources());
Iterator<TaskRequest> iterator = targetVM.getRunningTasks().iterator();
double oldJobsTotal=0.0;
while(iterator.hasNext())
oldJobsTotal += taskResourceGetter.call(iterator.next());
double usedResource = taskResourceGetter.call(request);
Iterator<TaskAssignmentResult> taskAssignmentResultIterator = targetVM.getTasksCurrentlyAssigned().iterator();
while(taskAssignmentResultIterator.hasNext())
usedResource += taskResourceGetter.call(taskAssignmentResultIterator.next().getRequest());
totalRes += oldJobsTotal;
usedResource += oldJobsTotal;
return usedResource / totalRes;
}
}
| 9,184 |
0 | Create_ds/Fenzo/fenzo-core/src/main/java/com/netflix/fenzo | Create_ds/Fenzo/fenzo-core/src/main/java/com/netflix/fenzo/plugins/InactiveClusterScaleDownConstraintEvaluator.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.fenzo.plugins;
import com.netflix.fenzo.ScaleDownOrderEvaluator;
import com.netflix.fenzo.VirtualMachineLease;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.function.Function;
import static java.util.Arrays.asList;
/**
* VM constraint evaluator that splits all VMs into two equivalence classes: inactive and active, with
* inactive class being first to scale down.
*/
public class InactiveClusterScaleDownConstraintEvaluator implements ScaleDownOrderEvaluator {
private final Function<VirtualMachineLease, Boolean> isInactive;
public InactiveClusterScaleDownConstraintEvaluator(Function<VirtualMachineLease, Boolean> isInactive) {
this.isInactive = isInactive;
}
@Override
public List<Set<VirtualMachineLease>> evaluate(Collection<VirtualMachineLease> candidates) {
Set<VirtualMachineLease> active = new HashSet<>();
Set<VirtualMachineLease> inactive = new HashSet<>();
candidates.forEach(l -> {
if (isInactive(l)) {
inactive.add(l);
} else {
active.add(l);
}
});
inactive.addAll(active);
return asList(inactive, active);
}
private boolean isInactive(VirtualMachineLease lease) {
try {
Boolean inactive = isInactive.apply(lease);
return inactive != null && inactive;
} catch (Exception ignore) {
// We expect callback provider to handle all exceptions, and this is just a safeguard for Fenzo evaluator
}
return false;
}
}
| 9,185 |
0 | Create_ds/Fenzo/fenzo-core/src/main/java/com/netflix/fenzo | Create_ds/Fenzo/fenzo-core/src/main/java/com/netflix/fenzo/plugins/NoOpScaleDownOrderEvaluator.java | package com.netflix.fenzo.plugins;
import com.netflix.fenzo.ScaleDownOrderEvaluator;
import com.netflix.fenzo.VirtualMachineLease;
import java.util.*;
public class NoOpScaleDownOrderEvaluator implements ScaleDownOrderEvaluator {
@Override
public List<Set<VirtualMachineLease>> evaluate(Collection<VirtualMachineLease> candidates) {
Set<VirtualMachineLease> singleGroup = new HashSet<>();
singleGroup.addAll(candidates);
return Collections.singletonList(singleGroup);
}
}
| 9,186 |
0 | Create_ds/Fenzo/fenzo-core/src/main/java/com/netflix/fenzo | Create_ds/Fenzo/fenzo-core/src/main/java/com/netflix/fenzo/plugins/BalancedHostAttrConstraint.java | /*
* Copyright 2015 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.fenzo.plugins;
import com.netflix.fenzo.ConstraintEvaluator;
import com.netflix.fenzo.TaskRequest;
import com.netflix.fenzo.TaskTracker;
import com.netflix.fenzo.TaskTrackerState;
import com.netflix.fenzo.VMTaskFitnessCalculator;
import com.netflix.fenzo.VirtualMachineCurrentState;
import com.netflix.fenzo.functions.Func1;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
/**
* A balanced host attribute constraint attempts to distribute co-tasks evenly among host types, where their
* types are determined by the values of particular host attributes.
*/
public class BalancedHostAttrConstraint implements ConstraintEvaluator {
private final String name;
private final Func1<String, Set<String>> coTasksGetter;
private final String hostAttributeName;
private final int expectedValues;
/**
* Create a constraint evaluator to balance tasks across hosts based on a given host attribute. For example,
* if ten hosts have three distinct host attribute values between them of A, B, and C, when nine tasks are
* scheduled, three tasks are assigned to hosts with attribute value A, another three tasks to hosts with
* attribute B, and so on.
*
* @param coTasksGetter a one-argument function that, given a task ID being considered for assignment,
* returns the set of Task IDs of the tasks that form the group of tasks which need to
* be balanced
* @param hostAttributeName the name of the host attribute whose values need to be balanced across the
* co-tasks
* @param expectedValues the number of distinct values to expect for {@code hostAttributeName}
*/
public BalancedHostAttrConstraint(Func1<String, Set<String>> coTasksGetter, String hostAttributeName, int expectedValues) {
this.coTasksGetter = coTasksGetter;
this.hostAttributeName = hostAttributeName;
this.name = BalancedHostAttrConstraint.class.getName()+"-"+hostAttributeName;
this.expectedValues = expectedValues;
}
/**
* Returns the name of the balanced host attribute constraint, which takes the form of the name of the
* class (or subclass) followed by a dash followed by the value of {@code hostAttributeName} as it was set
* when the constraint object was created.
*
* @return the name of the balanced host attribute constraint
*/
@Override
public String getName() {
return name;
}
@Override
public Result evaluate(TaskRequest taskRequest, VirtualMachineCurrentState targetVM, TaskTrackerState taskTrackerState) {
Set<String> coTasks = coTasksGetter.call(taskRequest.getId());
String targetHostAttrVal = AttributeUtilities.getAttrValue(targetVM.getCurrAvailableResources(), hostAttributeName);
if(targetHostAttrVal==null || targetHostAttrVal.isEmpty()) {
return new Result(false, hostAttributeName + " attribute unavailable on host " + targetVM.getCurrAvailableResources().hostname());
}
Map<String, Integer> usedAttribsMap = null;
try {
usedAttribsMap = getUsedAttributesMap(coTasks, taskTrackerState);
} catch (Exception e) {
return new Result(false, e.getMessage());
}
final Integer integer = usedAttribsMap.get(targetHostAttrVal);
if(integer==null || usedAttribsMap.isEmpty())
return new Result(true, "");
int min=Integer.MAX_VALUE;
int max=Integer.MIN_VALUE;
for(Integer i: usedAttribsMap.values()) {
min = Math.min(min, i);
max = Math.max(max, i);
}
min = expectedValues>usedAttribsMap.size()? 0 : min;
if(min == max || integer<max)
return new Result(true, "");
return new Result(false, "Would further imbalance by host attribute " + hostAttributeName);
}
private Map<String, Integer> getUsedAttributesMap(Set<String> coTasks, TaskTrackerState taskTrackerState) throws Exception {
Map<String, Integer> usedAttribsMap = new HashMap<>();
for(String coTask: coTasks) {
TaskTracker.ActiveTask activeTask = taskTrackerState.getAllRunningTasks().get(coTask);
if(activeTask==null)
activeTask = taskTrackerState.getAllCurrentlyAssignedTasks().get(coTask);
if(activeTask!=null) {
String usedAttrVal = AttributeUtilities.getAttrValue(activeTask.getTotalLease(), hostAttributeName);
if(usedAttrVal==null || usedAttrVal.isEmpty())
throw new Exception(hostAttributeName+" attribute unavailable on host " + activeTask.getTotalLease().hostname() +
" running co-task " + coTask); // indicate missing attribute in host
if(usedAttribsMap.get(usedAttrVal)==null)
usedAttribsMap.put(usedAttrVal, 1);
else
usedAttribsMap.put(usedAttrVal, usedAttribsMap.get(usedAttrVal)+1);
}
}
return usedAttribsMap;
}
/**
* Converts this constraint into a "soft" constraint. By default, a balanced host attribute constraint is a
* "hard" constraint, which is to say that Fenzo will guarantee that the constraint is applied and will fail
* to place a task if the only way it can do so is to violate the constraint. This method returns a
* {@link VMTaskFitnessCalculator} that represents this constraint as a "soft" constraint that will permit
* Fenzo to place a task in violation of the constraint if it cannot do so otherwise.
*
* @return a task fitness calculator that represents the balanced host attribute constraint as a soft
* constraint
*/
public VMTaskFitnessCalculator asSoftConstraint() {
return new VMTaskFitnessCalculator() {
@Override
public String getName() {
return name;
}
@Override
public double calculateFitness(TaskRequest taskRequest, VirtualMachineCurrentState targetVM, TaskTrackerState taskTrackerState) {
String targetHostAttrVal = AttributeUtilities.getAttrValue(targetVM.getCurrAvailableResources(), hostAttributeName);
if(targetHostAttrVal==null || targetHostAttrVal.isEmpty()) {
return 0.0;
}
Set<String> coTasks = coTasksGetter.call(taskRequest.getId());
Map<String, Integer> usedAttribsMap = null;
try {
usedAttribsMap = getUsedAttributesMap(coTasks, taskTrackerState);
} catch (Exception e) {
return 0.0;
}
final Integer integer = usedAttribsMap.get(targetHostAttrVal);
if(integer==null)
return 1.0;
if(usedAttribsMap.isEmpty())
return 1.0;
double avg=0.0;
for(Integer i: usedAttribsMap.values())
avg += i;
avg = Math.ceil(avg+1 / Math.max(expectedValues, usedAttribsMap.size()));
if(integer<=avg)
return (avg-(double)integer) / avg;
return 0.0;
}
};
}
}
| 9,187 |
0 | Create_ds/Fenzo/fenzo-core/src/main/java/com/netflix/fenzo | Create_ds/Fenzo/fenzo-core/src/main/java/com/netflix/fenzo/plugins/UniqueHostAttrConstraint.java | /*
* Copyright 2015 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.fenzo.plugins;
import com.netflix.fenzo.ConstraintEvaluator;
import com.netflix.fenzo.TaskRequest;
import com.netflix.fenzo.TaskTracker;
import com.netflix.fenzo.TaskTrackerState;
import com.netflix.fenzo.VirtualMachineCurrentState;
import com.netflix.fenzo.functions.Func1;
import java.util.Set;
/**
* A unique constraint evaluator that constrains tasks according to a given host attribute. Use this evaluator
* to constrain a given set of tasks (co-tasks) by assigning them to hosts such that each task is assigned to a
* host that has a different value for the host attribute you specify.
* <p>
* For example, if you specify the host attribute {@code ZoneAttribute}, the evaluator will place the co-tasks
* such that each task is in a different zone. Note that because of this, if more tasks are submitted than there
* are zones available for them, the excess tasks will not be assigned to any hosts. If instead you want to
* implement a load balancing strategy, use {@link BalancedHostAttrConstraint} instead.
* <p>
* If you construct this evaluator without passing in a host attribute name, it will use the host name as the
* host attribute by which it uniquely identifies hosts.
*/
public class UniqueHostAttrConstraint implements ConstraintEvaluator {
private final Func1<String, Set<String>> coTasksGetter;
private final String hostAttributeName;
private final String name;
/**
* Create this constraint evaluator with the given co-tasks of a group. This is equivalent to
* {@code UniqueHostAttrConstraint(coTasksGetter, null)}.
*
* @param coTasksGetter a single-argument function that, given a task ID, returns the set of task IDs of its
* co-tasks
*/
public UniqueHostAttrConstraint(Func1<String, Set<String>> coTasksGetter) {
this(coTasksGetter, AttributeUtilities.DEFAULT_ATTRIBUTE);
}
/**
* Create this constraint evaluator with the given co-tasks of a group and a given host attribute name.
*
* @param coTasksGetter a single-argument function that, given a task ID, returns the set of task IDs of its
* co-tasks
* @param hostAttributeName the name of the host attribute whose value is to be unique for each co-task's
* host assignment. If this is {@code null}, this indicates that the host name is
* to be unique for each co-task's host assignment.
*/
public UniqueHostAttrConstraint(Func1<String, Set<String>> coTasksGetter, String hostAttributeName) {
this.coTasksGetter = coTasksGetter;
this.hostAttributeName = hostAttributeName;
this.name = UniqueHostAttrConstraint.class.getName()+"-"+hostAttributeName;
}
/**
* Returns the name of this constraint evaluator as a String in the form of the name of this class followed
* by a dash followed by the host attribute name that this evaluator uses to uniquely identify the host.
*
* @return the name of this constraint evaluator
*/
@Override
public String getName() {
return name;
}
/**
* Determines whether a particular target host is appropriate for a particular task request by rejecting any
* host that has the same value for the unique constraint attribute as another host that is already assigned
* a co-task of the specified task request.
*
* @param taskRequest describes the task being considered for assignment to the host
* @param targetVM describes the host being considered as a target for the task
* @param taskTrackerState describes the state of tasks previously assigned or already running throughout
* the system
* @return a successful Result if the target does not have the same value for its unique constraint
* attribute as another host that has already been assigned a co-task of {@code taskRequest}, or an
* unsuccessful Result otherwise
*/
@Override
public Result evaluate(TaskRequest taskRequest, VirtualMachineCurrentState targetVM, TaskTrackerState taskTrackerState) {
Set<String> coTasks = coTasksGetter.call(taskRequest.getId());
String targetHostAttrVal = AttributeUtilities.getAttrValue(targetVM.getCurrAvailableResources(), hostAttributeName);
if(targetHostAttrVal==null || targetHostAttrVal.isEmpty()) {
return new Result(false, hostAttributeName + " attribute unavailable on host " + targetVM.getCurrAvailableResources().hostname());
}
for(String coTask: coTasks) {
TaskTracker.ActiveTask activeTask = taskTrackerState.getAllRunningTasks().get(coTask);
if(activeTask==null)
activeTask = taskTrackerState.getAllCurrentlyAssignedTasks().get(coTask);
if(activeTask!=null) {
String usedAttrVal = AttributeUtilities.getAttrValue(activeTask.getTotalLease(), hostAttributeName);
if(usedAttrVal==null || usedAttrVal.isEmpty())
return new Result(false, hostAttributeName+" attribute unavailable on host " + activeTask.getTotalLease().hostname() +
" running co-task " + coTask);
if(usedAttrVal.equals(targetHostAttrVal)) {
return new Result(false, hostAttributeName+" " + targetHostAttrVal + " already used for another co-task " + coTask);
}
}
}
return new Result(true, "");
}
}
| 9,188 |
0 | Create_ds/Fenzo/fenzo-core/src/main/java/com/netflix/fenzo | Create_ds/Fenzo/fenzo-core/src/main/java/com/netflix/fenzo/plugins/ExclusiveHostConstraint.java | /*
* Copyright 2015 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.fenzo.plugins;
import com.netflix.fenzo.ConstraintEvaluator;
import com.netflix.fenzo.TaskAssignmentResult;
import com.netflix.fenzo.TaskRequest;
import com.netflix.fenzo.TaskTrackerState;
import com.netflix.fenzo.VirtualMachineCurrentState;
import java.util.Collection;
/**
* This constraint ensures that the host is exclusively assigned to the given job. You may not extend this
* class.
* <p>
* The task scheduler gives this constraint special treatment: While usually the scheduler only evaluates the
* constraints of a new task, if an already-assigned task has an {@code ExclusiveHostRestraint} then the host on
* which the task has been assigned fails this exclusive host constraint check as well.
*/
public final class ExclusiveHostConstraint implements ConstraintEvaluator {
/**
* Returns the name of this class as a String.
*
* @return the name of this class
*/
@Override
public String getName() {
return ExclusiveHostConstraint.class.getName();
}
/**
* Determines whether the prospective host already has tasks either running on it or assigned to be run on
* it, and returns a false Result if either of those things is the case.
*
* @param taskRequest describes the task to be considered for assignment to the host
* @param targetVM describes the host to be considered for accepting the task
* @param taskTrackerState describes the state of tasks assigned to or running on hosts throughout the
* system
* @return an unsuccessful Result if the target already has running tasks or assigned tasks, or a successful
* Result otherwise
*/
@Override
public Result evaluate(TaskRequest taskRequest, VirtualMachineCurrentState targetVM, TaskTrackerState taskTrackerState) {
Collection<TaskRequest> runningTasks = targetVM.getRunningTasks();
if(runningTasks!=null && !runningTasks.isEmpty())
return new Result(false, "Already has " + runningTasks.size() + " tasks running on it");
Collection<TaskAssignmentResult> tasksCurrentlyAssigned = targetVM.getTasksCurrentlyAssigned();
if(tasksCurrentlyAssigned!=null && !tasksCurrentlyAssigned.isEmpty())
return new Result(false, "Already has " + tasksCurrentlyAssigned.size() + " assigned on it");
return new Result(true, "");
}
}
| 9,189 |
0 | Create_ds/Fenzo/fenzo-core/src/main/java/com/netflix/fenzo | Create_ds/Fenzo/fenzo-core/src/main/java/com/netflix/fenzo/plugins/WeightedAverageFitnessCalculator.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.fenzo.plugins;
import java.util.List;
import com.netflix.fenzo.TaskRequest;
import com.netflix.fenzo.TaskTrackerState;
import com.netflix.fenzo.VMTaskFitnessCalculator;
import com.netflix.fenzo.VirtualMachineCurrentState;
/**
* A fitness calculator that calculates the weighted average of multiple fitness calculators.
*/
public class WeightedAverageFitnessCalculator implements VMTaskFitnessCalculator {
private final List<WeightedFitnessCalculator> calculators;
public WeightedAverageFitnessCalculator(List<WeightedFitnessCalculator> calculators) {
this.calculators = calculators;
if (calculators == null || calculators.isEmpty()) {
throw new IllegalArgumentException("There must be at least 1 calculator");
}
double sum = calculators.stream()
.map(WeightedFitnessCalculator::getWeight)
.mapToDouble(Double::doubleValue).sum();
if (sum != 1.0) {
throw new IllegalArgumentException("The sum of the weights must equal 1.0");
}
}
@Override
public String getName() {
return toString();
}
@Override
public double calculateFitness(TaskRequest taskRequest, VirtualMachineCurrentState targetVM, TaskTrackerState taskTrackerState) {
double totalWeightedScores = 0.0;
double totalWeights = 0.0;
for (WeightedFitnessCalculator calculator : calculators) {
double score = calculator.getFitnessCalculator().calculateFitness(taskRequest, targetVM, taskTrackerState);
// If any of the scores are 0.0 then the final score should be 0.0
if (score == 0.0) {
return score;
}
totalWeightedScores += (score * calculator.getWeight());
totalWeights += calculator.getWeight();
}
return totalWeightedScores / totalWeights;
}
@Override
public String toString() {
return "Weighted Average Fitness Calculator: " + calculators;
}
public static class WeightedFitnessCalculator {
private final VMTaskFitnessCalculator fitnessCalculator;
private final double weight;
public WeightedFitnessCalculator(VMTaskFitnessCalculator fitnessCalculator, double weight) {
if (fitnessCalculator == null) {
throw new IllegalArgumentException("Fitness Calculator cannot be null");
}
this.fitnessCalculator = fitnessCalculator;
this.weight = weight;
}
public VMTaskFitnessCalculator getFitnessCalculator() {
return fitnessCalculator;
}
public double getWeight() {
return weight;
}
@Override
public String toString() {
return "{ fitnessCalculator: " + fitnessCalculator.getName() + ", weight: " + weight + " }";
}
}
}
| 9,190 |
0 | Create_ds/Fenzo/fenzo-core/src/main/java/com/netflix/fenzo | Create_ds/Fenzo/fenzo-core/src/main/java/com/netflix/fenzo/samples/SampleQbasedScheduling.java | /*
* Copyright 2016 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.fenzo.samples;
import com.netflix.fenzo.*;
import com.netflix.fenzo.functions.Action0;
import com.netflix.fenzo.functions.Action1;
import com.netflix.fenzo.plugins.BinPackingFitnessCalculators;
import com.netflix.fenzo.plugins.VMLeaseObject;
import com.netflix.fenzo.queues.*;
import org.apache.mesos.MesosSchedulerDriver;
import org.apache.mesos.Protos;
import org.apache.mesos.Scheduler;
import org.apache.mesos.SchedulerDriver;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;
public class SampleQbasedScheduling {
private static class MesosScheduler implements Scheduler {
private final AtomicInteger numTasksCompleted;
private final AtomicReference<TaskSchedulingService> schedSvcGetter;
private Action1<List<Protos.Offer>> leaseAction = null;
MesosScheduler(AtomicInteger numTasksCompleted, AtomicReference<TaskSchedulingService> schedSvcGetter) {
this.numTasksCompleted = numTasksCompleted;
this.schedSvcGetter = schedSvcGetter;
}
@Override
public void registered(SchedulerDriver driver, Protos.FrameworkID frameworkId, Protos.MasterInfo masterInfo) {
System.out.println("Mesos scheduler registered");
}
@Override
public void reregistered(SchedulerDriver driver, Protos.MasterInfo masterInfo) {
System.out.println("Mesos scheduler re-registered");
}
@Override
public void resourceOffers(SchedulerDriver driver, List<Protos.Offer> offers) {
leaseAction.call(offers);
}
@Override
public void offerRescinded(SchedulerDriver driver, Protos.OfferID offerId) {
System.out.println("Unexpected offers Rescinded");
}
@Override
public void statusUpdate(SchedulerDriver driver, Protos.TaskStatus status) {
switch (status.getState()) {
case TASK_FAILED:
case TASK_LOST:
case TASK_FINISHED:
System.out.println("Task status for " + status.getTaskId().getValue() + ": " + status.getState());
schedSvcGetter.get().removeTask(status.getTaskId().getValue(),
allTasks.get(status.getTaskId().getValue()).getQAttributes(),
tasksToHostnameMap.get(status.getTaskId().getValue()));
numTasksCompleted.incrementAndGet();
}
}
@Override
public void frameworkMessage(SchedulerDriver driver, Protos.ExecutorID executorId, Protos.SlaveID slaveId, byte[] data) {
}
@Override
public void disconnected(SchedulerDriver driver) {
System.out.println("Mesos driver disconnected");
}
@Override
public void slaveLost(SchedulerDriver driver, Protos.SlaveID slaveId) {
System.out.println("Mesos agent lost");
}
@Override
public void executorLost(SchedulerDriver driver, Protos.ExecutorID executorId, Protos.SlaveID slaveId, int status) {
System.out.println("Mesos executor lost");
}
@Override
public void error(SchedulerDriver driver, String message) {
System.out.println("Unexpected mesos scheduler error: " + message);
}
}
private final static QAttributes qAttribs = new QAttributes.QAttributesAdaptor(0, "onlyBucket");
private final static ConcurrentMap<String, QueuableTask> allTasks = new ConcurrentHashMap<>();
private final static ConcurrentMap<String, String> tasksToHostnameMap = new ConcurrentHashMap<>();
/**
* This is the main method of this sample framework. It showcases how to use Fenzo queues for scheduling. It creates
* some number of tasks and launches them into Mesos using the Mesos built-in command executor. The tasks launched
* are simple sleep commands that sleep for 3 seconds each.
* @param args Requires one argument for the location of Mesos master to connect to.
* @throws Exception Upon catching any exceptions within the program.
*/
public static void main(String[] args) throws Exception {
if(args.length!=1) {
System.err.println("Must provide one argument - Mesos master location string");
System.exit(1);
}
int numTasks=10;
final AtomicInteger numTasksCompleted = new AtomicInteger();
// create Fenzo TaskScheduler object.
final TaskScheduler taskScheduler = new TaskScheduler.Builder()
.withFitnessCalculator(BinPackingFitnessCalculators.cpuMemBinPacker)
.withLeaseOfferExpirySecs(1000000)
.withLeaseRejectAction(new Action1<VirtualMachineLease>() {
@Override
public void call(VirtualMachineLease v) {
System.out.println("Unexpected to reject lease on " + v.hostname());
}
})
.build();
// Create a queue from Fenzo provided queue implementations.
final TaskQueue queue = TaskQueues.createTieredQueue(2);
// Create our Mesos scheduler callback implementation
AtomicReference<TaskSchedulingService> schedSvcGetter = new AtomicReference<>();
final MesosScheduler mesosSchedulerCallback = new MesosScheduler(numTasksCompleted, schedSvcGetter);
// create Mesos driver
Protos.FrameworkInfo framework = Protos.FrameworkInfo.newBuilder()
.setName("Sample Fenzo Framework")
.setUser("")
.build();
final MesosSchedulerDriver driver = new MesosSchedulerDriver(mesosSchedulerCallback, framework, args[0]);
// Build Fenzo task scheduling service using the TaskScheduler and TaskQueue objects created above
final AtomicInteger schedCounter = new AtomicInteger();
final TaskSchedulingService schedulingService = new TaskSchedulingService.Builder()
.withLoopIntervalMillis(1000)
.withMaxDelayMillis(1500)
.withPreSchedulingLoopHook(new Action0() {
@Override
public void call() {
System.out.println("Starting scheduling iteration " + schedCounter.incrementAndGet());
}
})
.withTaskQueue(queue)
.withTaskScheduler(taskScheduler)
// TaskSchedulingService will call us back when there are task assignments. Handle them by launching
// tasks using MesosDriver
.withSchedulingResultCallback(new Action1<SchedulingResult>() {
@Override
public void call(SchedulingResult schedulingResult) {
final List<Exception> exceptions = schedulingResult.getExceptions();
if (exceptions != null && !exceptions.isEmpty()) {
System.out.println("Exceptions from scheduling iteration:");
for (Exception e: exceptions)
e.printStackTrace();
}
else {
for (Map.Entry<String, VMAssignmentResult> e: schedulingResult.getResultMap().entrySet()) {
List<Protos.OfferID> offers = new ArrayList<Protos.OfferID>();
for (VirtualMachineLease l: e.getValue().getLeasesUsed())
offers.add(l.getOffer().getId());
List<Protos.TaskInfo> taskInfos = new ArrayList<Protos.TaskInfo>();
for (TaskAssignmentResult r: e.getValue().getTasksAssigned()) {
taskInfos.add(SampleFramework.getTaskInfo(
e.getValue().getLeasesUsed().iterator().next().getOffer().getSlaveId(),
r.getTaskId(),
"sleep 2"
));
tasksToHostnameMap.put(r.getTaskId(), r.getHostname());
}
driver.launchTasks(
offers,
taskInfos
);
}
}
}
})
.build();
schedSvcGetter.set(schedulingService);
// set up action in our scheduler callback to send resource offers into our scheduling service
mesosSchedulerCallback.leaseAction = new Action1<List<Protos.Offer>>() {
@Override
public void call(List<Protos.Offer> offers) {
List<VirtualMachineLease> leases = new ArrayList<>();
for (Protos.Offer o: offers)
leases.add(new VMLeaseObject(o)); // Fenzo lease object adapter for Mesos Offer object
schedulingService.addLeases(leases);
}
};
schedulingService.start();
// start Mesos driver
new Thread() {
@Override
public void run() {
driver.run();
}
}.start();
// submit some tasks
for (int i=0; i<numTasks; i++) {
final QueuableTask task = getTask(i);
allTasks.put(task.getId(), task);
queue.queueTask(task);
}
// wait for tasks to complete
while (numTasksCompleted.get() < numTasks) {
Thread.sleep(1000);
System.out.println(" #tasks completed: " + numTasksCompleted.get() + " of " + numTasks);
}
// verify that Fenzo has no tasks in its queue
final CountDownLatch latch = new CountDownLatch(1);
schedulingService.requestAllTasks(new Action1<Map<TaskQueue.TaskState, Collection<QueuableTask>>>() {
@Override
public void call(Map<TaskQueue.TaskState, Collection<QueuableTask>> taskStateCollectionMap) {
System.out.println("Fenzo queue has " + taskStateCollectionMap.size() + " items");
latch.countDown();
}
});
if (!latch.await(5, TimeUnit.SECONDS))
System.err.println("Timeout waiting for listing all tasks in Fenzo queues");
System.out.println("ALL DONE");
System.exit(0);
}
private static QueuableTask getTask(final int i) {
return new QueuableTask() {
@Override
public QAttributes getQAttributes() {
return qAttribs;
}
@Override
public String getId() {
return "Task-" + i;
}
@Override
public String taskGroupName() {
return "groupA";
}
@Override
public double getCPUs() {
return 1;
}
@Override
public double getMemory() {
return 100;
}
@Override
public double getNetworkMbps() {
return 0;
}
@Override
public double getDisk() {
return 0;
}
@Override
public int getPorts() {
return 0;
}
@Override
public Map<String, Double> getScalarRequests() {
return null;
}
@Override
public Map<String, NamedResourceSetRequest> getCustomNamedResources() {
return null;
}
@Override
public List<? extends ConstraintEvaluator> getHardConstraints() {
return null;
}
@Override
public List<? extends VMTaskFitnessCalculator> getSoftConstraints() {
return null;
}
@Override
public void setAssignedResources(AssignedResources assignedResources) {
// no-op, unexpected for this sample
}
@Override
public AssignedResources getAssignedResources() {
return null;
}
};
}
}
| 9,191 |
0 | Create_ds/Fenzo/fenzo-core/src/main/java/com/netflix/fenzo | Create_ds/Fenzo/fenzo-core/src/main/java/com/netflix/fenzo/samples/TaskGenerator.java | /*
* Copyright 2015 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.fenzo.samples;
import com.netflix.fenzo.ConstraintEvaluator;
import com.netflix.fenzo.TaskRequest;
import com.netflix.fenzo.VMTaskFitnessCalculator;
import com.netflix.fenzo.functions.Action1;
import com.netflix.fenzo.functions.Func1;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;
/**
* A simple task generator to use with {@link SampleFramework}.
* This is the main class to run a sample framework.
* Create and submit a given number of tasks for given number of iterations until all tasks complete.
*/
public class TaskGenerator implements Runnable {
private final BlockingQueue<TaskRequest> taskQueue;
private final int numIters;
private final int numTasks;
private final AtomicInteger tasksCompleted = new AtomicInteger();
public TaskGenerator(BlockingQueue<TaskRequest> taskQueue, int numIters, int numTasks) {
this.taskQueue = taskQueue;
this.numIters = numIters;
this.numTasks = numTasks;
}
private int launchedTasks = 0;
@Override
public void run() {
for (int i = 0; i < numIters; i++) {
for (int j = 0; j < numTasks; j++)
taskQueue.offer(getTaskRequest(launchedTasks++));
System.out.println(" Generated " + numTasks + " tasks so far");
try {
Thread.sleep(1000);
} catch (InterruptedException ie) {
}
}
}
private TaskRequest getTaskRequest(final int id) {
final String taskId = "" + id;
final AtomicReference<TaskRequest.AssignedResources> assgndResRef = new AtomicReference<>();
return new TaskRequest() {
@Override
public String getId() {
return taskId;
}
@Override
public String taskGroupName() {
return "";
}
@Override
public double getCPUs() {
return 1.0;
}
@Override
public double getMemory() {
return 1024;
}
@Override
public double getNetworkMbps() {
return 0;
}
@Override
public double getDisk() {
return 10;
}
@Override
public int getPorts() {
return 1;
}
@Override
public Map<String, Double> getScalarRequests() {
return null;
}
@Override
public List<? extends ConstraintEvaluator> getHardConstraints() {
return null;
}
@Override
public List<? extends VMTaskFitnessCalculator> getSoftConstraints() {
return null;
}
@Override
public void setAssignedResources(AssignedResources assignedResources) {
assgndResRef.set(assignedResources);
}
@Override
public AssignedResources getAssignedResources() {
return assgndResRef.get();
}
@Override
public Map<String, NamedResourceSetRequest> getCustomNamedResources() {
return Collections.emptyMap();
}
};
}
/**
* Main method to run the task generator.
* @param args Arguments to the program. Provide as the only argument, the mesos connection string.
*/
public static void main(String[] args) {
if(args.length!=1) {
System.err.println("Must provide one argument - Mesos master location string");
System.exit(1);
}
int numTasks=10;
int numIters=5;
BlockingQueue<TaskRequest> taskQueue = new LinkedBlockingQueue<>();
final TaskGenerator taskGenerator = new TaskGenerator(taskQueue, numIters, numTasks);
final SampleFramework framework = new SampleFramework(taskQueue, args[0], // mesos master location string
new Action1<String>() {
@Override
public void call(String s) {
taskGenerator.tasksCompleted.incrementAndGet();
}
},
new Func1<String, String>() {
@Override
public String call(String s) {
return "sleep 2";
}
});
long start = System.currentTimeMillis();
(new Thread(taskGenerator)).start();
new Thread(new Runnable() {
@Override
public void run() {
framework.runAll();
}
}).start();
while(taskGenerator.tasksCompleted.get() < (numIters*numTasks)) {
System.out.println("NUM TASKS COMPLETED: " + taskGenerator.tasksCompleted.get() + " of " + (numIters*numTasks));
try{Thread.sleep(1000);}catch(InterruptedException ie){}
}
System.out.println("Took " + (System.currentTimeMillis()-start) + " mS to complete " + (numIters*numTasks) + " tasks");
framework.shutdown();
System.exit(0);
}
}
| 9,192 |
0 | Create_ds/Fenzo/fenzo-core/src/main/java/com/netflix/fenzo | Create_ds/Fenzo/fenzo-core/src/main/java/com/netflix/fenzo/samples/SampleFramework.java | /*
* Copyright 2015 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.fenzo.samples;
import com.netflix.fenzo.SchedulingResult;
import com.netflix.fenzo.TaskAssignmentResult;
import com.netflix.fenzo.TaskRequest;
import com.netflix.fenzo.TaskScheduler;
import com.netflix.fenzo.VMAssignmentResult;
import com.netflix.fenzo.VirtualMachineLease;
import com.netflix.fenzo.functions.Action1;
import com.netflix.fenzo.functions.Func1;
import com.netflix.fenzo.plugins.VMLeaseObject;
import org.apache.mesos.MesosSchedulerDriver;
import org.apache.mesos.Protos;
import org.apache.mesos.Scheduler;
import org.apache.mesos.SchedulerDriver;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicReference;
/**
* A sample Mesos framework that shows a sample usage of Fenzo {@link TaskScheduler}.
*/
public class SampleFramework {
/**
* A sample mesos scheduler that shows how mesos callbacks can be setup for use with Fenzo TaskScheduler.
*/
public class MesosScheduler implements Scheduler {
/**
* When we register successfully with mesos, any previous resource offers are invalid. Tell Fenzo scheduler
* to expire all leases (aka offers) right away.
*/
@Override
public void registered(SchedulerDriver driver, Protos.FrameworkID frameworkId, Protos.MasterInfo masterInfo) {
System.out.println("Registered! ID = " + frameworkId.getValue());
scheduler.expireAllLeases();
}
/**
* Similar to {@code registered()} method, expire any previously known resource offers by asking Fenzo
* scheduler to expire all leases right away.
*/
@Override
public void reregistered(SchedulerDriver driver, Protos.MasterInfo masterInfo) {
System.out.println("Re-registered " + masterInfo.getId());
scheduler.expireAllLeases();
}
/**
* Add the received Mesos resource offers to the lease queue. Fenzo scheduler is used by calling its main
* allocation routine in a loop, see {@link SampleFramework#runAll()}. Collect offers from mesos into a queue
* so the next call to Fenzo's allocation routine can pick them up.
*/
@Override
public void resourceOffers(SchedulerDriver driver, List<Protos.Offer> offers) {
for(Protos.Offer offer: offers) {
System.out.println("Adding offer " + offer.getId() + " from host " + offer.getHostname());
leasesQueue.offer(new VMLeaseObject(offer));
}
}
/**
* Tell Fenzo scheduler that a resource offer should be expired immediately.
*/
@Override
public void offerRescinded(SchedulerDriver driver, Protos.OfferID offerId) {
scheduler.expireLease(offerId.getValue());
}
/**
* Update Fenzo scheduler of task completion if received status indicates a terminal state. There is no need
* to tell Fenzo scheduler of task started because that is supposed to have been already done before launching
* the task in Mesos.
*
* In a real world framework, this state change would also be persisted with a state machine of choice.
*/
@Override
public void statusUpdate(SchedulerDriver driver, Protos.TaskStatus status) {
System.out.println("Task Update: " + status.getTaskId().getValue() + " in state " + status.getState());
switch (status.getState()) {
case TASK_FAILED:
case TASK_LOST:
case TASK_FINISHED:
onTaskComplete.call(status.getTaskId().getValue());
scheduler.getTaskUnAssigner().call(status.getTaskId().getValue(), launchedTasks.get(status.getTaskId().getValue()));
break;
}
}
@Override
public void frameworkMessage(SchedulerDriver driver, Protos.ExecutorID executorId, Protos.SlaveID slaveId, byte[] data) {}
@Override
public void disconnected(SchedulerDriver driver) {}
/**
* Upon slave lost notification, tell Fenzo scheduler to expire all leases with the given slave ID. Note, however,
* that if there was no offer received from that slave prior to this call, Fenzo would not have a mapping from
* the slave ID to hostname (Fenzo maintains slaves state by hostname). This is OK since there would be no offers
* to expire. However, any tasks running on the lost slave will not be removed by this call to Fenzo. Task lost
* status updates would ensure that.
*/
@Override
public void slaveLost(SchedulerDriver driver, Protos.SlaveID slaveId) {
scheduler.expireAllLeasesByVMId(slaveId.getValue());
}
/**
* Do nothing, instead, rely on task lost status updates to inform Fenzo of task completions.
*/
@Override
public void executorLost(SchedulerDriver driver, Protos.ExecutorID executorId, Protos.SlaveID slaveId, int status) {
System.out.println("Executor " + executorId.getValue() + " lost, status=" + status);
}
@Override
public void error(SchedulerDriver driver, String message) {}
}
private final BlockingQueue<TaskRequest> taskQueue;
private final BlockingQueue<VirtualMachineLease> leasesQueue;
private final Map<String, String> launchedTasks;
private final TaskScheduler scheduler;
private final MesosSchedulerDriver mesosSchedulerDriver;
private final AtomicReference<MesosSchedulerDriver> ref = new AtomicReference<>();
private final Map<String, TaskRequest> pendingTasksMap = new HashMap<>();
private final Action1<String> onTaskComplete;
private final Func1<String, String> taskCmdGetter;
private final AtomicBoolean isShutdown = new AtomicBoolean(false);
/**
* Create a sample mesos framework with the given task queue and mesos master connection string. As would be typical
* for frameworks that wish to use Fenzo task scheduler, a lease queue is created for mesos scheduler callback to
* insert offers received from mesos. This sample implementation obtains the tasks to run via a task queue. The
* {@link SampleFramework#runAll()} method implements the scheduling loop that continuously takes pending tasks from
* the queue and uses Fenzo's task scheduler to assign resources to them.
*
* The task scheduler created in this sample is a rather simple one, with no advanced features.
*
* @param taskQueue The task queue.
* @param mesosMaster Connection string for mesos master.
* @param onTaskComplete A single argument action trigger to invoke upon task completion, with task ID is the argument.
* @param taskCmdGetter A single argument function to invoke to get the command line to execute for a given task ID,
* passed as the only argument.
*/
public SampleFramework(BlockingQueue<TaskRequest> taskQueue, String mesosMaster, Action1<String> onTaskComplete,
Func1<String, String> taskCmdGetter) {
this.taskQueue = taskQueue;
this.leasesQueue = new LinkedBlockingQueue<>();
this.onTaskComplete = onTaskComplete;
this.taskCmdGetter = taskCmdGetter;
launchedTasks = new HashMap<>();
scheduler = new TaskScheduler.Builder()
.withLeaseOfferExpirySecs(1000000000)
.withLeaseRejectAction(new Action1<VirtualMachineLease>() {
@Override
public void call(VirtualMachineLease lease) {
System.out.println("Declining offer on " + lease.hostname());
ref.get().declineOffer(lease.getOffer().getId());
}
})
.build();
Protos.FrameworkInfo framework = Protos.FrameworkInfo.newBuilder()
.setName("Sample Fenzo Framework")
.setUser("")
.build();
Scheduler mesosScheduler = new MesosScheduler();
mesosSchedulerDriver = new MesosSchedulerDriver(mesosScheduler, framework, mesosMaster);
ref.set(mesosSchedulerDriver);
new Thread() {
public void run() {
mesosSchedulerDriver.run();
}
}.start();
}
/**
* Shuts down the Mesos driver.
*/
public void shutdown() {
System.out.println("Stopping down mesos driver");
Protos.Status status = mesosSchedulerDriver.stop();
isShutdown.set(true);
}
public void start() {
new Thread(new Runnable() {
@Override
public void run() {
runAll();
}
}).start();
}
/**
* Run scheduling loop until shutdown is called.
* This sample implementation shows the general pattern of using Fenzo's task scheduler. Scheduling occurs in a
* continuous loop, iteratively calling {@link TaskScheduler#scheduleOnce(List, List)} method, passing in the
* list of tasks currently pending launch, and a list of any new resource offers obtained from mesos since the last
* time the lease queue was drained. The call returns an assignments result object from which any tasks assigned
* can be launched via the mesos driver. The result contains a map with hostname as the key and assignment result
* as the value. The assignment result contains the resource offers of the host that were used for the assignments
* and a list of tasks assigned resources from the host. The resource offers were removed from the internal state in
* Fenzo. However, the task assignments are not updated, yet. If the returned assignments are being used to launch
* the tasks in mesos, call Fenzo's task assigner for each task launched to indicate that the task is being launched.
* If the returned assignments are not being used, the resource offers in the assignment results must either be
* rejected in mesos, or added back into Fenzo explicitly.
*/
void runAll() {
System.out.println("Running all");
List<VirtualMachineLease> newLeases = new ArrayList<>();
while(true) {
if(isShutdown.get())
return;
newLeases.clear();
List<TaskRequest> newTaskRequests = new ArrayList<>();
System.out.println("#Pending tasks: " + pendingTasksMap.size());
TaskRequest taskRequest=null;
try {
taskRequest = pendingTasksMap.size()==0?
taskQueue.poll(5, TimeUnit.SECONDS) :
taskQueue.poll(1, TimeUnit.MILLISECONDS);
}
catch (InterruptedException ie) {
System.err.println("Error polling task queue: " + ie.getMessage());
}
if(taskRequest!=null) {
taskQueue.drainTo(newTaskRequests);
newTaskRequests.add(0, taskRequest);
for(TaskRequest request: newTaskRequests)
pendingTasksMap.put(request.getId(), request);
}
leasesQueue.drainTo(newLeases);
SchedulingResult schedulingResult = scheduler.scheduleOnce(new ArrayList<>(pendingTasksMap.values()), newLeases);
System.out.println("result=" + schedulingResult);
Map<String,VMAssignmentResult> resultMap = schedulingResult.getResultMap();
if(!resultMap.isEmpty()) {
for(VMAssignmentResult result: resultMap.values()) {
List<VirtualMachineLease> leasesUsed = result.getLeasesUsed();
List<Protos.TaskInfo> taskInfos = new ArrayList<>();
StringBuilder stringBuilder = new StringBuilder("Launching on VM " + leasesUsed.get(0).hostname() + " tasks ");
final Protos.SlaveID slaveId = leasesUsed.get(0).getOffer().getSlaveId();
for(TaskAssignmentResult t: result.getTasksAssigned()) {
stringBuilder.append(t.getTaskId()).append(", ");
taskInfos.add(getTaskInfo(slaveId, t.getTaskId(), taskCmdGetter.call(t.getTaskId())));
// unqueueTask task from pending tasks map and put into launched tasks map
// (in real world, transition the task state)
pendingTasksMap.remove(t.getTaskId());
launchedTasks.put(t.getTaskId(), leasesUsed.get(0).hostname());
scheduler.getTaskAssigner().call(t.getRequest(), leasesUsed.get(0).hostname());
}
List<Protos.OfferID> offerIDs = new ArrayList<>();
for(VirtualMachineLease l: leasesUsed)
offerIDs.add(l.getOffer().getId());
System.out.println(stringBuilder.toString());
mesosSchedulerDriver.launchTasks(offerIDs, taskInfos);
}
}
// insert a short delay before scheduling any new tasks or tasks from before that haven't been launched yet.
try{Thread.sleep(100);}catch(InterruptedException ie){}
}
}
static Protos.TaskInfo getTaskInfo(Protos.SlaveID slaveID, final String taskId, String cmd) {
Protos.TaskID pTaskId = Protos.TaskID.newBuilder()
.setValue(taskId).build();
return Protos.TaskInfo.newBuilder()
.setName("task " + pTaskId.getValue())
.setTaskId(pTaskId)
.setSlaveId(slaveID)
.addResources(Protos.Resource.newBuilder()
.setName("cpus")
.setType(Protos.Value.Type.SCALAR)
.setScalar(Protos.Value.Scalar.newBuilder().setValue(1)))
.addResources(Protos.Resource.newBuilder()
.setName("mem")
.setType(Protos.Value.Type.SCALAR)
.setScalar(Protos.Value.Scalar.newBuilder().setValue(128)))
.setCommand(Protos.CommandInfo.newBuilder().setValue(cmd).build())
.build();
}
}
| 9,193 |
0 | Create_ds/Fenzo/fenzo-core/src/main/java/com/netflix/fenzo | Create_ds/Fenzo/fenzo-core/src/main/java/com/netflix/fenzo/common/ThreadFactoryBuilder.java | package com.netflix.fenzo.common;
import java.util.Locale;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.atomic.AtomicLong;
/**
* A ThreadFactory builder based on <a href="https://github.com/google/guava">Guava's</a> ThreadFactoryBuilder.
*/
public final class ThreadFactoryBuilder {
private String nameFormat = null;
private Boolean daemon = null;
private ThreadFactoryBuilder() {
}
/**
* Creates a new {@link ThreadFactoryBuilder} builder.
*/
public static ThreadFactoryBuilder newBuilder() {
return new ThreadFactoryBuilder();
}
/**
* Sets the naming format to use when naming threads ({@link Thread#setName}) which are created
* with this ThreadFactory.
*
* @param nameFormat a {@link String#format(String, Object...)}-compatible format String, to which
* a unique integer (0, 1, etc.) will be supplied as the single parameter. This integer will
* be unique to the built instance of the ThreadFactory and will be assigned sequentially. For
* example, {@code "rpc-pool-%d"} will generate thread names like {@code "rpc-pool-0"},
* {@code "rpc-pool-1"}, {@code "rpc-pool-2"}, etc.
* @return this for the builder pattern
*/
public ThreadFactoryBuilder withNameFormat(String nameFormat) {
this.nameFormat = nameFormat;
return this;
}
/**
* Sets whether or not the created thread will be a daemon thread.
*
* @param daemon whether or not new Threads created with this ThreadFactory will be daemon threads
* @return this for the builder pattern
*/
public ThreadFactoryBuilder withDaemon(boolean daemon) {
this.daemon = daemon;
return this;
}
public ThreadFactory build() {
return build(this);
}
private static ThreadFactory build(ThreadFactoryBuilder builder) {
final String nameFormat = builder.nameFormat;
final Boolean daemon = builder.daemon;
final AtomicLong count = (nameFormat != null) ? new AtomicLong(0) : null;
return runnable -> {
Thread thread = new Thread(runnable);
if (nameFormat != null) {
thread.setName(format(nameFormat, count.getAndIncrement()));
}
if (daemon != null) {
thread.setDaemon(daemon);
}
return thread;
};
}
private static String format(String format, Object... args) {
return String.format(Locale.ROOT, format, args);
}
} | 9,194 |
0 | Create_ds/Fenzo/fenzo-core/src/main/java/com/netflix/fenzo | Create_ds/Fenzo/fenzo-core/src/main/java/com/netflix/fenzo/queues/Assignable.java | package com.netflix.fenzo.queues;
import com.netflix.fenzo.AssignmentFailure;
/**
* A wrapper object containing a task, and optionally an assignment failure for this task.
*/
public class Assignable<T> {
private final T task;
private final AssignmentFailure assignmentFailure;
private Assignable(T task, AssignmentFailure assignmentFailure) {
this.task = task;
this.assignmentFailure = assignmentFailure;
}
public T getTask() {
return task;
}
public boolean hasFailure() {
return assignmentFailure != null;
}
public AssignmentFailure getAssignmentFailure() {
return assignmentFailure;
}
public static <T> Assignable<T> success(T task) {
return new Assignable<>(task, null);
}
public static <T> Assignable<T> error(T task, AssignmentFailure assignmentFailure) {
return new Assignable<>(task, assignmentFailure);
}
}
| 9,195 |
0 | Create_ds/Fenzo/fenzo-core/src/main/java/com/netflix/fenzo | Create_ds/Fenzo/fenzo-core/src/main/java/com/netflix/fenzo/queues/TaskQueueException.java | /*
* Copyright 2016 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.fenzo.queues;
public class TaskQueueException extends Exception {
public TaskQueueException(String msg) {
super(msg);
}
public TaskQueueException(String msg, Throwable t) {
super(msg, t);
}
public TaskQueueException(Exception e) {
super(e);
}
}
| 9,196 |
0 | Create_ds/Fenzo/fenzo-core/src/main/java/com/netflix/fenzo | Create_ds/Fenzo/fenzo-core/src/main/java/com/netflix/fenzo/queues/TaskQueues.java | /*
* Copyright 2016 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.fenzo.queues;
import com.netflix.fenzo.queues.tiered.TieredQueue;
/**
* A class to create instances of various {@link TaskQueue} implementations.
*/
public class TaskQueues {
/**
* Create a tiered {@link TaskQueue} with the given number of tiers.
* @param numTiers The number of tiers.
* @return A {@link TaskQueue} implementation that supports tiered queues.
*/
public static TaskQueue createTieredQueue(int numTiers) {
return new TieredQueue(numTiers);
}
}
| 9,197 |
0 | Create_ds/Fenzo/fenzo-core/src/main/java/com/netflix/fenzo | Create_ds/Fenzo/fenzo-core/src/main/java/com/netflix/fenzo/queues/TaskQueueSla.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.fenzo.queues;
public interface TaskQueueSla {
}
| 9,198 |
0 | Create_ds/Fenzo/fenzo-core/src/main/java/com/netflix/fenzo | Create_ds/Fenzo/fenzo-core/src/main/java/com/netflix/fenzo/queues/InternalTaskQueues.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.fenzo.queues;
import com.netflix.fenzo.queues.tiered.TieredQueue;
public class InternalTaskQueues {
public static InternalTaskQueue createQueueOf(TaskQueue queue) {
if (queue instanceof TieredQueue) {
return new TieredQueue(((TieredQueue)queue).getNumTiers());
}
throw new IllegalArgumentException("Unknown queue implementation: " + queue.getClass().getName());
}
}
| 9,199 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.