Debian Codegraph @

src/plugins/schedulers/tj/taskjuggler/Project.cpp

raw
1 /*
2 * Project.cpp - TaskJuggler
3 *
4 * Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006
5 * by Chris Schlaeger <[email protected]>
6 * SPDX-FileCopyrightText: 2011 Dag Andersen <[email protected]>
7 *
8 * This program is free software; you can redistribute it and/or modify
9 * it under the terms of version 2 of the GNU General Public License as
10 * published by the Free Software Foundation.
11 *
12 * $Id$
13 */
14
15 #define tjDebug qDebug
16
17 // clazy:excludeall=qstring-arg
18 #include "Project.h"
19
20 #include <stdlib.h>
21 #include <QList>
22 #include <QString>
23 #include <QStringList>
24 #include <QDebug>
25
26 #include <KLocalizedString>
27
28 #include "TjMessageHandler.h"
29 #include "Scenario.h"
30 #include "Shift.h"
31 // #include "Account.h"
32 #include "Resource.h"
33 /*#include "HTMLTaskReport.h"
34 #include "HTMLResourceReport.h"
35 #include "HTMLAccountReport.h"
36 #include "HTMLWeeklyCalendar.h"
37 #include "HTMLStatusReport.h"
38 #include "CSVTaskReport.h"
39 #include "CSVResourceReport.h"
40 #include "CSVAccountReport.h"
41 #include "ExportReport.h"
42 #include "ReportXML.h"*/
43 #include "UsageLimits.h"
44 #include "CustomAttributeDefinition.h"
45
46 DebugController DebugCtrl;
47
48 namespace TJ
49 {
50
51 Project::Project() :
52 QObject(),
53 start(0),
54 end(0),
55 now(0),
56 allowRedefinitions(false),
57 weekStartsMonday(true),
58 name(),
59 version(),
60 copyright(),
61 customer(),
62 timeZone(),
63 timeFormat("%Y-%m-%d %H:%M"),
64 shortTimeFormat("%H:%M"),
65 // currency(),
66 // currencyDigits(3),
67 // numberFormat("-", "", ",", ".", 1),
68 // currencyFormat("(", ")", ",", ".", 0),
69 priority(500),
70 minEffort(0.0),
71 resourceLimits(nullptr),
72 rate(0.0),
73 dailyWorkingHours(8.0),
74 yearlyWorkingDays(260.714),
75 workingHours(),
76 scheduleGranularity(ONEHOUR),
77 allowedFlags(),
78 projectIDs(),
79 currentId(),
80 maxErrors(0),
81 // journal(),
82 vacationList(),
83 scenarioList(),
84 taskList(),
85 resourceList(),
86 // accountList(),
87 shiftList(),
88 originalTaskList(),
89 originalResourceList(),
90 // originalAccountList(),
91 taskAttributes(),
92 resourceAttributes(),
93 // accountAttributes(),
94 // xmlreport(0),
95 // reports(),
96 // interactiveReports(),
97 sourceFiles(),
98 breakFlag(false),
99 cancelSchedulingFlag(false)
100 {
101 //qDebug()<<"Project:"<<this;
102 /* Pick some reasonable initial number since we don't know the
103 * project time frame yet. */
104 initUtility(20000);
105
106 // vacationList.setAutoDelete(true);
107 // accountAttributes.setAutoDelete(true);
108 // taskAttributes.setAutoDelete(true);
109 // resourceAttributes.setAutoDelete(true);
110 // reports.setAutoDelete(true);
111
112 new Scenario(this, "plan", "Plan", nullptr);
113 scenarioList.createIndex(true);
114 scenarioList.createIndex(false);
115 // for (CoreAttributes *s : std::as_const(scenarioList)) {
116 // qDebug()<<"Project:"<<static_cast<CoreAttributes*>(s)<<static_cast<CoreAttributes*>(s)->getName()<<static_cast<CoreAttributes*>(s)->getSequenceNo();
117 // }
118 setNow(time(nullptr));
119
120 /* Initialize working hours with default values that match the Monday -
121 * Friday 9 - 6 (with 1 hour lunch break) pattern used by many western
122 * countries. */
123 // Sunday
124 workingHours[0] = new QList<Interval*>();
125 // workingHours[0]->setAutoDelete(true);
126
127 for (int i = 1; i < 6; ++i)
128 {
129 workingHours[i] = new QList<Interval*>();
130 // workingHours[i]->setAutoDelete(true);
131 workingHours[i]->append(new Interval(9 * ONEHOUR, 12 * ONEHOUR - 1));
132 workingHours[i]->append(new Interval(13 * ONEHOUR, 18 * ONEHOUR - 1));
133 }
134
135 // Saturday
136 workingHours[6] = new QList<Interval*>();
137 // workingHours[6]->setAutoDelete(true);
138 }
139
140 Project::~Project()
141 {
142 //qDebug()<<"~Project:"<<this<<">>>";
143 taskList.deleteContents();
144 resourceList.deleteContents();
145 Resource::deleteStaticData();
146
147 // accountList.deleteContents();
148 shiftList.deleteContents();
149 scenarioList.deleteContents();
150
151 delete resourceLimits;
152
153 // Remove support for 1.0 XML reports for next major release. */
154 // delete xmlreport;
155
156 for (int i = 0; i < 7; ++i) {
157 while (! workingHours[i]->isEmpty()) {
158 delete workingHours[i]->takeFirst();
159 }
160 delete workingHours[i];
161 }
162 exitUtility();
163
164 //qDebug()<<"~Project:"<<this<<"<<<";
165 }
166
167 // void
168 // Project::addSourceFile(const QString& f)
169 // {
170 // if (sourceFiles.find(f) == sourceFiles.end())
171 // sourceFiles.append(f);
172 // }
173 //
174 // QStringList
175 // Project::getSourceFiles() const
176 // {
177 // return sourceFiles;
178 // }
179
180 void
181 Project::setProgressInfo(const QString& i)
182 {
183 Q_EMIT updateProgressInfo(i);
184 }
185
186 void
187 Project::setProgressBar(int i, int of)
188 {
189 Q_EMIT updateProgressBar(i, of);
190 }
191
192 bool
193 Project::setTimeZone(const QString& tz)
194 {
195 if (!setTimezone(tz.toLocal8Bit().constData()))
196 return false;
197
198 timeZone = tz;
199 return true;
200 }
201
202 Scenario*
203 Project::getScenario(int sc) const
204 {
205 return static_cast<Scenario*>(scenarioList.value(sc));
206 }
207
208 QString
209 Project::getScenarioName(int sc) const
210 {
211 Scenario *s = getScenario(sc);
212 return s ? s->getName() : QString();
213 }
214
215 QString
216 Project::getScenarioId(int sc) const
217 {
218 Scenario *s = getScenario(sc);
219 return s ? s->getId() : QString();
220 }
221
222 int
223 Project::getScenarioIndex(const QString& id) const
224 {
225 return scenarioList.getIndex(id);
226 }
227
228 void
229 Project::setNow(time_t n)
230 {
231 /* Align 'now' time to timing resolution. If the resolution is
232 * changed later, this has to be done again. */
233 now = (n / scheduleGranularity) * scheduleGranularity;
234 }
235
236 void
237 Project::setWorkingHours(int day, const QList< Interval* >& l)
238 {
239 if (day < 0 || day > 6)
240 qFatal("day out of range");
241 delete workingHours[day];
242
243 // Create a deep copy of the interval list.
244 workingHours[day] = new QList<Interval*>;
245 // workingHours[day]->setAutoDelete(true);
246 for (Interval *i : l) {
247 workingHours[day]->append(new Interval(*i));
248
249 }
250 }
251
252 bool
253 Project::addId(const QString& id, bool changeCurrentId)
254 {
255 if (projectIDs.indexOf(id) != -1)
256 return false;
257 else
258 projectIDs.append(id);
259
260 if (changeCurrentId)
261 currentId = id;
262
263 return true;
264 }
265
266 QString
267 Project::getIdIndex(const QString& i) const
268 {
269 int idx;
270 if ((idx = projectIDs.indexOf(i)) == -1)
271 return QString("?");
272 QString idxStr;
273 do
274 {
275 idxStr = QChar('A' + idx % ('Z' - 'A')) + idxStr;
276 idx /= 'Z' - 'A';
277 } while (idx > 'Z' - 'A');
278
279 return idxStr;
280 }
281
282 void
283 Project::addScenario(Scenario* s)
284 {
285 scenarioList.append(s);
286
287 /* This is not too efficient, but since there are usually only a few
288 * scenarios in a project, this doesn't hurt too much. */
289 scenarioList.createIndex(true);
290 scenarioList.createIndex(false);
291 }
292
293 void
294 Project::deleteScenario(Scenario* s)
295 {
296 if (scenarioList.contains(s)) {
297 scenarioList.removeAt(scenarioList.indexOf(s));
298 }
299 }
300
301 void
302 Project::setResourceLimits(UsageLimits* l)
303 {
304 if (resourceLimits)
305 delete resourceLimits;
306 resourceLimits = l;
307 }
308
309 void
310 Project::addTask(Task* t)
311 {
312 taskList.append(t);
313 }
314
315 void
316 Project::deleteTask(Task* t)
317 {
318 if (taskList.contains(t)) {
319 taskList.removeAt(taskList.indexOf(t));
320 }
321 }
322
323 bool
324 Project::addTaskAttribute(const QString& id, CustomAttributeDefinition* cad)
325 {
326 if (taskAttributes.contains(id))
327 return false;
328
329 taskAttributes.insert(id, cad);
330 return true;
331 }
332
333 const CustomAttributeDefinition*
334 Project::getTaskAttribute(const QString& id) const
335 {
336 return taskAttributes[id];
337 }
338
339 void
340 Project::addShift(Shift* s)
341 {
342 shiftList.append(s);
343 }
344
345 void
346 Project::deleteShift(Shift* s)
347 {
348 if (shiftList.contains(s)) {
349 shiftList.removeAt(shiftList.indexOf(s));
350 }
351 }
352
353 void
354 Project::addResource(Resource* r)
355 {
356 //qDebug()<<"Project::addResource:"<<r<<resourceList;
357 resourceList.append(r);
358 }
359
360 void
361 Project::deleteResource(Resource* r)
362 {
363 if (resourceList.contains(r)) {
364 resourceList.removeAt(resourceList.indexOf(r));
365 }
366 }
367
368 bool
369 Project::addResourceAttribute(const QString& id,
370 CustomAttributeDefinition* cad)
371 {
372 if (resourceAttributes.contains(id))
373 return false;
374
375 resourceAttributes.insert(id, cad);
376 return true;
377 }
378
379 const CustomAttributeDefinition*
380 Project::getResourceAttribute(const QString& id) const
381 {
382 return resourceAttributes[id];
383 }
384
385 // void
386 // Project::addAccount(Account* a)
387 // {
388 // accountList.append(a);
389 // }
390 //
391 // void
392 // Project::deleteAccount(Account* a)
393 // {
394 // if (accountList.contains(a)) {
395 // accountList.removeAt(accountList.indexOf(a);
396 // }
397 //
398 // bool
399 // Project::addAccountAttribute(const QString& id,
400 // CustomAttributeDefinition* cad)
401 // {
402 // if (accountAttributes.find(id))
403 // return false;
404 //
405 // accountAttributes.insert(id, cad);
406 // return true;
407 // }
408
409 // const CustomAttributeDefinition*
410 // Project::getAccountAttribute(const QString& id) const
411 // {
412 // return accountAttributes[id];
413 // }
414
415 bool
416 Project::isWorkingDay(time_t wd) const
417 {
418 return !(workingHours[dayOfWeek(wd, false)]->isEmpty() ||
419 isVacation(wd));
420 }
421
422 bool
423 Project::isWorkingTime(time_t wd) const
424 {
425 if (isVacation(wd))
426 return false;
427
428 int dow = dayOfWeek(wd, false);
429 const auto lst = *getWorkingHours(dow);
430 for (Interval *i : lst) {
431 if (i->contains(secondsOfDay(wd)))
432 return true;
433 }
434 return false;
435 }
436
437 bool
438 Project::isWorkingTime(const Interval& iv) const
439 {
440 if (isVacation(iv.getStart()))
441 return false;
442
443 int dow = dayOfWeek(iv.getStart(), false);
444 const auto lst = *(workingHours[dow]);
445 for (Interval *i : lst) {
446 if (i->contains(Interval(secondsOfDay(iv.getStart()),
447 secondsOfDay(iv.getEnd()))))
448 return true;
449 }
450 return false;
451 }
452
453 int
454 Project::calcWorkingDays(const Interval& iv) const
455 {
456 int workingDays = 0;
457
458 for (time_t s = midnight(iv.getStart()); s <= iv.getEnd();
459 s = sameTimeNextDay(s))
460 if (isWorkingDay(s))
461 workingDays++;
462
463 return workingDays;
464 }
465
466 double
467 Project::convertToDailyLoad(long secs) const
468 {
469 return ((double) secs / (dailyWorkingHours * ONEHOUR));
470 }
471
472 // void
473 // Project::addJournalEntry(JournalEntry* entry)
474 // {
475 // journal.inSort(entry);
476 // }
477
478 // Journal::Iterator
479 // Project::getJournalIterator() const
480 // {
481 // return Journal::Iterator(journal);
482 // }
483
484 bool
485 Project::pass2(bool noDepCheck)
486 {
487 int oldErrors = TJMH.getErrors();
488
489 if (taskList.isEmpty())
490 {
491 TJMH.errorMessage(xi18nc("@info/plain", "The project does not contain any tasks."));
492 return false;
493 }
494 // qDebug()<<"pass2 task info:";
495 // for (CoreAttributes *a : std::as_const(taskList)) {
496 // Task *t = static_cast<Task*>(a);
497 // qDebug()<<t->getName()<<t->getDuration(0)<<t->getPrecedes()<<t->getDepends();
498 // }
499 QMap<QString, Task*> idHash;
500
501 /* The optimum size for the localtime hash is twice the number of time
502 * slots times 2 (because of timeslot and timeslot - 1s). */
503 initUtility(4 * ((end - start) / scheduleGranularity));
504
505 // Generate sequence numbers for all lists.
506 taskList.createIndex(true);
507 resourceList.createIndex(true);
508 // accountList.createIndex(true);
509 shiftList.createIndex(true);
510
511 // Initialize random generator.
512 srand((int) start);
513
514 // Create hash to map task IDs to pointers.
515 for (CoreAttributes *t : std::as_const(taskList))
516 {
517 idHash.insert(static_cast<Task*>(t)->getId(), static_cast<Task*>(t));
518 }
519 // Create cross links from dependency lists.
520 for (CoreAttributes *t : std::as_const(taskList))
521 static_cast<Task*>(t)->xRef(idHash);
522
523 for (CoreAttributes *t : std::as_const(taskList))
524 {
525 // Set dates according to implicit dependencies
526 static_cast<Task*>(t)->implicitXRef();
527
528 // Sort allocations properly
529 static_cast<Task*>(t)->sortAllocations();
530
531 // Save so far booked resources as specified resources
532 static_cast<Task*>(t)->saveSpecifiedBookedResources();
533 }
534
535 // Save a copy of all manually booked resources.
536 for (CoreAttributes *r : std::as_const(resourceList))
537 static_cast<Resource*>(r)->saveSpecifiedBookings();
538
539 /* Now we can copy the missing values from the plan scenario to the other
540 * scenarios. */
541 if (scenarioList.count() > 1)
542 {
543 qWarning()<<"TODO";
544 /* for (ScenarioListIterator sli(scenarioList[0]->getSubListIterator());
545 *sli; ++sli)
546 overlayScenario(0, (*sli)->getSequenceNo() - 1);*/
547 }
548
549 // Now check that all tasks have sufficient data to be scheduled.
550 setProgressInfo(QString("Checking scheduling data..."));
551 bool error = false;
552 for (CoreAttributes *s : std::as_const(scenarioList)) {
553 for (CoreAttributes *t : std::as_const(taskList)) {
554 if (!static_cast<Task*>(t)->preScheduleOk(static_cast<Scenario*>(s)->getSequenceNo() - 1))
555 {
556 error = true;
557 }
558 }
559 }
560 if (error)
561 return false;
562
563 if (!noDepCheck)
564 {
565 setProgressInfo(QString("Searching for dependency loops ..."));
566 if (DEBUGPS(1))
567 tjDebug("Searching for dependency loops ...");
568 // Check all tasks for dependency loops.
569 LDIList chkedTaskList;
570 for (CoreAttributes *t : std::as_const(taskList)) {
571 if (static_cast<Task*>(t)->loopDetector(chkedTaskList))
572 return false;
573 }
574
575 setProgressInfo(QString("Searching for underspecified tasks ..."));
576 if (DEBUGPS(1))
577 tjDebug("Searching for underspecified tasks ...");
578 for (CoreAttributes *s : std::as_const(scenarioList)) {
579 for (CoreAttributes *t : std::as_const(taskList)) {
580 if (!static_cast<Task*>(t)->checkDetermination(static_cast<Scenario*>(s)->getSequenceNo() - 1))
581 error = true;
582 }
583 }
584
585 if (error)
586 return false;
587 }
588 TJ::TaskList starts;
589 TJ::TaskList ends;
590 QStringList tl;
591 for (TJ::CoreAttributes *t : std::as_const(taskList)) {
592 tl << t->getName();
593 if (! static_cast<TJ::Task*>(t)->hasPrevious()) {
594 starts << static_cast<TJ::Task*>(t);
595 tl << "(s)";
596 }
597 if (! static_cast<TJ::Task*>(t)->hasFollowers()) {
598 ends << static_cast<TJ::Task*>(t);
599 tl << "(e)";
600 }
601 }
602 tl.clear();
603 for (TJ::CoreAttributes *t : std::as_const(taskList)) {
604 tl << t->getName();
605 if (! static_cast<TJ::Task*>(t)->hasPrevious()) {
606 starts << static_cast<TJ::Task*>(t);
607 tl << "(s)";
608 }
609 if (! static_cast<TJ::Task*>(t)->hasFollowers()) {
610 ends << static_cast<TJ::Task*>(t);
611 tl << "(e)";
612 }
613 }
614 if (DEBUGPS(2)) {
615 qDebug()<<"Tasks:"<<tl;
616 qDebug()<<"Depends/precedes: -------------------";
617 tl.clear();
618 for (TJ::CoreAttributes *t : std::as_const(taskList)) {
619 tl << t->getName() + (static_cast<TJ::Task*>(t)->getScheduling() == TJ::Task::ASAP ? " (ASAP)" : " (ALAP)") + " depends: ";
620 for (QListIterator<TJ::TaskDependency*> it = static_cast<TJ::Task*>(t)->getDependsIterator(); it.hasNext();) {
621 const TJ::Task *a = it.next()->getTaskRef();
622 QString s = a->getName() + (a->getScheduling() == TJ::Task::ASAP ? " (ASAP)" : " (ALAP)");
623 tl << s;
624 }
625 qDebug()<<tl; tl.clear();
626 tl << t->getName() + (static_cast<TJ::Task*>(t)->getScheduling() == TJ::Task::ASAP ? " (ASAP)" : " (ALAP)") + " precedes: ";
627 for (QListIterator<TJ::TaskDependency*> it = static_cast<TJ::Task*>(t)->getPrecedesIterator(); it.hasNext();) {
628 const TJ::Task *a = it.next()->getTaskRef();
629 QString s = a->getName() + (a->getScheduling() == TJ::Task::ASAP ? " (ASAP)" : " (ALAP)");
630 tl << s;
631 }
632 qDebug()<<tl; tl.clear();
633 }
634 qDebug()<<"Followers/previous: -------------------";
635 tl.clear();
636 for (TJ::CoreAttributes *t : std::as_const(taskList)) {
637 tl << t->getName() + (static_cast<TJ::Task*>(t)->getScheduling() == TJ::Task::ASAP ? " (ASAP)" : " (ALAP)") + " followers: ";
638 for (TJ::TaskListIterator it = static_cast<TJ::Task*>(t)->getFollowersIterator(); it.hasNext();) {
639 const TJ::Task *a = static_cast<TJ::Task*>(it.next());
640 QString s = a->getName() + (a->getScheduling() == TJ::Task::ASAP ? " (ASAP)" : " (ALAP)");
641 tl << s;
642 }
643 qDebug()<<tl; tl.clear();
644 tl << t->getName() + (static_cast<TJ::Task*>(t)->getScheduling() == TJ::Task::ASAP ? " (ASAP)" : " (ALAP)") + " previous: ";
645 for (TJ::TaskListIterator it = static_cast<TJ::Task*>(t)->getPreviousIterator(); it.hasNext();) {
646 const TJ::Task *a = static_cast<TJ::Task*>(it.next());
647 QString s = a->getName() + (a->getScheduling() == TJ::Task::ASAP ? " (ASAP)" : " (ALAP)");
648 tl << s;
649 }
650 qDebug()<<tl; tl.clear();
651 }
652 qDebug()<<"Successors/predecessors: -------------------";
653 tl.clear();
654 for (TJ::CoreAttributes *c : std::as_const(taskList)) {
655 tl << c->getName() + (static_cast<TJ::Task*>(c)->getScheduling() == TJ::Task::ASAP ? " (ASAP)" : " (ALAP)") + " successors: ";
656 const auto succs = static_cast<TJ::Task*>(c)->getSuccessors();
657 for (TJ::CoreAttributes *t : succs) {
658 TJ::Task *a = static_cast<TJ::Task*>(t);
659 QString s = a->getName() + (a->getScheduling() == TJ::Task::ASAP ? " (ASAP)" : " (ALAP)");
660 tl << s;
661 }
662 qDebug()<<tl; tl.clear();
663 tl << c->getName() + (static_cast<TJ::Task*>(c)->getScheduling() == TJ::Task::ASAP ? " (ASAP)" : " (ALAP)") + " predecessors: ";
664 const auto preds = static_cast<TJ::Task*>(c)->getPredecessors();
665 for (TJ::CoreAttributes *t : preds) {
666 TJ::Task *a = static_cast<TJ::Task*>(t);
667 QString s = a->getName() + (a->getScheduling() == TJ::Task::ASAP ? " (ASAP)" : " (ALAP)");
668 tl << s;
669 }
670 qDebug()<<tl; tl.clear();
671 }
672 }
673 return TJMH.getErrors() == oldErrors;
674 }
675
676 bool
677 Project::scheduleScenario(Scenario* sc)
678 {
679 int oldErrors = TJMH.getErrors();
680
681 // setProgressInfo(QString("Scheduling scenario %1...").arg(sc->getName()));
682
683 int scIdx = sc->getSequenceNo() - 1;
684 prepareScenario(scIdx);
685
686 if (!schedule(scIdx))
687 {
688 if (DEBUGPS(2))
689 tjDebug()<<"Scheduling errors in scenario: "<<(sc->getId());
690 if (breakFlag)
691 return false;
692 }
693 finishScenario(scIdx);
694
695 for (CoreAttributes *r : std::as_const(resourceList))
696 {
697 if (!static_cast<Resource*>(r)->bookingsOk(scIdx))
698 break;
699 }
700
701 return TJMH.getErrors() == oldErrors;
702 }
703
704 void
705 Project::completeBuffersAndIndices()
706 {
707 for (CoreAttributes *t : std::as_const(taskList)) {
708 static_cast<Task*>(t)->computeBuffers();
709 }
710 /* Create indices for all lists according to their default sorting
711 * criteria. */
712 taskList.createIndex();
713 resourceList.createIndex();
714 // accountList.createIndex();
715 shiftList.createIndex();
716 }
717
718 bool
719 Project::scheduleAllScenarios()
720 {
721 bool schedulingOk = true;
722 for (CoreAttributes *s : std::as_const(scenarioList)) {
723 if (static_cast<Scenario*>(s)->getEnabled())
724 {
725 if (DEBUGPS(1))
726 tjDebug()<<"Scheduling scenario:"<<static_cast<Scenario*>(s)->getId();
727
728 if (!scheduleScenario(static_cast<Scenario*>(s)))
729 schedulingOk = false;
730 if (breakFlag)
731 return false;
732 }
733 }
734
735 completeBuffersAndIndices();
736
737 return schedulingOk;
738 }
739
740 void
741 Project::overlayScenario(int base, int sc)
742 {
743 for (CoreAttributes *t : std::as_const(taskList)) {
744 static_cast<Task*>(t)->overlayScenario(base, sc);
745 }
746 const auto lst = scenarioList[sc]->getSubList();
747 for (CoreAttributes *s : lst) {
748 overlayScenario(sc, static_cast<Scenario*>(s)->getSequenceNo() - 1);
749 }
750 }
751
752 void
753 Project::prepareScenario(int sc)
754 {
755 for (CoreAttributes *r : std::as_const(resourceList)) {
756 static_cast<Resource*>(r)->prepareScenario(sc);
757 }
758 for (CoreAttributes *t : std::as_const(taskList)) {
759 static_cast<Task*>(t)->prepareScenario(sc);
760 }
761
762 /* First we compute the criticalness of the individual task without their
763 * dependency context. */
764 for (CoreAttributes *t : std::as_const(taskList)) {
765 static_cast<Task*>(t)->computeCriticalness(sc);
766 }
767 /* Then we compute the path criticalness that represents the criticalness
768 * of a task taking their dependency context into account. */
769 for (CoreAttributes *t : std::as_const(taskList)) {
770 static_cast<Task*>(t)->computePathCriticalness(sc);
771 }
772
773 for (CoreAttributes *t : std::as_const(taskList)) {
774 static_cast<Task*>(t)->propagateInitialValues(sc);
775 }
776
777 if (DEBUGTS(4))
778 {
779 tjDebug("Allocation probabilities for the resources:");
780 for (CoreAttributes *r : std::as_const(resourceList)) {
781 qDebug()<<QString("Resource %1: %2%")
782 .arg(static_cast<Resource*>(r)->getName())
783 .arg(static_cast<Resource*>(r)->getAllocationProbability(sc));
784 }
785 tjDebug("Criticalnesses of the tasks with respect to resource "
786 "availability:");
787 for (CoreAttributes *t : std::as_const(taskList)) {
788 qDebug()<<QString("Task %1: %2 %3").arg(static_cast<Task*>(t)->getName())
789 .arg(static_cast<Task*>(t)->getCriticalness(sc))
790 .arg(static_cast<Task*>(t)->getPathCriticalness(sc));
791 }
792 }
793 }
794
795 void
796 Project::cancelScheduling()
797 {
798 cancelSchedulingFlag = true;
799 }
800
801 void
802 Project::finishScenario(int sc)
803 {
804 for (CoreAttributes *r : std::as_const(resourceList)) {
805 static_cast<Resource*>(r)->finishScenario(sc);
806 }
807 for (CoreAttributes *t : std::as_const(taskList)) {
808 static_cast<Task*>(t)->finishScenario(sc);
809 }
810 #if 0
811 /* We need to have finished the scenario for all tasks before we can
812 * calculate the completion degree. */
813 for (CoreAttributes *t : std::as_const(taskList)) {
814 static_cast<Task*>(t)->calcCompletionDegree(sc);
815 }
816 #endif
817 /* If the user has not set the minSlackRate to 0 we look for critical
818 * paths. */
819 if (getScenario(sc)->getMinSlackRate() > 0.0)
820 {
821 setProgressInfo(QString("Computing critical paths..."));
822 /* The critical path detector needs to know the end of the last task.
823 * So we have to find this out first. */
824 time_t maxEnd = 0;
825 for (CoreAttributes *t : std::as_const(taskList)) {
826 if (maxEnd < static_cast<Task*>(t)->getEnd(sc))
827 maxEnd = static_cast<Task*>(t)->getEnd(sc);
828 }
829 for (CoreAttributes *t : std::as_const(taskList)) {
830 static_cast<Task*>(t)->checkAndMarkCriticalPath
831 (sc, getScenario(sc)->getMinSlackRate(), maxEnd);
832 }
833 }
834 }
835
836 TaskList Project::tasksReadyToBeScheduled(int sc, const TaskList& allLeafTasks)
837 {
838 TaskList workItems;
839 for (CoreAttributes *t : std::as_const(allLeafTasks)) {
840 if (static_cast<Task*>(t)->isReadyForScheduling())
841 workItems.append(static_cast<Task*>(t));
842 }
843 if (workItems.isEmpty()) {
844 for (CoreAttributes *t : std::as_const(allLeafTasks)) {
845 if (!static_cast<Task*>(t)->isSchedulingDone() && !static_cast<Task*>(t)->isReadyForScheduling()) {
846 TJMH.debugMessage("Not ready to be scheduled", t);
847 }
848 }
849 for (CoreAttributes *c : std::as_const(allLeafTasks)) {
850 Task *t = static_cast<Task*>(c);
851 if (!t->isSchedulingDone() /*&& !t->isRunaway()*/) {
852 if (t->getScheduling() == Task::ASAP) {
853 time_t es = t->earliestStart(sc);
854 //qDebug()<<"schedule rest: earliest start"<<time2ISO(es)<<time2ISO(time_t(1));
855 if (es > 1) { // NOTE: es is 1 if predecessor is not scheduled!
856 t->propagateStart(sc, es);
857 } else if (t->hasAlapPredecessor()) {
858 time_t le = t->latestEnd(sc);
859 if (le > time_t(0)) {
860 t->setScheduling(Task::ALAP);
861 t->propagateEnd(sc, le);
862 }// else qDebug()<<"schedule rest: no end time"<<t;
863 } //else qDebug()<<"schedule rest: no start time"<<t;
864 } else {
865 time_t le = t->latestEnd(sc);
866 if (le > time_t(0)) {
867 t->propagateEnd(sc, le);
868 } else qDebug()<<"ALAP schedule rest: no end time"<<t;
869 }
870 if (t->isReadyForScheduling()) {
871 workItems.append(t);
872 } else qDebug()<<"Schedule rest: not ready"<<t;
873 }
874 if (workItems.isEmpty()) {
875 TaskList lst;
876 for (CoreAttributes *c : std::as_const(allLeafTasks)) {
877 Task *t = static_cast<Task*>(c);
878 if (!t->isSchedulingDone()) {
879 lst << t;
880 }
881 }
882 if (lst.isEmpty()) {
883 return workItems; // finished
884 }
885 if (DEBUGPS(5)) {
886 if (!lst.isEmpty()) {
887 qDebug()<<"These tasks are still not ready to be scheduled:"<<allLeafTasks;
888 }
889 }
890 }
891 }
892 }
893 /* if (workItems.isEmpty() && getTask("TJ::StartJob")->getScheduling() == Task::ASAP) {
894 for (CoreAttributes *c : std::as_const(allLeafTasks)) {
895 }
896 } */
897 if (workItems.isEmpty() && getTask("TJ::StartJob")->getScheduling() == Task::ALAP) {
898 qDebug()<<"tasksReadyToSchedule:"<<"backward, try really hard";
899 for (CoreAttributes *c : std::as_const(allLeafTasks)) {
900 Task *task = static_cast<Task*>(c);
901 if (!task->isSchedulingDone()) {
902 continue;
903 }
904 qDebug()<<"tasksReadyToSchedule:"<<"scheduled task:"<<task<<time2ISO(task->start)<<time2ISO(task->end);
905 Task *predecessor = nullptr;
906 long gapLength = 0;
907 long gapDuration = 0;
908 for (CoreAttributes *c : std::as_const(task->previous)) {
909 Task *t = static_cast<Task*>(c);
910 if (t->isSchedulingDone()) {
911 continue;
912 }
913 // get the dependency/longest gap
914 for (TaskDependency *d : std::as_const(t->precedes)) {
915 if (d->getTaskRef() == task) {
916 predecessor = t;
917 gapLength = qMax(gapLength, d->getGapLength(sc));
918 gapDuration = qMax(gapDuration, d->getGapDuration(sc));
919 }
920 }
921 }
922 if (predecessor == nullptr) {
923 continue;
924 }
925 time_t potentialDate = task->start - 1;
926 time_t dateBeforeLengthGap;
927 for (dateBeforeLengthGap = potentialDate; gapLength > 0 && dateBeforeLengthGap >= start; dateBeforeLengthGap -= getScheduleGranularity()) {
928 if (isWorkingTime(dateBeforeLengthGap)) {
929 gapLength -= getScheduleGranularity();
930 }
931 if (dateBeforeLengthGap < potentialDate - gapDuration) {
932 potentialDate = dateBeforeLengthGap;
933 } else {
934 potentialDate -= gapDuration;
935 }
936 }
937 qDebug()<<"tasksReadyToSchedule:"<<"schedule predecessor:"<<predecessor<<time2ISO(potentialDate);
938 predecessor->propagateEnd(sc, potentialDate);
939 workItems << predecessor;
940 break;
941 }
942 }
943 return workItems;
944 }
945
946 bool
947 Project::schedule(int sc)
948 {
949 int oldErrors = TJMH.getErrors();
950 int maxProgress = 0;
951
952 // The scheduling function only cares about leaf tasks. Container tasks
953 // are scheduled automatically when all their children are scheduled. So
954 // we create a task list that only contains leaf tasks.
955 TaskList allLeafTasks;
956 for (CoreAttributes *t : std::as_const(taskList)) {
957 if (!static_cast<Task*>(t)->hasSubs()) {
958 allLeafTasks.append(static_cast<Task*>(t));
959 // TJMH.debugMessage("Leaf task", t);
960 }
961 }
962
963 allLeafTasks.setSorting(CoreAttributesList::PrioDown, 0);
964 allLeafTasks.setSorting(CoreAttributesList::PathCriticalnessDown, 1);
965 allLeafTasks.setSorting(CoreAttributesList::SequenceUp, 2);
966 allLeafTasks.sort();
967 maxProgress = allLeafTasks.count();
968 int sortedTasks = 0;
969 for (CoreAttributes *t : std::as_const(allLeafTasks)) {
970 if (static_cast<Task*>(t)->isSchedulingDone())
971 sortedTasks++;
972 }
973 /* The workItems list contains all tasks that are ready to be scheduled at
974 * any given iteration. When a tasks has been scheduled completely, this
975 * list needs to be updated again as some tasks may now have become ready
976 * to be scheduled. */
977 TaskList workItems = tasksReadyToBeScheduled(sc, allLeafTasks);
978
979 bool done;
980 /* While the scheduling process progresses, the list contains more and
981 * more scheduled tasks. We use the cleanupTimer to remove those in
982 * certain intervals. As we potentially have already completed tasks in
983 * the list when we start, we initialize the timer with a very large
984 * number so the first round of cleanup is done right after the first
985 * scheduling pass. */
986 breakFlag = false;
987 // bool runAwayFound = false;
988 do
989 {
990 done = true;
991 time_t slot = 0;
992 int priority = 0;
993 double pathCriticalness = 0.0;
994 Task::SchedulingInfo schedulingInfo = Task::ASAP;
995
996 // helpers to avoid updating workItems list inside loop
997 bool updateList = false;
998 TaskList temp;
999
1000 /* The task list is sorted by priority. The priority decreases towards
1001 * the end of the list. We iterate through the list and look for a
1002 * task that can be scheduled. It the determines the time slot that
1003 * will be scheduled during this run for all subsequent tasks as well.
1004 */
1005 for (CoreAttributes *t : std::as_const(workItems)) {
1006 if (cancelSchedulingFlag) {
1007 break;
1008 }
1009 // TJMH.debugMessage(QString("'%1' schedule for slot: %2, (%3 -%4)").arg(static_cast<Task*>(t)->getName()).arg(time2ISO(slot)).arg(time2ISO(start)).arg(time2ISO(end)));
1010
1011 if (slot == 0)
1012 {
1013 /* No time slot has been set yet. Check if this task can be
1014 * scheduled and provides a suggestion. */
1015 slot = static_cast<Task*>(t)->nextSlot(scheduleGranularity);
1016 // TJMH.debugMessage(QString("'%1' first slot: %2, (%3 -%4)").arg(static_cast<Task*>(t)->getName()).arg(time2ISO(slot)).arg(time2ISO(start)).arg(time2ISO(end)), t);
1017 /* If not, try the next task. */
1018 if (slot == 0)
1019 continue;
1020 priority = static_cast<Task*>(t)->getPriority();
1021 pathCriticalness = static_cast<Task*>(t)->getPathCriticalness(sc);
1022 schedulingInfo = static_cast<Task*>(t)->getScheduling();
1023
1024 if (DEBUGPS(4))
1025 qDebug()<<QString("Task '%1' (Prio %2, Direction: %3) requests slot %4")
1026 .arg(static_cast<Task*>(t)->getName()).arg(static_cast<Task*>(t)->getPriority())
1027 .arg(static_cast<Task*>(t)->getScheduling())
1028 .arg(time2ISO(slot));
1029 /* If the task wants a time slot outside of the project time
1030 * frame, we flag this task as a runaway and go to the next
1031 * task. */
1032 if (slot < start ||
1033 slot > (end - (time_t) scheduleGranularity + 1))
1034 {
1035 if (!static_cast<Task*>(t)->isRunaway()) {
1036 if (slot < start) {
1037 static_cast<Task*>(t)->warningMessage(i18n("Attempt to schedule task at %1 to start before project target start time: %2", formatTime(slot), formatTime(start)));
1038 } else {
1039 static_cast<Task*>(t)->warningMessage(i18n("Attempt to schedule task at %1 to end after project target end time: %2", formatTime(slot), formatTime(end)));
1040 }
1041 static_cast<Task*>(t)->setRunaway();
1042 }
1043 // runAwayFound = true;
1044 slot = 0;
1045 continue;
1046 }
1047 }
1048 done = false;
1049 /* Each task has a scheduling direction (forward or backward)
1050 * depending on it's constrains. The task with the highest
1051 * priority/pathCriticalness determines the time slot and hence the
1052 * scheduling direction. Since tasks that have the other direction
1053 * cannot the scheduled then, we have to stop this run as soon as
1054 * we hit a task that runs in the other direction. If we would not
1055 * do this, tasks with lower priority/pathCriticalness would grab
1056 * resources form tasks with higher priority. */
1057 if (static_cast<Task*>(t)->getScheduling() != schedulingInfo &&
1058 !static_cast<Task*>(t)->isMilestone())
1059 {
1060 if (DEBUGPS(4))
1061 qDebug()<<QString("Changing scheduling direction to %1 due to task '%2'")
1062 .arg(static_cast<Task*>(t)->getScheduling())
1063 .arg(static_cast<Task*>(t)->getName());
1064 break;
1065 }
1066 /* We must avoid that lower priority tasks get resources even
1067 * though there are higher priority tasks that are ready to be
1068 * scheduled but have a non-adjacent last slot. If two tasks have
1069 * the same priority the pathCriticalness is being used. */
1070 if (static_cast<Task*>(t)->getPriority() < priority ||
1071 (static_cast<Task*>(t)->getPriority() == priority &&
1072 static_cast<Task*>(t)->getPathCriticalness(sc) < pathCriticalness))
1073 break;
1074
1075 // Schedule this task for the current time slot.
1076 if (static_cast<Task*>(t)->schedule(sc, slot, scheduleGranularity))
1077 {
1078 temp = tasksReadyToBeScheduled(sc, allLeafTasks);
1079 updateList = true;
1080 int oldSortedTasks = sortedTasks;
1081 sortedTasks = 0;
1082 for (CoreAttributes *t : std::as_const(allLeafTasks)) {
1083 if (static_cast<Task*>(t)->isSchedulingDone())
1084 sortedTasks++;
1085 }
1086 // Update the progress bar after every 10th completed tasks.
1087 if (oldSortedTasks / 10 != sortedTasks / 10)
1088 {
1089 setProgressBar(100 * ((double)sortedTasks / maxProgress), sortedTasks);
1090 setProgressInfo(QString("Scheduling scenario %1 at %2")
1091 .arg(getScenarioId(sc)).arg(time2tjp(slot)));
1092 }
1093 }
1094 }
1095 if (updateList) {
1096 workItems = temp;
1097 }
1098 } while (!done && !breakFlag && !cancelSchedulingFlag);
1099
1100 if (cancelSchedulingFlag)
1101 {
1102 setProgressInfo("");
1103 setProgressBar(100, 0);
1104 TJMH.infoMessage(xi18nc("@info/plain", "Scheduling aborted on user request"));
1105 return false;
1106 }
1107 if (breakFlag)
1108 {
1109 setProgressInfo("");
1110 setProgressBar(0, 0);
1111 TJMH.infoMessage(xi18nc("@info/plain", "Scheduling aborted on user request"));
1112 return false;
1113 }
1114 // if (runAwayFound) {
1115 // for (CoreAttributes *t : std::as_const(taskList)) {
1116 // if (static_cast<Task*>(t)->isRunaway()) {
1117 // if (static_cast<Task*>(t)->getScheduling() == Task::ASAP) {
1118 // TJMH.errorMessage(xi18nc("@info/plain", "Cannot meet the projects target finish time. Try using a later project end date.", t->getName()), t);
1119 // } else {
1120 // TJMH.errorMessage(xi18nc("@info/plain", "Cannot meet the projects target start time. Try using an earlier project start date.", t->getName()), t);
1121 // }
1122 // }
1123 // }
1124 // }
1125 if (TJMH.getErrors() == oldErrors)
1126 setProgressBar(100, 100);
1127
1128 /* Check that the resulting schedule meets all the requirements that the
1129 * user has specified. */
1130 setProgressInfo(QString("Checking schedule of scenario %1")
1131 .arg(getScenarioId(sc)));
1132 checkSchedule(sc);
1133
1134 return TJMH.getErrors() == oldErrors;
1135 }
1136
1137 void
1138 Project::breakScheduling()
1139 {
1140 breakFlag = true;
1141 }
1142
1143 bool
1144 Project::checkSchedule(int sc) const
1145 {
1146 int oldErrors = TJMH.getErrors();
1147 for (CoreAttributes *t : std::as_const(taskList)) {
1148 /* Only check top-level tasks, since they recursively check their sub
1149 * tasks. */
1150 if (static_cast<Task*>(t)->getParent() == nullptr)
1151 static_cast<Task*>(t)->scheduleOk(sc);
1152 if (maxErrors > 0 && TJMH.getErrors() >= maxErrors)
1153 {
1154 TJMH.errorMessage(xi18nc("@info/plain", "Too many errors. Giving up."));
1155 return false;
1156 }
1157 }
1158
1159 return TJMH.getErrors() == oldErrors;
1160 }
1161
1162 // Report*
1163 // Project::getReport(uint idx) const
1164 // {
1165 // QPtrListIterator<Report> it(reports);
1166 // for (uint i = 0; *it && i < idx; ++it, ++i)
1167 // ;
1168 // return *it;
1169 // }
1170 //
1171 // /*QPtr*/ListIterator<Report>
1172 // Project::getReportListIterator() const
1173 // {
1174 // return QPtrListIterator<Report>(reports);
1175 // }
1176 //
1177 // bool
1178 // Project::generateReports() const
1179 // {
1180 // // Generate reports
1181 // int errors = 0;
1182 // for (QPtrListIterator<Report> ri(reports); *ri != 0; ++ri)
1183 // {
1184 // // We generate all but Qt*Reports. Those are for the GUI version.
1185 // if (strncmp((*ri)->getType(), "Qt", 2) != 0)
1186 // {
1187 // if (DEBUGPS(1))
1188 // tjDebug(QString("Generating report '%1' ...")
1189 // .arg((*ri)->getFileName()));
1190 //
1191 // if (!(*ri)->generate())
1192 // errors++;
1193 // }
1194 // }
1195 //
1196 // generateXMLReport();
1197 //
1198 // return errors == 0;
1199 // }
1200 //
1201 // bool Project::generateXMLReport() const
1202 // {
1203 // if (xmlreport)
1204 // return xmlreport->generate();
1205 // else
1206 // return false;
1207 // }
1208
1209 } // namespace TJ