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