2 Copyright (C) 2012-2016 Carl Hetherington <cth@carlh.net>
4 This file is part of DCP-o-matic.
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.
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.
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/>.
22 * @brief A parent class to represent long-running tasks which are run in their own thread.
28 #include "exceptions.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>
45 using boost::shared_ptr;
46 using boost::optional;
47 using boost::function;
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); }
52 /** @param film Associated film, or 0 */
53 Job::Job (shared_ptr<const Film> film)
68 _thread->interrupt ();
69 /* We can't use DCPOMATIC_ASSERT here as it may throw an exception */
70 if (_thread->joinable ()) {
74 /* Too late to do anything about this */
82 /** Start the job in a separate thread, returning immediately */
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");
95 /** A wrapper for the ::run() method to catch exceptions */
103 } catch (dcp::FileError& e) {
105 string m = String::compose (_("An error occurred whilst handling the file %1."), boost::filesystem::path (e.filename()).leaf());
108 boost::filesystem::space_info const s = boost::filesystem::space (e.filename());
109 if (s.available < pow (1024, 3)) {
111 m += _("The drive that the film is stored on is low in disc space. Free some more space and try again.");
117 set_error (e.what(), m);
119 set_state (FINISHED_ERROR);
121 } catch (OpenFileError& e) {
124 String::compose (_("Could not open %1"), e.file().string()),
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(),
133 set_state (FINISHED_ERROR);
135 } catch (boost::filesystem::filesystem_error& e) {
137 if (e.code() == boost::system::errc::no_such_file_or_directory) {
139 String::compose (_("Could not open %1"), e.path1().string ()),
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(),
149 string (_("It is not known what caused this error.")) + " " + REPORT_PROBLEM
154 set_state (FINISHED_ERROR);
156 } catch (boost::thread_interrupted &) {
158 set_state (FINISHED_CANCELLED);
160 } catch (sub::SubripError& e) {
162 string extra = "Error is near:\n";
163 BOOST_FOREACH (string i, e.context()) {
167 set_error (e.what (), extra);
169 set_state (FINISHED_ERROR);
171 } catch (std::bad_alloc& e) {
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."));
175 set_state (FINISHED_ERROR);
177 } catch (dcp::DCPReadError& e) {
179 set_error (e.what(), "");//message(), e.detail().get_value_or(""));
181 set_state (FINISHED_ERROR);
183 } catch (KDMError& e) {
185 set_error (e.summary(), e.detail());
187 set_state (FINISHED_ERROR);
189 } catch (std::exception& e) {
193 string (_("It is not known what caused this error.")) + " " + REPORT_PROBLEM
197 set_state (FINISHED_ERROR);
203 string (_("It is not known what caused this error.")) + " " + REPORT_PROBLEM
207 set_state (FINISHED_ERROR);
211 /** @return true if this job is new (ie has not started running) */
215 boost::mutex::scoped_lock lm (_state_mutex);
216 return _state == NEW;
219 /** @return true if the job is running */
221 Job::running () const
223 boost::mutex::scoped_lock lm (_state_mutex);
224 return _state == RUNNING;
227 /** @return true if the job has finished (either successfully or unsuccessfully) */
229 Job::finished () const
231 boost::mutex::scoped_lock lm (_state_mutex);
232 return _state == FINISHED_OK || _state == FINISHED_ERROR || _state == FINISHED_CANCELLED;
235 /** @return true if the job has finished successfully */
237 Job::finished_ok () const
239 boost::mutex::scoped_lock lm (_state_mutex);
240 return _state == FINISHED_OK;
243 /** @return true if the job has finished unsuccessfully */
245 Job::finished_in_error () const
247 boost::mutex::scoped_lock lm (_state_mutex);
248 return _state == FINISHED_ERROR;
252 Job::finished_cancelled () const
254 boost::mutex::scoped_lock lm (_state_mutex);
255 return _state == FINISHED_CANCELLED;
259 Job::paused_by_user () const
261 boost::mutex::scoped_lock lm (_state_mutex);
262 return _state == PAUSED_BY_USER;
266 Job::paused_by_priority () const
268 boost::mutex::scoped_lock lm (_state_mutex);
269 return _state == PAUSED_BY_PRIORITY;
272 /** Set the state of this job.
273 * @param s New state.
276 Job::set_state (State s)
278 bool finished = false;
281 boost::mutex::scoped_lock lm (_state_mutex);
284 if (_state == FINISHED_OK || _state == FINISHED_ERROR || _state == FINISHED_CANCELLED) {
285 _ran_for = time(0) - _start_time;
293 emit (boost::bind (boost::ref (Finished)));
296 Analytics::instance()->job_state_changed (this);
299 /** @return DCPTime (in seconds) that this sub-job has been running */
301 Job::elapsed_sub_time () const
303 if (_sub_start_time == 0) {
307 return time (0) - _sub_start_time;
310 /** Check to see if this job has been interrupted or paused */
312 Job::check_for_interruption_or_pause ()
314 boost::this_thread::interruption_point ();
316 boost::mutex::scoped_lock lm (_state_mutex);
317 while (_state == PAUSED_BY_USER || _state == PAUSED_BY_PRIORITY) {
318 emit (boost::bind (boost::ref (Progress)));
319 _pause_changed.wait (lm);
323 /** Set the progress of the current part of the job.
324 * @param p Progress (from 0 to 1)
325 * @param force Do not ignore this update, even if it hasn't been long since the last one.
328 Job::set_progress (float p, bool force)
330 check_for_interruption_or_pause ();
333 /* Check for excessively frequent progress reporting */
334 boost::mutex::scoped_lock lm (_progress_mutex);
336 gettimeofday (&now, 0);
337 if (_last_progress_update && _last_progress_update->tv_sec > 0) {
338 double const elapsed = (now.tv_sec + now.tv_usec / 1000000.0)
339 - (_last_progress_update->tv_sec + _last_progress_update->tv_usec / 1000000.0);
344 _last_progress_update = now;
347 set_progress_common (p);
351 Job::set_progress_common (optional<float> p)
354 boost::mutex::scoped_lock lm (_progress_mutex);
358 emit (boost::bind (boost::ref (Progress)));
361 /** @return fractional progress of the current sub-job, if known */
363 Job::progress () const
365 boost::mutex::scoped_lock lm (_progress_mutex);
373 boost::mutex::scoped_lock lm (_progress_mutex);
374 LOG_GENERAL ("Sub-job %1 starting", n);
378 set_progress (0, true);
379 _sub_start_time = time (0);
383 Job::error_details () const
385 boost::mutex::scoped_lock lm (_state_mutex);
386 return _error_details;
389 /** @return A summary of any error that the job has generated */
391 Job::error_summary () const
393 boost::mutex::scoped_lock lm (_state_mutex);
394 return _error_summary;
397 /** Set the current error string.
398 * @param s New error string.
399 * @param d New error detail string.
402 Job::set_error (string s, string d)
407 _film->log()->log (String::compose ("Error in job: %1 (%2)", s, d), LogEntry::TYPE_ERROR);
410 boost::mutex::scoped_lock lm (_state_mutex);
415 /** Say that this job's progress will be unknown until further notice */
417 Job::set_progress_unknown ()
419 check_for_interruption_or_pause ();
420 set_progress_common (optional<float> ());
423 /** @return Human-readable status of this job */
427 optional<float> p = progress ();
428 int const t = elapsed_sub_time ();
429 int const r = remaining_time ();
432 if (!finished () && p) {
433 int pc = lrintf (p.get() * 100);
435 /* 100% makes it sound like we've finished when we haven't */
440 snprintf (buffer, sizeof(buffer), "%d%%", pc);
443 if (t > 10 && r > 0) {
444 boost::posix_time::ptime now = boost::posix_time::second_clock::local_time();
445 boost::posix_time::ptime finish = now + boost::posix_time::seconds(r);
446 char finish_string[16];
447 snprintf (finish_string, sizeof(finish_string), "%02d:%02d", int(finish.time_of_day().hours()), int(finish.time_of_day().minutes()));
449 if (now.date() != finish.date()) {
450 /// TRANSLATORS: the %1 in this string will be filled in with a day of the week
451 /// to say what day a job will finish.
452 day = String::compose (_(" on %1"), finish.date().day_of_week().as_long_string());
454 /// TRANSLATORS: "remaining; finishing at" here follows an amount of time that is remaining
455 /// on an operation; after it is an estimated wall-clock completion time.
456 s += String::compose(
457 _("; %1 remaining; finishing at %2%3"),
458 seconds_to_approximate_hms(r), finish_string, day
461 } else if (finished_ok ()) {
462 s = String::compose (_("OK (ran for %1)"), seconds_to_hms (_ran_for));
463 } else if (finished_in_error ()) {
464 s = String::compose (_("Error: %1"), error_summary ());
465 } else if (finished_cancelled ()) {
473 Job::json_status () const
475 boost::mutex::scoped_lock lm (_state_mutex);
481 return N_("running");
483 case PAUSED_BY_PRIORITY:
486 return N_("finished_ok");
488 return N_("finished_error");
489 case FINISHED_CANCELLED:
490 return N_("finished_cancelled");
496 /** @return An estimate of the remaining time for this sub-job, in seconds */
498 Job::remaining_time () const
500 if (progress().get_value_or(0) == 0) {
501 return elapsed_sub_time ();
504 return elapsed_sub_time() / progress().get() - elapsed_sub_time();
514 if (paused_by_user() || paused_by_priority()) {
518 _thread->interrupt ();
519 DCPOMATIC_ASSERT (_thread->joinable ());
526 Job::pause_by_user ()
529 set_state (PAUSED_BY_USER);
530 _pause_changed.notify_all ();
535 Job::pause_by_priority ()
538 set_state (PAUSED_BY_PRIORITY);
539 _pause_changed.notify_all ();
546 if (paused_by_user() || paused_by_priority()) {
548 _pause_changed.notify_all ();
553 Job::when_finished (boost::signals2::connection& connection, function<void()> finished)
555 boost::mutex::scoped_lock lm (_state_mutex);
556 if (_state == FINISHED_OK || _state == FINISHED_ERROR || _state == FINISHED_CANCELLED) {
559 connection = Finished.connect (finished);