source: xssim/trunk/src/test/rewolucja/reservation/LocalReservationManagerNew.java @ 202

Revision 202, 72.5 KB checked in by wojtekp, 13 years ago (diff)
  • Property svn:mime-type set to text/plain
Line 
1package test.rewolucja.reservation;
2
3import gridsim.gssim.policy.InExecuionList;
4
5import java.util.ArrayList;
6import java.util.List;
7import java.util.Properties;
8
9import org.apache.commons.logging.Log;
10import org.apache.commons.logging.LogFactory;
11import org.joda.time.DateTime;
12import org.qcg.broker.schemas.resreqs.ExecutionTimeType;
13
14import schedframe.exceptions.ModuleException;
15import schedframe.exceptions.ReservationException;
16import schedframe.resources.ResourceDescription;
17import schedframe.resources.ResourceProvider;
18import schedframe.resources.ResourceStateDescription;
19import schedframe.resources.providers.LocalSystem;
20import schedframe.resources.units.Processors;
21import schedframe.resources.units.ResourceUnit;
22import schedframe.scheduling.AbstractResourceRequirements;
23import schedframe.scheduling.AbstractTimeRequirements;
24import schedframe.scheduling.Offer;
25import schedframe.scheduling.Queue;
26import schedframe.scheduling.ResourceRequirements;
27import schedframe.scheduling.ResourceUsage;
28import schedframe.scheduling.TaskInterface;
29import schedframe.scheduling.TimeRequirements;
30import schedframe.scheduling.TimeResourceAllocation;
31import schedframe.scheduling.plugin.grid.ModuleType;
32import schedframe.scheduling.plugin.local.LocalReservationManager;
33import schedframe.scheduling.plugin.local.TimeOperations;
34import schedframe.scheduling.utils.ResourceParameterName;
35import simulator.utils.MergeSort;
36import test.rewolucja.GSSIMJobInterface;
37import test.rewolucja.reservation.ReservationNew.Status;
38import test.rewolucja.resources.ProcessingElements;
39import test.rewolucja.resources.ResourceStatus;
40import test.rewolucja.resources.ResourceType;
41import test.rewolucja.resources.manager.implementation.ResourceManager;
42import test.rewolucja.resources.manager.interfaces.ResourceManagerInterface;
43import test.rewolucja.resources.physical.base.ComputingResource;
44import test.rewolucja.resources.physical.implementation.Processor;
45
46public class LocalReservationManagerNew implements LocalReservationManager {
47
48        protected static Log log = LogFactory.getLog(LocalReservationManagerNew.class);
49       
50        protected ReservationListNew reservationList;
51         
52        protected TimeOperations timeOpers;
53         
54        protected long timeDelta;
55
56        protected ResourceProvider resourceProvider;
57       
58         
59          public LocalReservationManagerNew(long timeDelta, String resourceName) {
60            this.timeDelta = timeDelta;
61            this.timeOpers = new TimeOperations(timeDelta);
62            this.reservationList = new GssimReservationListNew();
63            this.resourceProvider = new LocalSystem(resourceName , null, null);
64          }
65
66          public LocalReservationManagerNew(long timeDelta, TimeOperations timeOpers, String resourceName) {
67                this.timeDelta = timeDelta;
68                this.timeOpers = timeOpers;
69                this.reservationList = new GssimReservationListNew();
70                this.resourceProvider = new LocalSystem(resourceName , null, null);
71          }
72
73         
74          /**
75           * Find the first free slot with regard to given resources and according to time requirements
76         * @throws NoSuchFieldException
77           */
78         
79          public TimeResourceAllocation findFreeSlot(ExecutionTimeType time, ResourceUnit resReqs, ResourceUnit[] resStates) throws NoSuchFieldException {
80
81               
82                 
83                if (time == null)
84              return null;
85
86            DateTime currentTime = timeOpers.getTime();//Calendar.getInstance();
87
88            //start of period
89            DateTime startPeriod = timeOpers.getTime();//Calendar.getInstance();
90            if (time.getTimePeriod() != null)
91              if (time.getTimePeriod().getPeriodStart() != null)
92                startPeriod = new DateTime(time.getTimePeriod().getPeriodStart().getTime());
93
94           
95            //end of period
96            DateTime endPeriod = new DateTime(Long.MAX_VALUE);//timeOpers.getTime();//Calendar.getInstance();
97            //endPeriod.setTimeInMillis(Long.MAX_VALUE);
98            if (time.getTimePeriod() != null)
99              if (time.getTimePeriod().getTimePeriodChoice() != null)
100                if (time.getTimePeriod().getTimePeriodChoice().getPeriodEnd() != null) {
101                  endPeriod = new DateTime(time.getTimePeriod().getTimePeriodChoice().getPeriodEnd().getTime());
102                }
103                else if (time.getTimePeriod().getTimePeriodChoice().getPeriodDuration() != null)
104                  endPeriod = new DateTime(startPeriod.getMillis() + time.getTimePeriod().getTimePeriodChoice().getPeriodDuration().toLong());
105
106                 
107            //days of the week
108            boolean[] weekDays = new boolean[7];
109            ArrayList<DateTime> inclDates = null;
110            ArrayList<DateTime> exclDates = null;
111           
112            if (time.getTimePeriod() != null) {
113               
114              //all weekdays allowed
115              for (int i=0; i < 7; i++)
116                  weekDays[i] = true;
117               
118              if (time.getTimePeriod().getIncluding() != null) {
119                 
120                //only weekdays defined in Including element allowed
121                for (int i=0; i < 7; i++)
122                  weekDays[i] = false;
123               
124                for (int i=0; i < time.getTimePeriod().getIncluding().getDaysTypeItemCount(); i++) {
125                  if (time.getTimePeriod().getIncluding().getDaysTypeItem(i).getWeekDay() != null) {
126                    int day = time.getTimePeriod().getIncluding().getDaysTypeItem(i).getWeekDay().ordinal();
127                    weekDays[(day+1)%7] = true;
128                  }
129                  else {
130                          org.exolab.castor.types.Date dateDay = time.getTimePeriod().getIncluding().getDaysTypeItem(i).getDateDay(); 
131                    if (time.getTimePeriod().getIncluding().getDaysTypeItem(i).getDateDay() != null) {
132                      if (inclDates == null)
133                        inclDates = new ArrayList<DateTime>();
134                      inclDates.add(new DateTime(dateDay.toLong()));
135                    }
136                  }
137                }
138              }
139              if (time.getTimePeriod().getExcluding() != null) {
140                for (int i=0; i < time.getTimePeriod().getExcluding().getDaysTypeItemCount(); i++) {
141                  if (time.getTimePeriod().getExcluding().getDaysTypeItem(i).getWeekDay() != null) {
142                    int day = time.getTimePeriod().getExcluding().getDaysTypeItem(i).getWeekDay().ordinal();
143                    weekDays[(day+1)%7] = false;
144                  }
145                  else {
146                        org.exolab.castor.types.Date dateDay = time.getTimePeriod().getExcluding().getDaysTypeItem(i).getDateDay(); 
147                    if (time.getTimePeriod().getExcluding().getDaysTypeItem(i).getDateDay() != null) {
148                      if (exclDates == null)
149                        exclDates = new ArrayList<DateTime>();
150                      exclDates.add(new DateTime(dateDay.toLong()));
151                    }
152                  }
153                }
154              }
155              //find latest possible date
156              DateTime latestDate = timeOpers.findLatestDate(inclDates, exclDates);
157              if (timeOpers.beforeDate(latestDate, endPeriod)) {
158                  endPeriod = timeOpers.setDate(endPeriod, latestDate);
159                  //endPeriod.set(Calendar.DAY_OF_MONTH, endPeriod.get(Calendar.DAY_OF_MONTH) + 1);
160                  endPeriod = endPeriod.plusDays(1);
161              }
162            }
163            //time slot
164            DateTime startTime = null;
165            DateTime endTime = null;
166            if (time.getTimeSlot() != null) {
167                //start of time slot
168                if (time.getTimeSlot().getSlotStart() != null){
169                        //startTime = timeOpers.getTime();//Calendar.getInstance();
170                        startTime = new DateTime(time.getTimeSlot().getSlotStart().
171                                        getContent().toDate().getTime());
172                }
173                //end of time slot 
174                if (time.getTimeSlot().getTimeSlotChoice() != null)
175                        if (time.getTimeSlot().getTimeSlotChoice().getSlotEnd() != null){
176                                //endTime = timeOpers.getTime();//Calendar.getInstance();
177                                endTime = new DateTime(time.getTimeSlot().getTimeSlotChoice().
178                                                getSlotEnd().toDate().getTime());
179                        }
180                        else
181                                if (time.getTimeSlot().getTimeSlotChoice().getSlotDuration() != null){
182                                        //endTime = timeOpers.getTime();//Calendar.getInstance();
183                                        endTime = new DateTime(time.getTimeSlot().getTimeSlotChoice().
184                                                        getSlotDuration().toLong());
185                                }
186            }
187           
188            //duration
189            long duration = time.getExecutionDuration().toLong();
190
191            //find a first free slot
192            TimeResourceAllocation firstSlot = null;
193            DateTime firstStartTime = (startTime != null) ? new DateTime(startTime) : timeOpers.getTime();//Calendar.getInstance();
194            for (int i=0; i < resStates.length; i++) {     
195              TimeResourceAllocation slot = findFreeHostSlot(resReqs, duration, startTime, endTime,
196                                           startPeriod, endPeriod, weekDays, inclDates,
197                                                                           exclDates, resStates[i]);
198              if (firstSlot == null)
199                firstSlot = slot;
200              if (slot != null) {
201                //if (firstSlot.getStartTime() > slot.getStartTime())
202                if(firstSlot.getStart().isAfter(slot.getStart()))
203                  firstSlot = slot;
204                if (firstSlot.getStartMillis() <= Math.max(firstStartTime.getMillis(), currentTime.getMillis()) + timeDelta)
205                  return firstSlot;
206              }     
207            }
208           
209            return firstSlot;
210          }
211
212          /**
213           * Find the required free slot
214         * @throws NoSuchFieldException
215           */
216          public TimeResourceAllocation findFreeSlot(TimeResourceAllocation timeReq, ResourceUnit resReqs, ResourceUnit[] resStates) throws NoSuchFieldException {
217
218            if (timeReq == null)
219              return null;
220
221            DateTime currentTime = timeOpers.getTime();//Calendar.getInstance();
222
223            //start of period
224            DateTime startPeriod = timeReq.getStart();
225
226            //end of period
227            DateTime endPeriod = timeReq.getEnd();
228           
229            //days of the week
230            boolean[] weekDays = new boolean[7];
231            ArrayList<DateTime> inclDates = null;
232            ArrayList<DateTime> exclDates = null;
233               
234            //all weekdays allowed
235            for (int i=0; i < 7; i++)
236                 weekDays[i] = true;
237               
238            //find latest possible date
239            DateTime latestDate = timeOpers.findLatestDate(inclDates, exclDates);
240            if (timeOpers.beforeDate(latestDate, endPeriod)) {
241                endPeriod = new DateTime(latestDate.getYear(),
242                                                                latestDate.getMonthOfYear(),
243                                                                latestDate.getDayOfMonth() + 1,
244                                                                endPeriod.getHourOfDay(),
245                                                                endPeriod.getMinuteOfHour(),
246                                                                endPeriod.getSecondOfMinute(),
247                                                                endPeriod.getMillisOfSecond(),
248                                                                endPeriod.getChronology());//timeOpers.setDate(endPeriod, latestDate);
249            //  endPeriod.set(Calendar.DAY_OF_MONTH, endPeriod.get(Calendar.DAY_OF_MONTH) + 1);
250            }
251
252            //time slot
253            DateTime startTime = null;
254            DateTime endTime = null;
255                //start of time slot
256                        startTime = timeReq.getStart();
257                //end of time slot 
258                        endTime = timeReq.getEnd();
259           
260            //duration
261            long duration = timeReq.getEndMillis() - timeReq.getStartMillis() - timeDelta;
262
263            //find a first free slot
264            TimeResourceAllocation firstSlot = null;
265            DateTime firstStartTime = (startTime!=null)? new DateTime(startTime) : timeOpers.getTime();//Calendar.getInstance();
266            for (int i=0; i < resStates.length; i++) {     
267              TimeResourceAllocation slot = findFreeHostSlot(resReqs, duration, startTime, endTime,
268                                           startPeriod, endPeriod, weekDays, inclDates,
269                                                                           exclDates, resStates[i]);
270              if (firstSlot == null)
271                firstSlot = slot;
272              if (slot != null) {
273               // if (firstSlot.getStartTime() > slot.getStartTime())
274                if (firstSlot.getStart().isAfter(slot.getStart()))
275                  firstSlot = slot;
276                if (firstSlot.getStartMillis() <= Math.max(firstStartTime.getMillis(), currentTime.getMillis()) + timeDelta)
277                  return firstSlot;
278              }     
279            }
280           
281            return firstSlot;
282          }
283         
284          /**
285           * Find the first free slot according to time requirements
286           */
287          public TimeResourceAllocation findFreeSlot(ExecutionTimeType time) {
288
289            if (time == null)
290              return null;
291
292            DateTime currentTime = timeOpers.getTime();//Calendar.getInstance();
293
294            //start of period
295            DateTime startPeriod = timeOpers.getTime();//Calendar.getInstance();
296            if (time.getTimePeriod() != null)
297              if (time.getTimePeriod().getPeriodStart() != null)
298                //startPeriod.setTimeInMillis(time.getTimePeriod().getPeriodStart().getTime());
299                  startPeriod = new DateTime(time.getTimePeriod().getPeriodStart().getTime());
300
301            //end of period
302            DateTime endPeriod = new DateTime(Long.MAX_VALUE);//timeOpers.getTime();//Calendar.getInstance();
303            //endPeriod.setTimeInMillis(Long.MAX_VALUE);
304            if (time.getTimePeriod() != null)
305              if (time.getTimePeriod().getTimePeriodChoice() != null)
306                if (time.getTimePeriod().getTimePeriodChoice().getPeriodEnd() != null) {
307                  //endPeriod.setTimeInMillis(time.getTimePeriod().getTimePeriodChoice().getPeriodEnd().getTime());
308                        endPeriod = new DateTime(time.getTimePeriod().getTimePeriodChoice().getPeriodEnd().getTime());
309                }
310                else if (time.getTimePeriod().getTimePeriodChoice().getPeriodDuration() != null)
311                  //endPeriod.setTimeInMillis(startPeriod.getTimeInMillis() + time.getTimePeriod().getTimePeriodChoice().getPeriodDuration().toLong());
312                        endPeriod = new DateTime(startPeriod.getMillis() + time.getTimePeriod().getTimePeriodChoice().getPeriodDuration().toLong());
313               
314
315            //days of the week
316            boolean[] weekDays = new boolean[7];
317            ArrayList<DateTime> inclDates = null;
318            ArrayList<DateTime> exclDates = null;
319           
320            //all weekdays allowed
321            for (int i=0; i < 7; i++)
322                weekDays[i] = true;
323                       
324            if (time.getTimePeriod() != null) {
325               
326              if (time.getTimePeriod().getIncluding() != null) {
327
328                //only weekdays defined in Including element allowed
329                  for (int i=0; i < 7; i++)
330                    weekDays[i] = false;
331                 
332                for (int i=0; i < time.getTimePeriod().getIncluding().getDaysTypeItemCount(); i++) {
333                  if (time.getTimePeriod().getIncluding().getDaysTypeItem(i).getWeekDay() != null) {
334                    int day = time.getTimePeriod().getIncluding().getDaysTypeItem(i).getWeekDay().ordinal();
335                    weekDays[(day+1)%7] = true;
336                  }
337                  else {
338                        org.exolab.castor.types.Date dateDay = time.getTimePeriod().getIncluding().getDaysTypeItem(i).getDateDay();
339                    if (dateDay != null) {
340                      if (inclDates == null)
341                        inclDates = new ArrayList<DateTime>();
342                      inclDates.add(new DateTime(dateDay));
343                    }
344                  }
345                }
346              }
347              if (time.getTimePeriod().getExcluding() != null) {
348                for (int i=0; i < time.getTimePeriod().getExcluding().getDaysTypeItemCount(); i++) {
349                  if (time.getTimePeriod().getExcluding().getDaysTypeItem(i).getWeekDay() != null) {
350                    int day = time.getTimePeriod().getExcluding().getDaysTypeItem(i).getWeekDay().ordinal();
351                    weekDays[(day+1)%7] = false;
352                  }
353                  else {
354                        org.exolab.castor.types.Date dateDay = time.getTimePeriod().getExcluding().getDaysTypeItem(i).getDateDay();
355                    if (time.getTimePeriod().getExcluding().getDaysTypeItem(i).getDateDay() != null) {
356                      if (exclDates == null)
357                        exclDates = new ArrayList<DateTime>();
358                      exclDates.add(new DateTime(dateDay));
359                    }
360                  }
361                }
362              }
363              //find latest possible date
364              DateTime latestDate = timeOpers.findLatestDate(inclDates, exclDates);
365              if (timeOpers.beforeDate(latestDate, endPeriod)) {
366                  endPeriod = timeOpers.setDate(endPeriod, latestDate);
367                  //endPeriod.set(Calendar.DAY_OF_MONTH, endPeriod.get(Calendar.DAY_OF_MONTH) + 1);
368                  endPeriod = endPeriod.plusDays(1);
369              }
370            }
371
372            //start of time slot
373            DateTime startSlot = null;
374            DateTime endSlot = null;
375            if (time.getTimeSlot() != null) {
376                if (time.getTimeSlot().getSlotStart() != null){
377                        //startSlot = timeOpers.getTime();//Calendar.getInstance();
378                        startSlot = new DateTime(time.getTimeSlot().getSlotStart().
379                                        getContent().toDate().getTime());
380                }
381                //end of time slot 
382                if (time.getTimeSlot().getTimeSlotChoice() != null)
383                        if (time.getTimeSlot().getTimeSlotChoice().getSlotEnd() != null){
384                                //endSlot = timeOpers.getTime();//Calendar.getInstance();
385                                endSlot = new DateTime(time.getTimeSlot().getTimeSlotChoice().
386                                                getSlotEnd().toDate().getTime());
387                        }
388                        else
389                                if (time.getTimeSlot().getTimeSlotChoice().getSlotDuration() != null){
390                                        //endSlot = timeOpers.getTime();//Calendar.getInstance();
391                                        endSlot = new DateTime(time.getTimeSlot().getTimeSlotChoice().
392                                                        getSlotDuration().toLong());
393                                }
394            }
395           
396            //duration
397            long duration = time.getExecutionDuration().toLong();
398           
399            //if task duration longer than slot length
400            if (startSlot != null && endSlot != null)
401                if (duration + timeDelta > timeOpers.periodDayTimeDuration(startSlot, endSlot))
402                        return null;
403           
404                boolean inclDay = false;
405            //check if there are any not excluded weekdays
406            if (inclDates == null) {
407                for (int i=0; i < 7; i++)
408                        if (weekDays[i] == true)
409                                inclDay = true;
410            }//check if there are included dates later than startPeriod
411            else {
412                for (int i=0; i < inclDates.size(); i++)
413                        if (startPeriod.isBefore(inclDates.get(i)))
414                                inclDay = true;
415            }
416                if (!inclDay)
417                        return null;
418               
419            DateTime startTime = null; //timeOpers.getTime();//Calendar.getInstance();
420
421            //start from startPeriod
422            startTime = new DateTime(Math.max(startPeriod.getMillis(), currentTime.getMillis()));
423            if (startSlot != null)
424                if (timeOpers.beforePeriodDayTime(startTime, startSlot, endSlot))
425                        startTime = timeOpers.setDayTime(startTime, startSlot);
426
427            //start from startSlot
428            while (!meetTimeRequirements(startTime, duration, startSlot, endSlot, weekDays, inclDates, exclDates, endPeriod)) {
429                 if (!timeOpers.withinPeriod(duration, startTime, endPeriod))
430                        return null;
431                 nextSlot(startTime, duration, startSlot, endSlot);
432            }
433
434            DateTime cStart = new DateTime(startTime.getMillis() + timeDelta);
435            DateTime cEnd = new DateTime(startTime.getMillis() + timeDelta + duration);
436            TimeResourceAllocation slot = new TimeResourceAllocation(cStart, cEnd);
437           
438            return slot;
439          }
440
441          /**
442           * Find the free slots concerning given resources and according to time requirements
443           */
444          public TimeResourceAllocation[] findFreeSlots(ExecutionTimeType time, ResourceUnit resReqs, ResourceUnit[] resStates) {
445            //TODO
446            return null;
447          }
448
449          /**
450           * Checks whether a given slot meets requirements
451           * @param slot a given slot
452           * @param resReqs requirement
453           * @param resStates states of resources
454           * @return true if slot is free
455         * @throws NoSuchFieldException
456           */
457/*        public boolean isSlotFree(TimeResourceAllocation slot, ResourceUnit resReqs, ResourceUnit[] resStates) throws NoSuchFieldException {
458                 
459                  if (slot == null)
460                          return false;
461                 
462                  if (resStates == null || resStates.length == 0)
463                          return false;
464                                 
465                  if (resReqs == null)
466                          resReqs = new DiscreteProcessors(1, 0);
467
468                  ResourceUnit totalResource = null;
469                  for (int i=0; i < resStates.length; i++) {
470                          if (resStates[i].getName() == resReqs.getName()) {
471                                  totalResource = resStates[i];
472                                  break;
473                          }
474                  }
475                       
476                  if (totalResource == null)
477                          return false;
478                 
479                  TimeResourceAllocation[] usage = resourceUsage(totalResource, slot.getStart(), slot.getEnd());
480                 
481                  try {
482                          for (int i=0; i < usage.length; i++){
483                                  float usedResources = 0;
484                                  usedResources = totalResource.getAmount() - usage[i].getAllocatedResource().getProcessorsAmount();
485                                 /* if(usage[i].getResourceUnit(Constants.PE).getResourceUnitType() == ResourceUnitType.DISCRETE_RESOURCE){
486                                          usedResources = usage[i].getResourceUnit(Constants.PE).getAmount();
487                                  } else {
488                                          usedResources = totalResource.getAmount() - usage[i].getResourceUnit(Constants.PE).getAmount();
489                                  }
490                                  */
491/*                                      if(resReqs.getResourceUnitType() == ResourceUnitType.DISCRETE_RESOURCE){
492                                          DiscreteProcessors discResReq = (DiscreteProcessors) resReqs;
493                                          DiscreteProcessors avlUnit = (DiscreteProcessors)usage[i].
494                                                                                                                                getAllocatedResource().
495                                                                                                                                getResourceUnit(ResourceParameterName.CPUCOUNT);
496                                          for(int j = 0; j < discResReq.getAmount(); j++){
497                                                  // request availability of processor which is not available
498                                                  //if(reqAvl[j] == Avl.REQUESTED && avl[j] == Avl.USED){
499                                                  if(discResReq.getStatus(j) == Avl.USED && avlUnit.getStatus(j) == Avl.USED){
500                                                          return false;
501                                                  }
502                                          }
503                                  } else {
504                                          //if (totalResource.getAmount() - usage[i].getResourceUnit().getAmount() < resReqs.getAmount())
505                                        //        return false;
506                                          if(usedResources < resReqs.getAmount())
507                                                  return false;
508                                  }
509                          }
510                  } catch(NoSuchFieldException e){
511                          log.error(e.getMessage());
512                          return false;
513                  }
514
515                  //TODO check specific resources for discrete resource units, e.g. number of processors!
516                 
517                  return true;
518          }
519*/       
520          public String reserveResource(String jobID, String taskID, String userID,
521                                                                        ExecutionTimeType time, ResourceUnit resReqs, ResourceUnit[] resStates) throws NoSuchFieldException {
522
523            TimeResourceAllocation slot = findFreeSlot(time, resReqs, resStates);
524
525            if (slot == null)
526              return null;
527           
528            return addReservation(slot.getStart(), slot.getEnd(), jobID, taskID, userID, slot.getAllocatedResource());
529          }
530         
531          public boolean cancelReservation(String reservId) {
532               
533                if (setReservStatus(reservId, ReservationNew.Status.CANCELED) == Status.CANCELED)
534                        return true;
535               
536            return false;
537          }
538         
539          public int clearReservations() {
540                  int n = reservationList.size();
541                  reservationList.clear();
542                 
543                  return n;
544          }
545
546          public String addReservation(DateTime startTime, DateTime finishTime,
547                                                                        String jobId, String taskId, String userId,
548                                                                        ResourceDescription resources) {
549           
550                //TODO check if reservation can be added (take into account specific resources for discrete resource units, e.g. number of processors!)
551                 
552            ReservationNew res = new ReservationNew(resources, startTime, finishTime, null);
553            res.setJobId(jobId);
554            res.setTaskId(taskId);
555            res.setUserId(userId);
556           
557            reservationList.add(res);
558             
559            return res.getId();
560          }
561
562          public String addReservation(ReservationNew res) {
563                 
564                  //TODO check if reservation can be added (take into account specific resources for discrete resource units, e.g. number of processors!)
565                 
566                  reservationList.add(res);
567                 
568                  return res.getId();
569          }
570         
571          public ReservationNew getReservation(String reservId) {
572           
573            for (int i=0; i < reservationList.size(); i++) {
574              if (((ReservationNew)reservationList.get(i)).getId().equals(reservId))
575                return (ReservationNew)reservationList.get(i);
576            }
577           
578            return null;
579          }
580
581          public Status getReservStatus(String reservId) {
582            ReservationNew res = getReservation(reservId);
583            if (res == null)
584              throw new IllegalArgumentException("There is no reservation with id " + reservId);
585           
586            return res.getStatus();
587          }
588
589          public Status setReservStatus(String reservId, Status status) {
590            ReservationNew res = getReservation(reservId);
591           
592            if (res == null)
593              throw new IllegalArgumentException("There is no reservation with id " + reservId);
594           
595            Status st = res.getStatus();
596            res.setStatus(status);
597            return st;
598          }
599
600          /**
601           * @return identifiers of jobs that have to be started
602           */
603          public String[] checkJobsToStart() {
604           
605            //TODO Get jobInfos from registry (maybe in constructor)
606           
607            //TODO Construct generic reservation manager
608             
609            long currentTime = timeOpers.getTime().getMillis();
610            ArrayList<String> v = new ArrayList<String>();
611           
612            for (int i=0; i < reservationList.size(); i++) {
613              if (((ReservationNew)reservationList.get(i)).getStatus() == ReservationNew.Status.COMMITTED)
614                if (((ReservationNew)reservationList.get(i)).getStart().getMillis() > currentTime - timeDelta)
615                  v.add(((ReservationNew)reservationList.get(i)).getId());
616            }
617
618            if (v.size() == 0)
619              return null;
620           
621            String[] resIds = new String[v.size()];
622            resIds = (String[])v.toArray(resIds);
623           
624            return resIds;
625          }
626
627          /**
628           * @return identifiers of jobs that have to be stopped
629           */
630          public String[] checkJobsToStop() {
631         
632            //TODO Get jobInfos from registry (maybe in constructor)
633           
634            //TODO Construct generic reservation manager
635
636            long currentTime = timeOpers.getTime().getMillis();
637            ArrayList<String> v = new ArrayList<String>();
638           
639            for (int i=0; i < reservationList.size(); i++) {
640              if (((ReservationNew)reservationList.get(i)).getStatus() == ReservationNew.Status.ACTIVE)
641                if (((ReservationNew)reservationList.get(i)).getEnd().getMillis() > currentTime - timeDelta)
642                  v.add(((ReservationNew)reservationList.get(i)).getId());
643            }
644
645            if (v.size() == 0)
646              return null;
647           
648            String[] resIds = new String[v.size()];
649            resIds = (String[])v.toArray(resIds);
650           
651            return resIds;
652          }
653
654          /**
655           * 
656           * @uml.property name="timeDelta"
657           */
658          public long getTimeDelta() {
659            return timeDelta;
660          }
661
662          /**
663           * 
664           * @uml.property name="timeDelta"
665           */
666          public void setTimeDelta(long timeDelta) {
667            this.timeDelta = timeDelta;
668            timeOpers.setTimeDelta(timeDelta);
669          }
670
671          public void setTimeOperations(TimeOperations timeOpers) {
672                  this.timeOpers = timeOpers;
673          }
674         
675          public boolean prolongReservation(String reservID, DateTime newEndTime, ResourceUnit resAvail) throws Exception {
676           
677            ReservationNew reserv = getReservation(reservID);
678            if (reserv == null)
679              return false;
680           
681            TimeResourceAllocation s = reserv;
682            if (s == null)
683              return false;   
684           
685            ResourceUnit resource = s.getAllocatedResource().getResourceUnit(ResourceParameterName.CPUCOUNT);
686            if (resource == null)
687              return false;   
688           
689            if (newEndTime.getMillis() <= s.getEnd().getMillis()){
690                s.setEnd(newEndTime);
691                return true;     
692            }
693           
694            TimeResourceAllocation[] slots = resourceUsage(resource, s.getEnd(), newEndTime);
695           
696            if (slots == null) {
697              s.setEnd(newEndTime);
698              return true;
699            }
700           
701            for (int i=0; i < slots.length; i++) {
702              ResourceUnit res = slots[i].getAllocatedResource().getResourceUnit(ResourceParameterName.CPUCOUNT);     
703              if (res.getAmount() + resource.getAmount() > resAvail.getAmount())//not enough resources
704                return false;
705            }
706               
707            s.setEnd(newEndTime);
708            return true;
709          }
710
711          /**
712           * Creates a list of time slots with usage of given resource type
713           * Slots reflect time periods within which resource usage is constant
714           * @param resourceUnit only two parameters of this object are used, type - which should be
715           * the same type handled by this particular ReservationManager and resource id. Unit amount
716           * is not used by this method, therefore this value may be set to 0 or null.
717           * @param startTime begin of the time period within which resource usage should be calculated
718           * @param endTime end of the time period within which resource usage should be calculated
719           * @return list of time slots with various resource usage
720           * @throws NoSuchFieldException
721           */
722          public ArrayList<TimeResourceAllocation> resourceUsageList(ResourceUnit resourceUnit, DateTime startTime, DateTime endTime)
723                                                                                                                                throws NoSuchFieldException {
724                 
725                String rmc = resourceUnit.getResourceId();
726           
727            //Create a list of slots based on existing reservations that haven't been completed
728            ArrayList<TimeResourceAllocation> v = new ArrayList<TimeResourceAllocation>();
729           
730            for (int i=0; i < reservationList.size(); i++) {
731               
732                ReservationNew r =(ReservationNew)reservationList.get(i);
733                if (r == null)
734                        continue;
735               
736                if (r.getStatus() != ReservationNew.Status.INITIAL &&
737                        r.getStatus() != ReservationNew.Status.COMMITTED &&
738                        r.getStatus() != ReservationNew.Status.ACTIVE)
739                        continue;
740               
741                if(!rmc.equals(r.getResourceName()))
742                  continue;
743
744                TimeResourceAllocation orgSlot = r;
745                if (orgSlot == null)
746                  continue;
747               
748          //       sprawdzic jak to sie zachowa gdy rezerwacje przyjda dla ResUnit typu continous
749                TimeResourceAllocation reserverdSlot = new TimeResourceAllocation(
750                                                                                                (ResourceDescription)orgSlot.getAllocatedResource().clone(),
751                                                                                                orgSlot.getStart(),
752                                                                                                orgSlot.getEnd());
753               
754                // reserved slot ends before requested period starts
755                if (reserverdSlot.getEnd().getMillis() <= startTime.getMillis())
756                  continue;
757
758                // reserved slot starts after requested period ends
759                if (reserverdSlot.getStart().getMillis() >= endTime.getMillis())
760                  break;
761               
762                //slot partially before requested period
763                if (reserverdSlot.getStart().isBefore(startTime)){
764                    reserverdSlot = new TimeResourceAllocation(reserverdSlot);
765                        reserverdSlot.setStart(startTime);
766                }
767               
768                // first reserved slot starts after begin of the requested time period, which means that
769                // resource between start time of requested time period and start time of first reservation
770                // is not used.
771                if (v.size() == 0)
772                        if (reserverdSlot.getStart().isAfter(startTime)) {
773                                ResourceUnit ru = (ResourceUnit)resourceUnit.clone();
774                                ru.reset();
775                                ResourceStateDescription rd = new ResourceStateDescription(this.resourceProvider);
776                                rd.addResourceUnit(ru);
777                                v.add(new TimeResourceAllocation(rd, startTime, reserverdSlot.getStart()));
778
779                        }
780               
781                //slot partially after requested period
782                TimeResourceAllocation oldSlot;
783                if (reserverdSlot.getEnd().isAfter(endTime)) {
784                        oldSlot = reserverdSlot;
785                    reserverdSlot = new TimeResourceAllocation(oldSlot);
786                        reserverdSlot.setEnd(endTime);
787                }
788
789                v.add(reserverdSlot);
790            }
791               
792            //if there is no resource usage in the requested period
793            if (v.size() == 0) {
794                ResourceUnit ru = (ResourceUnit) resourceUnit.clone();
795                ru.reset();
796                ResourceStateDescription rd = new ResourceStateDescription(this.resourceProvider);
797                rd.addResourceUnit(ru);
798                v.add(new TimeResourceAllocation(rd, startTime, endTime));
799            }
800            else { //last slot ends before end of the requested period
801                TimeResourceAllocation slot = (TimeResourceAllocation)v.get(v.size() - 1); //last slot
802                if (slot.getEnd().isBefore(endTime)) {
803                        ResourceUnit ru = (ResourceUnit) resourceUnit.clone();
804                        ru.reset();
805                        ResourceStateDescription rd = new ResourceStateDescription(this.resourceProvider);
806                        rd.addResourceUnit(ru);
807                        v.add(new TimeResourceAllocation(rd, slot.getEnd(), endTime));
808                }
809            }
810           
811            //Find gaps between slots and overlapping slots, and based on them generate additional slots 
812            int i = 0;
813            while (i < v.size()) {
814              TimeResourceAllocation previousSlot = (TimeResourceAllocation)v.get(i);
815
816              TimeResourceAllocation slot = (TimeResourceAllocation)v.get(i);
817             
818              if (i + 1 < v.size())
819                slot = (TimeResourceAllocation)v.get(i + 1);
820              else
821                break;
822
823              if(slot.getStart().compareTo(previousSlot.getEnd()) == 0) // one slot immediately after another
824                i++;
825              else if (slot.getStart().isAfter(previousSlot.getEnd())) { // there is a gap between two slots
826
827                ResourceUnit resUsage = (ResourceUnit) resourceUnit.clone();
828                resUsage.reset();
829
830                ResourceStateDescription rd = new ResourceStateDescription(this.resourceProvider);
831                rd.addResourceUnit(resUsage);
832                TimeResourceAllocation slot1 = new TimeResourceAllocation(rd, previousSlot.getEnd(), slot.getStart());
833                v.add(++i, slot1);
834               
835              } else {                                                                  // slots overlap (slot.getStartTime() < lastSlot.getEndTime())
836                DateTime start = previousSlot.getStart();
837                DateTime newStart = slot.getStart();
838                long lnewEnd = Math.min(previousSlot.getEnd().getMillis(),slot.getEnd().getMillis());
839                DateTime newEnd = new DateTime(lnewEnd);
840               
841                long lend = Math.max(previousSlot.getEnd().getMillis(),slot.getEnd().getMillis());
842                DateTime end = new DateTime(lend);
843               
844                ResourceDescription resUsage = (ResourceDescription) previousSlot.getAllocatedResource().clone();
845                TimeResourceAllocation slot1 = new TimeResourceAllocation(resUsage, start, newStart);
846
847                resUsage = (ResourceDescription) previousSlot.getAllocatedResource().clone();
848                // mark processors which are unavailable in slot.resourceUnit as unavailable also in resUsage.resourceUnit object.
849                // this should be a synonym for: previousSlot.getResourceUnit().getAmount()+slot.getResourceUnit().getAmount()
850                {
851                        ResourceUnit unit = resUsage.getResourceUnit(ResourceParameterName.CPUCOUNT);
852                        if(unit instanceof List){
853                                List<Processor> peResUsage = (List<Processor>) unit;
854                                ResourceUnit resUnit = slot.getAllocatedResource().getResourceUnit(ResourceParameterName.CPUCOUNT);
855                                if(resUnit instanceof List){
856                                        List<Processor> disResUnit = (List<Processor>) resUnit;
857                                       
858                                        for(int a = 0; a < disResUnit.size(); a++){
859                                                Processor p = disResUnit.get(a);
860                                                if(p.getStatus() ==  ResourceStatus.BUSY){
861                                                        peResUsage.get(a).setStatus(ResourceStatus.BUSY);
862                                                } else if(p.getStatus() == ResourceStatus.RESERVED){
863                                                        peResUsage.get(a).setStatus(ResourceStatus.RESERVED);
864                                                }
865                                        }
866                                } else {
867                                        log.warn("CHECK AND WERIFY IF THIS CODE IS CORRECT");
868                                        int cnt = Float.valueOf(resUnit.getAmount()).intValue();
869                                        for(int a = 0; a < peResUsage.size() && cnt > 0; a++){
870                                                if(peResUsage.get(a).getStatus() == ResourceStatus.FREE){
871                                                        peResUsage.get(a).setStatus(ResourceStatus.BUSY);
872                                                        cnt--;
873                                                }
874                                        }
875                                }
876               
877                        } else {
878                                ResourceUnit prevResUnit = previousSlot.getAllocatedResource().getResourceUnit(ResourceParameterName.CPUCOUNT);
879                                ResourceUnit resUnit = slot.getAllocatedResource().getResourceUnit(ResourceParameterName.CPUCOUNT);
880                                ResourceUnit usedUnit = resUsage.getResourceUnit(ResourceParameterName.CPUCOUNT);
881                                usedUnit.setUsedAmount(prevResUnit.getUsedAmount() + resUnit.getUsedAmount());
882                        }
883                }
884                TimeResourceAllocation slot2 = new TimeResourceAllocation(resUsage, newStart, newEnd);
885               
886                if (previousSlot.getEnd().isAfter(slot.getEnd())) {
887
888                        resUsage = (ResourceDescription) previousSlot.getAllocatedResource().clone();
889               
890                } else {
891
892                        resUsage = (ResourceDescription) slot.getAllocatedResource().clone();
893                }
894               
895                TimeResourceAllocation slot3 = new TimeResourceAllocation(resUsage, newEnd, end);
896               
897                if (newEnd.compareTo(end) != 0){
898                        int j=i+2;
899                        while ((j < v.size()) && (newEnd.isAfter(((TimeResourceAllocation)v.get(j)).getStart())))
900                                j++;
901                    v.add(j, slot3);
902                }
903                v.remove(previousSlot);
904                v.remove(slot);
905                if (start.compareTo(newStart) != 0) {
906                          v.add(i++, slot1);
907                          v.add(i, slot2);
908                    }
909                else {//equal start times of slots
910                       
911                        TimeResourceAllocation tra = null;
912                        float amount = -1;
913                        if (i > 0) {
914                                tra = (TimeResourceAllocation)v.get(i-1);
915                                amount = tra.getAllocatedResource().getResourceUnit(ResourceParameterName.CPUCOUNT).getUsedAmount();   
916                        }
917                               
918                        if (amount == slot2.getAllocatedResource().getResourceUnit(ResourceParameterName.CPUCOUNT).getUsedAmount()) { //two subsequent slots with equal resource usage
919                                tra.setEnd(slot2.getEnd()); //extend previous slot
920                                i--;
921                        }
922                        else
923                                v.add(i, slot2);
924                }//equal start times of slots
925              }
926            }
927
928            if (v.size() == 0){
929                if(log.isErrorEnabled())
930                                log.error(getClass().getName()+" resourceUsage() - end, v.size = 0");
931              return null;
932            }
933
934            return v;
935          }
936
937          /**
938           * Creates a list of time slots with usage of given resource type
939           * Slots reflect time periods within which resource usage is constant
940           * @return list of time slots with various resource usage
941         * @throws NoSuchFieldException
942           */
943          public TimeResourceAllocation[] resourceUsage(ResourceUnit resourceUnit, DateTime startTime, DateTime endTime) throws NoSuchFieldException {
944                 
945                  ArrayList<TimeResourceAllocation> al;
946                  al = resourceUsageList(resourceUnit, startTime, endTime);
947                 
948                  if (al == null)
949                          return null;
950                 
951                  TimeResourceAllocation[] slot = new TimeResourceAllocation[al.size()];
952                  slot = (TimeResourceAllocation[])al.toArray(slot);
953                  return slot;
954          }
955                 
956
957          /**
958           * Find first free slot for the selected host
959         * @throws NoSuchFieldException
960           */
961          public TimeResourceAllocation findFreeHostSlot(
962            ResourceUnit resReq,
963            long duration,
964            DateTime startSlot,
965            DateTime endSlot,
966            DateTime startPeriod,
967            DateTime endPeriod,
968            boolean[] weekDays,
969            ArrayList<DateTime> inclDates,
970            ArrayList<DateTime> exclDates,
971            ResourceUnit resource) throws NoSuchFieldException {
972
973            if (resource.getName() != resReq.getName())
974              return null;
975           
976            if (resReq.getAmount() > resource.getAmount())
977                return null;
978               
979/*          ResourceUnit resDest = new ResourceUnit(resource.getResourceId(),
980                                                                                        resource.getResUnitName(), resReq.getAmount());
981            resDest.setLocalInterfaceType(resource.getLocalInterfaceType());
982            resDest.setValues(resource.getValues());
983*/
984            ResourceUnit resDest = (ResourceUnit)resource.clone();
985           
986            DateTime currentTime = timeOpers.getTime();//Calendar.getInstance();
987            DateTime startTime = null; //timeOpers.getTime();//Calendar.getInstance();
988
989            //start from startPeriod
990            startTime = new DateTime(Math.max(startPeriod.getMillis(), currentTime.getMillis()));
991            if (startSlot != null)
992                if (timeOpers.beforePeriodDayTime(startTime, startSlot, endSlot))
993                        startTime = timeOpers.setDayTime(startTime, startSlot);
994
995            long startTimeLong = startTime.getMillis();
996
997            if ((startSlot != null) && (endSlot != null)) {
998                        long endSlotLong = endSlot.getMillis();
999                        if (endSlotLong < startSlot.getMillis()) {
1000                                endSlot = endSlot.plusHours(24);
1001                                endSlotLong = endSlot.getMillis();
1002                        }
1003                    //if task duration longer than slot length
1004                        if (duration + timeDelta > endSlotLong - startSlot.getMillis())
1005                                return null;
1006                }
1007           
1008                boolean inclDay = false;
1009            //check if there are not excluded weekdays
1010            if (inclDates == null) {
1011                for (int i=0; i < 7; i++)
1012                        if (weekDays[i] == true)
1013                                inclDay = true;
1014            }//check if there are included dates later than startPeriod
1015            else {
1016                for (int i=0; i < inclDates.size(); i++)
1017                        if (startPeriod.isBefore(inclDates.get(i)))
1018                                inclDay = true;
1019            }
1020                if (!inclDay)
1021                        return null;
1022           
1023            //start from startSlot
1024            while (!meetTimeRequirements(startTime, duration, startSlot, endSlot, weekDays, inclDates, exclDates, endPeriod)
1025                           && timeOpers.withinPeriod(duration, startTime, endPeriod)) {
1026                nextSlot(startTime, duration, startSlot, endSlot);
1027                startTimeLong = startTime.getMillis();
1028               }
1029
1030            //while still in period
1031            while (timeOpers.withinPeriod(duration, startTime, endPeriod)) {
1032
1033              DateTime startTimeCal = new DateTime(startTimeLong);
1034              DateTime endTimeCal = new DateTime(Long.MAX_VALUE);
1035             
1036              TimeResourceAllocation[] slot = resourceUsage(resource, startTimeCal, endTimeCal);
1037
1038              if (slot == null) {
1039                  startTimeCal = new DateTime(startTimeLong + timeDelta);
1040                  endTimeCal = new DateTime(startTimeLong + timeDelta + duration);
1041                  ResourceStateDescription rd = new ResourceStateDescription(this.resourceProvider);
1042                      rd.addResourceUnit(resDest);
1043                  return new TimeResourceAllocation(rd, startTimeCal, endTimeCal);
1044              }
1045
1046              for (int i = 0; i < slot.length; i++) {
1047                  float freeRes = 0;
1048                  ResourceUnit resUnit = slot[i].getAllocatedResource().getResourceUnit(ResourceParameterName.CPUCOUNT);
1049                  freeRes = resUnit.getFreeAmount();
1050                 
1051                if (startTimeLong + timeDelta + duration < slot[i].getStart().getMillis()) {
1052                        startTimeCal = new DateTime(startTimeLong + timeDelta);
1053                        endTimeCal = new DateTime(startTimeLong + timeDelta + duration);
1054                        ResourceStateDescription rd = new ResourceStateDescription(this.resourceProvider);
1055                            rd.addResourceUnit(resDest);
1056                  return new TimeResourceAllocation(rd, startTimeCal, endTimeCal);
1057                }
1058               // else if (resReq.getAmount() <= resource.getAmount() - slot[i].getResourceUnit(Constants.PE).getAmount()) {
1059                else if(resReq.getAmount() <= freeRes) {
1060                  if (startTimeLong + timeDelta + duration < slot[i].getEnd().getMillis() ||
1061                      i == slot.length - 1) {
1062                          startTimeCal = new DateTime(startTimeLong + timeDelta);
1063                          endTimeCal = new DateTime(startTimeLong + timeDelta + duration);
1064                          ResourceStateDescription rd = new ResourceStateDescription(this.resourceProvider);
1065                          rd.addResourceUnit(resDest);
1066                    return new TimeResourceAllocation(rd, startTimeCal, endTimeCal);
1067                  }
1068                } else {
1069                  startTimeLong = slot[i].getEnd().getMillis();
1070                  startTime = new DateTime(startTimeLong);
1071                }
1072
1073                //check if still in slot
1074                if (!timeOpers.withinPeriodDayTime(startTime, duration, startSlot, endSlot)) {
1075                  do {
1076                        nextSlot(startTime, duration, startSlot, endSlot);
1077                    startTimeLong = startTime.getMillis();
1078                  } while (!meetTimeRequirements(startTime, duration, startSlot, endSlot, weekDays, inclDates, exclDates, endPeriod)
1079                                   && timeOpers.withinPeriod(duration, startTime, endPeriod));
1080                  break;
1081                }
1082                //
1083               
1084                //check if still in period
1085                if (!timeOpers.withinPeriod(duration, startTime, endPeriod))
1086                  return null;
1087                //
1088              }
1089            }
1090
1091            return null;
1092          }
1093
1094          /**
1095                 * Simple findFreeSlot
1096                 *
1097                 * @param resReq
1098                 * @param duration
1099                 * @param startPeriod
1100                 * @param endPeriod
1101                 * @param resource
1102                 * @return
1103         * @throws NoSuchFieldException
1104                 */
1105        public TimeResourceAllocation findFreeSlot(ResourceUnit resReq, long duration, DateTime startPeriod, DateTime endPeriod, ResourceUnit resource) throws NoSuchFieldException {
1106
1107                if (resource.getName() != resReq.getName())
1108                        return null;
1109
1110                if (resReq.getAmount() > resource.getAmount())
1111                        return null;
1112
1113                ResourceUnit resDest = (ResourceUnit) resource.clone();
1114
1115                DateTime currentTime = timeOpers.getTime();
1116                DateTime startTime = null;
1117
1118                // start from startPeriod
1119                startTime = new DateTime(Math.max(startPeriod.getMillis(), currentTime.getMillis()));
1120
1121                long startTimeLong = startTime.getMillis();
1122                DateTime slotStart = timeOpers.getTime();
1123                DateTime slotEnd = timeOpers.getTime();
1124
1125                // get resource usage
1126                TimeResourceAllocation[] slot = resourceUsage(resource, startTime,
1127                                endPeriod);
1128
1129                // whole period free
1130                if (slot == null) {
1131                        slotStart = new DateTime(startTimeLong + timeDelta);
1132                        slotEnd = new DateTime(startTimeLong + timeDelta + duration);
1133                        ResourceStateDescription rd = new ResourceStateDescription(this.resourceProvider);
1134                        rd.addResourceUnit(resDest);
1135                        return new TimeResourceAllocation(rd, slotStart, slotEnd);
1136                }
1137
1138                int startSlot = 0; //binarySearch(startTime, slot);
1139               
1140                // otherwise browse slots
1141                for (int i = startSlot; i < slot.length; i++) {
1142                        float freeRes = 0;
1143                        ResourceUnit resUnit = slot[i].getAllocatedResource().getResourceUnit(ResourceParameterName.CPUCOUNT);
1144                        freeRes = resource.getAmount() - resUnit.getUsedAmount();
1145
1146                        // if requested slot can be reserved before start of the first slot from resource usage (TODO: is it possible - to look at resourceUsage)
1147                        if (startTimeLong + timeDelta + duration < slot[i].getStart().getMillis()) {
1148                                slotStart = new DateTime(startTimeLong + timeDelta);
1149                                slotEnd = new DateTime(startTimeLong + timeDelta + duration);
1150                                ResourceStateDescription rd = new ResourceStateDescription(this.resourceProvider);
1151                                rd.addResourceUnit(resDest);
1152                                return new TimeResourceAllocation(rd, slotStart, slotEnd);
1153                        } // otherwise if there are enough resources in the current slot
1154                        else if (resReq.getAmount() <= freeRes) {
1155                                if (startTimeLong + timeDelta + duration < slot[i].getEnd().getMillis() || i == slot.length - 1) {
1156                                        slotStart = new DateTime(startTimeLong + timeDelta);
1157                                        slotEnd = new DateTime(startTimeLong + timeDelta + duration);
1158                                        ResourceStateDescription rd = new ResourceStateDescription(this.resourceProvider);
1159                                        rd.addResourceUnit(resDest);
1160                                        return new TimeResourceAllocation(rd, slotStart, slotEnd);
1161                                }
1162                        } else {
1163                                startTimeLong = slot[i].getEnd().getMillis();
1164                                startTime = new DateTime(startTimeLong);
1165                        }
1166
1167                        // check if still in period
1168                        if (!timeOpers.withinPeriod(duration, startTime, endPeriod))
1169                                return null;
1170                }
1171
1172                return null;
1173        }
1174
1175        /**
1176         *
1177         * @param time
1178         * @param startPeriod
1179         * @param endPeriod
1180         * @return number of slot
1181         */
1182        public int binarySearch(DateTime time, TimeResourceAllocation[] tra) {
1183               
1184                if (tra == null)
1185                        return -1;
1186               
1187                int start = 0;
1188                int end = tra.length - 1;
1189               
1190                int slotNumber = -1;
1191                int pos = 0;
1192               
1193                while (slotNumber < 0) {
1194               
1195                        pos = (end - start) / 2;
1196                       
1197                        if (pos == 0) {
1198                                slotNumber = 0;
1199                                break;
1200                        }
1201               
1202                        if (time.isBefore(tra[pos].getStart()))
1203                                end = pos - 1;
1204                        else
1205                                if (time.isAfter(tra[pos].getEnd()))
1206                                        start = pos + 1;
1207                                else
1208                                        if (time.isBefore(tra[pos - 1].getEnd()))
1209                                                end = pos - 1;
1210                                        else
1211                                                slotNumber = pos;
1212                }
1213               
1214                return slotNumber;
1215        }
1216         
1217          protected boolean meetTimeRequirements(
1218            DateTime startTime,
1219            long duration,
1220            DateTime startSlot,
1221            DateTime endSlot,
1222            boolean[] weekDays,
1223            ArrayList<DateTime> inclDates,
1224            ArrayList<DateTime> exclDates,
1225            DateTime endPeriod) {
1226
1227            if (!timeOpers.withinPeriodDayTime(startTime, duration, startSlot, endSlot))
1228              return false;
1229           
1230            //date not included
1231            if (inclDates != null) {
1232                if (!timeOpers.findDate(startTime, inclDates) &&
1233                        !weekDays[startTime.getDayOfWeek() - 1])
1234                      return false;
1235            }
1236            else
1237            //weekday not included or excluded
1238            if (!weekDays[startTime.getDayOfWeek() - 1])
1239               return false;   
1240           
1241            //date exluded
1242            if (timeOpers.findDate(startTime, exclDates))
1243              return false;
1244
1245            //deadline (endPeriod) exceeded
1246            if (!timeOpers.withinPeriod(duration, startTime, endPeriod))
1247              return false;
1248
1249            return true;
1250          }
1251
1252          /**
1253           * Checks whether slot beginning at startTime and ending at startTime + duration
1254           * meets time requirements.
1255           * @param startTime
1256           * @param duration
1257           * @param reqDuration
1258           * @param startSlot
1259           * @param endSlot
1260           * @param weekDays
1261           * @param inclDates
1262           * @param exclDates
1263           * @param startPeriod
1264           * @param endPeriod
1265           * @return 0 if slot meets all requirements; 1 if slot meets all requirements but is too short; -1 otherwise
1266           */
1267          protected int fitTimeSlot(DateTime startTime, long duration,
1268                                long reqDuration, DateTime startSlot, DateTime endSlot, boolean[] weekDays,
1269                                ArrayList<DateTime> inclDates, ArrayList<DateTime> exclDates, DateTime startPeriod, DateTime endPeriod) {
1270
1271                    // slot end before start of the requested period
1272                        if (startTime.getMillis() + duration <= startPeriod.getMillis())
1273                        return -1;
1274                 
1275                        // deadline (endPeriod) exceeded
1276                        //if (!timeOpers.withinPeriod(duration, startTime, endPeriod))
1277                        if (startTime.getMillis() >= endPeriod.getMillis())
1278                                return -1;
1279
1280                        if (!timeOpers.overlapPeriodDayTime(startTime, duration, startSlot,
1281                                        endSlot))
1282                                return -1;
1283
1284                        // date not included
1285                        if (inclDates != null) {
1286                                if (!timeOpers.findDate(startTime, inclDates)
1287                                                && !weekDays[startTime.getDayOfWeek() - 1])
1288                                        return -1;
1289                        } else
1290                        // weekday not included or excluded
1291                        if (!weekDays[startTime.getDayOfWeek() - 1])
1292                                return -1;
1293
1294                        // date exluded
1295                        if (timeOpers.findDate(startTime, exclDates))
1296                                return -1;
1297                       
1298                        //calculate new duration
1299                        if (startTime.getMillis() + duration > endPeriod.getMillis())
1300                                duration = endPeriod.getMillis() - startTime.getMillis();
1301                        if (timeOpers.afterDayTime(startTime, duration, endSlot)) {
1302                                DateTime newEndTime = new DateTime(startTime.getMillis() + duration);
1303                                newEndTime = timeOpers.setDayTime(newEndTime, endSlot);
1304                                duration = newEndTime.getMillis() - startTime.getMillis();
1305                        }
1306                       
1307                        //slot is too short
1308                        if (reqDuration > duration)
1309                                return 1;
1310
1311                        return 0;
1312                }
1313         
1314          /**
1315           * Checks whether a reservation meeting time requirements within a given slot is possible.
1316           * @param slot
1317           * @param time
1318           * @return 0 if slot meets all requirements; 1 if slot meets all requirements but is too short; -1 otherwise
1319           */
1320          public int fitTimeSlot(TimeResourceAllocation slot, ExecutionTimeType time) {
1321
1322                      if (time == null)
1323                        return 0;
1324                   
1325                      //start of period
1326                      DateTime startPeriod = timeOpers.getTime();//Calendar.getInstance();
1327                      if (time.getTimePeriod() != null)
1328                        if (time.getTimePeriod().getPeriodStart() != null)
1329                          startPeriod = new DateTime(time.getTimePeriod().getPeriodStart().getTime());
1330
1331                      //end of period
1332                      DateTime endPeriod = new DateTime(Long.MAX_VALUE);
1333                      if (time.getTimePeriod() != null)
1334                        if (time.getTimePeriod().getTimePeriodChoice() != null)
1335                          if (time.getTimePeriod().getTimePeriodChoice().getPeriodEnd() != null) {
1336                            endPeriod = new DateTime(time.getTimePeriod().getTimePeriodChoice().getPeriodEnd().getTime());
1337                          }
1338                          else if (time.getTimePeriod().getTimePeriodChoice().getPeriodDuration() != null)
1339                            endPeriod = new DateTime(startPeriod.getMillis() + time.getTimePeriod().getTimePeriodChoice().getPeriodDuration().toLong());         
1340
1341                      //days of the week
1342                      boolean[] weekDays = new boolean[7];
1343                      ArrayList<DateTime> inclDates = null;
1344                      ArrayList<DateTime> exclDates = null;
1345                     
1346                      //all weekdays allowed
1347                      for (int i=0; i < 7; i++)
1348                          weekDays[i] = true;
1349                               
1350                      if (time.getTimePeriod() != null) {
1351                       
1352                        if (time.getTimePeriod().getIncluding() != null) {
1353
1354                                //only weekdays defined in Including element allowed
1355                            for (int i=0; i < 7; i++)
1356                              weekDays[i] = false;
1357                         
1358                          for (int i=0; i < time.getTimePeriod().getIncluding().getDaysTypeItemCount(); i++) {
1359                            if (time.getTimePeriod().getIncluding().getDaysTypeItem(i).getWeekDay() != null) {
1360                              int day = time.getTimePeriod().getIncluding().getDaysTypeItem(i).getWeekDay().ordinal();
1361                              weekDays[(day+1)%7] = true;
1362                            }
1363                            else {
1364                                org.exolab.castor.types.Date dateDay = time.getTimePeriod().getIncluding().getDaysTypeItem(i).getDateDay();
1365                              if (dateDay != null) {
1366                                if (inclDates == null)
1367                                  inclDates = new ArrayList<DateTime>();
1368                                inclDates.add(new DateTime(dateDay.toLong()));
1369                              }
1370                            }
1371                          }
1372                        }
1373                        if (time.getTimePeriod().getExcluding() != null) {
1374                          for (int i=0; i < time.getTimePeriod().getExcluding().getDaysTypeItemCount(); i++) {
1375                            if (time.getTimePeriod().getExcluding().getDaysTypeItem(i).getWeekDay() != null) {
1376                              int day = time.getTimePeriod().getExcluding().getDaysTypeItem(i).getWeekDay().ordinal();
1377                              weekDays[(day+1)%7] = false;
1378                            }
1379                            else {
1380                                org.exolab.castor.types.Date dateDay = time.getTimePeriod().getExcluding().getDaysTypeItem(i).getDateDay();
1381                              if (time.getTimePeriod().getExcluding().getDaysTypeItem(i).getDateDay() != null) {
1382                                if (exclDates == null)
1383                                  exclDates = new ArrayList<DateTime>();
1384                                exclDates.add(new DateTime(dateDay.toLong()));
1385                              }
1386                            }
1387                          }
1388                        }
1389                        //find latest possible date
1390                        DateTime latestDate = timeOpers.findLatestDate(inclDates, exclDates);
1391                        if (timeOpers.beforeDate(latestDate, endPeriod)) {
1392                          endPeriod = timeOpers.setDate(endPeriod, latestDate);
1393                          endPeriod = endPeriod.plusDays(1); //(Calendar.DAY_OF_MONTH, endPeriod.getDayOfMonth() + 1);
1394                        }
1395                      }
1396
1397                      //start of time slot
1398                      DateTime startSlot = null;
1399                      DateTime endSlot = null;
1400                      if (time.getTimeSlot() != null) {
1401                        if (time.getTimeSlot().getSlotStart() != null){
1402                                startSlot = new DateTime(time.getTimeSlot().getSlotStart().
1403                                                getContent().toDate().getTime());
1404                        }
1405                        //end of time slot 
1406                        if (time.getTimeSlot().getTimeSlotChoice() != null)
1407                                if (time.getTimeSlot().getTimeSlotChoice().getSlotEnd() != null){
1408                                        endSlot = new DateTime(time.getTimeSlot().getTimeSlotChoice().
1409                                                        getSlotEnd().toDate().getTime());
1410                                }
1411                                else
1412                                        if (time.getTimeSlot().getTimeSlotChoice().getSlotDuration() != null){
1413                                                endSlot = new DateTime(time.getTimeSlot().getTimeSlotChoice().
1414                                                                getSlotDuration().toLong());
1415                                        }
1416                      }
1417                         
1418                   
1419                   long lTime = Math.max(slot.getStartMillis(), startPeriod.getMillis());
1420                   DateTime startTime = new DateTime(lTime);
1421                   
1422                   if (startSlot != null)
1423                           if (timeOpers.beforeDayTime(startTime, startSlot))
1424                                   timeOpers.setDayTime(startTime, startSlot); // sets startTime at the beginning of the required daytime window
1425
1426                   //duration
1427                   long duration = time.getExecutionDuration().toLong();
1428                   
1429                   return fitTimeSlot(startTime, slot.getEnd().getMillis() - startTime.getMillis(),
1430                                                                duration, startSlot, endSlot, weekDays, inclDates, exclDates, startPeriod, endPeriod); 
1431          }
1432         
1433         
1434          /**
1435                 * Change given time to the start time of the next available slot.
1436                 *
1437                 * @param time -
1438                 *            time to be changed
1439                 * @param duration -
1440                 *            duration of a period to be checked
1441                 * @param start -
1442                 *            start time of a slot
1443                 * @param end -
1444                 *            end time of a slot
1445                 * @return new time
1446                 */
1447          protected DateTime nextSlot(DateTime time, long duration, DateTime start, DateTime end) {
1448
1449                if (time == null)
1450                        return null;
1451               
1452                if (start == null || end == null) {
1453                        time = time.plusDays(1);//(Calendar.DAY_OF_MONTH, 1);
1454                        return time;
1455                }
1456               
1457                //if within slot move to next day
1458                if (timeOpers.withinPeriodDayTime(time, duration, start, end))
1459                        time = time.plusDays(1); //(Calendar.DAY_OF_MONTH, 1);
1460                else //if not check when is start of the next slot
1461                if (timeOpers.beforeDayTime(start, end) && !timeOpers.beforeDayTime(time, start))
1462                        time = time.plusDays(1); //(Calendar.DAY_OF_MONTH, 1);
1463
1464                //set time to start time of the slot
1465                timeOpers.setDayTime(time, start);
1466               
1467                return time;
1468          }
1469
1470        public ReservationListNew getReservations() {
1471                return reservationList;
1472        }
1473         
1474         /**
1475           * Creates a list of time slots with usage of given resource type(including tasks
1476           * running without reservation)
1477           * Slots reflect time periods within which resource usage is constant
1478           * @param resourceUnit only two parameters of this object are used, type - which should be
1479           * the same type handled by this particular ReservationManager and resource id. Unit amount
1480           * is not used by this method, therefore this value may be set to 0 or null.
1481           * @param inExecution list of tasks which are currently running
1482           * @param startTime begin of the time period within which resource usage should be calculated
1483           * @param endTime end of the time period within which resource usage should be calculated
1484           * @return list of time slots with various resource usage
1485           * @throws NoSuchFieldException
1486           */
1487          public ArrayList<TimeResourceAllocation> resourceUsageList(ResourceUnit resourceUnit, List<? extends TaskInterface<?>> inExecution, DateTime startTime, DateTime endTime)
1488                                                                                                                                throws NoSuchFieldException {
1489                 
1490                String rmc = resourceUnit.getResourceId();
1491           
1492            //Create a list of slots based on existing reservations that haven't been completed
1493            ArrayList<TimeResourceAllocation> v = new ArrayList<TimeResourceAllocation>();
1494           
1495            for (int i=0; i < reservationList.size(); i++) {
1496               
1497                ReservationNew r =(ReservationNew)reservationList.get(i);
1498                if (r == null)
1499                        continue;
1500               
1501                if (r.getStatus() != ReservationNew.Status.INITIAL &&
1502                        r.getStatus() != ReservationNew.Status.COMMITTED &&
1503                        r.getStatus() != ReservationNew.Status.ACTIVE)
1504                        continue;
1505               
1506                if(!rmc.equals(r.getResourceName()))
1507                  continue;
1508
1509                TimeResourceAllocation orgSlot = r;
1510                if (orgSlot == null)
1511                  continue;
1512               
1513          //       sprawdzic jak to sie zachowa gdy rezerwacje przyjda dla ResUnit typu continous
1514                TimeResourceAllocation reserverdSlot = new TimeResourceAllocation(
1515                                                                                                (ResourceDescription)orgSlot.getAllocatedResource().clone(),
1516                                                                                                orgSlot.getStart(),
1517                                                                                                orgSlot.getEnd());
1518               
1519                // reserved slot ends before requested period starts
1520                if (reserverdSlot.getEnd().getMillis() <= startTime.getMillis())
1521                  continue;
1522
1523                // reserved slot starts after requested period ends
1524                if (reserverdSlot.getStart().getMillis() >= endTime.getMillis())
1525                  break;
1526               
1527                //slot partially before requested period
1528                if (reserverdSlot.getStart().isBefore(startTime)){
1529                    reserverdSlot = new TimeResourceAllocation(reserverdSlot);
1530                        reserverdSlot.setStart(startTime);
1531                }
1532               
1533                // first reserved slot starts after begin of the requested time period, which means that
1534                // resource between start time of requested time period and start time of first reservation
1535                // is not used.
1536                if (v.size() == 0)
1537                        if (reserverdSlot.getStart().isAfter(startTime)) {
1538                                ResourceUnit ru = (ResourceUnit)resourceUnit.clone();
1539                                ru.reset();
1540                                ResourceStateDescription rd = new ResourceStateDescription(this.resourceProvider);
1541                                rd.addResourceUnit(ru);
1542                                v.add(new TimeResourceAllocation(rd, startTime, reserverdSlot.getStart()));
1543
1544                        }
1545               
1546                //slot partially after requested period
1547                TimeResourceAllocation oldSlot;
1548                if (reserverdSlot.getEnd().isAfter(endTime)) {
1549                        oldSlot = reserverdSlot;
1550                    reserverdSlot = new TimeResourceAllocation(oldSlot);
1551                        reserverdSlot.setEnd(endTime);
1552                }
1553
1554                v.add(reserverdSlot);
1555            }
1556            InExecuionList inExec = (InExecuionList)inExecution;
1557            ArrayList<TimeResourceAllocation> v2 = inExec.nonARTasksResourceUsageList(resourceUnit, startTime, endTime);
1558           
1559            ArrayList<TimeResourceAllocation> tempv = new ArrayList<TimeResourceAllocation>();
1560            tempv.addAll(v);
1561            tempv.addAll(v2);
1562               
1563            TimeResourceAllocation[] traTable = new TimeResourceAllocation[tempv.size()];
1564        int k = 0;
1565        for(TimeResourceAllocation task: tempv){
1566                traTable[k] = task;
1567                k++;
1568        }
1569       
1570        MergeSort<TimeResourceAllocation> mergeSort = new MergeSort<TimeResourceAllocation>();
1571        mergeSort.initSort(traTable, "getStartMillis", true);
1572       
1573        v.clear();
1574        for(int i = 0; i < traTable.length; i++){
1575                v.add(traTable[i]);
1576        }
1577           
1578            //if there is no resource usage in the requested period
1579            if (v.size() == 0) {
1580                ResourceUnit ru = (ResourceUnit) resourceUnit.clone();
1581                ru.reset();
1582                ResourceStateDescription rd = new ResourceStateDescription(this.resourceProvider);
1583                rd.addResourceUnit(ru);
1584                v.add(new TimeResourceAllocation(rd, startTime, endTime));
1585            }
1586            else { //last slot ends before end of the requested period
1587                TimeResourceAllocation slot = (TimeResourceAllocation)v.get(v.size() - 1); //last slot
1588                if (slot.getEnd().isBefore(endTime)) {
1589                        ResourceUnit ru = (ResourceUnit) resourceUnit.clone();
1590                        ru.reset();
1591                        ResourceStateDescription rd = new ResourceStateDescription(this.resourceProvider);
1592                        rd.addResourceUnit(ru);
1593                        v.add(new TimeResourceAllocation(rd, slot.getEnd(), endTime));
1594                }
1595            }
1596           
1597            //Find gaps between slots and overlapping slots, and based on them generate additional slots 
1598            int i = 0;
1599            while (i < v.size()) {
1600              TimeResourceAllocation previousSlot = (TimeResourceAllocation)v.get(i);
1601
1602              TimeResourceAllocation slot = (TimeResourceAllocation)v.get(i);
1603             
1604              if (i + 1 < v.size())
1605                slot = (TimeResourceAllocation)v.get(i + 1);
1606              else
1607                break;
1608
1609              if(slot.getStart().compareTo(previousSlot.getEnd()) == 0) // one slot immediately after another
1610                i++;
1611              else if (slot.getStart().isAfter(previousSlot.getEnd())) { // there is a gap between two slots
1612
1613                ResourceUnit resUsage = (ResourceUnit) resourceUnit.clone();
1614                resUsage.reset();
1615
1616                ResourceStateDescription rd = new ResourceStateDescription(this.resourceProvider);
1617                rd.addResourceUnit(resUsage);
1618                TimeResourceAllocation slot1 = new TimeResourceAllocation(rd, previousSlot.getEnd(), slot.getStart());
1619                v.add(++i, slot1);
1620               
1621              } else {                                                                  // slots overlap (slot.getStartTime() < lastSlot.getEndTime())
1622                DateTime start = previousSlot.getStart();
1623                DateTime newStart = slot.getStart();
1624                long lnewEnd = Math.min(previousSlot.getEnd().getMillis(),slot.getEnd().getMillis());
1625                DateTime newEnd = new DateTime(lnewEnd);
1626               
1627                long lend = Math.max(previousSlot.getEnd().getMillis(),slot.getEnd().getMillis());
1628                DateTime end = new DateTime(lend);
1629               
1630                ResourceDescription resUsage = (ResourceDescription) previousSlot.getAllocatedResource().clone();
1631                TimeResourceAllocation slot1 = new TimeResourceAllocation(resUsage, start, newStart);
1632
1633                resUsage = (ResourceDescription) previousSlot.getAllocatedResource().clone();
1634                // mark processors which are unavailable in slot.resourceUnit as unavailable also in resUsage.resourceUnit object.
1635                // this should be a synonym for: previousSlot.getResourceUnit().getAmount()+slot.getResourceUnit().getAmount()
1636                {
1637                        ResourceUnit unit = resUsage.getResourceUnit(ResourceParameterName.CPUCOUNT);
1638                        if(unit instanceof List){
1639                                List<Processor> peResUsage = (List<Processor>) unit;
1640                                ResourceUnit resUnit = slot.getAllocatedResource().getResourceUnit(ResourceParameterName.CPUCOUNT);
1641                                if(resUnit instanceof List){
1642                                        List<Processor> disResUnit = (List<Processor>) resUnit;
1643                                       
1644                                        for(int a = 0; a < disResUnit.size(); a++){
1645                                                Processor p = disResUnit.get(a);
1646                                                if(p.getStatus() == ResourceStatus.BUSY){
1647                                                        peResUsage.get(a).setStatus(ResourceStatus.BUSY);
1648                                                } else if(p.getStatus() == ResourceStatus.RESERVED){
1649                                                        peResUsage.get(a).setStatus(ResourceStatus.RESERVED);
1650                                                }
1651                                        }
1652                                } else {
1653                                        log.warn("CHECK AND WERIFY IF THIS CODE IS CORRECT");
1654                                        int cnt = Float.valueOf(resUnit.getAmount()).intValue();
1655                                        for(int a = 0; a < peResUsage.size() && cnt > 0; a++){
1656                                                if(peResUsage.get(a).getStatus() == ResourceStatus.FREE){
1657                                                        peResUsage.get(a).setStatus(ResourceStatus.BUSY);
1658                                                        cnt--;
1659                                                }
1660                                        }
1661                                }
1662               
1663                        } else {
1664                                ResourceUnit prevResUnit = previousSlot.getAllocatedResource().getResourceUnit(ResourceParameterName.CPUCOUNT);
1665                                ResourceUnit resUnit = slot.getAllocatedResource().getResourceUnit(ResourceParameterName.CPUCOUNT);
1666                                ResourceUnit usedUnit = resUsage.getResourceUnit(ResourceParameterName.CPUCOUNT);
1667                                usedUnit.setUsedAmount(prevResUnit.getUsedAmount() + resUnit.getUsedAmount());
1668                        }
1669                }
1670                TimeResourceAllocation slot2 = new TimeResourceAllocation(resUsage, newStart, newEnd);
1671               
1672                if (previousSlot.getEnd().isAfter(slot.getEnd())) {
1673
1674                        resUsage = (ResourceDescription) previousSlot.getAllocatedResource().clone();
1675               
1676                } else {
1677
1678                        resUsage = (ResourceDescription) slot.getAllocatedResource().clone();
1679                }
1680               
1681                TimeResourceAllocation slot3 = new TimeResourceAllocation(resUsage, newEnd, end);
1682               
1683                if (newEnd.compareTo(end) != 0){
1684                        int j=i+2;
1685                        while ((j < v.size()) && (newEnd.isAfter(((TimeResourceAllocation)v.get(j)).getStart())))
1686                                j++;
1687                    v.add(j, slot3);
1688                }
1689                v.remove(previousSlot);
1690                v.remove(slot);
1691                if (start.compareTo(newStart) != 0) {
1692                          v.add(i++, slot1);
1693                          v.add(i, slot2);
1694                    }
1695                else {//equal start times of slots
1696                       
1697                        TimeResourceAllocation tra = null;
1698                        float amount = -1;
1699                        if (i > 0) {
1700                                tra = (TimeResourceAllocation)v.get(i-1);
1701                                amount = tra.getAllocatedResource().getResourceUnit(ResourceParameterName.CPUCOUNT).getUsedAmount();   
1702                        }
1703                               
1704                        if (amount == slot2.getAllocatedResource().getResourceUnit(ResourceParameterName.CPUCOUNT).getUsedAmount()) { //two subsequent slots with equal resource usage
1705                                tra.setEnd(slot2.getEnd()); //extend previous slot
1706                                i--;
1707                        }
1708                        else
1709                                v.add(i, slot2);
1710                }//equal start times of slots
1711              }
1712            }
1713
1714            if (v.size() == 0){
1715                if(log.isErrorEnabled())
1716                                log.error(getClass().getName()+" resourceUsage() - end, v.size = 0");
1717              return null;
1718            }
1719
1720            return v;
1721          }
1722
1723        @Override
1724        public void init(Properties properties) throws ModuleException {
1725                // TODO Auto-generated method stub
1726               
1727        }
1728
1729        @Override
1730        public void dispose() throws ModuleException {
1731                // TODO Auto-generated method stub
1732               
1733        }
1734
1735        @Override
1736        public ModuleType getType() {
1737                return ModuleType.LOCAL_RESERVATION_MANAGER;
1738        }
1739       
1740       
1741       
1742       
1743       
1744        /*********************************/
1745       
1746       
1747       
1748       
1749       
1750       
1751        public void cancelReservation(ReservationNew reservation,
1752                        List<? extends GSSIMJobInterface<?>> inExecution,
1753                                        List<? extends Queue<? extends GSSIMJobInterface<?>>> queues)
1754                        throws ReservationException {
1755                // This method is not used in example configuration.
1756        }
1757
1758        public ReservationNew commitReservation(ReservationNew initialReservation,
1759                        List<? extends GSSIMJobInterface<?>> inExecution,
1760                                        List<? extends Queue<? extends GSSIMJobInterface<?>>> queues,
1761                        ResourceManagerInterface unitsManager)
1762                        throws ReservationException {
1763               
1764                // this simple implementation changes status of the reservation
1765                // from INITIAL to COMMITED
1766               
1767                // list of reservations is managed by reservation manager
1768                List<ReservationNew> list = getReservations();
1769               
1770                for(int i = 0; i < list.size(); i++){
1771                        ReservationNew r = list.get(i);
1772
1773                        // find correct reservation in reservations list
1774                        if(initialReservation.getId().equals(r.getId())){
1775                       
1776                                // change status to COMMITED
1777                                r.setStatus(ReservationNew.Status.COMMITTED);
1778                               
1779                                // set job and task id on behalf which this reservation is
1780                                // created. This is mostly for debugging purpose.
1781                                r.setJobId(initialReservation.getJobId());
1782                                r.setTaskId(initialReservation.getTaskId());
1783                               
1784                                // change status of initial reservation to COMMITED.
1785                                // This allows grid plugin to notice, that reservation is
1786                                // successfully committed.
1787                                initialReservation.setStatus(ReservationNew.Status.COMMITTED);
1788                                return initialReservation;
1789                        }
1790                }
1791               
1792                return null;
1793        }
1794
1795        public ReservationNew commitReservation(ReservationNew initialReservation,
1796                        TimeResourceAllocation resourceUsage,
1797                        List<? extends GSSIMJobInterface<?>> inExecution,
1798                                        List<? extends Queue<? extends GSSIMJobInterface<?>>> queues,
1799                        ResourceManagerInterface unitsManager)
1800                        throws ReservationException {
1801                // This method is not used in example configuration.
1802                return null;
1803        }
1804
1805        public List<ReservationNew> createReservation(ResourceUsage resourceUsage,
1806                        List<? extends GSSIMJobInterface<?>> inExecution,
1807                                        List<? extends Queue<? extends GSSIMJobInterface<?>>> queues,
1808                                                        ResourceManagerInterface unitsManager)
1809                        throws ReservationException {
1810               
1811                TimeResourceAllocation allocation = resourceUsage.get(0);
1812               
1813                ReservationNew reservation =
1814                                                                        getReservations().add(allocation, ReservationNew.Status.INITIAL);
1815                List<ReservationNew> list = new ArrayList<ReservationNew>(1);
1816                list.add(reservation);
1817               
1818                return list;
1819        }
1820
1821        public ReservationNew createReservation(
1822                        AbstractTimeRequirements<?> timeRequirements,
1823                        AbstractResourceRequirements<?> resourceRequirements,
1824                        List<? extends GSSIMJobInterface<?>> inExecution,
1825                                        List<? extends Queue<? extends GSSIMJobInterface<?>>> queues,
1826                        ResourceManagerInterface unitsManager)
1827                        throws ReservationException {
1828                // This method is not used in example configuration.
1829                return null;
1830        }
1831
1832
1833        public Status getStatus(ReservationNew reservation)
1834                        throws ReservationException {
1835                // This method is not used in example configuration.
1836                return null;
1837        }
1838
1839        public ReservationNew modifyReservation(ReservationNew reservation,
1840                        TimeResourceAllocation resourceUsage,
1841                        List<? extends GSSIMJobInterface<?>> inExecution,
1842                                        List<? extends Queue<? extends GSSIMJobInterface<?>>> queues,
1843                        ResourceManagerInterface unitManager)
1844                        throws ReservationException {
1845                // This method is not used in example configuration.
1846                return null;
1847        }
1848
1849        public List<Offer> getOffers(AbstractTimeRequirements<?> timeReqs,
1850                        AbstractResourceRequirements<?> resReqs,
1851                        List<? extends GSSIMJobInterface<?>> inExecution,
1852                                        List<? extends Queue<? extends GSSIMJobInterface<?>>> queues,
1853                        ResourceManagerInterface unitsManagerInterface)
1854                        throws ReservationException {
1855
1856
1857                ResourceManager unitsManager = (ResourceManager) unitsManagerInterface;
1858               
1859                List<TimeResourceAllocation> usageList = null;
1860                int reqCpuCnt = 0;
1861                List<Offer> list = new ArrayList<Offer>(1);
1862               
1863                try {
1864
1865                        // get number of processors requested by the task
1866                        reqCpuCnt = Double.valueOf(resReqs.getCpuCntRequest()).intValue();
1867               
1868                        // create unit for which resource usage will be created
1869                        List<ComputingResource> processors = null ;
1870                        try {
1871                                processors = (List<ComputingResource>)unitsManager.getResourcesOfType(ResourceType.CPU);
1872                        } catch (Exception e) {
1873                                // TODO Auto-generated catch block
1874                                e.printStackTrace();
1875                        }
1876                        ProcessingElements pes = new ProcessingElements(processors.get(0).getParent().getName());
1877                        pes.addAll(processors);
1878
1879                        DateTime startTime = timeReqs.getStart();
1880                        DateTime endTime = timeReqs.getEnd();
1881
1882                        // get resource usage
1883                        usageList = resourceUsageList(pes, startTime, endTime);
1884                       
1885                        // check if resource can provide enough resources in requested time.
1886                        // Prepare one, the earliest time period, which is suited exactly
1887                        // for resource and time requirements.
1888                        TimeResourceAllocation allocation = createSuitedAllocation(usageList,
1889                                                                                                                                                (TimeRequirements) timeReqs,
1890                                                                                                                                                (ResourceRequirements) resReqs);
1891                        // allocation is null when it is impossible to provide enough resources
1892                        // in requested time. Return empty offers list.
1893                        if(allocation == null)
1894                                return list;
1895                       
1896                        // add information about resource described by this allocation.
1897                        // provider
1898                        LocalSystem provider = new LocalSystem(pes.getResourceId(), null, null);
1899                       
1900                        // available resource units
1901                        ResourceStateDescription resDesc = new ResourceStateDescription(provider);
1902                                resDesc.addResourceUnit(new Processors(pes.getResourceId(), pes.size(), reqCpuCnt));
1903                       
1904                        allocation.setAllocatedResource(resDesc);
1905                       
1906                        // prepare offer
1907                        Offer offer = new Offer();
1908                                offer.setProvider(provider);
1909                                offer.add(allocation);
1910                       
1911                        list.add(offer);
1912                       
1913                } catch (NoSuchFieldException e) {
1914                        e.printStackTrace();
1915                        return list;
1916                }
1917               
1918                return list;
1919        }
1920       
1921        private TimeResourceAllocation createSuitedAllocation(List<TimeResourceAllocation> usageList,
1922                        TimeRequirements timeRequirements,
1923                        ResourceRequirements resourceRequirements){
1924
1925try {
1926
1927long reqDuration = timeRequirements.getEndMillis() - timeRequirements.getStartMillis();
1928long duration = reqDuration;
1929int reqCpu = Double.valueOf(resourceRequirements.getCpuCntRequest()).intValue();
1930DateTime start = null;
1931
1932for(int i = 0; i < usageList.size() && duration > 0; i++){
1933TimeResourceAllocation allocation = usageList.get(i);
1934ResourceUnit unit = allocation.getAllocatedResource().
1935getResourceUnit(ResourceParameterName.CPUCOUNT);
1936if(unit.getFreeAmount() >= reqCpu){
1937duration = duration - (allocation.getEndMillis() - allocation.getStartMillis());
1938if(start == null)
1939start = allocation.getStart();
1940} else {
1941duration = reqDuration;
1942start = null;
1943}
1944}
1945
1946if(duration > 0){
1947log.error("There is not enough free resources between " +
1948timeRequirements.getStart() + " and " + timeRequirements.getEnd());
1949return null;
1950}
1951
1952TimeResourceAllocation allocation = new TimeResourceAllocation(start, start.plus(reqDuration));
1953
1954return allocation;
1955
1956} catch (NoSuchFieldException e) {
1957e.printStackTrace();
1958}
1959
1960return null;
1961}
1962}
Note: See TracBrowser for help on using the repository browser.