source: trunk/debathena/third/schroot/sbuild/sbuild-lock.cc @ 24167

Revision 24167, 8.4 KB checked in by broder, 15 years ago (diff)
Import schroot upstream into subversion.
Line 
1/* Copyright © 2005-2007  Roger Leigh <rleigh@debian.org>
2 *
3 * schroot is free software: you can redistribute it and/or modify it
4 * under the terms of the GNU General Public License as published by
5 * the Free Software Foundation, either version 3 of the License, or
6 * (at your option) any later version.
7 *
8 * schroot is distributed in the hope that it will be useful, but
9 * WITHOUT ANY WARRANTY; without even the implied warranty of
10 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
11 * General Public License for more details.
12 *
13 * You should have received a copy of the GNU General Public License
14 * along with this program.  If not, see
15 * <http://www.gnu.org/licenses/>.
16 *
17 *********************************************************************/
18
19#include <config.h>
20
21#include "sbuild-lock.h"
22#include "sbuild-log.h"
23
24#include <cerrno>
25#include <cstdlib>
26#include <cstring>
27
28#include <unistd.h>
29
30#include <boost/format.hpp>
31
32#ifdef SBUILD_FEATURE_DEVLOCK
33#include <lockdev.h>
34#endif // SBUILD_FEATURE_DEVLOCK
35
36using boost::format;
37using namespace sbuild;
38
39namespace
40{
41
42  typedef std::pair<lock::error_code,const char *> emap;
43
44  /**
45   * This is a list of the supported error codes.  It's used to
46   * construct the real error codes map.
47   */
48  emap init_errors[] =
49    {
50      emap(lock::TIMEOUT_HANDLER,        N_("Failed to set timeout handler")),
51      emap(lock::TIMEOUT_SET,            N_("Failed to set timeout")),
52      emap(lock::TIMEOUT_CANCEL,         N_("Failed to cancel timeout")),
53      emap(lock::LOCK,                   N_("Failed to lock file")),
54      emap(lock::UNLOCK,                 N_("Failed to unlock file")),
55      // TRANSLATORS: %4% = time in seconds
56      emap(lock::LOCK_TIMEOUT,           N_("Failed to lock file (timed out after %4% seconds)")),
57      // TRANSLATORS: %4% = time in seconds
58      emap(lock::UNLOCK_TIMEOUT,         N_("Failed to unlock file (timed out after %4% seconds)")),
59      emap(lock::DEVICE_LOCK,            N_("Failed to lock device")),
60      // TRANSLATORS: %4% = time in seconds
61      // TRANSLATORS: %5% = integer process ID
62      emap(lock::DEVICE_LOCK_TIMEOUT,    N_("Failed to lock device (timed out after %4% seconds; lock held by PID %5%)")),
63      emap(lock::DEVICE_TEST,            N_("Failed to test device lock")),
64      emap(lock::DEVICE_UNLOCK,         N_("Failed to unlock device")),
65      // TRANSLATORS: %4% = time in seconds
66      // TRANSLATORS: %5% = integer process ID
67      emap(lock::DEVICE_UNLOCK_TIMEOUT, N_("Failed to unlock device (timed out after %4% seconds; lock held by PID %5%)"))
68    };
69
70}
71
72template<>
73error<lock::error_code>::map_type
74error<lock::error_code>::error_strings
75(init_errors,
76 init_errors + (sizeof(init_errors) / sizeof(init_errors[0])));
77
78namespace
79{
80  /// Set to true when a SIGALRM is received.
81  volatile bool lock_timeout = false;
82
83  /**
84   * Handle the SIGALRM signal.
85   *
86   * @param ignore the signal number.
87   */
88  void
89  alarm_handler (int ignore)
90  {
91    /* This exists so that system calls get interrupted. */
92    /* lock_timeout is used for polling for a timeout, rather than
93       interruption, used by the device_lock code. */
94    lock_timeout = true;
95  }
96}
97
98lock::lock ():
99  saved_signals()
100{
101}
102
103lock::~lock ()
104{
105}
106
107void
108lock::set_alarm ()
109{
110  struct sigaction new_sa;
111  sigemptyset(&new_sa.sa_mask);
112  new_sa.sa_flags = 0;
113  new_sa.sa_handler = alarm_handler;
114
115  if (sigaction(SIGALRM, &new_sa, &this->saved_signals) != 0)
116    throw error(TIMEOUT_HANDLER, strerror(errno));
117}
118
119void
120lock::clear_alarm ()
121{
122  /* Restore original handler */
123  sigaction (SIGALRM, &this->saved_signals, 0);
124}
125
126void
127lock::set_timer(struct itimerval const& timer)
128{
129  set_alarm();
130
131  if (setitimer(ITIMER_REAL, &timer, 0) == -1)
132    {
133      clear_alarm();
134      throw error(TIMEOUT_SET, strerror(errno));
135    }
136}
137
138void
139lock::unset_timer ()
140{
141  struct itimerval disable_timer;
142  disable_timer.it_interval.tv_sec = disable_timer.it_interval.tv_usec = 0;
143  disable_timer.it_value.tv_sec = disable_timer.it_value.tv_usec = 0;
144
145  if (setitimer(ITIMER_REAL, &disable_timer, 0) == -1)
146    {
147      clear_alarm();
148      throw error(TIMEOUT_CANCEL, strerror(errno));
149    }
150
151  clear_alarm();
152}
153
154file_lock::file_lock (int fd):
155  lock(),
156  fd(fd),
157  locked(false)
158{
159}
160
161file_lock::~file_lock ()
162{
163  // Release a lock if held.  Note that the code is duplicated from
164  // set_lock because we don't want to throw an exception in a
165  // destructor under any circumstances.  Any error is logged.
166  if (locked)
167    {
168      struct flock read_lock;
169      read_lock.l_type = LOCK_NONE;
170      read_lock.l_whence = SEEK_SET;
171      read_lock.l_start = 0;
172      read_lock.l_len = 0; // Lock entire file
173      read_lock.l_pid = 0;
174
175      if (fcntl(this->fd, F_SETLK, &read_lock) == -1)
176        log_exception_warning(error(UNLOCK, strerror(errno)));
177    }
178}
179
180void
181file_lock::set_lock (lock::type   lock_type,
182                     unsigned int timeout)
183{
184  try
185    {
186      struct itimerval timeout_timer;
187      timeout_timer.it_interval.tv_sec = timeout_timer.it_interval.tv_usec = 0;
188      timeout_timer.it_value.tv_sec = timeout;
189      timeout_timer.it_value.tv_usec = 0;
190      set_timer(timeout_timer);
191
192      /* Now the signal handler and itimer are set, the function can't
193         return without stopping the timer and restoring the signal
194         handler to its original state. */
195
196      /* Wait on lock until interrupted by a signal if a timeout was set,
197         otherwise return immediately. */
198      struct flock read_lock;
199      read_lock.l_type = lock_type;
200      read_lock.l_whence = SEEK_SET;
201      read_lock.l_start = 0;
202      read_lock.l_len = 0; // Lock entire file
203      read_lock.l_pid = 0;
204
205      if (fcntl(this->fd,
206                (timeout != 0) ? F_SETLKW : F_SETLK,
207                &read_lock) == -1)
208        {
209          if (errno == EINTR)
210            throw error((lock_type == LOCK_SHARED ||
211                         lock_type == LOCK_EXCLUSIVE)
212                        ? LOCK_TIMEOUT : UNLOCK_TIMEOUT,
213                        timeout);
214          else
215            throw error((lock_type == LOCK_SHARED ||
216                         lock_type == LOCK_EXCLUSIVE) ? LOCK : UNLOCK,
217                        strerror(errno));
218        }
219
220      if (lock_type == LOCK_SHARED || lock_type == LOCK_EXCLUSIVE)
221        this->locked = true;
222      else
223        this->locked = false;
224
225      unset_timer();
226    }
227  catch (error const& e)
228    {
229      unset_timer();
230      throw;
231    }
232}
233
234void
235file_lock::unset_lock ()
236{
237  set_lock(LOCK_NONE, 0);
238}
239
240#ifdef SBUILD_FEATURE_DEVLOCK
241
242device_lock::device_lock (std::string const& device):
243  lock(),
244  device(device),
245  locked(false)
246{
247}
248
249device_lock::~device_lock ()
250{
251  if (locked)
252    {
253      pid_t status = 0;
254      status = dev_unlock(this->device.c_str(), getpid());
255      if (status < 0) // Failure
256        log_exception_warning(error(DEVICE_UNLOCK));
257    }
258}
259
260void
261device_lock::set_lock (lock::type   lock_type,
262                       unsigned int timeout)
263{
264  try
265    {
266      lock_timeout = false;
267
268      struct itimerval timeout_timer;
269      timeout_timer.it_interval.tv_sec = timeout_timer.it_interval.tv_usec = 0;
270      timeout_timer.it_value.tv_sec = timeout;
271      timeout_timer.it_value.tv_usec = 0;
272      set_timer(timeout_timer);
273
274      /* Now the signal handler and itimer are set, the function can't
275         return without stopping the timer and restoring the signal
276         handler to its original state. */
277
278      /* Wait on lock until interrupted by a signal if a timeout was set,
279         otherwise return immediately. */
280      pid_t status = 0;
281      while (lock_timeout == false)
282        {
283          if (lock_type == LOCK_SHARED || lock_type == LOCK_EXCLUSIVE)
284            {
285              status = dev_lock(this->device.c_str());
286              if (status == 0) // Success
287                {
288                  this->locked = true;
289                  break;
290                }
291              else if (status < 0) // Failure
292                {
293                  throw error(DEVICE_LOCK);
294                }
295            }
296          else
297            {
298              pid_t cur_lock_pid = dev_testlock(this->device.c_str());
299              if (cur_lock_pid < 0) // Test failure
300                {
301                  throw error(DEVICE_TEST);
302                }
303              else if (cur_lock_pid > 0 && cur_lock_pid != getpid())
304                {
305                  // Another process owns the lock, so we successfully
306                  // "drop" our nonexistent lock.
307                  break;
308                }
309              status = dev_unlock(this->device.c_str(), getpid());
310              if (status == 0) // Success
311                {
312                  this->locked = false;
313                  break;
314                }
315              else if (status < 0) // Failure
316                {
317                  throw error(DEVICE_UNLOCK);
318                }
319            }
320        }
321
322      if (lock_timeout)
323        {
324          throw error(((lock_type == LOCK_SHARED || lock_type == LOCK_EXCLUSIVE)
325                       ? DEVICE_LOCK_TIMEOUT : DEVICE_UNLOCK_TIMEOUT),
326                      timeout, status);
327        }
328
329      unset_timer();
330    }
331  catch (error const& e)
332    {
333      unset_timer();
334      throw;
335    }
336}
337
338void
339device_lock::unset_lock ()
340{
341  set_lock(LOCK_NONE, 0);
342}
343
344#endif // SBUILD_FEATURE_DEVLOCK
345
Note: See TracBrowser for help on using the repository browser.