53527d265da66d99262d7924d6e0f16d7647dc1b
[dcpomatic.git] / src / lib / job.cc
1 /*
2     Copyright (C) 2012-2021 Carl Hetherington <cth@carlh.net>
3
4     This file is part of DCP-o-matic.
5
6     DCP-o-matic is free software; you can redistribute it and/or modify
7     it under the terms of the GNU General Public License as published by
8     the Free Software Foundation; either version 2 of the License, or
9     (at your option) any later version.
10
11     DCP-o-matic is distributed in the hope that it will be useful,
12     but WITHOUT ANY WARRANTY; without even the implied warranty of
13     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14     GNU General Public License for more details.
15
16     You should have received a copy of the GNU General Public License
17     along with DCP-o-matic.  If not, see <http://www.gnu.org/licenses/>.
18
19 */
20
21
22 /** @file  src/job.cc
23  *  @brief A parent class to represent long-running tasks which are run in their own thread.
24  */
25
26
27 #include "compose.hpp"
28 #include "constants.h"
29 #include "cross.h"
30 #include "dcpomatic_log.h"
31 #include "exceptions.h"
32 #include "film.h"
33 #include "job.h"
34 #include "log.h"
35 #include "util.h"
36 #include <dcp/exceptions.h>
37 #include <sub/exceptions.h>
38 #include <boost/date_time/posix_time/posix_time.hpp>
39 #include <boost/filesystem.hpp>
40 #include <boost/thread.hpp>
41 #include <iostream>
42
43 #include "i18n.h"
44
45
46 using std::cout;
47 using std::function;
48 using std::list;
49 using std::shared_ptr;
50 using std::string;
51 using boost::optional;
52 using namespace dcpomatic;
53
54
55 /** @param film Associated film, or 0 */
56 Job::Job (shared_ptr<const Film> film)
57         : _film (film)
58         , _state (NEW)
59         , _start_time (0)
60         , _sub_start_time (0)
61         , _progress (0)
62         , _ran_for (0)
63 {
64
65 }
66
67
68 Job::~Job ()
69 {
70 #ifdef DCPOMATIC_DEBUG
71         /* Any subclass should have called stop_thread in its destructor */
72         assert (!_thread.joinable());
73 #endif
74 }
75
76
77 void
78 Job::stop_thread ()
79 {
80         boost::this_thread::disable_interruption dis;
81
82         _thread.interrupt ();
83         try {
84                 _thread.join ();
85         } catch (...) {}
86 }
87
88
89 /** Start the job in a separate thread, returning immediately */
90 void
91 Job::start ()
92 {
93         set_state (RUNNING);
94         _start_time = time (0);
95         _sub_start_time = time (0);
96         _thread = boost::thread (boost::bind(&Job::run_wrapper, this));
97 #ifdef DCPOMATIC_LINUX
98         pthread_setname_np (_thread.native_handle(), "job-wrapper");
99 #endif
100 }
101
102
103 /** A wrapper for the ::run() method to catch exceptions */
104 void
105 Job::run_wrapper ()
106 {
107         start_of_thread (String::compose("Job-%1", json_name()));
108
109         try {
110
111                 run ();
112
113         } catch (dcp::FileError& e) {
114
115                 string m = String::compose (_("An error occurred whilst handling the file %1."), boost::filesystem::path (e.filename()).leaf());
116
117                 try {
118                         auto const s = boost::filesystem::space (e.filename());
119                         if (s.available < pow (1024, 3)) {
120                                 m += N_("\n\n");
121                                 m += _("The drive that the film is stored on is low in disc space.  Free some more space and try again.");
122                         }
123                 } catch (...) {
124
125                 }
126
127                 set_error (e.what(), m);
128                 set_progress (1);
129                 set_state (FINISHED_ERROR);
130
131         } catch (dcp::StartCompressionError& e) {
132
133                 bool done = false;
134
135 #ifdef DCPOMATIC_WINDOWS
136 #if (__GNUC__ && !__x86_64__)
137                 /* 32-bit */
138                 set_error (
139                         _("Failed to encode the DCP."),
140                         _("This error has probably occurred because you are running the 32-bit version of DCP-o-matic and "
141                           "trying to use too many encoding threads.  Please reduce the 'number of threads DCP-o-matic should "
142                           "use' in the General tab of Preferences and try again.")
143                         );
144                 done = true;
145 #else
146                 /* 64-bit */
147                 if (running_32_on_64()) {
148                         set_error (
149                                 _("Failed to encode the DCP."),
150                                 _("This error has probably occurred because you are running the 32-bit version of DCP-o-matic.  Please re-install DCP-o-matic with the 64-bit installer and try again.")
151                                 );
152                         done = true;
153                 }
154 #endif
155 #endif
156
157                 if (!done) {
158                         set_error (
159                                 e.what (),
160                                 string (_("It is not known what caused this error.")) + "  " + REPORT_PROBLEM
161                                 );
162                 }
163
164                 set_progress (1);
165                 set_state (FINISHED_ERROR);
166
167         } catch (OpenFileError& e) {
168
169                 set_error (
170                         String::compose (_("Could not open %1"), e.file().string()),
171                         String::compose (
172                                 _("DCP-o-matic could not open the file %1 (%2).  Perhaps it does not exist or is in an unexpected format."),
173                                 boost::filesystem::absolute (e.file()).string(),
174                                 e.what()
175                                 )
176                         );
177
178                 set_progress (1);
179                 set_state (FINISHED_ERROR);
180
181         } catch (boost::filesystem::filesystem_error& e) {
182
183                 if (e.code() == boost::system::errc::no_such_file_or_directory) {
184                         set_error (
185                                 String::compose (_("Could not open %1"), e.path1().string ()),
186                                 String::compose (
187                                         _("DCP-o-matic could not open the file %1 (%2).  Perhaps it does not exist or is in an unexpected format."),
188                                         boost::filesystem::absolute (e.path1()).string(),
189                                         e.what()
190                                         )
191                                 );
192                 } else {
193                         set_error (
194                                 e.what (),
195                                 string (_("It is not known what caused this error.")) + "  " + REPORT_PROBLEM
196                                 );
197                 }
198
199                 set_progress (1);
200                 set_state (FINISHED_ERROR);
201
202         } catch (boost::thread_interrupted &) {
203                 /* The job was cancelled; there's nothing else we need to do here */
204         } catch (sub::SubripError& e) {
205
206                 string extra = "Error is near:\n";
207                 for (auto i: e.context()) {
208                         extra += i + "\n";
209                 }
210
211                 set_error (e.what (), extra);
212                 set_progress (1);
213                 set_state (FINISHED_ERROR);
214
215         } catch (std::bad_alloc& e) {
216
217                 set_error (_("Out of memory"), _("There was not enough memory to do this.  If you are running a 32-bit operating system try reducing the number of encoding threads in the General tab of Preferences."));
218                 set_progress (1);
219                 set_state (FINISHED_ERROR);
220
221         } catch (dcp::ReadError& e) {
222
223                 set_error (e.message(), e.detail().get_value_or(""));
224                 set_progress (1);
225                 set_state (FINISHED_ERROR);
226
227         } catch (KDMError& e) {
228
229                 set_error (e.summary(), e.detail());
230                 set_progress (1);
231                 set_state (FINISHED_ERROR);
232
233         } catch (FileError& e) {
234
235                 set_error (e.what(), e.what());
236                 set_progress (1);
237                 set_state (FINISHED_ERROR);
238
239         } catch (CPLNotFoundError& e) {
240
241                 set_error(e.what());
242                 set_progress(1);
243                 set_state(FINISHED_ERROR);
244
245         } catch (std::exception& e) {
246
247                 set_error (
248                         e.what (),
249                         string (_("It is not known what caused this error.")) + "  " + REPORT_PROBLEM
250                         );
251
252                 set_progress (1);
253                 set_state (FINISHED_ERROR);
254
255         } catch (...) {
256
257                 set_error (
258                         _("Unknown error"),
259                         string (_("It is not known what caused this error.")) + "  " + REPORT_PROBLEM
260                         );
261
262                 set_progress (1);
263                 set_state (FINISHED_ERROR);
264         }
265 }
266
267
268 /** @return true if this job is new (ie has not started running) */
269 bool
270 Job::is_new () const
271 {
272         boost::mutex::scoped_lock lm (_state_mutex);
273         return _state == NEW;
274 }
275
276
277 /** @return true if the job is running */
278 bool
279 Job::running () const
280 {
281         boost::mutex::scoped_lock lm (_state_mutex);
282         return _state == RUNNING;
283 }
284
285
286 /** @return true if the job has finished (either successfully or unsuccessfully) */
287 bool
288 Job::finished () const
289 {
290         boost::mutex::scoped_lock lm (_state_mutex);
291         return _state == FINISHED_OK || _state == FINISHED_ERROR || _state == FINISHED_CANCELLED;
292 }
293
294
295 /** @return true if the job has finished successfully */
296 bool
297 Job::finished_ok () const
298 {
299         boost::mutex::scoped_lock lm (_state_mutex);
300         return _state == FINISHED_OK;
301 }
302
303
304 /** @return true if the job has finished unsuccessfully */
305 bool
306 Job::finished_in_error () const
307 {
308         boost::mutex::scoped_lock lm (_state_mutex);
309         return _state == FINISHED_ERROR;
310 }
311
312
313 bool
314 Job::finished_cancelled () const
315 {
316         boost::mutex::scoped_lock lm (_state_mutex);
317         return _state == FINISHED_CANCELLED;
318 }
319
320
321 bool
322 Job::paused_by_user () const
323 {
324         boost::mutex::scoped_lock lm (_state_mutex);
325         return _state == PAUSED_BY_USER;
326 }
327
328
329 bool
330 Job::paused_by_priority () const
331 {
332         boost::mutex::scoped_lock lm (_state_mutex);
333         return _state == PAUSED_BY_PRIORITY;
334 }
335
336
337 /** Set the state of this job.
338  *  @param s New state.
339  */
340 void
341 Job::set_state (State s)
342 {
343         bool finished = false;
344
345         {
346                 boost::mutex::scoped_lock lm (_state_mutex);
347                 if (_state == s) {
348                         return;
349                 }
350
351                 _state = s;
352
353                 if (_state == FINISHED_OK || _state == FINISHED_ERROR || _state == FINISHED_CANCELLED) {
354                         _ran_for = time(0) - _start_time;
355                         finished = true;
356                         _sub_name.clear ();
357                 }
358         }
359
360         if (finished) {
361                 emit (boost::bind (boost::ref (Finished)));
362                 FinishedImmediate ();
363         }
364 }
365
366
367 /** @return DCPTime (in seconds) that this sub-job has been running */
368 int
369 Job::elapsed_sub_time () const
370 {
371         if (_sub_start_time == 0) {
372                 return 0;
373         }
374
375         return time (0) - _sub_start_time;
376 }
377
378
379 /** Check to see if this job has been interrupted or paused */
380 void
381 Job::check_for_interruption_or_pause ()
382 {
383         boost::this_thread::interruption_point ();
384
385         boost::mutex::scoped_lock lm (_state_mutex);
386         while (_state == PAUSED_BY_USER || _state == PAUSED_BY_PRIORITY) {
387                 emit (boost::bind (boost::ref (Progress)));
388                 _pause_changed.wait (lm);
389         }
390 }
391
392
393 optional<float>
394 Job::seconds_since_last_progress_update () const
395 {
396         boost::mutex::scoped_lock lm (_progress_mutex);
397         if (!_last_progress_update) {
398                 return {};
399         }
400
401         struct timeval now;
402         gettimeofday (&now, 0);
403
404         return seconds(now) - seconds(*_last_progress_update);
405 }
406
407
408 /** Set the progress of the current part of the job.
409  *  @param p Progress (from 0 to 1)
410  *  @param force Do not ignore this update, even if it hasn't been long since the last one.
411  */
412 void
413 Job::set_progress (float p, bool force)
414 {
415         check_for_interruption_or_pause ();
416
417         if (!force) {
418                 /* Check for excessively frequent progress reporting */
419                 boost::mutex::scoped_lock lm (_progress_mutex);
420                 struct timeval now;
421                 gettimeofday (&now, 0);
422                 if (_last_progress_update && _last_progress_update->tv_sec > 0) {
423                         double const elapsed = seconds(now) - seconds(*_last_progress_update);
424                         if (elapsed < 0.5) {
425                                 return;
426                         }
427                 }
428                 _last_progress_update = now;
429         }
430
431         set_progress_common (p);
432 }
433
434
435 void
436 Job::set_progress_common (optional<float> p)
437 {
438         {
439                 boost::mutex::scoped_lock lm (_progress_mutex);
440                 _progress = p;
441         }
442
443         emit (boost::bind (boost::ref (Progress)));
444 }
445
446
447 /** @return fractional progress of the current sub-job, if known */
448 optional<float>
449 Job::progress () const
450 {
451         boost::mutex::scoped_lock lm (_progress_mutex);
452         return _progress;
453 }
454
455
456 void
457 Job::sub (string n)
458 {
459         {
460                 boost::mutex::scoped_lock lm (_progress_mutex);
461                 LOG_GENERAL ("Sub-job %1 starting", n);
462                 _sub_name = n;
463         }
464
465         set_progress (0, true);
466         _sub_start_time = time (0);
467 }
468
469
470 string
471 Job::error_details () const
472 {
473         boost::mutex::scoped_lock lm (_state_mutex);
474         return _error_details;
475 }
476
477
478 /** @return A summary of any error that the job has generated */
479 string
480 Job::error_summary () const
481 {
482         boost::mutex::scoped_lock lm (_state_mutex);
483         return _error_summary;
484 }
485
486
487 /** Set the current error string.
488  *  @param s New error string.
489  *  @param d New error detail string.
490  */
491 void
492 Job::set_error (string s, string d)
493 {
494         if (_film) {
495                 _film->log()->log (String::compose ("Error in job: %1 (%2)", s, d), LogEntry::TYPE_ERROR);
496         }
497
498         boost::mutex::scoped_lock lm (_state_mutex);
499         _error_summary = s;
500         _error_details = d;
501 }
502
503
504 /** Say that this job's progress will be unknown until further notice */
505 void
506 Job::set_progress_unknown ()
507 {
508         check_for_interruption_or_pause ();
509         set_progress_common (optional<float> ());
510 }
511
512
513 /** @return Human-readable status of this job */
514 string
515 Job::status () const
516 {
517         optional<float> p = progress ();
518         int const t = elapsed_sub_time ();
519         int const r = remaining_time ();
520
521         auto day_of_week_to_string = [](boost::gregorian::greg_weekday d) -> std::string {
522                 switch (d.as_enum()) {
523                 case boost::date_time::Sunday:
524                         return _("Sunday");
525                 case boost::date_time::Monday:
526                         return _("Monday");
527                 case boost::date_time::Tuesday:
528                         return _("Tuesday");
529                 case boost::date_time::Wednesday:
530                         return _("Wednesday");
531                 case boost::date_time::Thursday:
532                         return _("Thursday");
533                 case boost::date_time::Friday:
534                         return _("Friday");
535                 case boost::date_time::Saturday:
536                         return _("Saturday");
537                 }
538
539                 return d.as_long_string();
540         };
541
542         string s;
543         if (!finished () && p) {
544                 int pc = lrintf (p.get() * 100);
545                 if (pc == 100) {
546                         /* 100% makes it sound like we've finished when we haven't */
547                         pc = 99;
548                 }
549
550                 char buffer[64];
551                 snprintf (buffer, sizeof(buffer), "%d%%", pc);
552                 s += buffer;
553
554                 if (t > 10 && r > 0) {
555                         auto now = boost::posix_time::second_clock::local_time();
556                         auto finish = now + boost::posix_time::seconds(r);
557                         char finish_string[16];
558                         snprintf (finish_string, sizeof(finish_string), "%02d:%02d", int(finish.time_of_day().hours()), int(finish.time_of_day().minutes()));
559                         string day;
560                         if (now.date() != finish.date()) {
561                                 /// TRANSLATORS: the %1 in this string will be filled in with a day of the week
562                                 /// to say what day a job will finish.
563                                 day = String::compose (_(" on %1"), day_of_week_to_string(finish.date().day_of_week()));
564                         }
565                         /// TRANSLATORS: "remaining; finishing at" here follows an amount of time that is remaining
566                         /// on an operation; after it is an estimated wall-clock completion time.
567                         s += String::compose(
568                                 _("; %1 remaining; finishing at %2%3"),
569                                 seconds_to_approximate_hms(r), finish_string, day
570                                 );
571                 }
572         } else if (finished_ok ()) {
573                 s = String::compose (_("OK (ran for %1)"), seconds_to_hms (_ran_for));
574         } else if (finished_in_error ()) {
575                 s = String::compose (_("Error: %1"), error_summary ());
576         } else if (finished_cancelled ()) {
577                 s = _("Cancelled");
578         }
579
580         return s;
581 }
582
583
584 string
585 Job::json_status () const
586 {
587         boost::mutex::scoped_lock lm (_state_mutex);
588
589         switch (_state) {
590         case NEW:
591                 return N_("new");
592         case RUNNING:
593                 return N_("running");
594         case PAUSED_BY_USER:
595         case PAUSED_BY_PRIORITY:
596                 return N_("paused");
597         case FINISHED_OK:
598                 return N_("finished_ok");
599         case FINISHED_ERROR:
600                 return N_("finished_error");
601         case FINISHED_CANCELLED:
602                 return N_("finished_cancelled");
603         }
604
605         return "";
606 }
607
608
609 /** @return An estimate of the remaining time for this sub-job, in seconds */
610 int
611 Job::remaining_time () const
612 {
613         if (progress().get_value_or(0) == 0) {
614                 return elapsed_sub_time ();
615         }
616
617         return elapsed_sub_time() / progress().get() - elapsed_sub_time();
618 }
619
620
621 void
622 Job::cancel ()
623 {
624         if (_thread.joinable()) {
625                 resume();
626
627                 _thread.interrupt ();
628                 _thread.join ();
629         }
630
631         set_state (FINISHED_CANCELLED);
632 }
633
634
635 /** @return true if the job was paused, false if it was not running */
636 bool
637 Job::pause_by_user ()
638 {
639         bool paused = false;
640         {
641                 boost::mutex::scoped_lock lm (_state_mutex);
642                 /* We can set _state here directly because we have a lock and we aren't
643                    setting the job to FINISHED_*
644                 */
645                 if (_state == RUNNING) {
646                         paused = true;
647                         _state = PAUSED_BY_USER;
648                 }
649         }
650
651         if (paused) {
652                 _pause_changed.notify_all ();
653         }
654
655         return paused;
656 }
657
658
659 void
660 Job::pause_by_priority ()
661 {
662         if (running ()) {
663                 set_state (PAUSED_BY_PRIORITY);
664                 _pause_changed.notify_all ();
665         }
666 }
667
668
669 void
670 Job::resume ()
671 {
672         if (paused_by_user() || paused_by_priority()) {
673                 set_state (RUNNING);
674                 _pause_changed.notify_all ();
675         }
676 }
677
678
679 void
680 Job::when_finished (boost::signals2::connection& connection, function<void()> finished)
681 {
682         boost::mutex::scoped_lock lm (_state_mutex);
683         if (_state == FINISHED_OK || _state == FINISHED_ERROR || _state == FINISHED_CANCELLED) {
684                 finished ();
685         } else {
686                 connection = Finished.connect (finished);
687         }
688 }
689
690
691 optional<string>
692 Job::message () const
693 {
694         boost::mutex::scoped_lock lm (_state_mutex);
695         return _message;
696 }
697
698
699 void
700 Job::set_message (string m)
701 {
702         boost::mutex::scoped_lock lm (_state_mutex);
703         _message = m;
704 }