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