Fix nasty race in dcpomatic_create.
[dcpomatic.git] / src / lib / job.cc
1 /*
2     Copyright (C) 2012 Carl Hetherington <cth@carlh.net>
3
4     This program is free software; you can redistribute it and/or modify
5     it under the terms of the GNU General Public License as published by
6     the Free Software Foundation; either version 2 of the License, or
7     (at your option) any later version.
8
9     This program is distributed in the hope that it will be useful,
10     but WITHOUT ANY WARRANTY; without even the implied warranty of
11     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12     GNU General Public License for more details.
13
14     You should have received a copy of the GNU General Public License
15     along with this program; if not, write to the Free Software
16     Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
17
18 */
19
20 /** @file src/job.cc
21  *  @brief A parent class to represent long-running tasks which are run in their own thread.
22  */
23
24 #include <boost/thread.hpp>
25 #include <boost/filesystem.hpp>
26 #include <libdcp/exceptions.h>
27 #include "job.h"
28 #include "util.h"
29 #include "cross.h"
30 #include "ui_signaller.h"
31 #include "exceptions.h"
32
33 #include "i18n.h"
34
35 using std::string;
36 using std::list;
37 using std::cout;
38 using std::stringstream;
39 using boost::shared_ptr;
40
41 Job::Job (shared_ptr<const Film> f)
42         : _film (f)
43         , _thread (0)
44         , _state (NEW)
45         , _start_time (0)
46         , _progress (0)
47         , _ran_for (0)
48 {
49
50 }
51
52 /** Start the job in a separate thread, returning immediately */
53 void
54 Job::start ()
55 {
56         set_state (RUNNING);
57         _start_time = time (0);
58         _thread = new boost::thread (boost::bind (&Job::run_wrapper, this));
59 }
60
61 /** A wrapper for the ::run() method to catch exceptions */
62 void
63 Job::run_wrapper ()
64 {
65         try {
66
67                 run ();
68
69         } catch (libdcp::FileError& e) {
70                 
71                 string m = String::compose (_("An error occurred whilst handling the file %1."), boost::filesystem::path (e.filename()).leaf());
72
73                 try {
74                         boost::filesystem::space_info const s = boost::filesystem::space (e.filename());
75                         if (s.available < pow (1024, 3)) {
76                                 m += N_("\n\n");
77                                 m += _("The drive that the film is stored on is low in disc space.  Free some more space and try again.");
78                         }
79                 } catch (...) {
80
81                 }
82
83                 set_error (e.what(), m);
84                 set_progress (1);
85                 set_state (FINISHED_ERROR);
86                 
87         } catch (OpenFileError& e) {
88
89                 set_error (
90                         String::compose (_("Could not open %1"), e.file().string()),
91                         String::compose (_("DCP-o-matic could not open the file %1.  Perhaps it does not exist or is in an unexpected format."), e.file().string())
92                         );
93
94                 set_progress (1);
95                 set_state (FINISHED_ERROR);
96
97         } catch (boost::thread_interrupted &) {
98
99                 set_state (FINISHED_CANCELLED);
100
101         } catch (std::bad_alloc& e) {
102
103                 set_error (_("Out of memory"), _("There was not enough memory to do this."));
104                 set_progress (1);
105                 set_state (FINISHED_ERROR);
106                 
107         } catch (std::exception& e) {
108
109                 set_error (
110                         e.what (),
111                         _("It is not known what caused this error.  The best idea is to report the problem to the DCP-o-matic mailing list (carl@dcpomatic.com)")
112                         );
113
114                 set_progress (1);
115                 set_state (FINISHED_ERROR);
116                 
117         } catch (...) {
118
119                 set_error (
120                         _("Unknown error"),
121                         _("It is not known what caused this error.  The best idea is to report the problem to the DCP-o-matic mailing list (carl@dcpomatic.com)")
122                         );
123
124                 set_progress (1);
125                 set_state (FINISHED_ERROR);
126         }
127 }
128
129 /** @return true if this job is new (ie has not started running) */
130 bool
131 Job::is_new () const
132 {
133         boost::mutex::scoped_lock lm (_state_mutex);
134         return _state == NEW;
135 }
136
137 /** @return true if the job is running */
138 bool
139 Job::running () const
140 {
141         boost::mutex::scoped_lock lm (_state_mutex);
142         return _state == RUNNING;
143 }
144
145 /** @return true if the job has finished (either successfully or unsuccessfully) */
146 bool
147 Job::finished () const
148 {
149         boost::mutex::scoped_lock lm (_state_mutex);
150         return _state == FINISHED_OK || _state == FINISHED_ERROR || _state == FINISHED_CANCELLED;
151 }
152
153 /** @return true if the job has finished successfully */
154 bool
155 Job::finished_ok () const
156 {
157         boost::mutex::scoped_lock lm (_state_mutex);
158         return _state == FINISHED_OK;
159 }
160
161 /** @return true if the job has finished unsuccessfully */
162 bool
163 Job::finished_in_error () const
164 {
165         boost::mutex::scoped_lock lm (_state_mutex);
166         return _state == FINISHED_ERROR;
167 }
168
169 bool
170 Job::finished_cancelled () const
171 {
172         boost::mutex::scoped_lock lm (_state_mutex);
173         return _state == FINISHED_CANCELLED;
174 }
175
176 bool
177 Job::paused () const
178 {
179         boost::mutex::scoped_lock lm (_state_mutex);
180         return _state == PAUSED;
181 }
182         
183 /** Set the state of this job.
184  *  @param s New state.
185  */
186 void
187 Job::set_state (State s)
188 {
189         bool const finished = (s == FINISHED_OK || s == FINISHED_ERROR || s == FINISHED_CANCELLED);
190         
191         /* Do this first, so that we handle things that should happen on finish before the
192          * job is actually marked as such.  This is important for callers that do:
193          *
194          * while (JobManager::work_to_do ()) {
195          *   ui_signaller->ui_idle ();
196          * }
197          *
198          * as otherwise this loop can finish before the Finished handler has been executed
199          * (job finishes, calls set_state(), this sets the state and sets a pending signal
200          * for Finished, but this is never called as a ui_idle() never happens as work_to_do()
201          * is now false).
202          */
203         if (finished && ui_signaller) {
204                 ui_signaller->emit (boost::bind (boost::ref (Finished)));
205         }
206
207         {
208                 boost::mutex::scoped_lock lm (_state_mutex);
209                 _state = s;
210
211                 if (finished) {
212                         _ran_for = elapsed_time ();
213                         _sub_name.clear ();
214                 }
215         }
216 }
217
218 /** @return Time (in seconds) that this sub-job has been running */
219 int
220 Job::elapsed_time () const
221 {
222         if (_start_time == 0) {
223                 return 0;
224         }
225         
226         return time (0) - _start_time;
227 }
228
229 /** Set the progress of the current part of the job.
230  *  @param p Progress (from 0 to 1)
231  */
232 void
233 Job::set_progress (float p, bool force)
234 {
235         if (!force && fabs (p - progress()) < 0.01) {
236                 /* Calm excessive progress reporting */
237                 return;
238         }
239
240         boost::mutex::scoped_lock lm (_progress_mutex);
241         _progress = p;
242         boost::this_thread::interruption_point ();
243
244         if (paused ()) {
245                 dcpomatic_sleep (1);
246         }
247
248         if (ui_signaller) {
249                 ui_signaller->emit (boost::bind (boost::ref (Progress)));
250         }
251 }
252
253 /** @return fractional progress of the current sub-job, or -1 if not known */
254 float
255 Job::progress () const
256 {
257         boost::mutex::scoped_lock lm (_progress_mutex);
258         return _progress.get_value_or (-1);
259 }
260
261 void
262 Job::sub (string n)
263 {
264         {
265                 boost::mutex::scoped_lock lm (_progress_mutex);
266                 _sub_name = n;
267         }
268         
269         set_progress (0, true);
270 }
271
272 string
273 Job::error_details () const
274 {
275         boost::mutex::scoped_lock lm (_state_mutex);
276         return _error_details;
277 }
278
279 /** @return A summary of any error that the job has generated */
280 string
281 Job::error_summary () const
282 {
283         boost::mutex::scoped_lock lm (_state_mutex);
284         return _error_summary;
285 }
286
287 /** Set the current error string.
288  *  @param e New error string.
289  */
290 void
291 Job::set_error (string s, string d)
292 {
293         boost::mutex::scoped_lock lm (_state_mutex);
294         _error_summary = s;
295         _error_details = d;
296 }
297
298 /** Say that this job's progress will be unknown until further notice */
299 void
300 Job::set_progress_unknown ()
301 {
302         boost::mutex::scoped_lock lm (_progress_mutex);
303         _progress.reset ();
304 }
305
306 /** @return Human-readable status of this job */
307 string
308 Job::status () const
309 {
310         float const p = progress ();
311         int const t = elapsed_time ();
312         int const r = remaining_time ();
313
314         int pc = rint (p * 100);
315         if (pc == 100) {
316                 /* 100% makes it sound like we've finished when we haven't */
317                 pc = 99;
318         }
319
320         stringstream s;
321         if (!finished ()) {
322                 s << pc << N_("%");
323                 if (p >= 0 && t > 10 && r > 0) {
324                         /// TRANSLATORS: remaining here follows an amount of time that is remaining
325                         /// on an operation.
326                         s << "; " << seconds_to_approximate_hms (r) << " " << _("remaining");
327                 }
328         } else if (finished_ok ()) {
329                 s << String::compose (_("OK (ran for %1)"), seconds_to_hms (_ran_for));
330         } else if (finished_in_error ()) {
331                 s << String::compose (_("Error (%1)"), error_summary());
332         } else if (finished_cancelled ()) {
333                 s << _("Cancelled");
334         }
335
336         return s.str ();
337 }
338
339 string
340 Job::json_status () const
341 {
342         boost::mutex::scoped_lock lm (_state_mutex);
343
344         switch (_state) {
345         case NEW:
346                 return N_("new");
347         case RUNNING:
348                 return N_("running");
349         case PAUSED:
350                 return N_("paused");
351         case FINISHED_OK:
352                 return N_("finished_ok");
353         case FINISHED_ERROR:
354                 return N_("finished_error");
355         case FINISHED_CANCELLED:
356                 return N_("finished_cancelled");
357         }
358
359         return "";
360 }
361
362 /** @return An estimate of the remaining time for this sub-job, in seconds */
363 int
364 Job::remaining_time () const
365 {
366         return elapsed_time() / progress() - elapsed_time();
367 }
368
369 void
370 Job::cancel ()
371 {
372         if (!_thread) {
373                 return;
374         }
375
376         _thread->interrupt ();
377         _thread->join ();
378 }
379
380 void
381 Job::pause ()
382 {
383         if (running ()) {
384                 set_state (PAUSED);
385         }
386 }
387
388 void
389 Job::resume ()
390 {
391         if (paused ()) {
392                 set_state (RUNNING);
393         }
394 }