package schedframe.scheduling.policy.local; import eduni.simjava.Sim_event; import eduni.simjava.Sim_system; import gridsim.Accumulator; import gridsim.ResourceCalendar; import gridsim.gssim.DCWormsTags; import gridsim.gssim.filter.ExecTaskFilter; import gssim.schedframe.scheduling.ExecTask; import gssim.schedframe.scheduling.Executable; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import org.apache.commons.lang.ArrayUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.joda.time.DateTime; import org.joda.time.DateTimeUtilsExt; import org.qcg.broker.schemas.schedulingplan.types.AllocationStatus; import qcg.shared.constants.BrokerConstants; import schedframe.ResourceController; import schedframe.events.scheduling.SchedulingEvent; import schedframe.events.scheduling.SchedulingEventType; import schedframe.events.scheduling.StartTaskExecutionEvent; import schedframe.events.scheduling.TaskFinishedEvent; import schedframe.events.scheduling.TaskRequestedTimeExpiredEvent; import schedframe.exceptions.ResourceException; import schedframe.resources.computing.ComputingResource; import schedframe.resources.computing.profiles.energy.EnergyEvent; import schedframe.resources.computing.profiles.energy.EnergyEventType; import schedframe.resources.units.PEUnit; import schedframe.resources.units.ProcessingElements; import schedframe.resources.units.ResourceUnit; import schedframe.resources.units.ResourceUnitName; import schedframe.resources.units.StandardResourceUnitName; import schedframe.scheduling.ResourceHistoryItem; import schedframe.scheduling.Scheduler; import schedframe.scheduling.TaskListImpl; import schedframe.scheduling.UsedResourceList; import schedframe.scheduling.WorkloadUnitHandler; import schedframe.scheduling.manager.resources.LocalResourceManager; import schedframe.scheduling.manager.resources.ManagedResources; import schedframe.scheduling.manager.resources.ResourceManager; import schedframe.scheduling.plan.AllocationInterface; import schedframe.scheduling.plan.ScheduledTaskInterface; import schedframe.scheduling.plan.SchedulingPlanInterface; import schedframe.scheduling.plugin.SchedulingPlugin; import schedframe.scheduling.plugin.estimation.ExecutionTimeEstimationPlugin; import schedframe.scheduling.plugin.grid.ModuleListImpl; import schedframe.scheduling.plugin.grid.ModuleType; import schedframe.scheduling.policy.AbstractManagementSystem; import schedframe.scheduling.queue.TaskQueueList; import schedframe.scheduling.tasks.AbstractProcesses; import schedframe.scheduling.tasks.Job; import schedframe.scheduling.tasks.JobInterface; import schedframe.scheduling.tasks.Task; import schedframe.scheduling.tasks.TaskInterface; import schedframe.scheduling.tasks.WorkloadUnit; import simulator.DCWormsConstants; import simulator.utils.DoubleMath; public class LocalManagementSystem extends AbstractManagementSystem { private Log log = LogFactory.getLog(LocalManagementSystem.class); protected double lastUpdateTime; protected Accumulator accTotalLoad; public LocalManagementSystem(String providerId, String entityName, SchedulingPlugin schedPlugin, ExecutionTimeEstimationPlugin execTimeEstimationPlugin, TaskQueueList queues) throws Exception { super(providerId, entityName, execTimeEstimationPlugin, queues); //schedulingPlugin = (LocalSchedulingPlugin) InstanceFactory.createInstance(schedulingPluginClassName, LocalSchedulingPlugin.class); if (schedPlugin == null) { throw new Exception("Can not create local scheduling plugin instance."); } this.schedulingPlugin = schedPlugin; accTotalLoad = new Accumulator(); moduleList = new ModuleListImpl(1); } public void init(Scheduler sched, ManagedResources managedResources) { super.init(sched, managedResources); //scheduler = sched; //resourceManager = ResourceManagerFactory.createResourceManager(scheduler); double load = 0; accTotalLoad.add(load); } public void processEvent(Sim_event ev) { updateProcessingProgress(); int tag = ev.get_tag(); Object obj; switch (tag) { case DCWormsTags.TIMER: if (pluginSupportsEvent(tag)) { SchedulingEvent event = new SchedulingEvent(SchedulingEventType.TIMER); SchedulingPlanInterface decision = schedulingPlugin.schedule(event, queues, getJobRegistry(), getResourceManager(), moduleList); executeSchedulingPlan(decision); } sendTimerEvent(); break; case DCWormsTags.TASK_READY_FOR_EXECUTION: ExecTask data = (ExecTask) ev.get_data(); try { data.setStatus(DCWormsTags.READY); if (pluginSupportsEvent(tag)) { SchedulingEvent event = new StartTaskExecutionEvent(data.getJobId(), data.getId()); SchedulingPlanInterface decision = schedulingPlugin.schedule(event, queues, getJobRegistry(), getResourceManager(), moduleList); executeSchedulingPlan(decision); } } catch (Exception e) { e.printStackTrace(); } break; case DCWormsTags.TASK_EXECUTION_FINISHED: obj = ev.get_data(); ExecTask exec = (ExecTask) obj; if (exec.getStatus() == DCWormsTags.INEXEC) { finalizeExecutable(exec); sendFinishedWorkloadUnit(exec); //task.setGridletStatus(Gridlet.SUCCESS); //task.finalizeGridlet(); log.debug(exec.getJobId() + "_" + exec.getId() + " finished execution on " + new DateTime()); log.info(DCWormsConstants.USAGE_MEASURE_NAME + ": " + calculateTotalLoad(jobRegistry.getRunningTasks().size())); /*UsedResourceList lastUsedList = task.getUsedResources(); Map lastUsed = lastUsedList.getLast() .getResourceUnits(); getAllocationManager().freeResources(lastUsed); ProcessingElements pes = (ProcessingElements) lastUsed.get(StandardResourceUnitName.PROCESSINGELEMENTS); for (ComputingResource resource : pes) { resource.handleEvent(new EnergyEvent(EnergyEventType.TASK_FINISHED, task)); } SubTaskFilter filter = new SubTaskFilter(task.getGridletID(), GssimTags.TASK_REQUESTED_TIME_EXPIRED); scheduler.sim_cancel(filter, null); super.sendFinishJob((Executable) task.getGridlet());*/ } if (pluginSupportsEvent(tag)) { SchedulingEvent event = new TaskFinishedEvent(exec.getJobId(), exec.getId()); SchedulingPlanInterface decision = schedulingPlugin.schedule(event, queues, getJobRegistry(), getResourceManager(), moduleList); executeSchedulingPlan(decision); } Job job = jobRegistry.getJob(exec.getJobId()); if(!job.isFinished()){ getWorkloadUnitHandler().handleJob(job); } break; case DCWormsTags.TASK_REQUESTED_TIME_EXPIRED: obj = ev.get_data(); exec = (Executable) obj; if (pluginSupportsEvent(tag)) { SchedulingEvent event = new TaskRequestedTimeExpiredEvent(exec.getJobId(), exec.getId()); SchedulingPlanInterface decision = schedulingPlugin.schedule(event, queues, getJobRegistry(), getResourceManager(), moduleList); executeSchedulingPlan(decision); } break; case DCWormsTags.UPDATE: updateProcessingTimes(ev); break; } } public void notifyReturnedWorkloadUnit(WorkloadUnit wu) { if (pluginSupportsEvent(DCWormsTags.TASK_EXECUTION_FINISHED)) { SchedulingEvent event = new SchedulingEvent(SchedulingEventType.TASK_FINISHED); SchedulingPlanInterface decision = schedulingPlugin.schedule(event, queues, getJobRegistry(), getResourceManager(), moduleList); executeSchedulingPlan(decision); } //if(scheduler.getParent() != null){ sendFinishedWorkloadUnit(wu); //} } protected void executeSchedulingPlan(SchedulingPlanInterface decision) { ArrayList> taskSchedulingDecisions = decision.getTasks(); for (int i = 0; i < taskSchedulingDecisions.size(); i++) { ScheduledTaskInterface taskDecision = taskSchedulingDecisions.get(i); if (taskDecision.getStatus() == AllocationStatus.REJECTED) { continue; } ArrayList> allocations = taskDecision.getAllocations(); TaskInterface task = taskDecision.getTask(); for (int j = 0; j < allocations.size(); j++) { AllocationInterface allocation = allocations.get(j); if (allocation.isProcessing()) { ExecTask exec = (ExecTask) task; executeTask(exec, allocation.getRequestedResources()); } else if(resourceManager.getSchedulerName(allocation.getProviderName()) != null){ allocation.setProviderName(resourceManager.getSchedulerName(allocation.getProviderName())); submitTask(task, allocation); } else { ExecTask exec = (ExecTask) task; executeTask(exec, chooseResourcesForExecution(allocation.getProviderName(), (ExecTask)task)); } } } } protected void executeTask(ExecTask task, Map choosenResources) { Executable exec = (Executable)task; boolean allocationStatus = getAllocationManager().allocateResources(choosenResources); if(allocationStatus == false) return; removeFromQueue(task); //double completionPercentage = (submittedTask.getLength() - submittedTask.getRemainingGridletLength())/submittedTask.getLength(); SchedulingEvent event = new SchedulingEvent(SchedulingEventType.START_TASK_EXECUTION); int time = Double.valueOf( execTimeEstimationPlugin.execTimeEstimation(event, task, choosenResources, exec.getCompletionPercentage())).intValue(); log.debug(task.getJobId() + "_" + task.getId() + " starts executing on " + new DateTime() + " will finish after " + time); if (time < 0.0) return; exec.setEstimatedDuration(time); DateTime currentTime = new DateTime(); ResourceHistoryItem resHistItem = new ResourceHistoryItem(choosenResources, currentTime); exec.addUsedResources(resHistItem); scheduler.sendInternal(time, DCWormsTags.TASK_EXECUTION_FINISHED, exec); try { long expectedDuration = exec.getExpectedDuration().getMillis() / 1000; scheduler.sendInternal(expectedDuration, DCWormsTags.TASK_REQUESTED_TIME_EXPIRED, exec); } catch (NoSuchFieldException e) { double t = exec.getEstimatedDuration(); scheduler.sendInternal(t, DCWormsTags.TASK_REQUESTED_TIME_EXPIRED, exec); } try { exec.setStatus(DCWormsTags.INEXEC); } catch (Exception e1) { // TODO Auto-generated catch block e1.printStackTrace(); } log.info(DCWormsConstants.USAGE_MEASURE_NAME + ": " + calculateTotalLoad(jobRegistry.getRunningTasks().size())); PEUnit peUnit = (PEUnit)choosenResources.get(StandardResourceUnitName.PE); if(peUnit instanceof ProcessingElements){ ProcessingElements pes = (ProcessingElements) peUnit; for (ComputingResource resource : pes) { resource.handleEvent(new EnergyEvent(EnergyEventType.TASK_FINISHED, exec)); } } else { ComputingResource resource = null; try { resource = ResourceController.getComputingResourceByName(peUnit.getResourceId()); } catch (ResourceException e) { } resource.handleEvent(new EnergyEvent(EnergyEventType.TASK_FINISHED, exec)); } /*ProcessingElements pes = (ProcessingElements) choosenResources.get(StandardResourceUnitName.PE); for (ComputingResource resource : pes) { resource.handleEvent(new EnergyEvent(EnergyEventType.TASK_STARTED, submittedTask)); }*/ /*for(ExecTaskInterface etask : jobRegistry.getRunningTasks()){ System.out.println(etask.getJobId()); for(String taskId: etask.getVisitedResources()) System.out.println("====="+taskId); }*/ } public void finalizeExecutable(ExecTask execTask){ Executable exec = (Executable)execTask; try { exec.setStatus(DCWormsTags.SUCCESS); } catch (Exception e1) { // TODO Auto-generated catch block e1.printStackTrace(); } exec.finalizeExecutable(); UsedResourceList lastUsedList = exec.getUsedResources(); Map lastUsed = lastUsedList.getLast() .getResourceUnits(); getAllocationManager().freeResources(lastUsed); PEUnit peUnit = (PEUnit)lastUsed.get(StandardResourceUnitName.PE); if(peUnit instanceof ProcessingElements){ ProcessingElements pes = (ProcessingElements) peUnit; for (ComputingResource resource : pes) { resource.handleEvent(new EnergyEvent(EnergyEventType.TASK_FINISHED, exec)); } } else { ComputingResource resource = null; try { resource = ResourceController.getComputingResourceByName(peUnit.getResourceId()); } catch (ResourceException e) { } resource.handleEvent(new EnergyEvent(EnergyEventType.TASK_FINISHED, exec)); } /*ProcessingElements pes = (ProcessingElements) lastUsed.get(StandardResourceUnitName.PE); for (ComputingResource resource : pes) { resource.handleEvent(new EnergyEvent(EnergyEventType.TASK_FINISHED, subTask)); }*/ ExecTaskFilter filter = new ExecTaskFilter(exec.getUniqueId(), DCWormsTags.TASK_REQUESTED_TIME_EXPIRED); scheduler.sim_cancel(filter, null); Job job = jobRegistry.getJob(exec.getJobId()); Task task = null; try { task = job.getTask(exec.getTaskId()); } catch (NoSuchFieldException e) { e.printStackTrace(); } if(exec.getProcessesId() == null){ try { task.setStatus(exec.getStatus()); } catch (Exception e) { e.printStackTrace(); } } else { List processesList = task.getProcesses(); for(int i = 0; i < processesList.size(); i++){ AbstractProcesses processes = processesList.get(i); if(processes.getId().equals(exec.getProcessesId())){ processes.setStatus(exec.getStatus()); break; } } } //sendFinishedWorkloadUnit(executable); } protected void updateProcessingProgress() { double timeSpan = DoubleMath.subtract(Sim_system.clock(), lastUpdateTime); if (timeSpan <= 0.0) { // don't update when nothing changed return; } lastUpdateTime = Sim_system.clock(); Iterator iter = jobRegistry.getRunningTasks().iterator(); while (iter.hasNext()) { ExecTask task = iter.next(); Executable exec = (Executable)task; UsedResourceList usedResourcesList = exec.getUsedResources(); ResourceUnit unit = usedResourcesList.getLast().getResourceUnits() .get(StandardResourceUnitName.PE); double load = getMIShare(timeSpan, (PEUnit) unit); exec.setCompletionPercentage(100 * timeSpan/exec.getEstimatedDuration()); addTotalLoad(load); } } private double getMIShare(double timeSpan, PEUnit pes) { double localLoad; ResourceCalendar resCalendar = (ResourceCalendar) moduleList.getModule(ModuleType.RESOURCE_CALENDAR); if (resCalendar == null) localLoad = 0; else // 1 - localLoad_ = available MI share percentage localLoad = resCalendar.getCurrentLoad(); int speed = pes.getSpeed(); int cnt = pes.getAmount(); double totalMI = speed * cnt * timeSpan * (1 - localLoad); return totalMI; } protected void updateProcessingTimes(Sim_event ev) { updateProcessingProgress(); for (ExecTask task : jobRegistry.getRunningTasks()) { Executable exec = (Executable)task; List visitedResource = exec.getVisitedResources(); String originResource = ev.get_data().toString(); if(!ArrayUtils.contains(visitedResource.toArray(new String[visitedResource.size()]), originResource)){ continue; } Map choosenResources = exec.getUsedResources().getLast().getResourceUnits(); //double completionPercentage = (task.getLength() - subTask.getRemainingGridletLength())/task.getLength(); double time = execTimeEstimationPlugin.execTimeEstimation(new SchedulingEvent(SchedulingEventType.RESOURCE_STATE_CHANGED), task, choosenResources, exec.getCompletionPercentage()); /*if(!subTask.getVisitedResources().contains(ev.get_data().toString())) { continue; }*/ //check if the new estimated end time is equal to the previous one; if yes the continue without update if( DoubleMath.subtract((exec.getExecStartTime() + exec.getEstimatedDuration()), (new DateTime().getMillis()/1000 + time)) == 0.0){ continue; } ExecTaskFilter filter = new ExecTaskFilter(exec.getUniqueId(), DCWormsTags.TASK_EXECUTION_FINISHED); scheduler.sim_cancel(filter, null); scheduler.sendInternal(time, DCWormsTags.TASK_EXECUTION_FINISHED, task); } } public double calculateTotalLoad(int size) { // background load, defined during initialization double load; ResourceCalendar resCalendar = (ResourceCalendar) moduleList.getModule(ModuleType.RESOURCE_CALENDAR); if (resCalendar == null) load = 0; else load = resCalendar.getCurrentLoad(); int numberOfPE = 0; try { for(ResourceUnit resUnit : getResourceManager().getPE()){ numberOfPE = numberOfPE + resUnit.getAmount(); } //numberOfPE = getResourceManager().getPE().size(); } catch (Exception e) { numberOfPE = 1; } double tasksPerPE = (double) size / numberOfPE; load += Math.min(1.0 - load, tasksPerPE); return load; } public Accumulator getTotalLoad() { return accTotalLoad; } protected void addTotalLoad(double load) { accTotalLoad.add(load); } private Map chooseResourcesForExecution(String resourceName, ExecTask task) { ResourceManager resourceManager = this.resourceManager; if(resourceName != null){ ComputingResource resource = null; try { resource = resourceManager.getResourceByName(resourceName); } catch (ResourceException e) { return null; } resourceManager = new LocalResourceManager(resource); } Map map = new HashMap(); int cpuRequest; try { cpuRequest = Double.valueOf(task.getCpuCntRequest()).intValue(); } catch (NoSuchFieldException e) { cpuRequest = 1; } //PEUnit processingUnits = null; if (cpuRequest != 0) { List availableUnits = null; try { availableUnits = getResourceManager().getPE(); } catch (ResourceException e) { return null; } List choosenPEUnits = new ArrayList(); for (int i = 0; i < availableUnits.size() && cpuRequest > 0; i++) { PEUnit peUnit = (PEUnit) availableUnits .get(i); if(peUnit.getFreeAmount() > 0){ int allocPE = Math.min(peUnit.getFreeAmount(), cpuRequest); cpuRequest = cpuRequest - allocPE; choosenPEUnits.add(peUnit.replicate(allocPE)); } } if(cpuRequest > 0){ return null; } map.put(StandardResourceUnitName.PE, choosenPEUnits.get(0)); } return map; } public void notifySubmittedWorkloadUnit(WorkloadUnit wu, boolean ack) { updateProcessingProgress(); registerWorkloadUnit(wu); } private void registerWorkloadUnit(WorkloadUnit wu){ if(!wu.isRegistered()){ wu.register(jobRegistry); } wu.accept(getWorkloadUnitHandler()); } class LocalWorkloadUnitHandler implements WorkloadUnitHandler{ public void handleJob(Job job){ if (log.isInfoEnabled()) log.info("Received job " + job.getId() + " at " + new DateTime(DateTimeUtilsExt.currentTimeMillis())); List> jobsList = new ArrayList>(); jobsList.add(job); TaskListImpl readyTasks = new TaskListImpl(); for(Task task: jobRegistry.getAvailableTasks(jobsList)){ task.setStatus((int)BrokerConstants.TASK_STATUS_QUEUED); readyTasks.add(task); } for(WorkloadUnit e:readyTasks){ registerWorkloadUnit(e); } } public void handleTask(TaskInterface ti){ Task task = (Task)ti; List processes = task.getProcesses(); if(processes == null || processes.size() == 0){ Executable exec = new Executable(task); registerWorkloadUnit(exec); } else { for(int j = 0; j < processes.size(); j++){ AbstractProcesses procesesSet = processes.get(j); Executable exec = new Executable(task, procesesSet); registerWorkloadUnit(exec); } } } public void handleExecutable(ExecTask task){ Executable exec = (Executable) task; // int cost = // this.resourceManager.getResourceCharacteristic().getResUnits() != // null ? // this.resourceManager.getResourceCharacteristic().getResUnits().get(ResourceParameterName.COST).getAmount() // : 1; exec.visitResource(scheduler.get_name()); Scheduler parentScheduler = scheduler.getParent(); while (parentScheduler != null && !exec.getVisitedResources().contains(parentScheduler.get_name())) { exec.visitResource(parentScheduler.get_name()); parentScheduler = parentScheduler.getParent(); } exec.setSchedulerName(scheduler.get_id()); jobRegistry.addExecTask(exec); TaskListImpl newTasks = new TaskListImpl(); newTasks.add(exec); schedulingPlugin.placeTasksInQueues(newTasks, queues, getResourceManager(), moduleList); if (exec.getStatus() == DCWormsTags.QUEUED) { sendExecutableReadyEvent(exec); } } } public WorkloadUnitHandler getWorkloadUnitHandler() { return new LocalWorkloadUnitHandler(); } public LocalResourceManager getResourceManager() { if (resourceManager instanceof ResourceManager) return (LocalResourceManager) resourceManager; else return null; } }