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