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