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