source: DCWoRMS/branches/coolemall/src/schedframe/scheduling/policy/local/LocalManagementSystem.java @ 1362

Revision 1362, 26.6 KB checked in by wojtekp, 11 years ago (diff)
  • Property svn:mime-type set to text/plain
Line 
1package schedframe.scheduling.policy.local;
2
3import java.util.ArrayList;
4import java.util.HashMap;
5import java.util.Iterator;
6import java.util.LinkedList;
7import java.util.List;
8import java.util.Map;
9import java.util.Set;
10
11import org.apache.commons.logging.Log;
12import org.apache.commons.logging.LogFactory;
13import org.joda.time.DateTime;
14import org.joda.time.DateTimeUtilsExt;
15import org.qcg.broker.schemas.schedulingplan.types.AllocationStatus;
16
17import qcg.shared.constants.BrokerConstants;
18import schedframe.SimulatedEnvironment;
19import schedframe.events.scheduling.SchedulingEvent;
20import schedframe.events.scheduling.SchedulingEventType;
21import schedframe.events.scheduling.StartTaskExecutionEvent;
22import schedframe.events.scheduling.TaskFinishedEvent;
23import schedframe.events.scheduling.TaskRequestedTimeExpiredEvent;
24import schedframe.exceptions.ResourceException;
25import schedframe.resources.StandardResourceType;
26import schedframe.resources.computing.ComputingResource;
27import schedframe.resources.computing.profiles.energy.EnergyEvent;
28import schedframe.resources.computing.profiles.energy.EnergyEventType;
29import schedframe.resources.units.PEUnit;
30import schedframe.resources.units.ProcessingElements;
31import schedframe.resources.units.ResourceUnit;
32import schedframe.resources.units.ResourceUnitName;
33import schedframe.resources.units.StandardResourceUnitName;
34import schedframe.scheduling.ExecutionHistoryItem;
35import schedframe.scheduling.ResourceHistoryItem;
36import schedframe.scheduling.Scheduler;
37import schedframe.scheduling.TaskList;
38import schedframe.scheduling.TaskListImpl;
39import schedframe.scheduling.WorkloadUnitHandler;
40import schedframe.scheduling.manager.resources.LocalResourceManager;
41import schedframe.scheduling.manager.resources.ManagedResources;
42import schedframe.scheduling.manager.resources.ResourceManager;
43import schedframe.scheduling.plan.AllocationInterface;
44import schedframe.scheduling.plan.ScheduledTaskInterface;
45import schedframe.scheduling.plan.SchedulingPlanInterface;
46import schedframe.scheduling.plugin.SchedulingPlugin;
47import schedframe.scheduling.plugin.estimation.ExecutionTimeEstimationPlugin;
48import schedframe.scheduling.plugin.grid.ModuleListImpl;
49import schedframe.scheduling.policy.AbstractManagementSystem;
50import schedframe.scheduling.queue.TaskQueueList;
51import schedframe.scheduling.tasks.AbstractProcesses;
52import schedframe.scheduling.tasks.Job;
53import schedframe.scheduling.tasks.JobInterface;
54import schedframe.scheduling.tasks.Task;
55import schedframe.scheduling.tasks.TaskInterface;
56import schedframe.scheduling.tasks.WorkloadUnit;
57import simulator.DCWormsConstants;
58import simulator.stats.GSSAccumulator;
59import simulator.utils.DoubleMath;
60import dcworms.schedframe.scheduling.ExecTask;
61import dcworms.schedframe.scheduling.Executable;
62import eduni.simjava.Sim_event;
63import eduni.simjava.Sim_system;
64import gridsim.dcworms.DCWormsTags;
65import gridsim.dcworms.filter.ExecTaskFilter;
66
67public class LocalManagementSystem extends AbstractManagementSystem {
68
69        private Log log = LogFactory.getLog(LocalManagementSystem.class);
70
71        protected double lastUpdateTime;
72
73        public LocalManagementSystem(String providerId, String entityName, SchedulingPlugin schedPlugin,
74                        ExecutionTimeEstimationPlugin execTimeEstimationPlugin, TaskQueueList queues)
75                        throws Exception {
76
77                super(providerId, entityName, execTimeEstimationPlugin, queues);
78               
79                if (schedPlugin == null) {
80                        throw new Exception("Can not create local scheduling plugin instance.");
81                }
82                this.schedulingPlugin =  schedPlugin;
83                this.moduleList = new ModuleListImpl(1);
84        }
85
86        public void init(Scheduler sched, ManagedResources managedResources) {
87                super.init(sched, managedResources);
88        }
89
90        public void processEvent(Sim_event ev) {
91
92                updateProcessingProgress();
93
94                int tag = ev.get_tag();
95
96                switch (tag) {
97
98                case DCWormsTags.TIMER:
99                        if (pluginSupportsEvent(tag)) {
100                                SchedulingEvent event = new SchedulingEvent(SchedulingEventType.TIMER);
101                                SchedulingPlanInterface<?> decision =  schedulingPlugin.schedule(event,
102                                                queues,  getJobRegistry(), getResourceManager(), moduleList);
103                                executeSchedulingPlan(decision);
104                        }
105                        sendTimerEvent();
106                        break;
107
108                case DCWormsTags.TASK_READY_FOR_EXECUTION:
109                        ExecTask execTask = (ExecTask) ev.get_data();
110                        try {
111                                execTask.setStatus(DCWormsTags.READY);
112                                if (pluginSupportsEvent(tag)) {
113                                        SchedulingEvent event = new StartTaskExecutionEvent(execTask.getJobId(), execTask.getId());
114                                        SchedulingPlanInterface<?> decision =  schedulingPlugin.schedule(event,
115                                                        queues,  getJobRegistry(), getResourceManager(), moduleList);
116                                        executeSchedulingPlan(decision);
117                                }
118                        } catch (Exception e) {
119                                e.printStackTrace();
120                        }
121                        break;
122
123                case DCWormsTags.TASK_EXECUTION_FINISHED:
124                        execTask = (ExecTask) ev.get_data();
125                        if (execTask.getStatus() == DCWormsTags.INEXEC) {
126                               
127                                finalizeExecutable(execTask);
128                                sendFinishedWorkloadUnit(execTask);
129                                if (pluginSupportsEvent(tag)) {
130                                        SchedulingEvent event = new TaskFinishedEvent(execTask.getJobId(), execTask.getId());
131                                        SchedulingPlanInterface<?> decision = schedulingPlugin.schedule(event,
132                                                        queues, getJobRegistry(), getResourceManager(), moduleList);
133                                        executeSchedulingPlan(decision);
134                                }
135                        }
136
137                        Job job = jobRegistry.getJob(execTask.getJobId());
138                        if(!job.isFinished()){
139                                getWorkloadUnitHandler().handleJob(job);
140                        }
141                        //SUPPORTS PRECEDING CONSTRAINST COMING BOTH FROM SWF FILES
142                        /*else {
143                                try {
144                                        job.setStatus((int)BrokerConstants.JOB_STATUS_FINISHED);
145                                } catch (Exception e) {
146
147                                }
148                                for(JobInterface<?> j: jobRegistry.getJobs((int)BrokerConstants.JOB_STATUS_SUBMITTED)){
149                                        getWorkloadUnitHandler().handleJob(j); 
150                                }
151                        }*/
152                        break;
153                       
154                case DCWormsTags.TASK_REQUESTED_TIME_EXPIRED:
155                        execTask = (Executable) ev.get_data();
156                        if (pluginSupportsEvent(tag)) {
157                                SchedulingEvent event = new TaskRequestedTimeExpiredEvent(execTask.getJobId(), execTask.getId());
158                                SchedulingPlanInterface<?> decision = schedulingPlugin.schedule(event,
159                                                queues, getJobRegistry(), getResourceManager(), moduleList);
160                                executeSchedulingPlan(decision);
161                        }
162                        break;
163                       
164                case DCWormsTags.TASK_PAUSE:{
165                        String[] ids = (String[]) ev.get_data();
166                        execTask = jobRegistry.getTask(ids[0], ids[1]);
167                        taskPause(execTask);
168                        if (pluginSupportsEvent(tag)) {
169                                SchedulingEvent event = new SchedulingEvent(SchedulingEventType.TASK_PAUSED);
170                                SchedulingPlanInterface<?> decision = schedulingPlugin.schedule(event,
171                                                queues, getJobRegistry(), getResourceManager(), moduleList);
172                                executeSchedulingPlan(decision);
173                        }
174                }
175                break;
176               
177                case DCWormsTags.TASK_RESUME:{
178                        String[] ids = (String[]) ev.get_data();
179                        execTask = jobRegistry.getTask(ids[0], ids[1]);
180                        taskResume(execTask, execTask.getAllocatedResources().getLast().getResourceUnits());
181                        if (pluginSupportsEvent(tag)) {
182                                SchedulingEvent event = new StartTaskExecutionEvent(ids[0], ids[1]);
183                                SchedulingPlanInterface<?> decision = schedulingPlugin.schedule(event,
184                                                queues, getJobRegistry(), getResourceManager(), moduleList);
185                                executeSchedulingPlan(decision);
186                        }
187                }
188                break;
189                       
190                case DCWormsTags.TASK_MOVE:{
191                        Object[] data = (Object[]) ev.get_data();
192                        execTask = jobRegistry.getTask((String)data[0], (String)data[1]);
193                        taskMove(execTask, (Map<ResourceUnitName, ResourceUnit>)data[2]);
194                        if (pluginSupportsEvent(tag)) {
195                                SchedulingEvent event = new StartTaskExecutionEvent((String)data[0], (String)data[1]);
196                                SchedulingPlanInterface<?> decision = schedulingPlugin.schedule(event,
197                                                queues, getJobRegistry(), getResourceManager(), moduleList);
198                                executeSchedulingPlan(decision);
199                        }
200                }
201                break;
202                       
203                case DCWormsTags.TASK_EXECUTION_CHANGED:
204                        execTask = (ExecTask) ev.get_data();
205                        updateTaskExecutionPhase(execTask, SchedulingEventType.RESOURCE_STATE_CHANGED);
206                        break;
207
208                case DCWormsTags.UPDATE_PROCESSING:
209                        updateProcessingTimes();
210                        break;
211                       
212                case DCWormsTags.POWER_LIMIT_EXCEEDED:
213                        if (pluginSupportsEvent(tag)) {
214                                SchedulingEvent event = new SchedulingEvent(SchedulingEventType.POWER_LIMIT_EXCEEDED);
215                                SchedulingPlanInterface<?> decision = schedulingPlugin.schedule(event,
216                                                queues,  getJobRegistry(), getResourceManager(), moduleList);
217                                executeSchedulingPlan(decision);
218                        }
219                        break;
220                }
221        }
222
223
224        public void taskPause(ExecTask execTask) {
225                if (execTask == null) {
226                        return;
227                } else {
228                        try {
229                                execTask.setStatus(DCWormsTags.PAUSED);
230                               
231                                Executable exec = (Executable) execTask;
232                                Map<ResourceUnitName, ResourceUnit> lastUsed = exec.getAllocatedResources().getLast().getResourceUnits();
233                                getAllocationManager().freeResources(lastUsed);
234                               
235                                saveExecutionHistory(exec, exec.getCompletionPercentage(), exec.getEstimatedDuration());
236                               
237                                ExecTaskFilter filter = new ExecTaskFilter(exec.getUniqueId(), -1);
238                                scheduler.sim_cancel(filter, null);
239                               
240                                PEUnit peUnit = (PEUnit)lastUsed.get(StandardResourceUnitName.PE);
241                                updateComputingResources(peUnit, EnergyEventType.TASK_FINISHED, exec);
242                        } catch (Exception e) {
243                                // TODO Auto-generated catch block
244                                e.printStackTrace();
245                        }
246                }               
247        }
248       
249        public void taskResume(ExecTask execTask, Map<ResourceUnitName, ResourceUnit> resources) {
250                if (execTask == null) {
251                        return;
252                } else if (execTask.getStatus() == DCWormsTags.PAUSED) {
253                        try {
254                                execTask.setStatus(DCWormsTags.RESUMED);
255                                Executable exec = (Executable) execTask;
256
257                                boolean status = allocateResources(exec, resources);
258                                if(status == false){
259                                        TaskList newTasks = new TaskListImpl();
260                                        newTasks.add(exec);
261                                        schedulingPlugin.placeTasksInQueues(newTasks, queues, getResourceManager(), moduleList);
262                                        exec.setStatus(DCWormsTags.READY);
263                                } else {
264                                        runTask(execTask);
265                                       
266                                        PEUnit peUnit = (PEUnit)resources.get(StandardResourceUnitName.PE);
267                                        updateComputingResources(peUnit, EnergyEventType.TASK_STARTED, exec);
268                                }
269
270                        } catch (Exception e) {
271                                // TODO Auto-generated catch block
272                                e.printStackTrace();
273                        }
274                }                       
275        }
276       
277        public void taskMove(ExecTask execTask, Map<ResourceUnitName, ResourceUnit> map) {
278                taskPause(execTask);
279                taskResume(execTask, map);
280        }
281       
282        public void notifyReturnedWorkloadUnit(WorkloadUnit wu) {
283                if (pluginSupportsEvent(DCWormsTags.TASK_EXECUTION_FINISHED)) {
284                        SchedulingEvent event = new SchedulingEvent(SchedulingEventType.TASK_FINISHED);
285                        SchedulingPlanInterface<?> decision =  schedulingPlugin.schedule(event,
286                                        queues, getJobRegistry(), getResourceManager(), moduleList);
287                        executeSchedulingPlan(decision);
288                }
289                //if(scheduler.getParent() != null){
290                        sendFinishedWorkloadUnit(wu);
291                //}
292        }
293       
294        protected void executeSchedulingPlan(SchedulingPlanInterface<?> decision) {
295
296                ArrayList<ScheduledTaskInterface<?>> taskSchedulingDecisions = decision.getTasks();
297                for (int i = 0; i < taskSchedulingDecisions.size(); i++) {
298                        ScheduledTaskInterface<?> taskDecision = taskSchedulingDecisions.get(i);
299
300                        if (taskDecision.getStatus() == AllocationStatus.REJECTED) {
301                                continue;
302                        }
303
304                        ArrayList<AllocationInterface<?>> allocations = taskDecision.getAllocations();
305
306                        TaskInterface<?> task = taskDecision.getTask();
307                        for (int j = 0; j < allocations.size(); j++) {
308
309                                AllocationInterface<?> allocation = allocations.get(j);
310                                if (allocation.getRequestedResources() == null || allocation.getRequestedResources().size() > 0) {
311                                        ExecTask exec = (ExecTask) task;                                       
312                                        executeTask(exec, allocation.getRequestedResources());
313                                } else if(resourceManager.getSchedulerName(allocation.getProviderName()) != null){
314                                        allocation.setProviderName(resourceManager.getSchedulerName(allocation.getProviderName()));
315                                        submitTask(task, allocation);
316                                } else {
317                                        ExecTask exec = (ExecTask) task;
318                                        executeTask(exec, chooseResourcesForExecution(allocation.getProviderName(), exec));
319                                }
320                        }
321                }
322        }
323
324        protected void executeTask(ExecTask task, Map<ResourceUnitName, ResourceUnit> choosenResources) {
325
326                Executable exec = (Executable)task;
327                boolean allocationStatus = allocateResources(exec, choosenResources);
328                if(allocationStatus == false){
329                        log.info("Task " + task.getJobId() + "_" + task.getId() + " requires more resources than is available at this moment.");
330                        return;
331                }
332
333                removeFromQueue(task);
334
335                log.debug(task.getJobId() + "_" + task.getId() + " starts executing on " + new DateTime());
336
337                runTask(exec);
338               
339                PEUnit peUnit = (PEUnit)choosenResources.get(StandardResourceUnitName.PE);
340                updateComputingResources(peUnit, EnergyEventType.TASK_STARTED, exec);
341               
342
343                try {
344                        long expectedDuration = exec.getExpectedDuration().getMillis() / 1000;
345                        scheduler.sendInternal(expectedDuration, DCWormsTags.TASK_REQUESTED_TIME_EXPIRED, exec);
346                } catch (NoSuchFieldException e) {
347                        //double t = exec.getEstimatedDuration();
348                        //scheduler.sendInternal(t, DCWormsTags.TASK_REQUESTED_TIME_EXPIRED, exec);
349                }
350
351                log.info(DCWormsConstants.USAGE_MEASURE_NAME + ": " + calculateTotalLoad());           
352        }
353       
354        private void runTask(ExecTask execTask){
355                Executable exec = (Executable) execTask;
356                Map<ResourceUnitName, ResourceUnit> resources = exec.getAllocatedResources().getLast().getResourceUnits();
357               
358                try {
359                        exec.setStatus(DCWormsTags.INEXEC);
360                } catch (Exception e) {
361                        // TODO Auto-generated catch block
362                        e.printStackTrace();
363                }
364
365                int phaseDuration = Double.valueOf(execTimeEstimationPlugin.execTimeEstimation(new SchedulingEvent(SchedulingEventType.START_TASK_EXECUTION),
366                                execTask, resources, exec.getCompletionPercentage())).intValue();
367
368                saveExecutionHistory(exec, exec.getCompletionPercentage(), phaseDuration);
369                if(exec.getResourceConsumptionProfile().isLast()){
370                        scheduler.sendInternal(phaseDuration, DCWormsTags.TASK_EXECUTION_FINISHED, execTask);;
371                } else {
372                        scheduler.sendInternal(phaseDuration, DCWormsTags.TASK_EXECUTION_CHANGED, execTask);
373                }
374               
375                PEUnit peUnit = (PEUnit)resources.get(StandardResourceUnitName.PE);
376                updateComputingResources(peUnit, EnergyEventType.TASK_STARTED, exec);
377               
378        }
379        protected void finalizeExecutable(ExecTask execTask){
380               
381                Executable exec = (Executable)execTask;
382                exec.finalizeExecutable();
383               
384                ExecTaskFilter filter = new ExecTaskFilter(exec.getUniqueId(), DCWormsTags.TASK_REQUESTED_TIME_EXPIRED);
385                scheduler.sim_cancel(filter, null);
386               
387                Task task;
388                Job job = jobRegistry.getJob(exec.getJobId());
389                try {
390                        task = job.getTask(exec.getTaskId());
391                } catch (NoSuchFieldException e) {
392                        return;
393                }
394                if(exec.getProcessesId() == null){
395                        try {
396                                task.setStatus(exec.getStatus());
397                        } catch (Exception e) {
398                                e.printStackTrace();
399                        }
400                } else {
401                        List<AbstractProcesses> processesList = task.getProcesses();
402                        for(int i = 0; i < processesList.size(); i++){
403                                AbstractProcesses processes = processesList.get(i);
404                                if(processes.getId().equals(exec.getProcessesId())){
405                                        processes.setStatus(exec.getStatus());
406                                        break;
407                                }
408                        }
409                }
410
411                Map<ResourceUnitName, ResourceUnit> lastUsed = exec.getAllocatedResources().getLast().getResourceUnits();
412                getAllocationManager().freeResources(lastUsed);
413               
414                saveExecutionHistory(exec, 100,0);
415               
416                PEUnit peUnit = (PEUnit)lastUsed.get(StandardResourceUnitName.PE);
417                updateComputingResources(peUnit, EnergyEventType.TASK_FINISHED, exec);
418               
419                log.debug(execTask.getJobId() + "_" + execTask.getId() + " finished execution on " + new DateTime());
420                log.info(DCWormsConstants.USAGE_MEASURE_NAME + ": " + calculateTotalLoad());
421        }
422       
423        protected void updateProcessingProgress() {
424
425                double timeSpan = DoubleMath.subtract(Sim_system.clock(), lastUpdateTime);
426                if (timeSpan <= 0.0) {
427                        // don't update when nothing changed
428                        return;
429                }
430                lastUpdateTime = Sim_system.clock();
431                Iterator<ExecTask> iter = jobRegistry.getRunningTasks().iterator();
432                while (iter.hasNext()) {
433                        ExecTask task = iter.next();
434                        Executable exec = (Executable)task;
435                        ExecutionHistoryItem execHistItem = exec.getExecHistory().getLast();
436                        //System.out.println("--- upadteProgressX: " + Sim_system.sim_clock() );
437                        //System.out.println("taskId: " + exec.getId() + "; completion percentage: " + exec.getCompletionPercentage() + "; timespan: " + timeSpan + "; estimatedDuration: " +  execHistItem.getCompletionPercentage());
438                        exec.setCompletionPercentage(exec.getCompletionPercentage() + 100 * (timeSpan / (execHistItem.getEstimatedDuration()) * (1.0 - execHistItem.getCompletionPercentage()/100.0)));
439                        //System.out.println("newProgress: " + exec.getCompletionPercentage()  );       
440
441                }
442        }
443       
444        private void updateComputingResources(PEUnit peUnit, EnergyEventType eventType, Object obj){
445                if(peUnit instanceof ProcessingElements){
446                        ProcessingElements pes = (ProcessingElements) peUnit;
447                        for (ComputingResource resource : pes) {
448                                resource.handleEvent(new EnergyEvent(eventType, obj, scheduler.getFullName()));
449                                //DataCenterWorkloadSimulator.getEventManager().sendToResources(resource.getType(), 0, new EnergyEvent(eventType, obj));
450                        }
451                        /*try {
452                                for (ComputingResource resource : resourceManager.getResourcesOfType(pes.get(0).getType())) {
453                                        resource.handleEvent(new EnergyEvent(eventType, obj));
454                                }
455                        } catch (ResourceException e) {
456                                // TODO Auto-generated catch block
457                                e.printStackTrace();
458                        }*/
459                } else {
460                        ComputingResource resource = null;
461                        try {
462                                resource = SimulatedEnvironment.getComputingResourceByName(peUnit.getResourceId());
463                        } catch (ResourceException e) {
464                                return;
465                        }
466                        resource.handleEvent(new EnergyEvent(eventType, obj, scheduler.getFullName()));
467                }
468        }
469
470        protected void updateProcessingTimes() {
471                for (ExecTask execTask : jobRegistry.getRunningTasks()) {
472                        Executable exec = (Executable)execTask;
473
474
475                        Map<ResourceUnitName, ResourceUnit> choosenResources = exec.getAllocatedResources().getLast().getResourceUnits();
476
477                        int phaseDuration = Double.valueOf(execTimeEstimationPlugin.execTimeEstimation(new SchedulingEvent(SchedulingEventType.RESOURCE_STATE_CHANGED),
478                                        execTask, choosenResources, exec.getCompletionPercentage())).intValue();
479
480                        ExecutionHistoryItem execHistItem = exec.getExecHistory().getLast();
481                        double lastTimeStamp = execHistItem.getTimeStamp().getMillis()/1000;
482                        if(DoubleMath.subtract((lastTimeStamp + execHistItem.getEstimatedDuration()), (new DateTime().getMillis()/1000 + phaseDuration)) == 0.0){
483                                continue;
484                        }
485                        //System.out.println("=== upadteTIme: " + Sim_system.sim_clock() );
486                        //System.out.println("execId: " + exec.getId() +  "; estimatedDuration " + execHistItem.getEstimatedDuration());
487                        //System.out.println("execId: " + exec.getId() + "; difference " + DoubleMath.subtract((lastTimeStamp + execHistItem.getEstimatedDuration()), (new DateTime().getMillis()/1000 + phaseDuration)));
488                        //System.out.println("completionPercantage: " + exec.getCompletionPercentage() + "; basic duration: " +exec.getResourceConsumptionProfile().getCurrentResourceConsumption().getDuration() +   "; phaseDuration: " +  phaseDuration);
489
490                        saveExecutionHistory(exec, exec.getCompletionPercentage(), phaseDuration);
491                       
492                        if(exec.getResourceConsumptionProfile().isLast()){
493                                ExecTaskFilter filter = new ExecTaskFilter(exec.getUniqueId(), DCWormsTags.TASK_EXECUTION_FINISHED);
494                                scheduler.sim_cancel(filter, null);
495                                scheduler.sendInternal(phaseDuration , DCWormsTags.TASK_EXECUTION_FINISHED, execTask);
496                                //PEUnit peUnit = (PEUnit)exec.getUsedResources().getLast().getResourceUnits().get(StandardResourceUnitName.PE);
497                                //notifyComputingResources(peUnit, EnergyEventType.RESOURCE_UTILIZATION_CHANGED, exec);
498                        } else{
499                                ExecTaskFilter filter = new ExecTaskFilter(exec.getUniqueId(), DCWormsTags.TASK_EXECUTION_CHANGED);
500                                scheduler.sim_cancel(filter, null);
501                                scheduler.sendInternal(phaseDuration, DCWormsTags.TASK_EXECUTION_CHANGED, execTask);
502                                //PEUnit peUnit = (PEUnit)exec.getUsedResources().getLast().getResourceUnits().get(StandardResourceUnitName.PE);
503                                //notifyComputingResources(peUnit, EnergyEventType.RESOURCE_UTILIZATION_CHANGED, exec);
504                        }
505                }
506        }       
507
508        protected void updateTaskExecutionPhase(ExecTask execTask, SchedulingEventType schedEvType) {
509
510                if (execTask.getStatus() == DCWormsTags.INEXEC) {
511                        Executable exec = (Executable)execTask;
512                       
513                        try {
514                                exec.setStatus(DCWormsTags.NEW_EXEC_PHASE);
515                        } catch (Exception e) {
516                               
517                        }
518
519                        Map<ResourceUnitName, ResourceUnit> choosenResources = exec.getAllocatedResources().getLast().getResourceUnits();
520
521                        int phaseDuration = Double.valueOf(execTimeEstimationPlugin.execTimeEstimation(new SchedulingEvent(schedEvType),
522                                        execTask, choosenResources, exec.getCompletionPercentage())).intValue();
523                       
524                        saveExecutionHistory(exec, exec.getCompletionPercentage(), phaseDuration);
525                       
526                        if(exec.getResourceConsumptionProfile().isLast()){
527                                scheduler.sendInternal(phaseDuration, DCWormsTags.TASK_EXECUTION_FINISHED, execTask);
528                        } else {
529                                scheduler.sendInternal(phaseDuration, DCWormsTags.TASK_EXECUTION_CHANGED, execTask);
530                        }
531                       
532                        PEUnit peUnit = (PEUnit)exec.getAllocatedResources().getLast().getResourceUnits().get(StandardResourceUnitName.PE);
533                        updateComputingResources(peUnit, EnergyEventType.RESOURCE_UTILIZATION_CHANGED, exec);
534                }
535        }       
536
537        public double calculateTotalLoad() {
538
539                GSSAccumulator loadAcc = new GSSAccumulator();
540                try {
541                        for(ComputingResource compRes: getResourceManager().getResourcesOfType(StandardResourceType.Node)){
542                                loadAcc.add(compRes.getLoadInterface().getRecentUtilization().getValue());                             
543                        }
544                } catch (ResourceException e) {
545                        // TODO Auto-generated catch block
546                        e.printStackTrace();
547                }
548               
549                return loadAcc.getMean();
550        }
551
552        private Map<ResourceUnitName, ResourceUnit> chooseResourcesForExecution(String resourceName,
553                        ExecTask task) {
554
555                Map<ResourceUnitName, ResourceUnit> map = new HashMap<ResourceUnitName, ResourceUnit>();
556                LocalResourceManager resourceManager = getResourceManager();
557                if(resourceName != null){
558                        ComputingResource resource = null;
559                        try {
560                                resource = resourceManager.getResourceByName(resourceName);
561                        } catch (ResourceException e) {
562                                return null;
563                        }
564                        resourceManager = new LocalResourceManager(resource);
565                }
566
567                int cpuRequest;
568                try {
569                        cpuRequest = Double.valueOf(task.getCpuCntRequest()).intValue();
570                } catch (NoSuchFieldException e) {
571                        cpuRequest = 1;
572                }
573
574                if (cpuRequest != 0) {
575                       
576                        List<ResourceUnit> availableUnits = null;
577                        try {
578                                availableUnits = resourceManager.getPE();
579                        } catch (ResourceException e) {
580                                return null;
581                        }
582                       
583                        List<ResourceUnit> choosenPEUnits = new ArrayList<ResourceUnit>();
584                        for (int i = 0; i < availableUnits.size() && cpuRequest > 0; i++) {
585                                PEUnit peUnit = (PEUnit) availableUnits.get(i);
586                                if(peUnit.getFreeAmount() > 0){
587                                        int allocPE = Math.min(peUnit.getFreeAmount(), cpuRequest);
588                                        cpuRequest = cpuRequest - allocPE;
589                                        choosenPEUnits.add(peUnit.replicate(allocPE)); 
590                                }       
591                        }
592                       
593                        if(cpuRequest > 0){
594                                return null;
595                        }
596                        map.put(StandardResourceUnitName.PE, choosenPEUnits.get(0));
597                }
598
599                return  map;
600        }
601       
602        public void notifySubmittedWorkloadUnit(WorkloadUnit wu) {
603                //250314
604                //updateProcessingProgress();
605                if (log.isInfoEnabled())
606                        log.info("Received job " + wu.getId() + " at " + new DateTime(DateTimeUtilsExt.currentTimeMillis()));
607                registerWorkloadUnit(wu);
608        }
609
610        private void registerWorkloadUnit(WorkloadUnit wu){
611                if(!wu.isRegistered()){
612                        wu.register(jobRegistry);
613                }
614                wu.accept(getWorkloadUnitHandler());
615        }
616       
617        class LocalWorkloadUnitHandler implements WorkloadUnitHandler{
618               
619                public void handleJob(JobInterface<?> job){
620
621                        if (log.isInfoEnabled())
622                                log.info("Handle " + job.getId() + " at " + new DateTime(DateTimeUtilsExt.currentTimeMillis()));
623                       
624                        try {
625                                if(job.getStatus() == BrokerConstants.JOB_STATUS_UNSUBMITTED)
626                                        job.setStatus((int)BrokerConstants.JOB_STATUS_SUBMITTED);
627                        } catch (Exception e) {
628                                e.printStackTrace();
629                        }
630                        List<JobInterface<?>> jobsList = new ArrayList<JobInterface<?>>();
631                        jobsList.add(job);
632                        TaskListImpl availableTasks = new TaskListImpl();
633                        for(Task task: jobRegistry.getAvailableTasks(jobsList)){
634                                task.setStatus((int)BrokerConstants.TASK_STATUS_QUEUED);
635                                availableTasks.add(task);
636                        }
637
638                        for(TaskInterface<?> task: availableTasks){     
639                                registerWorkloadUnit(task);
640                        }
641                }
642               
643                public void handleTask(TaskInterface<?> t){
644                        Task task = (Task)t;
645                        List<AbstractProcesses> processes = task.getProcesses();
646
647                        if(processes == null || processes.size() == 0){
648                                Executable exec = new Executable(task);
649                                registerWorkloadUnit(exec);
650                        } else {
651                                for(int j = 0; j < processes.size(); j++){
652                                        AbstractProcesses procesesSet = processes.get(j);
653                                        Executable exec = new Executable(task, procesesSet);
654                                        registerWorkloadUnit(exec);
655                                }
656                        }
657                }
658               
659                public void handleExecutable(ExecTask task){
660                       
661                        Executable exec = (Executable) task;
662                        jobRegistry.addExecTask(exec);
663
664                        exec.setSchedulerName(scheduler.getFullName());
665                       
666                        TaskList newTasks = new TaskListImpl();
667                        newTasks.add(exec);
668               
669                        schedulingPlugin.placeTasksInQueues(newTasks, queues, getResourceManager(), moduleList);
670
671                        if (exec.getStatus() == DCWormsTags.QUEUED) {
672                                sendExecutableReadyEvent(exec);
673                        }
674                }
675        }
676
677        public WorkloadUnitHandler getWorkloadUnitHandler() {
678                return new LocalWorkloadUnitHandler();
679        }
680       
681       
682        public LocalResourceManager getResourceManager() {
683                if (resourceManager instanceof ResourceManager)
684                        return (LocalResourceManager) resourceManager;
685                else
686                        return null;
687        }
688       
689       
690        public void saveExecutionHistory(Executable exec, double completionPercentage, double estimatedDuration){
691
692                ExecutionHistoryItem execHistoryItem = new ExecutionHistoryItem(new DateTime());
693                execHistoryItem.setCompletionPercentage(completionPercentage);
694                execHistoryItem.setEstimatedDuration(estimatedDuration);
695                execHistoryItem.setResIndex(exec.getAllocatedResources().size() -1);
696                execHistoryItem.setStatus(exec.getStatus());
697                exec.addExecHistory(execHistoryItem);
698               
699                ProcessingElements pes = (ProcessingElements) exec.getAllocatedResources().getLast().getResourceUnits().get(StandardResourceUnitName.PE);
700                for (ComputingResource resource : pes) {
701
702                        LinkedList<ComputingResource> toExamine = new LinkedList<ComputingResource>();
703                        toExamine.push(resource);
704
705                        while (!toExamine.isEmpty()) {
706                                ComputingResource compResource = toExamine.pop();
707                                List<ComputingResource> resources = compResource.getChildren();
708                                if(resources.isEmpty()){
709                                        Set<String> visitedResources = exec.getAllocatedResources().getLast().getVisitedResources();
710                                        if(!visitedResources.contains(compResource.getFullName())){
711                                                exec.getAllocatedResources().getLast().trackResource(compResource.getFullName());
712                                        }
713                                } else {
714                                        for (int i = 0; i < resources.size(); i++) {
715                                                ComputingResource resourceChild = resources.get(i);
716                                                toExamine.addLast(resourceChild);
717                                        }
718                                }
719                        }
720                }
721        }
722       
723        public boolean allocateResources(Executable exec, Map<ResourceUnitName, ResourceUnit> choosenResources){
724                boolean allocationStatus = getAllocationManager().allocateResources(choosenResources);
725                if(allocationStatus){
726                        ResourceHistoryItem resourceHistoryItem = new ResourceHistoryItem(choosenResources);
727                        exec.addAllocatedResources(resourceHistoryItem);
728                        return true;
729                }
730                return false;
731        }
732}
Note: See TracBrowser for help on using the repository browser.