lockfile.h 10.5 KB
Newer Older
1 2 3 4 5 6
#ifndef LOCKFILE_H
#define LOCKFILE_H

/*
 * File write-locks as used by Git.
 *
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
 * The lockfile API serves two purposes:
 *
 * * Mutual exclusion and atomic file updates. When we want to change
 *   a file, we create a lockfile `<filename>.lock`, write the new
 *   file contents into it, and then rename the lockfile to its final
 *   destination `<filename>`. We create the `<filename>.lock` file
 *   with `O_CREAT|O_EXCL` so that we can notice and fail if somebody
 *   else has already locked the file, then atomically rename the
 *   lockfile to its final destination to commit the changes and
 *   unlock the file.
 *
 * * Automatic cruft removal. If the program exits after we lock a
 *   file but before the changes have been committed, we want to make
 *   sure that we remove the lockfile. This is done by remembering the
 *   lockfiles we have created in a linked list and setting up an
 *   `atexit(3)` handler and a signal handler that clean up the
 *   lockfiles. This mechanism ensures that outstanding lockfiles are
 *   cleaned up if the program exits (including when `die()` is
 *   called) or if the program is terminated by a signal.
 *
 * Please note that lockfiles only block other writers. Readers do not
 * block, but they are guaranteed to see either the old contents of
 * the file or the new contents of the file (assuming that the
 * filesystem implements `rename(2)` atomically).
 *
32 33
 * Most of the heavy lifting is done by the tempfile module (see
 * "tempfile.h").
34 35 36 37 38 39
 *
 * Calling sequence
 * ----------------
 *
 * The caller:
 *
40 41 42 43 44 45
 * * Allocates a `struct lock_file` with whatever storage duration you
 *   desire. The struct does not have to be initialized before being
 *   used, but it is good practice to do so using by setting it to
 *   all-zeros (or using the LOCK_INIT macro). This puts the object in a
 *   consistent state that allows you to call rollback_lock_file() even
 *   if the lock was never taken (in which case it is a noop).
46
 *
47
 * * Attempts to create a lockfile by calling `hold_lock_file_for_update()`.
48 49 50 51 52 53 54 55 56 57
 *
 * * Writes new content for the destination file by either:
 *
 *   * writing to the file descriptor returned by the
 *     `hold_lock_file_for_*()` functions (also available via
 *     `lock->fd`).
 *
 *   * calling `fdopen_lock_file()` to get a `FILE` pointer for the
 *     open file and writing to the file using stdio.
 *
58 59 60 61
 *   Note that the file descriptor returned by hold_lock_file_for_update()
 *   is marked O_CLOEXEC, so the new contents must be written by the
 *   current process, not a spawned one.
 *
62 63 64 65 66 67 68 69 70 71
 * When finished writing, the caller can:
 *
 * * Close the file descriptor and rename the lockfile to its final
 *   destination by calling `commit_lock_file()` or
 *   `commit_lock_file_to()`.
 *
 * * Close the file descriptor and remove the lockfile by calling
 *   `rollback_lock_file()`.
 *
 * * Close the file descriptor without removing or renaming the
72
 *   lockfile by calling `close_lock_file_gently()`, and later call
73 74 75
 *   `commit_lock_file()`, `commit_lock_file_to()`,
 *   `rollback_lock_file()`, or `reopen_lock_file()`.
 *
76 77
 * After the lockfile is committed or rolled back, the `lock_file`
 * object can be discarded or reused.
78 79
 *
 * If the program exits before `commit_lock_file()`,
80 81 82
 * `commit_lock_file_to()`, or `rollback_lock_file()` is called, the
 * tempfile module will close and remove the lockfile, thereby rolling
 * back any uncommitted changes.
83 84 85
 *
 * If you need to close the file descriptor you obtained from a
 * `hold_lock_file_for_*()` function yourself, do so by calling
86
 * `close_lock_file_gently()`. See "tempfile.h" for more information.
87 88 89 90 91 92
 *
 *
 * Under the covers, a lockfile is just a tempfile with a few helper
 * functions. In particular, the state diagram and the cleanup
 * machinery are all implemented in the tempfile module.
 *
93 94 95 96 97 98 99 100 101 102 103 104
 *
 * Error handling
 * --------------
 *
 * The `hold_lock_file_for_*()` functions return a file descriptor on
 * success or -1 on failure (unless `LOCK_DIE_ON_ERROR` is used; see
 * "flags" below). On errors, `errno` describes the reason for
 * failure. Errors can be reported by passing `errno` to
 * `unable_to_lock_message()` or `unable_to_lock_die()`.
 *
 * Similarly, `commit_lock_file`, `commit_lock_file_to`, and
 * `close_lock_file` return 0 on success. On failure they set `errno`
105 106
 * appropriately and return -1. The `commit` variants (but not `close`)
 * do their best to delete the temporary file before returning.
107 108
 */

