File: sbuild-lock.cc

package info (click to toggle)
schroot 1.6.4-4
  • links: PTS, VCS
  • area: main
  • in suites: wheezy
  • size: 6,684 kB
  • sloc: cpp: 21,427; sh: 12,516; makefile: 829; ansic: 231; sed: 16
file content (351 lines) | stat: -rw-r--r-- 8,737 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
/* Copyright © 2005-2007  Roger Leigh <rleigh@debian.org>
 *
 * schroot is free software: you can redistribute it and/or modify it
 * under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * schroot is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see
 * <http://www.gnu.org/licenses/>.
 *
 *********************************************************************/

#include <config.h>

#include "sbuild-lock.h"
#include "sbuild-log.h"
#include "sbuild-feature.h"

#include <cerrno>
#include <cstdlib>
#include <cstring>

#include <unistd.h>

#include <boost/format.hpp>

#ifdef SBUILD_FEATURE_DEVLOCK
#include <lockdev.h>
#endif // SBUILD_FEATURE_DEVLOCK

using boost::format;
using namespace sbuild;

namespace
{

  typedef std::pair<lock::error_code,const char *> emap;

  /**
   * This is a list of the supported error codes.  It's used to
   * construct the real error codes map.
   */
  emap init_errors[] =
    {
      emap(lock::TIMEOUT_HANDLER,        N_("Failed to set timeout handler")),
      emap(lock::TIMEOUT_SET,            N_("Failed to set timeout")),
      emap(lock::TIMEOUT_CANCEL,         N_("Failed to cancel timeout")),
      emap(lock::LOCK,                   N_("Failed to lock file")),
      emap(lock::UNLOCK,                 N_("Failed to unlock file")),
      // TRANSLATORS: %4% = time in seconds
      emap(lock::LOCK_TIMEOUT,           N_("Failed to lock file (timed out after %4% seconds)")),
      // TRANSLATORS: %4% = time in seconds
      emap(lock::UNLOCK_TIMEOUT,         N_("Failed to unlock file (timed out after %4% seconds)")),
      emap(lock::DEVICE_LOCK,            N_("Failed to lock device")),
      // TRANSLATORS: %4% = time in seconds
      // TRANSLATORS: %5% = integer process ID
      emap(lock::DEVICE_LOCK_TIMEOUT,    N_("Failed to lock device (timed out after %4% seconds; lock held by PID %5%)")),
      emap(lock::DEVICE_TEST,            N_("Failed to test device lock")),
      emap(lock::DEVICE_UNLOCK,         N_("Failed to unlock device")),
      // TRANSLATORS: %4% = time in seconds
      // TRANSLATORS: %5% = integer process ID
      emap(lock::DEVICE_UNLOCK_TIMEOUT, N_("Failed to unlock device (timed out after %4% seconds; lock held by PID %5%)"))
    };

}

template<>
error<lock::error_code>::map_type
error<lock::error_code>::error_strings
(init_errors,
 init_errors + (sizeof(init_errors) / sizeof(init_errors[0])));

namespace
{
  /// Set to true when a SIGALRM is received.
  volatile bool lock_timeout = false;

  /**
   * Handle the SIGALRM signal.
   *
   * @param ignore the signal number.
   */
  void
  alarm_handler (int ignore)
  {
    /* This exists so that system calls get interrupted. */
    /* lock_timeout is used for polling for a timeout, rather than
       interruption, used by the device_lock code. */
    lock_timeout = true;
  }
}

lock::lock ():
  saved_signals()
{
}

lock::~lock ()
{
}

void
lock::set_alarm ()
{
  struct sigaction new_sa;
  sigemptyset(&new_sa.sa_mask);
  new_sa.sa_flags = 0;
  new_sa.sa_handler = alarm_handler;

  if (sigaction(SIGALRM, &new_sa, &this->saved_signals) != 0)
    throw error(TIMEOUT_HANDLER, strerror(errno));
}

void
lock::clear_alarm ()
{
  /* Restore original handler */
  sigaction (SIGALRM, &this->saved_signals, 0);
}

void
lock::set_timer(struct itimerval const& timer)
{
  set_alarm();

  if (setitimer(ITIMER_REAL, &timer, 0) == -1)
    {
      clear_alarm();
      throw error(TIMEOUT_SET, strerror(errno));
    }
}

void
lock::unset_timer ()
{
  struct itimerval disable_timer;
  disable_timer.it_interval.tv_sec = disable_timer.it_interval.tv_usec = 0;
  disable_timer.it_value.tv_sec = disable_timer.it_value.tv_usec = 0;

  if (setitimer(ITIMER_REAL, &disable_timer, 0) == -1)
    {
      clear_alarm();
      throw error(TIMEOUT_CANCEL, strerror(errno));
    }

  clear_alarm();
}

file_lock::file_lock (int fd):
  lock(),
  fd(fd),
  locked(false)
{
}