109 110
#include "tempfile.h"

111
struct lock_file {
112
	struct tempfile *tempfile;
113 114
};

115 116
#define LOCK_INIT { NULL }

117 118 119 120
/* String appended to a filename to derive the lockfile name: */
#define LOCK_SUFFIX ".lock"
#define LOCK_SUFFIX_LEN 5

121 122 123 124 125

/*
 * Flags
 * -----
 *
126
 * The following flags can be passed to `hold_lock_file_for_update()`.
127 128 129 130 131
 */

/*
 * If a lock is already taken for the file, `die()` with an error
 * message. If this flag is not specified, trying to lock a file that
132
 * is already locked silently returns -1 to the caller, or ...
133
 */
134
#define LOCK_DIE_ON_ERROR 1
135

136 137 138 139
/*
 * ... this flag can be passed instead to return -1 and give the usual
 * error message upon an error.
 */
140
#define LOCK_REPORT_ON_ERROR 4
141

142 143 144 145 146 147 148 149 150 151
/*
 * Usually symbolic links in the destination path are resolved. This
 * means that (1) the lockfile is created by adding ".lock" to the
 * resolved path, and (2) upon commit, the resolved path is
 * overwritten. However, if `LOCK_NO_DEREF` is set, then the lockfile
 * is created by adding ".lock" to the path argument itself. This
 * option is used, for example, when detaching a symbolic reference,
 * which for backwards-compatibility reasons, can be a symbolic link
 * containing the name of the referred-to-reference.
 */
152 153
#define LOCK_NO_DEREF 2

154 155 156 157 158 159 160 161
/*
 * Attempt to create a lockfile for the file at `path` and return a
 * file descriptor for writing to it, or -1 on error. If the file is
 * currently locked, retry with quadratic backoff for at least
 * timeout_ms milliseconds. If timeout_ms is 0, try exactly once; if
 * timeout_ms is -1, retry indefinitely. The flags argument and error
 * handling are described above.
 */
162 163 164 165
extern int hold_lock_file_for_update_timeout(
		struct lock_file *lk, const char *path,
		int flags, long timeout_ms);

166 167 168 169 170
/*
 * Attempt to create a lockfile for the file at `path` and return a
 * file descriptor for writing to it, or -1 on error. The flags
 * argument and error handling are described above.
 */
171 172 173 174 175 176 177
static inline int hold_lock_file_for_update(
		struct lock_file *lk, const char *path,
		int flags)
{
	return hold_lock_file_for_update_timeout(lk, path, flags, 0);
}

178 179 180 181 182
/*
 * Return a nonzero value iff `lk` is currently locked.
 */
static inline int is_lock_file_locked(struct lock_file *lk)
{
183
	return is_tempfile_active(lk->tempfile);
184 185
}

186 187
/*
 * Append an appropriate error message to `buf` following the failure
188 189
 * of `hold_lock_file_for_update()` to lock `path`. `err` should be the
 * `errno` set by the failing call.
190 191 192
 */
extern void unable_to_lock_message(const char *path, int err,
				   struct strbuf *buf);
193

194 195
/*
 * Emit an appropriate error message and `die()` following the failure
196 197
 * of `hold_lock_file_for_update()` to lock `path`. `err` should be the
 * `errno` set by the failing
198 199 200 201 202 203 204
 * call.
 */