file_lock::~file_lock ()
{
  // Release a lock if held.  Note that the code is duplicated from
  // set_lock because we don't want to throw an exception in a
  // destructor under any circumstances.  Any error is logged.
  if (locked)
    {
      struct flock read_lock;
      read_lock.l_type = LOCK_NONE;
      read_lock.l_whence = SEEK_SET;
      read_lock.l_start = 0;
      read_lock.l_len = 0; // Lock entire file
      read_lock.l_pid = 0;

      if (fcntl(this->fd, F_SETLK, &read_lock) == -1)
	log_exception_warning(error(UNLOCK, strerror(errno)));
    }
}

void
file_lock::set_lock (lock::type   lock_type,
		     unsigned int timeout)
{
  try
    {
      struct itimerval timeout_timer;
      timeout_timer.it_interval.tv_sec = timeout_timer.it_interval.tv_usec = 0;
      timeout_timer.it_value.tv_sec = timeout;
      timeout_timer.it_value.tv_usec = 0;
      set_timer(timeout_timer);

      /* Now the signal handler and itimer are set, the function can't
	 return without stopping the timer and restoring the signal
	 handler to its original state. */

      /* Wait on lock until interrupted by a signal if a timeout was set,
	 otherwise return immediately. */
      struct flock read_lock;
      read_lock.l_type = lock_type;
      read_lock.l_whence = SEEK_SET;
      read_lock.l_start = 0;
      read_lock.l_len = 0; // Lock entire file
      read_lock.l_pid = 0;

      if (fcntl(this->fd,
		(timeout != 0) ? F_SETLKW : F_SETLK,
		&read_lock) == -1)
	{
	  if (errno == EINTR)
	    throw error((lock_type == LOCK_SHARED ||
			 lock_type == LOCK_EXCLUSIVE)
			? LOCK_TIMEOUT : UNLOCK_TIMEOUT,
			timeout);
	  else
	    throw error((lock_type == LOCK_SHARED ||
			 lock_type == LOCK_EXCLUSIVE) ? LOCK : UNLOCK,
			strerror(errno));
	}

      if (lock_type == LOCK_SHARED || lock_type == LOCK_EXCLUSIVE)
	this->locked = true;
      else
	this->locked = false;

      unset_timer();
    }
  catch (error const& e)
    {
      unset_timer();
      throw;
    }
}

void
file_lock::unset_lock ()
{
  set_lock(LOCK_NONE, 0);
}

#ifdef SBUILD_FEATURE_DEVLOCK

namespace
{
  sbuild::feature feature_devlock("DEVLOCK", N_("Device locking"));
}

device_lock::device_lock (std::string const& device):
  lock(),
  device(device),
  locked(false)
{
}

device_lock::~device_lock ()
{
  if (locked)
    {
      pid_t status = 0;
      status = dev_unlock(this->device.c_str(), getpid());
      if (status < 0) // Failure
	log_exception_warning(error(DEVICE_UNLOCK));
    }
}

void
device_lock::set_lock (lock::type   lock_type,
		       unsigned int timeout)
{
  try
    {
      lock_timeout = false;

      struct itimerval timeout_timer;
      timeout_timer.it_interval.tv_sec = timeout_timer.it_interval.tv_usec = 0;
      timeout_timer.it_value.tv_sec = timeout;
      timeout_timer.it_value.tv_usec = 0;
      set_timer(timeout_timer);

      /* Now the signal handler and itimer are set, the function can't
	 return without stopping the timer and restoring the signal
	 handler to its original state. */

      /* Wait on lock until interrupted by a signal if a timeout was set,
	 otherwise return immediately. */
      pid_t status = 0;
      while (lock_timeout == false)
	{
	  if (lock_type == LOCK_SHARED || lock_type == LOCK_EXCLUSIVE)
	    {
	      status = dev_lock(this->device.c_str());
	      if (status == 0) // Success
		{
		  this->locked = true;
		  break;
		}
	      else if (status < 0) // Failure
		{
		  throw error(DEVICE_LOCK);
		}
	    }
	  else
	    {
	      pid_t cur_lock_pid = dev_testlock(this->device.c_str());
	      if (cur_lock_pid < 0) // Test failure
		{
		  throw error(DEVICE_TEST);
		}
	      else if (cur_lock_pid > 0 && cur_lock_pid != getpid())
		{
		  // Another process owns the lock, so we successfully
		  // "drop" our nonexistent lock.
		  break;
		}
	      status = dev_unlock(this->device.c_str(), getpid());
	      if (status == 0) // Success
		{
		  this->locked = false;
		  break;
		}
	      else if (status < 0) // Failure
		{
		  throw error(DEVICE_UNLOCK);
		}
	    }
	}

      if (lock_timeout)
	{
	  throw error(((lock_type == LOCK_SHARED || lock_type == LOCK_EXCLUSIVE)
		       ? DEVICE_LOCK_TIMEOUT : DEVICE_UNLOCK_TIMEOUT),
		      timeout, status);
	}

      unset_timer();
    }
  catch (error const& e)
    {
      unset_timer();
      throw;
    }
}

void
device_lock::unset_lock ()
{
  set_lock(LOCK_NONE, 0);
}

#endif // SBUILD_FEATURE_DEVLOCK