extern NORETURN void unable_to_lock_die(const char *path, int err);

/*
 * Associate a stdio stream with the lockfile (which must still be
 * open). Return `NULL` (*without* rolling back the lockfile) on
205 206 207
 * error. The stream is closed automatically when
 * `close_lock_file_gently()` is called or when the file is committed or
 * rolled back.
208
 */
209 210
static inline FILE *fdopen_lock_file(struct lock_file *lk, const char *mode)
{
211
	return fdopen_tempfile(lk->tempfile, mode);
212
}
213

214 215 216 217
/*
 * Return the path of the lockfile. The return value is a pointer to a
 * field within the lock_file object and should not be freed.
 */
218 219
static inline const char *get_lock_file_path(struct lock_file *lk)
{
220
	return get_tempfile_path(lk->tempfile);
221
}
222

223 224
static inline int get_lock_file_fd(struct lock_file *lk)
{
225
	return get_tempfile_fd(lk->tempfile);
226 227 228 229
}

static inline FILE *get_lock_file_fp(struct lock_file *lk)
{
230
	return get_tempfile_fp(lk->tempfile);
231
}
232

233 234 235 236 237 238 239 240 241 242
/*
 * Return the path of the file that is locked by the specified
 * lock_file object. The caller must free the memory.
 */
extern char *get_locked_file_path(struct lock_file *lk);

/*
 * If the lockfile is still open, close it (and the file pointer if it
 * has been opened using `fdopen_lock_file()`) without renaming the
 * lockfile over the file being locked. Return 0 upon success. On
243 244
 * failure to `close(2)`, return a negative value (the lockfile is not
 * rolled back). Usually `commit_lock_file()`, `commit_lock_file_to()`,
245
 * or `rollback_lock_file()` should eventually be called.
246
 */
247
static inline int close_lock_file_gently(struct lock_file *lk)
248
{
249
	return close_tempfile_gently(lk->tempfile);
250
}
251 252

/*
253
 * Re-open a lockfile that has been closed using `close_lock_file_gently()`
254 255 256 257 258
 * but not yet committed or rolled back. This can be used to implement
 * a sequence of operations like the following:
 *
 * * Lock file.
 *
259
 * * Write new contents to lockfile, then `close_lock_file_gently()` to
260 261 262 263 264 265 266 267 268 269 270
 *   cause the contents to be written to disk.
 *
 * * Pass the name of the lockfile to another program to allow it (and
 *   nobody else) to inspect the contents you wrote, while still
 *   holding the lock yourself.
 *
 * * `reopen_lock_file()` to reopen the lockfile. Make further updates
 *   to the contents.
 *
 * * `commit_lock_file()` to make the final version permanent.
 */
271 272
static inline int reopen_lock_file(struct lock_file *lk)
{
273
	return reopen_tempfile(lk->tempfile);
274
}
275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290

/*
 * Commit the change represented by `lk`: close the file descriptor
 * and/or file pointer if they are still open and rename the lockfile
 * to its final destination. Return 0 upon success. On failure, roll
 * back the lock file and return -1, with `errno` set to the value
 * from the failing call to `close(2)` or `rename(2)`. It is a bug to
 * call `commit_lock_file()` for a `lock_file` object that is not
 * currently locked.
 */
extern int commit_lock_file(struct lock_file *lk);

/*
 * Like `commit_lock_file()`, but rename the lockfile to the provided
 * `path`. `path` must be on the same filesystem as the lock file.
 */
291 292 293 294
static inline int commit_lock_file_to(struct lock_file *lk, const char *path)
{
	return rename_tempfile(&lk->tempfile, path);
}
295 296 297 298 299 300 301

/*
 * Roll back `lk`: close the file descriptor and/or file pointer and
 * remove the lockfile. It is a NOOP to call `rollback_lock_file()`
 * for a `lock_file` object that has already been committed or rolled
 * back.
 */
302 303 304 305
static inline void rollback_lock_file(struct lock_file *lk)
{
	delete_tempfile(&lk->tempfile);
}
306 307

#endif /* LOCKFILE_H */