Skip to contentSkip to conversation

Use ref transactions for all ref updates

PATCH Superseded Ronnie Sahlberg 3 participants 38 messages Jun 15, 2016

v4 of 12 Superseded Latest is v12 →

lore
Share & tools
lore
#0 lore raw

v4 cover Use ref transactions for all ref updates

This patch series is based on mhagger/ref-transactions and expands on the transaction API. It converts all external (outside of refs.c) callers to use the transaction API for any writes.
This makes most of the ref updates to become atomic when there are failures locking or writing to a ref.

Version 4:
- Rename patch series from "Use ref transactions from most callers" to "Use ref transactions for all ref updates".
- Convert all external ref writes to use transactions and make write_ref_sha1 and lock_ref_sha1 static functions.
- Change the ref commit and free handling so we no longer pass pointer to pointer to _commit. _commit no longer frees the transaction. The caller MUST call _free itself.
- Change _commit to take a strbuf pointer instead of a char* for error reporting back to the caller.
- Re-add the walker patch after fixing it.

Version 3:
- Remove the walker patch for now. Walker needs more complex solution so defer it until the basics are done.
- Remove the onerr argument to ref_transaction_commit(). All callers that need to die() on error now have to do this explicitely.
- Pass an error string from ref_transaction_commit() back to the callers so that they can craft a nice error message upon failures.
- Make ref_transaction_rollback() accept NULL as argument.
- Change ref_transaction_commit() to take a pointer to pointer argument for the transaction and have it clear the callers pointer to NULL when invoked. This allows for much nicer handling of transaction rollback on failure.

Version 2:
- Add a patch to ref_transaction_commit to make it honor onerr even if the error triggered in ref_Transaction_commit itself rather than in a call to other functions (that already honor onerr).
- Add a patch to make the update_ref() helper function use transactions internally.
- Change ref_transaction_update to die() instead of error() if we pass if a NULL old_sha1 but have have_old == true.
- Change ref_transaction_create to die() instead of error() if new_sha1 is false but we pass it a null_sha1.
- Change ref_transaction_delete die() instead of error() if we pass if a NULL old_sha1 but have have_old == true.
- Change several places to do if(!transaction || ref_transaction_update() || ref_Transaction_commit()) die(generic-message) instead of checking each step separately and having a different message for each failure. Most users are likely not interested in what step of the transaction failed and only whether it failed or not.
- Change commit.c to only pass a pointer to ref_transaction_update iff current_head is non-NULL.
The previous patch used to compute a garbage pointer for current_head->object.sha1 and relied on the fact that ref_transaction_update would not try to dereference this pointer if !!current_head was 0.
- Updated commit message for the walker_fetch change to try to justify why the change in locking semantics should not be harmful.

Ronnie Sahlberg (27):
refs.c: constify the sha arguments for
ref_transaction_create|delete|update
refs.c: allow passing NULL to ref_transaction_free
refs.c: add a strbuf argument to ref_transaction_commit for error
logging
refs.c: make ref_update_reject_duplicates take a strbuf argument for
errors
update-ref.c: log transaction error from the update_ref refs.c: make update_ref_write update a strbuf on failure refs.c: remove the onerr argument to ref_transaction_commit refs.c: change ref_transaction_update() to do error checking and
return status
refs.c: change ref_transaction_create to do error checking and return
status
refs.c: ref_transaction_delete to check for error and return status tag.c: use ref transactions when doing updates
replace.c: use the ref transaction functions for updates commit.c: use ref transactions for updates
sequencer.c: use ref transactions for all ref updates fast-import.c: change update_branch to use ref transactions branch.c: use ref transaction for all ref updates
refs.c: change update_ref to use a transaction
refs.c: free the transaction before returning when number of updates
is 0
refs.c: ref_transaction_commit should not free the transaction fetch.c: clear errno before calling functions that might set it fetch.c: change s_update_ref to use a ref transaction fetch.c: use a single ref transaction for all ref updates receive-pack.c: use a reference transaction for updating the refs fast-import.c: use a ref transaction when dumping tags walker.c: use ref transaction for ref updates
refs.c: make write_ref_sha1 static
refs.c: make lock_ref_sha1 static

 branch.c               |  31 +++++++-------
 builtin/commit.c       |  24 +++++------
 builtin/fetch.c        |  36 ++++++++--------
 builtin/receive-pack.c |  20 ++++-----
 builtin/replace.c      |  15 ++++---
 builtin/tag.c          |  15 ++++---
 builtin/update-ref.c   |  29 +++++++------
 fast-import.c          |  37 ++++++++++------
 refs.c                 | 112 +++++++++++++++++++++++++++++++++----------------
 refs.h                 |  45 ++++++++++----------
 sequencer.c            |  23 +++++++---
 walker.c               |  51 +++++++++++-----------
 12 files changed, 258 insertions(+), 180 deletions(-)
Signature · 1 line
1.9.1.528.g98b8868.dirty
#1 lore raw

PATCH v4 1/27 refs.c: constify the sha arguments for ref_transaction_create|delete|update

ref_transaction_create|delete|update has no need to modify the sha1 arguments passed to it so it should use const unsigned char* instead of unsigned char*.

Some functions, such as fast_forward_to(), already have its old/new sha1 arguments as consts. This function will at some point need to use ref_transaction_update() in which case this change is required.

---
 refs.c | 7 ++++---
 refs.h | 7 ++++---
 2 files changed, 8 insertions(+), 6 deletions(-)
refs.c +4 -3
index 728a761..138ab70 100644
@@ -3329,7 +3329,8 @@ static struct ref_update *add_update(struct ref_transaction *transaction,
 
 void ref_transaction_update(struct ref_transaction *transaction,
 			    const char *refname,
-			    unsigned char *new_sha1, unsigned char *old_sha1,
+			    const unsigned char *new_sha1,
+			    const unsigned char *old_sha1,
 			    int flags, int have_old)
 {
 	struct ref_update *update = add_update(transaction, refname);
@@ -3343,7 +3344,7 @@ void ref_transaction_update(struct ref_transaction *transaction,
 
 void ref_transaction_create(struct ref_transaction *transaction,
 			    const char *refname,
-			    unsigned char *new_sha1,
+			    const unsigned char *new_sha1,
 			    int flags)
 {
 	struct ref_update *update = add_update(transaction, refname);
@@ -3357,7 +3358,7 @@ void ref_transaction_create(struct ref_transaction *transaction,
 
 void ref_transaction_delete(struct ref_transaction *transaction,
 			    const char *refname,
-			    unsigned char *old_sha1,
+			    const unsigned char *old_sha1,
 			    int flags, int have_old)
 {
 	struct ref_update *update = add_update(transaction, refname);
refs.h +4 -3
index 0f08def..892c5b6 100644
@@ -239,7 +239,8 @@ void ref_transaction_rollback(struct ref_transaction *transaction);
  */
 void ref_transaction_update(struct ref_transaction *transaction,
 			    const char *refname,
-			    unsigned char *new_sha1, unsigned char *old_sha1,
+			    const unsigned char *new_sha1,
+			    const unsigned char *old_sha1,
 			    int flags, int have_old);
 
 /*
@@ -250,7 +251,7 @@ void ref_transaction_update(struct ref_transaction *transaction,
  */
 void ref_transaction_create(struct ref_transaction *transaction,
 			    const char *refname,
-			    unsigned char *new_sha1,
+			    const unsigned char *new_sha1,
 			    int flags);
 
 /*
@@ -260,7 +261,7 @@ void ref_transaction_create(struct ref_transaction *transaction,
  */
 void ref_transaction_delete(struct ref_transaction *transaction,
 			    const char *refname,
-			    unsigned char *old_sha1,
+			    const unsigned char *old_sha1,
 			    int flags, int have_old);
 
 /*
Signature · 1 line
1.9.1.528.g98b8868.dirty
#2 lore raw

PATCH v4 2/27 refs.c: allow passing NULL to ref_transaction_free

In reply to Ronnie Sahlberg

Allow ref_transaction_free to be called with NULL and in extension allow ref_transaction_rollback to be called for a NULL transaction.

This allows us to write code that will
if ( (!transaction ||

        ref_transaction_update(...))  ||
      (ref_transaction_commit(...) && !(transaction = NULL)) {
          ref_transaction_rollback(transaction);
          ...

}

In this case transaction is reset to NULL IFF ref_transaction_commit() was invoked and thus the rollback becomes ref_transaction_rollback(NULL) which is safe. IF the conditional triggered prior to ref_transaction_commit() then transaction is untouched and then ref_transaction_rollback(transaction) will rollback the failed transaction.

---
 refs.c | 3 +++
 1 file changed, 3 insertions(+)
refs.c +3 -0
index 138ab70..2d83ef6 100644
@@ -3303,6 +3303,9 @@ static void ref_transaction_free(struct ref_transaction *transaction)
 {
 	int i;
 
+	if (!transaction)
+		return;
+
 	for (i = 0; i < transaction->nr; i++)
 		free(transaction->updates[i]);
 
Signature · 1 line
1.9.1.528.g98b8868.dirty
#3 lore raw

PATCH v4 3/27 refs.c: add a strbuf argument to ref_transaction_commit for error logging

In reply to Ronnie Sahlberg

Add a strbuf argument to _commit so that we can pass an error string back to the caller. So that we can do error logging from the caller instead of from _commit.

Longer term plan is to first convert all callers to use onerr==QUIET_ON_ERR and craft any log messages from the callers themselves and finally remove the onerr argument completely.

---
 builtin/update-ref.c | 2 +-
 refs.c               | 6 +++++-
 refs.h               | 5 ++++-
 3 files changed, 10 insertions(+), 3 deletions(-)
builtin/update-ref.c +1 -1
index 405267f..aaa06aa 100644
@@ -367,7 +367,7 @@ int cmd_update_ref(int argc, const char **argv, const char *prefix)
 		if (end_null)
 			line_termination = '\0';
 		update_refs_stdin();
-		ret = ref_transaction_commit(transaction, msg,
+		ret = ref_transaction_commit(transaction, msg, NULL,
 					     UPDATE_REFS_DIE_ON_ERR);
 		return ret;
 	}
refs.c +5 -1
index 2d83ef6..64e8feb 100644
@@ -3414,7 +3414,8 @@ static int ref_update_reject_duplicates(struct ref_update **updates, int n,
 }
 
 int ref_transaction_commit(struct ref_transaction *transaction,
-			   const char *msg, enum action_on_err onerr)
+			   const char *msg, struct strbuf *err,
+			   enum action_on_err onerr)
 {
 	int ret = 0, delnum = 0, i;
 	const char **delnames;
@@ -3443,6 +3444,9 @@ int ref_transaction_commit(struct ref_transaction *transaction,
 					       update->flags,
 					       &update->type, onerr);
 		if (!update->lock) {
+			if (err)
+				strbuf_addf(err ,"Cannot lock the ref '%s'.",
+					    update->refname);
 			ret = 1;
 			goto cleanup;
 		}
refs.h +4 -1
index 892c5b6..ff87e14 100644
@@ -268,9 +268,12 @@ void ref_transaction_delete(struct ref_transaction *transaction,
  * Commit all of the changes that have been queued in transaction, as
  * atomically as possible.  Return a nonzero value if there is a
  * problem.  The ref_transaction is freed by this function.
+ * If err is non-NULL we will add an error string to it to explain why
+ * the transaction failed.
  */
 int ref_transaction_commit(struct ref_transaction *transaction,
-			   const char *msg, enum action_on_err onerr);
+			   const char *msg, struct strbuf *err,
+			   enum action_on_err onerr);
 
 /** Lock a ref and then write its file */
 int update_ref(const char *action, const char *refname,
Signature · 1 line
1.9.1.528.g98b8868.dirty
#4 lore raw

PATCH v4 4/27 refs.c: make ref_update_reject_duplicates take a strbuf argument for errors

In reply to Ronnie Sahlberg

Make ref_update_reject_duplicates return any error that occurs through a new strbuf argument.

---
 refs.c | 6 +++++-
 1 file changed, 5 insertions(+), 1 deletion(-)
refs.c +5 -1
index 64e8feb..21a147b 100644
@@ -3393,6 +3393,7 @@ static int ref_update_compare(const void *r1, const void *r2)
 }
 
 static int ref_update_reject_duplicates(struct ref_update **updates, int n,
+					struct strbuf *err,
 					enum action_on_err onerr)
 {
 	int i;
@@ -3400,6 +3401,9 @@ static int ref_update_reject_duplicates(struct ref_update **updates, int n,
 		if (!strcmp(updates[i - 1]->refname, updates[i]->refname)) {
 			const char *str =
 				"Multiple updates for ref '%s' not allowed.";
+			if (err)
+				strbuf_addf(err, str, updates[i]->refname);
+
 			switch (onerr) {
 			case UPDATE_REFS_MSG_ON_ERR:
 				error(str, updates[i]->refname); break;
@@ -3430,7 +3434,7 @@ int ref_transaction_commit(struct ref_transaction *transaction,
 
 	/* Copy, sort, and reject duplicate refs */
 	qsort(updates, n, sizeof(*updates), ref_update_compare);
-	ret = ref_update_reject_duplicates(updates, n, onerr);
+	ret = ref_update_reject_duplicates(updates, n, err, onerr);
 	if (ret)
 		goto cleanup;
 
Signature · 1 line
1.9.1.528.g98b8868.dirty
#5 lore raw

PATCH v4 5/27 update-ref.c: log transaction error from the update_ref

In reply to Ronnie Sahlberg

Call ref_transaction_commit with QUIET_ON_ERR and use the strbuf that is returned to print a log message if/after the transaction fails.

---
 builtin/update-ref.c | 10 +++++-----
 1 file changed, 5 insertions(+), 5 deletions(-)
builtin/update-ref.c +5 -5
index aaa06aa..207e24d 100644
@@ -342,6 +342,7 @@ int cmd_update_ref(int argc, const char **argv, const char *prefix)
 	const char *refname, *oldval, *msg = NULL;
 	unsigned char sha1[20], oldsha1[20];
 	int delete = 0, no_deref = 0, read_stdin = 0, end_null = 0, flags = 0;
+	struct strbuf err = STRBUF_INIT;
 	struct option options[] = {
 		OPT_STRING( 'm', NULL, &msg, N_("reason"), N_("reason of the update")),
 		OPT_BOOL('d', NULL, &delete, N_("delete the reference")),
@@ -359,17 +360,16 @@ int cmd_update_ref(int argc, const char **argv, const char *prefix)
 		die("Refusing to perform update with empty message.");
 
 	if (read_stdin) {
-		int ret;
 		transaction = ref_transaction_begin();
-
 		if (delete || no_deref || argc > 0)
 			usage_with_options(git_update_ref_usage, options);
 		if (end_null)
 			line_termination = '\0';
 		update_refs_stdin();
-		ret = ref_transaction_commit(transaction, msg, NULL,
-					     UPDATE_REFS_DIE_ON_ERR);
-		return ret;
+		if (ref_transaction_commit(transaction, msg, &err,
+					   UPDATE_REFS_QUIET_ON_ERR))
+			die("%s", err.buf);
+		return 0;
 	}
 
 	if (end_null)
Signature · 1 line
1.9.1.528.g98b8868.dirty
#6 lore raw

PATCH v4 6/27 refs.c: make update_ref_write update a strbuf on failure

In reply to Ronnie Sahlberg

Change update_ref_write to also update an error strbuf on failure. This makes the error available to ref_transaction_commit callers if the transaction failed due to update_ref_sha1/write_ref_sha1 failures.

---
 refs.c | 9 ++++++---
 1 file changed, 6 insertions(+), 3 deletions(-)
refs.c +6 -3
index 21a147b..5e06fd9 100644
@@ -3253,10 +3253,13 @@ static struct ref_lock *update_ref_lock(const char *refname,
 
 static int update_ref_write(const char *action, const char *refname,
 			    const unsigned char *sha1, struct ref_lock *lock,
-			    enum action_on_err onerr)
+			    struct strbuf *err, enum action_on_err onerr)
 {
 	if (write_ref_sha1(lock, sha1, action) < 0) {
 		const char *str = "Cannot update the ref '%s'.";
+		if (err)
+			strbuf_addf(err, str, refname);
+
 		switch (onerr) {
 		case UPDATE_REFS_MSG_ON_ERR: error(str, refname); break;
 		case UPDATE_REFS_DIE_ON_ERR: die(str, refname); break;
@@ -3382,7 +3385,7 @@ int update_ref(const char *action, const char *refname,
 	lock = update_ref_lock(refname, oldval, flags, NULL, onerr);
 	if (!lock)
 		return 1;
-	return update_ref_write(action, refname, sha1, lock, onerr);
+	return update_ref_write(action, refname, sha1, lock, NULL, onerr);
 }
 
 static int ref_update_compare(const void *r1, const void *r2)
@@ -3464,7 +3467,7 @@ int ref_transaction_commit(struct ref_transaction *transaction,
 			ret = update_ref_write(msg,
 					       update->refname,
 					       update->new_sha1,
-					       update->lock, onerr);
+					       update->lock, err, onerr);
 			update->lock = NULL; /* freed by update_ref_write */
 			if (ret)
 				goto cleanup;
Signature · 1 line
1.9.1.528.g98b8868.dirty
#7 lore raw

PATCH v4 7/27 refs.c: remove the onerr argument to ref_transaction_commit

In reply to Ronnie Sahlberg

Since all callers now use QUIET_ON_ERR we no longer need to provide an onerr argument any more. Remove the onerr argument from the ref_transaction_commit signature.

---
 builtin/update-ref.c |  3 +--
 refs.c               | 22 +++++++---------------
 refs.h               |  3 +--
 3 files changed, 9 insertions(+), 19 deletions(-)
builtin/update-ref.c +1 -2
index 207e24d..2bef2a0 100644
@@ -366,8 +366,7 @@ int cmd_update_ref(int argc, const char **argv, const char *prefix)
 		if (end_null)
 			line_termination = '\0';
 		update_refs_stdin();
-		if (ref_transaction_commit(transaction, msg, &err,
-					   UPDATE_REFS_QUIET_ON_ERR))
+		if (ref_transaction_commit(transaction, msg, &err))
 			die("%s", err.buf);
 		return 0;
 	}
refs.c +7 -15
index 5e06fd9..308e13e 100644
@@ -3396,8 +3396,7 @@ static int ref_update_compare(const void *r1, const void *r2)
 }
 
 static int ref_update_reject_duplicates(struct ref_update **updates, int n,
-					struct strbuf *err,
-					enum action_on_err onerr)
+					struct strbuf *err)
 {
 	int i;
 	for (i = 1; i < n; i++)
@@ -3407,22 +3406,13 @@ static int ref_update_reject_duplicates(struct ref_update **updates, int n,
 			if (err)
 				strbuf_addf(err, str, updates[i]->refname);
 
-			switch (onerr) {
-			case UPDATE_REFS_MSG_ON_ERR:
-				error(str, updates[i]->refname); break;
-			case UPDATE_REFS_DIE_ON_ERR:
-				die(str, updates[i]->refname); break;
-			case UPDATE_REFS_QUIET_ON_ERR:
-				break;
-			}
 			return 1;
 		}
 	return 0;
 }
 
 int ref_transaction_commit(struct ref_transaction *transaction,
-			   const char *msg, struct strbuf *err,
-			   enum action_on_err onerr)
+			   const char *msg, struct strbuf *err)
 {
 	int ret = 0, delnum = 0, i;
 	const char **delnames;
@@ -3437,7 +3427,7 @@ int ref_transaction_commit(struct ref_transaction *transaction,
 
 	/* Copy, sort, and reject duplicate refs */
 	qsort(updates, n, sizeof(*updates), ref_update_compare);
-	ret = ref_update_reject_duplicates(updates, n, err, onerr);
+	ret = ref_update_reject_duplicates(updates, n, err);
 	if (ret)
 		goto cleanup;
 
@@ -3449,7 +3439,8 @@ int ref_transaction_commit(struct ref_transaction *transaction,
 					       (update->have_old ?
 						update->old_sha1 : NULL),
 					       update->flags,
-					       &update->type, onerr);
+					       &update->type,
+					       UPDATE_REFS_QUIET_ON_ERR);
 		if (!update->lock) {
 			if (err)
 				strbuf_addf(err ,"Cannot lock the ref '%s'.",
@@ -3467,7 +3458,8 @@ int ref_transaction_commit(struct ref_transaction *transaction,
 			ret = update_ref_write(msg,
 					       update->refname,
 					       update->new_sha1,
-					       update->lock, err, onerr);
+					       update->lock, err,
+					       UPDATE_REFS_QUIET_ON_ERR);
 			update->lock = NULL; /* freed by update_ref_write */
 			if (ret)
 				goto cleanup;
refs.h +1 -2
index ff87e14..bc7715e 100644
@@ -272,8 +272,7 @@ void ref_transaction_delete(struct ref_transaction *transaction,
  * the transaction failed.
  */
 int ref_transaction_commit(struct ref_transaction *transaction,
-			   const char *msg, struct strbuf *err,
-			   enum action_on_err onerr);
+			   const char *msg, struct strbuf *err);
 
 /** Lock a ref and then write its file */
 int update_ref(const char *action, const char *refname,
Signature · 1 line
1.9.1.528.g98b8868.dirty
#8 lore raw

PATCH v4 8/27 refs.c: change ref_transaction_update() to do error checking and return status

In reply to Ronnie Sahlberg

Update ref_transaction_update() do some basic error checking and return true on error. Update all callers to check ref_transaction_update() for error.

---
 builtin/update-ref.c | 10 ++++++----
 refs.c               |  9 +++++++--
 refs.h               | 10 +++++-----
 3 files changed, 18 insertions(+), 11 deletions(-)
builtin/update-ref.c +6 -4
index 2bef2a0..59c4d6b 100644
@@ -197,8 +197,9 @@ static const char *parse_cmd_update(struct strbuf *input, const char *next)
 	if (*next != line_termination)
 		die("update %s: extra input: %s", refname, next);
 
-	ref_transaction_update(transaction, refname, new_sha1, old_sha1,
-			       update_flags, have_old);
+	if (ref_transaction_update(transaction, refname, new_sha1, old_sha1,
+				   update_flags, have_old))
+		die("update %s: failed", refname);
 
 	update_flags = 0;
 	free(refname);
@@ -286,8 +287,9 @@ static const char *parse_cmd_verify(struct strbuf *input, const char *next)
 	if (*next != line_termination)
 		die("verify %s: extra input: %s", refname, next);
 
-	ref_transaction_update(transaction, refname, new_sha1, old_sha1,
-			       update_flags, have_old);
+	if (ref_transaction_update(transaction, refname, new_sha1, old_sha1,
+				   update_flags, have_old))
+		die("failed transaction update for %s", refname);
 
 	update_flags = 0;
 	free(refname);
refs.c +7 -2
index 308e13e..1a903fb 100644
@@ -3333,19 +3333,24 @@ static struct ref_update *add_update(struct ref_transaction *transaction,
 	return update;
 }
 
-void ref_transaction_update(struct ref_transaction *transaction,
+int ref_transaction_update(struct ref_transaction *transaction,
 			    const char *refname,
 			    const unsigned char *new_sha1,
 			    const unsigned char *old_sha1,
 			    int flags, int have_old)
 {
-	struct ref_update *update = add_update(transaction, refname);
+	struct ref_update *update;
+
+	if (have_old && !old_sha1)
+		die("have_old is true but old_sha1 is NULL");
 
+	update = add_update(transaction, refname);
 	hashcpy(update->new_sha1, new_sha1);
 	update->flags = flags;
 	update->have_old = have_old;
 	if (have_old)
 		hashcpy(update->old_sha1, old_sha1);
+	return 0;
 }
 
 void ref_transaction_create(struct ref_transaction *transaction,
refs.h +5 -5
index bc7715e..0364a3e 100644
@@ -237,11 +237,11 @@ void ref_transaction_rollback(struct ref_transaction *transaction);
  * that the reference should have had before the update, or zeros if
  * it must not have existed beforehand.
  */
-void ref_transaction_update(struct ref_transaction *transaction,
-			    const char *refname,
-			    const unsigned char *new_sha1,
-			    const unsigned char *old_sha1,
-			    int flags, int have_old);
+int ref_transaction_update(struct ref_transaction *transaction,
+			   const char *refname,
+			   const unsigned char *new_sha1,
+			   const unsigned char *old_sha1,
+			   int flags, int have_old);
 
 /*
  * Add a reference creation to transaction.  new_sha1 is the value
Signature · 1 line
1.9.1.528.g98b8868.dirty
#9 lore raw

Re: [PATCH v4 08/27] refs.c: change ref_transaction_update() to do error checking and return status

Quoted 56 lines · Ronnie Sahlberg

Update ref_transaction_update() do some basic error checking and return true on error. Update all callers to check ref_transaction_update() for error.

---
 builtin/update-ref.c | 10 ++++++----
 refs.c               |  9 +++++++--
 refs.h               | 10 +++++-----
 3 files changed, 18 insertions(+), 11 deletions(-)
builtin/update-ref.c +6 -4
index 2bef2a0..59c4d6b 100644
@@ -197,8 +197,9 @@ static const char *parse_cmd_update(struct strbuf *input, const char *next)
        if (*next != line_termination)
                die("update %s: extra input: %s", refname, next);
 
-       ref_transaction_update(transaction, refname, new_sha1, old_sha1,
-                              update_flags, have_old);
+       if (ref_transaction_update(transaction, refname, new_sha1, old_sha1,
+                                  update_flags, have_old))
+               die("update %s: failed", refname);
 
        update_flags = 0;
        free(refname);
@@ -286,8 +287,9 @@ static const char *parse_cmd_verify(struct strbuf *input, const char *next)
        if (*next != line_termination)
                die("verify %s: extra input: %s", refname, next);
 
-       ref_transaction_update(transaction, refname, new_sha1, old_sha1,
-                              update_flags, have_old);
+       if (ref_transaction_update(transaction, refname, new_sha1, old_sha1,
+                                  update_flags, have_old))
+               die("failed transaction update for %s", refname);
 
        update_flags = 0;
        free(refname);
refs.c +3 -2
index 308e13e..1a903fb 100644
@@ -3333,19 +3333,24 @@ static struct ref_update *add_update(struct ref_transaction *transaction,
        return update;
 }
 
-void ref_transaction_update(struct ref_transaction *transaction,
+int ref_transaction_update(struct ref_transaction *transaction,
                            const char *refname,
                            const unsigned char *new_sha1,
                            const unsigned char *old_sha1,
                            int flags, int have_old)
 {
-       struct ref_update *update = add_update(transaction, refname);
+       struct ref_update *update;
+

refs.c static struct ref_update *add_update(struct ref_transaction *transaction, · line 3353

Quoted 10 lines
refs.c +4 -0
+       if (have_old && !old_sha1)
+               die("have_old is true but old_sha1 is NULL");
 
+       update = add_update(transaction, refname);
        hashcpy(update->new_sha1, new_sha1);
        update->flags = flags;
        update->have_old = have_old;
        if (have_old)
                hashcpy(update->old_sha1, old_sha1);
+       return 0;

Am I misreading? The commit message talks about returning true on error, but this code seems to only ever die() or return 0 (false).

Quoted 26 lines
refs.c +0 -0
 }
 
 void ref_transaction_create(struct ref_transaction *transaction,
refs.h +5 -6
index bc7715e..0364a3e 100644
@@ -237,11 +237,11 @@ void ref_transaction_rollback(struct ref_transaction *transaction);
  * that the reference should have had before the update, or zeros if
  * it must not have existed beforehand.
  */
-void ref_transaction_update(struct ref_transaction *transaction,
-                           const char *refname,
-                           const unsigned char *new_sha1,
-                           const unsigned char *old_sha1,
-                           int flags, int have_old);
+int ref_transaction_update(struct ref_transaction *transaction,
+                          const char *refname,
+                          const unsigned char *new_sha1,
+                          const unsigned char *old_sha1,
+                          int flags, int have_old);
 
 /*
  * Add a reference creation to transaction.  new_sha1 is the value
--

1.9.1.528.g98b8868.dirty

#11 lore raw

PATCH v4 9/27 refs.c: change ref_transaction_create to do error checking and return status

In reply to Ronnie Sahlberg

Do basic error checking in ref_transaction_create() and make it return status. Update all callers to check the result of ref_transaction_create()

---
 builtin/update-ref.c |  4 +++-
 refs.c               | 17 +++++++++++------
 refs.h               |  8 ++++----
 3 files changed, 18 insertions(+), 11 deletions(-)
builtin/update-ref.c +3 -1
index 59c4d6b..3fab810 100644
@@ -225,7 +225,9 @@ static const char *parse_cmd_create(struct strbuf *input, const char *next)
 	if (*next != line_termination)
 		die("create %s: extra input: %s", refname, next);
 
-	ref_transaction_create(transaction, refname, new_sha1, update_flags);
+	if (ref_transaction_create(transaction, refname, new_sha1,
+				   update_flags))
+		die("failed transaction create for %s", refname);
 
 	update_flags = 0;
 	free(refname);
refs.c +11 -6
index 1a903fb..27db737 100644
@@ -3353,18 +3353,23 @@ int ref_transaction_update(struct ref_transaction *transaction,
 	return 0;
 }
 
-void ref_transaction_create(struct ref_transaction *transaction,
-			    const char *refname,
-			    const unsigned char *new_sha1,
-			    int flags)
+int ref_transaction_create(struct ref_transaction *transaction,
+			   const char *refname,
+			   const unsigned char *new_sha1,
+			   int flags)
 {
-	struct ref_update *update = add_update(transaction, refname);
+	struct ref_update *update;
+
+	if (!new_sha1 || is_null_sha1(new_sha1))
+		die("create ref with null new_sha1");
+
+	update = add_update(transaction, refname);
 
-	assert(!is_null_sha1(new_sha1));
 	hashcpy(update->new_sha1, new_sha1);
 	hashclr(update->old_sha1);
 	update->flags = flags;
 	update->have_old = 1;
+	return 0;
 }
 
 void ref_transaction_delete(struct ref_transaction *transaction,
refs.h +4 -4
index 0364a3e..01d773c 100644
@@ -249,10 +249,10 @@ int ref_transaction_update(struct ref_transaction *transaction,
  * null SHA-1.  It is verified that the reference does not exist
  * already.
  */
-void ref_transaction_create(struct ref_transaction *transaction,
-			    const char *refname,
-			    const unsigned char *new_sha1,
-			    int flags);
+int ref_transaction_create(struct ref_transaction *transaction,
+			   const char *refname,
+			   const unsigned char *new_sha1,
+			   int flags);
 
 /*
  * Add a reference deletion to transaction.  If have_old is true, then
Signature · 1 line
1.9.1.528.g98b8868.dirty
#12 lore raw

PATCH v4 10/27 refs.c: ref_transaction_delete to check for error and return status

In reply to Ronnie Sahlberg

Change ref_transaction_delete() to do basic error checking and return status. Update all callers to check the return for ref_transaction_delete()

---
 builtin/update-ref.c |  5 +++--
 refs.c               | 15 ++++++++++-----
 refs.h               |  8 ++++----
 3 files changed, 17 insertions(+), 11 deletions(-)
builtin/update-ref.c +3 -2
index 3fab810..fc3512f 100644
@@ -257,8 +257,9 @@ static const char *parse_cmd_delete(struct strbuf *input, const char *next)
 	if (*next != line_termination)
 		die("delete %s: extra input: %s", refname, next);
 
-	ref_transaction_delete(transaction, refname, old_sha1,
-			       update_flags, have_old);
+	if (ref_transaction_delete(transaction, refname, old_sha1,
+				   update_flags, have_old))
+		die("failed transaction delete for %s", refname);
 
 	update_flags = 0;
 	free(refname);
refs.c +10 -5
index 27db737..0a4e28e 100644
@@ -3372,19 +3372,24 @@ int ref_transaction_create(struct ref_transaction *transaction,
 	return 0;
 }
 
-void ref_transaction_delete(struct ref_transaction *transaction,
-			    const char *refname,
-			    const unsigned char *old_sha1,
-			    int flags, int have_old)
+int ref_transaction_delete(struct ref_transaction *transaction,
+			   const char *refname,
+			   const unsigned char *old_sha1,
+			   int flags, int have_old)
 {
-	struct ref_update *update = add_update(transaction, refname);
+	struct ref_update *update;
 
+	if (have_old && !old_sha1)
+		die("have_old is true but old_sha1 is NULL");
+
+	update = add_update(transaction, refname);
 	update->flags = flags;
 	update->have_old = have_old;
 	if (have_old) {
 		assert(!is_null_sha1(old_sha1));
 		hashcpy(update->old_sha1, old_sha1);
 	}
+	return 0;
 }
 
 int update_ref(const char *action, const char *refname,
refs.h +4 -4
index 01d773c..5eb500e 100644
@@ -259,10 +259,10 @@ int ref_transaction_create(struct ref_transaction *transaction,
  * old_sha1 holds the value that the reference should have had before
  * the update (which must not be the null SHA-1).
  */
-void ref_transaction_delete(struct ref_transaction *transaction,
-			    const char *refname,
-			    const unsigned char *old_sha1,
-			    int flags, int have_old);
+int ref_transaction_delete(struct ref_transaction *transaction,
+			   const char *refname,
+			   const unsigned char *old_sha1,
+			   int flags, int have_old);
 
 /*
  * Commit all of the changes that have been queued in transaction, as
Signature · 1 line
1.9.1.528.g98b8868.dirty
#13 lore raw

PATCH v4 11/27 tag.c: use ref transactions when doing updates

In reply to Ronnie Sahlberg

Change tag.c to use ref transactions for all ref updates.

---
 builtin/tag.c | 14 ++++++++------
 1 file changed, 8 insertions(+), 6 deletions(-)
builtin/tag.c +8 -6
index 40356e3..31e32cb 100644
@@ -488,7 +488,6 @@ int cmd_tag(int argc, const char **argv, const char *prefix)
 	struct strbuf ref = STRBUF_INIT;
 	unsigned char object[20], prev[20];
 	const char *object_ref, *tag;
-	struct ref_lock *lock;
 	struct create_tag_options opt;
 	char *cleanup_arg = NULL;
 	int annotate = 0, force = 0, lines = -1;
@@ -496,6 +495,8 @@ int cmd_tag(int argc, const char **argv, const char *prefix)
 	const char *msgfile = NULL, *keyid = NULL;
 	struct msg_arg msg = { 0, STRBUF_INIT };
 	struct commit_list *with_commit = NULL;
+	struct ref_transaction *transaction;
+	struct strbuf err = STRBUF_INIT;
 	struct option options[] = {
 		OPT_CMDMODE('l', "list", &cmdmode, N_("list tag names"), 'l'),
 		{ OPTION_INTEGER, 'n', NULL, &lines, N_("n"),
@@ -641,11 +642,12 @@ int cmd_tag(int argc, const char **argv, const char *prefix)
 	if (annotate)
 		create_tag(object, tag, &buf, &opt, prev, object);
 
-	lock = lock_any_ref_for_update(ref.buf, prev, 0, NULL);
-	if (!lock)
-		die(_("%s: cannot lock the ref"), ref.buf);
-	if (write_ref_sha1(lock, object, NULL) < 0)
-		die(_("%s: cannot update the ref"), ref.buf);
+	transaction = ref_transaction_begin();
+	if (!transaction ||
+	    ref_transaction_update(transaction, ref.buf, object, prev,
+				   0, !is_null_sha1(prev)) ||
+	    ref_transaction_commit(transaction, NULL, &err))
+		die(_("%s: cannot update the ref: %s"), ref.buf, err.buf);
 	if (force && !is_null_sha1(prev) && hashcmp(prev, object))
 		printf(_("Updated tag '%s' (was %s)\n"), tag, find_unique_abbrev(prev, DEFAULT_ABBREV));
 
Signature · 1 line
1.9.1.528.g98b8868.dirty
#14 lore raw

PATCH v4 12/27 replace.c: use the ref transaction functions for updates

In reply to Ronnie Sahlberg

Update replace.c to use ref transactions for updates.

---
 builtin/replace.c | 14 ++++++++------
 1 file changed, 8 insertions(+), 6 deletions(-)
builtin/replace.c +8 -6
index b62420a..b037b29 100644
@@ -129,7 +129,8 @@ static int replace_object(const char *object_ref, const char *replace_ref,
 	unsigned char object[20], prev[20], repl[20];
 	enum object_type obj_type, repl_type;
 	char ref[PATH_MAX];
-	struct ref_lock *lock;
+	struct ref_transaction *transaction;
+	struct strbuf err = STRBUF_INIT;
 
 	if (get_sha1(object_ref, object))
 		die("Failed to resolve '%s' as a valid ref.", object_ref);
@@ -157,11 +158,12 @@ static int replace_object(const char *object_ref, const char *replace_ref,
 	else if (!force)
 		die("replace ref '%s' already exists", ref);
 
-	lock = lock_any_ref_for_update(ref, prev, 0, NULL);
-	if (!lock)
-		die("%s: cannot lock the ref", ref);
-	if (write_ref_sha1(lock, repl, NULL) < 0)
-		die("%s: cannot update the ref", ref);
+	transaction = ref_transaction_begin();
+	if (!transaction ||
+	    ref_transaction_update(transaction, ref, repl, prev,
+				   0, !is_null_sha1(prev)) ||
+	    ref_transaction_commit(transaction, NULL, &err))
+		die(_("%s: failed to replace ref: %s"), ref, err.buf);
 
 	return 0;
 }
Signature · 1 line
1.9.1.528.g98b8868.dirty
#15 lore raw

Re: [PATCH v4 12/27] replace.c: use the ref transaction functions for updates

Quoted 26 lines · Ronnie Sahlberg

Update replace.c to use ref transactions for updates.

---
 builtin/replace.c | 14 ++++++++------
 1 file changed, 8 insertions(+), 6 deletions(-)
builtin/replace.c +2 -2
index b62420a..b037b29 100644
@@ -129,7 +129,8 @@ static int replace_object(const char *object_ref, const char *replace_ref,
        unsigned char object[20], prev[20], repl[20];
        enum object_type obj_type, repl_type;
        char ref[PATH_MAX];
-       struct ref_lock *lock;
+       struct ref_transaction *transaction;
+       struct strbuf err = STRBUF_INIT;
 
        if (get_sha1(object_ref, object))
                die("Failed to resolve '%s' as a valid ref.", object_ref);
@@ -157,11 +158,12 @@ static int replace_object(const char *object_ref, const char *replace_ref,
        else if (!force)
                die("replace ref '%s' already exists", ref);
 
-       lock = lock_any_ref_for_update(ref, prev, 0, NULL);

builtin/replace.c static int replace_object(const char *object_ref, const char *replace_ref, · line 166

Quoted 10 lines
builtin/replace.c +6 -4
-       if (!lock)
-               die("%s: cannot lock the ref", ref);
-       if (write_ref_sha1(lock, repl, NULL) < 0)
-               die("%s: cannot update the ref", ref);
+       transaction = ref_transaction_begin();
+       if (!transaction ||
+           ref_transaction_update(transaction, ref, repl, prev,
+                                  0, !is_null_sha1(prev)) ||
+           ref_transaction_commit(transaction, NULL, &err))
+               die(_("%s: failed to replace ref: %s"), ref, err.buf);

Even though 'err' will be empty after this conditional, would strbuf_release(&err) here be warranted to future-proof it? Today's implementation of strbuf will not have allocated any memory, but perhaps a future change might pre-allocate (unlikely though that is), which would leak here.

Quoted 4 lines
builtin/replace.c +0 -1
        return 0;
 }
--

1.9.1.528.g98b8868.dirty

#18 lore raw

PATCH v4 13/27 commit.c: use ref transactions for updates

In reply to Ronnie Sahlberg

Change commit.c to use ref transactions for all ref updates. Make sure we pass a NULL pointer to ref_transaction_update if have_old is false.

---
 builtin/commit.c | 23 ++++++++++-------------
 1 file changed, 10 insertions(+), 13 deletions(-)
builtin/commit.c +10 -13
index d9550c5..a56f47a 100644
@@ -1541,11 +1541,12 @@ int cmd_commit(int argc, const char **argv, const char *prefix)
 	const char *index_file, *reflog_msg;
 	char *nl;
 	unsigned char sha1[20];
-	struct ref_lock *ref_lock;
 	struct commit_list *parents = NULL, **pptr = &parents;
 	struct stat statbuf;
 	struct commit *current_head = NULL;
 	struct commit_extra_header *extra = NULL;
+	struct ref_transaction *transaction;
+	struct strbuf err = STRBUF_INIT;
 
 	if (argc == 2 && !strcmp(argv[1], "-h"))
 		usage_with_options(builtin_commit_usage, builtin_commit_options);
@@ -1667,12 +1668,6 @@ int cmd_commit(int argc, const char **argv, const char *prefix)
 	strbuf_release(&author_ident);
 	free_commit_extra_headers(extra);
 
-	ref_lock = lock_any_ref_for_update("HEAD",
-					   !current_head
-					   ? NULL
-					   : current_head->object.sha1,
-					   0, NULL);
-
 	nl = strchr(sb.buf, '\n');
 	if (nl)
 		strbuf_setlen(&sb, nl + 1 - sb.buf);
@@ -1681,13 +1676,15 @@ int cmd_commit(int argc, const char **argv, const char *prefix)
 	strbuf_insert(&sb, 0, reflog_msg, strlen(reflog_msg));
 	strbuf_insert(&sb, strlen(reflog_msg), ": ", 2);
 
-	if (!ref_lock) {
-		rollback_index_files();
-		die(_("cannot lock HEAD ref"));
-	}
-	if (write_ref_sha1(ref_lock, sha1, sb.buf) < 0) {
+	transaction = ref_transaction_begin();
+	if (!transaction ||
+	    ref_transaction_update(transaction, "HEAD", sha1,
+				   current_head ?
+				   current_head->object.sha1 : NULL,
+				   0, !!current_head) ||
+	    ref_transaction_commit(transaction, sb.buf, &err)) {
 		rollback_index_files();
-		die(_("cannot update HEAD ref"));
+		die(_("HEAD: cannot update ref: %s"), err.buf);
 	}
 
 	unlink(git_path("CHERRY_PICK_HEAD"));
Signature · 1 line
1.9.1.528.g98b8868.dirty
#19 lore raw

PATCH v4 14/27 sequencer.c: use ref transactions for all ref updates

In reply to Ronnie Sahlberg

Change to use ref transactions for all updates to refs.

---
 sequencer.c | 23 +++++++++++++++++------
 1 file changed, 17 insertions(+), 6 deletions(-)
sequencer.c +17 -6
index bde5f04..449e093 100644
@@ -272,19 +272,30 @@ static int error_dirty_index(struct replay_opts *opts)
 static int fast_forward_to(const unsigned char *to, const unsigned char *from,
 			int unborn, struct replay_opts *opts)
 {
-	struct ref_lock *ref_lock;
+	struct ref_transaction *transaction;
 	struct strbuf sb = STRBUF_INIT;
-	int ret;
+	struct strbuf err = STRBUF_INIT;
 
 	read_cache();
 	if (checkout_fast_forward(from, to, 1))
 		exit(1); /* the callee should have complained already */
-	ref_lock = lock_any_ref_for_update("HEAD", unborn ? null_sha1 : from,
-					   0, NULL);
+
 	strbuf_addf(&sb, "%s: fast-forward", action_name(opts));
-	ret = write_ref_sha1(ref_lock, to, sb.buf);
+
+	transaction = ref_transaction_begin();
+	if ((!transaction ||
+	    ref_transaction_update(transaction, "HEAD", to, from,
+				   0, !unborn)) ||
+	    (ref_transaction_commit(transaction, sb.buf, &err) &&
+	     !(transaction = NULL))) {
+		ref_transaction_rollback(transaction);
+		strbuf_release(&sb);
+		return error(_("HEAD: Could not fast-forward: %s\n"),
+			     strbuf_detach(&err, NULL));
+	}
+
 	strbuf_release(&sb);
-	return ret;
+	return 0;
 }
 
 static int do_recursive_merge(struct commit *base, struct commit *next,
Signature · 1 line
1.9.1.528.g98b8868.dirty
#20 lore raw

PATCH v4 15/27 fast-import.c: change update_branch to use ref transactions

In reply to Ronnie Sahlberg

Change update_branch() to use ref transactions for updates.

---
 fast-import.c | 20 ++++++++++++--------
 1 file changed, 12 insertions(+), 8 deletions(-)
fast-import.c +12 -8
index fb4738d..300c8dc 100644
@@ -1678,36 +1678,40 @@ found_entry:
 static int update_branch(struct branch *b)
 {
 	static const char *msg = "fast-import";
-	struct ref_lock *lock;
+	struct ref_transaction *transaction;
 	unsigned char old_sha1[20];
+	struct strbuf err = STRBUF_INIT;
 
 	if (is_null_sha1(b->sha1))
 		return 0;
 	if (read_ref(b->name, old_sha1))
 		hashclr(old_sha1);
-	lock = lock_any_ref_for_update(b->name, old_sha1, 0, NULL);
-	if (!lock)
-		return error("Unable to lock %s", b->name);
 	if (!force_update && !is_null_sha1(old_sha1)) {
 		struct commit *old_cmit, *new_cmit;
 
 		old_cmit = lookup_commit_reference_gently(old_sha1, 0);
 		new_cmit = lookup_commit_reference_gently(b->sha1, 0);
 		if (!old_cmit || !new_cmit) {
-			unlock_ref(lock);
 			return error("Branch %s is missing commits.", b->name);
 		}
 
 		if (!in_merge_bases(old_cmit, new_cmit)) {
-			unlock_ref(lock);
 			warning("Not updating %s"
 				" (new tip %s does not contain %s)",
 				b->name, sha1_to_hex(b->sha1), sha1_to_hex(old_sha1));
 			return -1;
 		}
 	}
-	if (write_ref_sha1(lock, b->sha1, msg) < 0)
-		return error("Unable to update %s", b->name);
+	transaction = ref_transaction_begin();
+	if ((!transaction ||
+	    ref_transaction_update(transaction, b->name, b->sha1, old_sha1,
+				   0, 1)) ||
+	    (ref_transaction_commit(transaction, msg, &err) &&
+	     !(transaction = NULL))) {
+		ref_transaction_rollback(transaction);
+		return error("Unable to update branch %s: %s", b->name,
+			     strbuf_detach(&err, NULL));
+	}
 	return 0;
 }
 
Signature · 1 line
1.9.1.528.g98b8868.dirty
#21 lore raw

Re: [PATCH v4 15/27] fast-import.c: change update_branch to use ref transactions

Quoted 46 lines · Ronnie Sahlberg

Change update_branch() to use ref transactions for updates.

---
 fast-import.c | 20 ++++++++++++--------
 1 file changed, 12 insertions(+), 8 deletions(-)
fast-import.c +2 -7
index fb4738d..300c8dc 100644
@@ -1678,36 +1678,40 @@ found_entry:
 static int update_branch(struct branch *b)
 {
        static const char *msg = "fast-import";
-       struct ref_lock *lock;
+       struct ref_transaction *transaction;
        unsigned char old_sha1[20];
+       struct strbuf err = STRBUF_INIT;
 
        if (is_null_sha1(b->sha1))
                return 0;
        if (read_ref(b->name, old_sha1))
                hashclr(old_sha1);
-       lock = lock_any_ref_for_update(b->name, old_sha1, 0, NULL);
-       if (!lock)
-               return error("Unable to lock %s", b->name);
        if (!force_update && !is_null_sha1(old_sha1)) {
                struct commit *old_cmit, *new_cmit;
 
                old_cmit = lookup_commit_reference_gently(old_sha1, 0);
                new_cmit = lookup_commit_reference_gently(b->sha1, 0);
                if (!old_cmit || !new_cmit) {
-                       unlock_ref(lock);
                        return error("Branch %s is missing commits.", b->name);
                }
 
                if (!in_merge_bases(old_cmit, new_cmit)) {
-                       unlock_ref(lock);
                        warning("Not updating %s"
                                " (new tip %s does not contain %s)",
                                b->name, sha1_to_hex(b->sha1), sha1_to_hex(old_sha1));
                        return -1;
                }
        }
-       if (write_ref_sha1(lock, b->sha1, msg) < 0)

fast-import.c found_entry: · line 1713

Quoted 10 lines
fast-import.c +9 -1
-               return error("Unable to update %s", b->name);
+       transaction = ref_transaction_begin();
+       if ((!transaction ||
+           ref_transaction_update(transaction, b->name, b->sha1, old_sha1,
+                                  0, 1)) ||
+           (ref_transaction_commit(transaction, msg, &err) &&
+            !(transaction = NULL))) {
+               ref_transaction_rollback(transaction);
+               return error("Unable to update branch %s: %s", b->name,
+                            strbuf_detach(&err, NULL));

Iffy strbuf handling. The strbuf content is being leaked here whether detached or not.

Quoted 6 lines
fast-import.c +1 -1
+       }
        return 0;
 }
 
--

1.9.1.528.g98b8868.dirty

#24 lore raw

PATCH v4 16/27 branch.c: use ref transaction for all ref updates

In reply to Ronnie Sahlberg

Change create_branch to use a ref transaction when creating the new branch. ref_transaction_create will check that the ref does not already exist and fail otherwise meaning that we no longer need to keep a lock on the ref during the setup_tracking. This simplifies the code since we can now do the transaction in one single step.

If the forcing flag is false then use ref_transaction_create since this will fail if the ref already exist. Otherwise use ref_transaction_update.

This also fixes a race condition in the old code where two concurrent create_branch could race since the lock_any_ref_for_update/write_ref_sha1 did not protect against the ref already existsing. I.e. one thread could end up overwriting a branch even if the forcing flag is false.

---
 branch.c | 30 ++++++++++++++++--------------
 1 file changed, 16 insertions(+), 14 deletions(-)
branch.c +16 -14
index 660097b..2aa5c82 100644
@@ -226,7 +226,6 @@ void create_branch(const char *head,
 		   int force, int reflog, int clobber_head,
 		   int quiet, enum branch_track track)
 {
-	struct ref_lock *lock = NULL;
 	struct commit *commit;
 	unsigned char sha1[20];
 	char *real_ref, msg[PATH_MAX + 20];
@@ -285,15 +284,6 @@ void create_branch(const char *head,
 		die(_("Not a valid branch point: '%s'."), start_name);
 	hashcpy(sha1, commit->object.sha1);
 
-	if (!dont_change_ref) {
-		lock = lock_any_ref_for_update(ref.buf, NULL, 0, NULL);
-		if (!lock)
-			die_errno(_("Failed to lock ref for update"));
-	}
-
-	if (reflog)
-		log_all_ref_updates = 1;
-
 	if (forcing)
 		snprintf(msg, sizeof msg, "branch: Reset to %s",
 			 start_name);
@@ -301,13 +291,25 @@ void create_branch(const char *head,
 		snprintf(msg, sizeof msg, "branch: Created from %s",
 			 start_name);
 
+	if (reflog)
+		log_all_ref_updates = 1;
+
+	if (!dont_change_ref) {
+		struct ref_transaction *transaction;
+		struct strbuf err = STRBUF_INIT;
+
+		transaction = ref_transaction_begin();
+		if (!transaction ||
+			ref_transaction_update(transaction, ref.buf, sha1,
+					       null_sha1, 0, !forcing) ||
+			ref_transaction_commit(transaction, msg, &err))
+				die_errno(_("%s: failed to write ref: %s"),
+					  ref.buf, err.buf);
+	}
+
 	if (real_ref && track)
 		setup_tracking(ref.buf + 11, real_ref, track, quiet);
 
-	if (!dont_change_ref)
-		if (write_ref_sha1(lock, sha1, msg) < 0)
-			die_errno(_("Failed to write ref"));
-
 	strbuf_release(&ref);
 	free(real_ref);
 }
Signature · 1 line
1.9.1.528.g98b8868.dirty
#25 lore raw

PATCH v4 17/27 refs.c: change update_ref to use a transaction

In reply to Ronnie Sahlberg

Change the update_ref helper function to use a ref transaction internally.

---
 refs.c | 25 +++++++++++++++++++++----
 1 file changed, 21 insertions(+), 4 deletions(-)
refs.c +21 -4
index 0a4e28e..563f336 100644
@@ -3396,11 +3396,28 @@ int update_ref(const char *action, const char *refname,
 	       const unsigned char *sha1, const unsigned char *oldval,
 	       int flags, enum action_on_err onerr)
 {
-	struct ref_lock *lock;
-	lock = update_ref_lock(refname, oldval, flags, NULL, onerr);
-	if (!lock)
+	struct ref_transaction *t;
+	struct strbuf err = STRBUF_INIT;
+
+	t = ref_transaction_begin();
+	if ((!t ||
+	    ref_transaction_update(t, refname, sha1, oldval, flags,
+				   !!oldval)) ||
+	    (ref_transaction_commit(t, action, &err) && !(t = NULL))) {
+		const char *str = "update_ref failed for ref '%s': %s";
+
+		ref_transaction_rollback(t);
+		switch (onerr) {
+		case UPDATE_REFS_MSG_ON_ERR:
+			error(str, refname, err.buf); break;
+		case UPDATE_REFS_DIE_ON_ERR:
+			die(str, refname, err.buf); break;
+		case UPDATE_REFS_QUIET_ON_ERR: break;
+		}
+		strbuf_release(&err);
 		return 1;
-	return update_ref_write(action, refname, sha1, lock, NULL, onerr);
+	}
+	return 0;
 }
 
 static int ref_update_compare(const void *r1, const void *r2)
Signature · 1 line
1.9.1.528.g98b8868.dirty
#26 lore raw

PATCH v4 18/27 refs.c: free the transaction before returning when number of updates is 0

In reply to Ronnie Sahlberg

We have to free the transaction before returning in the early check for 'return early if number of updates == 0' or else the following code would create a memory leak with the transaction never being freed :
t = ref_transaction_begin()
ref_transaction_commit(t)

---
 refs.c | 4 +++-
 1 file changed, 3 insertions(+), 1 deletion(-)
refs.c +3 -1
index 563f336..c6ee43c 100644
@@ -3451,8 +3451,10 @@ int ref_transaction_commit(struct ref_transaction *transaction,
 	int n = transaction->nr;
 	struct ref_update **updates = transaction->updates;
 
-	if (!n)
+	if (!n) {
+		ref_transaction_free(transaction);
 		return 0;
+	}
 
 	/* Allocate work space */
 	delnames = xmalloc(sizeof(*delnames) * n);
Signature · 1 line
1.9.1.528.g98b8868.dirty
#27 lore raw

PATCH v4 19/27 refs.c: ref_transaction_commit should not free the transaction

In reply to Ronnie Sahlberg

Change ref_transaction_commit so that it does not free the transaction. Instead require that a caller will end a transaction by either calling ref_transaction_rollback or ref_transaction_free.

By having the transaction object remaining valid after _commit returns allows us to write much nicer code and still be able to call ref_transaction_rollback safely. Instead of this horribleness

	t = ref_transaction_begin();
	if ((!t ||
	    ref_transaction_update(t, refname, sha1, oldval, flags,
				   !!oldval)) ||
	    (ref_transaction_commit(t, action, &err) && !(t = NULL))) {
		ref_transaction_rollback(t);

we can now just do the much nicer

	t = ref_transaction_begin();
	if (!t ||
	    ref_transaction_update(t, refname, sha1, oldval, flags,
				   !!oldval) ||
	    ref_transaction_commit(&t, action, &err)) {
		ref_transaction_rollback(t);
		... die/return ...

	ref_transaction_free(transaction);
---
 branch.c             |  1 +
 builtin/commit.c     |  1 +
 builtin/replace.c    |  1 +
 builtin/tag.c        |  1 +
 builtin/update-ref.c |  1 +
 fast-import.c        |  8 ++++----
 refs.c               |  7 ++-----
 refs.h               | 14 +++++++++-----
 sequencer.c          |  8 ++++----
 9 files changed, 24 insertions(+), 18 deletions(-)
branch.c +1 -0
index 2aa5c82..8e58908 100644
@@ -305,6 +305,7 @@ void create_branch(const char *head,
 			ref_transaction_commit(transaction, msg, &err))
 				die_errno(_("%s: failed to write ref: %s"),
 					  ref.buf, err.buf);
+		ref_transaction_free(transaction);
 	}
 
 	if (real_ref && track)
builtin/commit.c +1 -0
index a56f47a..b806c59 100644
@@ -1686,6 +1686,7 @@ int cmd_commit(int argc, const char **argv, const char *prefix)
 		rollback_index_files();
 		die(_("HEAD: cannot update ref: %s"), err.buf);
 	}
+	ref_transaction_free(transaction);
 
 	unlink(git_path("CHERRY_PICK_HEAD"));
 	unlink(git_path("REVERT_HEAD"));
builtin/replace.c +1 -0
index b037b29..5999f7d 100644
@@ -165,6 +165,7 @@ static int replace_object(const char *object_ref, const char *replace_ref,
 	    ref_transaction_commit(transaction, NULL, &err))
 		die(_("%s: failed to replace ref: %s"), ref, err.buf);
 
+	ref_transaction_free(transaction);
 	return 0;
 }
 
builtin/tag.c +1 -0
index 31e32cb..4701bda 100644
@@ -648,6 +648,7 @@ int cmd_tag(int argc, const char **argv, const char *prefix)
 				   0, !is_null_sha1(prev)) ||
 	    ref_transaction_commit(transaction, NULL, &err))
 		die(_("%s: cannot update the ref: %s"), ref.buf, err.buf);
+	ref_transaction_free(transaction);
 	if (force && !is_null_sha1(prev) && hashcmp(prev, object))
 		printf(_("Updated tag '%s' (was %s)\n"), tag, find_unique_abbrev(prev, DEFAULT_ABBREV));
 
builtin/update-ref.c +1 -0
index fc3512f..7fe9c11 100644
@@ -373,6 +373,7 @@ int cmd_update_ref(int argc, const char **argv, const char *prefix)
 		update_refs_stdin();
 		if (ref_transaction_commit(transaction, msg, &err))
 			die("%s", err.buf);
+		ref_transaction_free(transaction);
 		return 0;
 	}
 
fast-import.c +4 -4
index 300c8dc..ab36de5 100644
@@ -1703,15 +1703,15 @@ static int update_branch(struct branch *b)
 		}
 	}
 	transaction = ref_transaction_begin();
-	if ((!transaction ||
+	if (!transaction ||
 	    ref_transaction_update(transaction, b->name, b->sha1, old_sha1,
-				   0, 1)) ||
-	    (ref_transaction_commit(transaction, msg, &err) &&
-	     !(transaction = NULL))) {
+				   0, 1) ||
+	    ref_transaction_commit(transaction, msg, &err)) {
 		ref_transaction_rollback(transaction);
 		return error("Unable to update branch %s: %s", b->name,
 			     strbuf_detach(&err, NULL));
 	}
+	ref_transaction_free(transaction);
 	return 0;
 }
 
refs.c +2 -5
index c6ee43c..add95ba 100644
@@ -3302,7 +3302,7 @@ struct ref_transaction *ref_transaction_begin(void)
 	return xcalloc(1, sizeof(struct ref_transaction));
 }
 
-static void ref_transaction_free(struct ref_transaction *transaction)
+void ref_transaction_free(struct ref_transaction *transaction)
 {
 	int i;
 
@@ -3451,10 +3451,8 @@ int ref_transaction_commit(struct ref_transaction *transaction,
 	int n = transaction->nr;
 	struct ref_update **updates = transaction->updates;
 
-	if (!n) {
-		ref_transaction_free(transaction);
+	if (!n)
 		return 0;
-	}
 
 	/* Allocate work space */
 	delnames = xmalloc(sizeof(*delnames) * n);
@@ -3520,7 +3518,6 @@ cleanup:
 		if (updates[i]->lock)
 			unlock_ref(updates[i]->lock);
 	free(delnames);
-	ref_transaction_free(transaction);
 	return ret;
 }
 
refs.h +9 -5
index 5eb500e..fcde43e 100644
@@ -210,8 +210,8 @@ enum action_on_err {
 
 /*
  * Begin a reference transaction.  The reference transaction must
- * eventually be commited using ref_transaction_commit() or rolled
- * back using ref_transaction_rollback().
+ * eventually be freed by either calling ref_transaction_rollback()
+ * or ref_transaction_free().
  */
 struct ref_transaction *ref_transaction_begin(void);
 
@@ -267,13 +267,17 @@ int ref_transaction_delete(struct ref_transaction *transaction,
 /*
  * Commit all of the changes that have been queued in transaction, as
  * atomically as possible.  Return a nonzero value if there is a
- * problem.  The ref_transaction is freed by this function.
- * If err is non-NULL we will add an error string to it to explain why
- * the transaction failed.
+ * problem. If err is non-NULL we will add an error string to it to explain
+ * why the transaction failed.
  */
 int ref_transaction_commit(struct ref_transaction *transaction,
 			   const char *msg, struct strbuf *err);
 
+/*
+ * Free an existing transaction.
+ */
+void ref_transaction_free(struct ref_transaction *transaction);
+
 /** Lock a ref and then write its file */
 int update_ref(const char *action, const char *refname,
 		const unsigned char *sha1, const unsigned char *oldval,
sequencer.c +4 -4
index 449e093..5c424be 100644
@@ -283,16 +283,16 @@ static int fast_forward_to(const unsigned char *to, const unsigned char *from,
 	strbuf_addf(&sb, "%s: fast-forward", action_name(opts));
 
 	transaction = ref_transaction_begin();
-	if ((!transaction ||
+	if (!transaction ||
 	    ref_transaction_update(transaction, "HEAD", to, from,
-				   0, !unborn)) ||
-	    (ref_transaction_commit(transaction, sb.buf, &err) &&
-	     !(transaction = NULL))) {
+				   0, !unborn) ||
+	    ref_transaction_commit(transaction, sb.buf, &err)) {
 		ref_transaction_rollback(transaction);
 		strbuf_release(&sb);
 		return error(_("HEAD: Could not fast-forward: %s\n"),
 			     strbuf_detach(&err, NULL));
 	}
+	ref_transaction_free(transaction);
 
 	strbuf_release(&sb);
 	return 0;
Signature · 1 line
1.9.1.528.g98b8868.dirty
#28 lore raw

PATCH v4 20/27 fetch.c: clear errno before calling functions that might set it

In reply to Ronnie Sahlberg

In s_update_ref there are two calls that when they fail we return an error based on the errno value. In particular we want to return a specific error if ENOTDIR happened. Both these functions do have failure modes where they may return an error without updating errno, in which case a previous and unrelated ENOTDIT may cause us to return the wrong error. Clear errno before calling any functions if we check errno afterwards.

Also skip initializing a static variable to 0. Statics live in .bss and are all automatically initialized to 0.

---
 builtin/fetch.c | 4 +++-
 1 file changed, 3 insertions(+), 1 deletion(-)
builtin/fetch.c +3 -1
index 55f457c..a93c893 100644
@@ -44,7 +44,7 @@ static struct transport *gtransport;
 static struct transport *gsecondary;
 static const char *submodule_prefix = "";
 static const char *recurse_submodules_default;
-static int shown_url = 0;
+static int shown_url;
 
 static int option_parse_recurse_submodules(const struct option *opt,
 				   const char *arg, int unset)
@@ -382,6 +382,8 @@ static int s_update_ref(const char *action,
 	if (!rla)
 		rla = default_rla.buf;
 	snprintf(msg, sizeof(msg), "%s: %s", rla, action);
+
+	errno = 0;
 	lock = lock_any_ref_for_update(ref->name,
 				       check_old ? ref->old_sha1 : NULL,
 				       0, NULL);
Signature · 1 line
1.9.1.528.g98b8868.dirty
#29 lore raw

PATCH v4 21/27 fetch.c: change s_update_ref to use a ref transaction

In reply to Ronnie Sahlberg

Change s_update_ref to use a ref transaction for the ref update.

---
 builtin/fetch.c | 17 +++++++++--------
 1 file changed, 9 insertions(+), 8 deletions(-)
builtin/fetch.c +9 -8
index a93c893..b41d7b7 100644
@@ -375,7 +375,7 @@ static int s_update_ref(const char *action,
 {
 	char msg[1024];
 	char *rla = getenv("GIT_REFLOG_ACTION");
-	static struct ref_lock *lock;
+	struct ref_transaction *transaction;
 
 	if (dry_run)
 		return 0;
@@ -384,15 +384,16 @@ static int s_update_ref(const char *action,
 	snprintf(msg, sizeof(msg), "%s: %s", rla, action);
 
 	errno = 0;
-	lock = lock_any_ref_for_update(ref->name,
-				       check_old ? ref->old_sha1 : NULL,
-				       0, NULL);
-	if (!lock)
-		return errno == ENOTDIR ? STORE_REF_ERROR_DF_CONFLICT :
-					  STORE_REF_ERROR_OTHER;
-	if (write_ref_sha1(lock, ref->new_sha1, msg) < 0)
+	transaction = ref_transaction_begin();
+	if (!transaction ||
+	    ref_transaction_update(transaction, ref->name, ref->new_sha1,
+				   ref->old_sha1, 0, check_old) ||
+	    ref_transaction_commit(transaction, msg, NULL)) {
+		ref_transaction_rollback(transaction);
 		return errno == ENOTDIR ? STORE_REF_ERROR_DF_CONFLICT :
 					  STORE_REF_ERROR_OTHER;
+	}
+	ref_transaction_free(transaction);
 	return 0;
 }
 
Signature · 1 line
1.9.1.528.g98b8868.dirty
#30 lore raw

PATCH v4 22/27 fetch.c: use a single ref transaction for all ref updates

In reply to Ronnie Sahlberg

Change store_updated_refs to use a single ref transaction for all refs that are updated during the fetch. This makes the fetch more atomic when update failures occur.

Since ref update failures will now no longer occur in the code path for updating a single ref in s_update_ref, we no longer have as detailed error message logging the exact reference and the ref log action as in the old cod Instead since we fail the entire transaction we log a much more generic message. But since we commit the transaction using MSG_ON_ERR we will log an error containing the ref name if either locking of writing the ref would so the regression in the log message is minor.

This will also change the order in which errors are checked for and logged which may alter which error will be logged if there are multiple errors occuring during a fetch.

For example, assume we have a fetch for two refs that both would fail. Where the first ref would fail with ENOTDIR due to a directory in the ref path not existing, and the second ref in the fetch would fail due to the check in update_logical_ref():

        if (current_branch &&
            !strcmp(ref->name, current_branch->name) &&
            !(update_head_ok || is_bare_repository()) &&
            !is_null_sha1(ref->old_sha1)) {
                /*
                 * If this is the head, and it's not okay to update
                 * the head, and the old value of the head isn't empty...
                 */

In the old code since we would update the refs one ref at a time we would first fail the ENOTDIR and then fail the second update of HEAD as well. But since the first ref failed with ENOTDIR we would eventually fail the who fetch with STORE_REF_ERROR_DF_CONFLICT

In the new code, since we defer committing the transaction until all refs have been processed, we would now detect that the second ref was bad and rollback the transaction before we would even try start writing the update t disk and thus we would not return STORE_REF_ERROR_DF_CONFLICT for this case.

I think this new behaviour is more correct, since if there was a problem we would not even try to commit the transaction but need to highlight this change in how/what errors are reported.
This change in what error is returned only occurs if there are multiple refs that fail to update and only some, but not all, of them fail due to ENOTDIR.

---
 builtin/fetch.c | 35 +++++++++++++++++------------------
 1 file changed, 17 insertions(+), 18 deletions(-)
builtin/fetch.c +17 -18
index b41d7b7..8f974a2 100644
@@ -45,6 +45,7 @@ static struct transport *gsecondary;
 static const char *submodule_prefix = "";
 static const char *recurse_submodules_default;
 static int shown_url;
+struct ref_transaction *transaction;
 
 static int option_parse_recurse_submodules(const struct option *opt,
 				   const char *arg, int unset)
@@ -373,27 +374,13 @@ static int s_update_ref(const char *action,
 			struct ref *ref,
 			int check_old)
 {
-	char msg[1024];
-	char *rla = getenv("GIT_REFLOG_ACTION");
-	struct ref_transaction *transaction;
-
 	if (dry_run)
 		return 0;
-	if (!rla)
-		rla = default_rla.buf;
-	snprintf(msg, sizeof(msg), "%s: %s", rla, action);
 
-	errno = 0;
-	transaction = ref_transaction_begin();
-	if (!transaction ||
-	    ref_transaction_update(transaction, ref->name, ref->new_sha1,
-				   ref->old_sha1, 0, check_old) ||
-	    ref_transaction_commit(transaction, msg, NULL)) {
-		ref_transaction_rollback(transaction);
-		return errno == ENOTDIR ? STORE_REF_ERROR_DF_CONFLICT :
-					  STORE_REF_ERROR_OTHER;
-	}
-	ref_transaction_free(transaction);
+	if (ref_transaction_update(transaction, ref->name, ref->new_sha1,
+			       ref->old_sha1, 0, check_old))
+		return STORE_REF_ERROR_OTHER;
+
 	return 0;
 }
 
@@ -565,6 +552,13 @@ static int store_updated_refs(const char *raw_url, const char *remote_name,
 		goto abort;
 	}
 
+	errno = 0;
+	transaction = ref_transaction_begin();
+	if (!transaction) {
+		rc = error(_("cannot start ref transaction\n"));
+		goto abort;
+	}
+
 	/*
 	 * We do a pass for each fetch_head_status type in their enum order, so
 	 * merged entries are written before not-for-merge. That lets readers
@@ -676,6 +670,11 @@ static int store_updated_refs(const char *raw_url, const char *remote_name,
 			}
 		}
 	}
+	if (ref_transaction_commit(transaction, "fetch_ref transaction",
+				   UPDATE_REFS_MSG_ON_ERR))
+		rc |= errno == ENOTDIR ? STORE_REF_ERROR_DF_CONFLICT :
+		  STORE_REF_ERROR_OTHER;
+	ref_transaction_free(transaction);
 
 	if (rc & STORE_REF_ERROR_DF_CONFLICT)
 		error(_("some local refs could not be updated; try running\n"
Signature · 1 line
1.9.1.528.g98b8868.dirty
#31 lore raw

PATCH v4 23/27 receive-pack.c: use a reference transaction for updating the refs

In reply to Ronnie Sahlberg

Wrap all the ref updates inside a transaction to make the update atomic.

---
 builtin/receive-pack.c | 20 ++++++++++----------
 1 file changed, 10 insertions(+), 10 deletions(-)
builtin/receive-pack.c +10 -10
index c323081..885aef4 100644
@@ -46,6 +46,8 @@ static void *head_name_to_free;
 static int sent_capabilities;
 static int shallow_update;
 static const char *alt_shallow_file;
+struct strbuf err = STRBUF_INIT;
+struct ref_transaction *transaction;
 
 static enum deny_action parse_deny_action(const char *var, const char *value)
 {
@@ -475,7 +477,6 @@ static const char *update(struct command *cmd, struct shallow_info *si)
 	const char *namespaced_name;
 	unsigned char *old_sha1 = cmd->old_sha1;
 	unsigned char *new_sha1 = cmd->new_sha1;
-	struct ref_lock *lock;
 
 	/* only refs/... are allowed */
 	if (!starts_with(name, "refs/") || check_refname_format(name + 5, 0)) {
@@ -580,15 +581,9 @@ static const char *update(struct command *cmd, struct shallow_info *si)
 		    update_shallow_ref(cmd, si))
 			return "shallow error";
 
-		lock = lock_any_ref_for_update(namespaced_name, old_sha1,
-					       0, NULL);
-		if (!lock) {
-			rp_error("failed to lock %s", name);
-			return "failed to lock";
-		}
-		if (write_ref_sha1(lock, new_sha1, "push")) {
-			return "failed to write"; /* error() already called */
-		}
+		if (ref_transaction_update(transaction, namespaced_name,
+					   new_sha1, old_sha1, 0, 1))
+			return "failed to update";
 		return NULL; /* good */
 	}
 }
@@ -812,6 +807,7 @@ static void execute_commands(struct command *commands,
 	head_name = head_name_to_free = resolve_refdup("HEAD", sha1, 0, NULL);
 
 	checked_connectivity = 1;
+	transaction = ref_transaction_begin();
 	for (cmd = commands; cmd; cmd = cmd->next) {
 		if (cmd->error_string)
 			continue;
@@ -827,6 +823,10 @@ static void execute_commands(struct command *commands,
 			checked_connectivity = 0;
 		}
 	}
+	if (ref_transaction_commit(transaction, "push", &err))
+		error("%s", err.buf);
+	ref_transaction_free(transaction);
+	strbuf_reset(&err);
 
 	if (shallow_update && !checked_connectivity)
 		error("BUG: run 'git fsck' for safety.\n"
Signature · 1 line
1.9.1.528.g98b8868.dirty
#32 lore raw

PATCH v4 24/27 fast-import.c: use a ref transaction when dumping tags

In reply to Ronnie Sahlberg
---
 fast-import.c | 17 ++++++++++++-----
 1 file changed, 12 insertions(+), 5 deletions(-)
fast-import.c +12 -5
index ab36de5..b105f17 100644
@@ -1730,15 +1730,22 @@ static void dump_tags(void)
 {
 	static const char *msg = "fast-import";
 	struct tag *t;
-	struct ref_lock *lock;
 	char ref_name[PATH_MAX];
+	struct strbuf err = STRBUF_INIT;
+	struct ref_transaction *transaction;
 
+	transaction = ref_transaction_begin();
 	for (t = first_tag; t; t = t->next_tag) {
-		sprintf(ref_name, "tags/%s", t->name);
-		lock = lock_ref_sha1(ref_name, NULL);
-		if (!lock || write_ref_sha1(lock, t->sha1, msg) < 0)
-			failure |= error("Unable to update %s", ref_name);
+		sprintf(ref_name, "refs/tags/%s", t->name);
+
+		if (ref_transaction_update(transaction, ref_name, t->sha1,
+					   NULL, 0, 0))
+			failure |= error("Unable to update %s", err.buf);
 	}
+	if (failure || ref_transaction_commit(transaction, msg, &err))
+		failure |= error("Unable to update %s", err.buf);
+	ref_transaction_free(transaction);
+	strbuf_reset(&err);
 }
 
 static void dump_marks_helper(FILE *f,
Signature · 1 line
1.9.1.528.g98b8868.dirty
#33 lore raw

PATCH v4 25/27 walker.c: use ref transaction for ref updates

In reply to Ronnie Sahlberg

Switch to using ref transactions in walker_fetch(). As part of the refactoring to use ref transactions we also fix a potential memory leak where in the original code if write_ref_sha1() would fail we would end up returning from the function without free()ing the msg string.

This changes the locking slightly for walker_fetch. Previously the code would lock all refs before writing them but now we do not lock the refs until the commit stage. There is thus a very short window where changes could be done locally during the fetch which would be overwritten when the fetch completes and commits its transaction. But this window should be reasonably short. Even if this race does trigger, since both the old code and the new code just overwrites the refs to the new values without checking or comparing them with the previous value, this is not too dissimilar to a similar scenario where you first do a ref change locally and then later do a fetch that overwrites the local change. With this in mind I do not see the change in locking semantics to be critical.

Note that this function is only called when fetching from a remote HTTP repository onto the local (most of the time single-user) repository which likely means that the type of collissions that the previous locking would protect against and cause the fetch to fail for to be even more rare.

---
 walker.c | 51 ++++++++++++++++++++++++++-------------------------
 1 file changed, 26 insertions(+), 25 deletions(-)
walker.c +26 -25
index 1dd86b8..382a63a 100644
@@ -251,24 +251,18 @@ void walker_targets_free(int targets, char **target, const char **write_ref)
 int walker_fetch(struct walker *walker, int targets, char **target,
 		 const char **write_ref, const char *write_ref_log_details)
 {
-	struct ref_lock **lock = xcalloc(targets, sizeof(struct ref_lock *));
+	char ref_name[PATH_MAX];
+	struct strbuf err = STRBUF_INIT;
+	struct ref_transaction *transaction;
 	unsigned char *sha1 = xmalloc(targets * 20);
-	char *msg;
-	int ret;
+	char *msg = NULL;
 	int i;
 
 	save_commit_buffer = 0;
 
-	for (i = 0; i < targets; i++) {
-		if (!write_ref || !write_ref[i])
-			continue;
-
-		lock[i] = lock_ref_sha1(write_ref[i], NULL);
-		if (!lock[i]) {
-			error("Can't lock ref %s", write_ref[i]);
-			goto unlock_and_fail;
-		}
-	}
+	transaction = ref_transaction_begin();
+	if (!transaction)
+		return -1;
 
 	if (!walker->get_recover)
 		for_each_ref(mark_complete, NULL);
@@ -276,14 +270,14 @@ int walker_fetch(struct walker *walker, int targets, char **target,
 	for (i = 0; i < targets; i++) {
 		if (interpret_target(walker, target[i], &sha1[20 * i])) {
 			error("Could not interpret response from server '%s' as something to pull", target[i]);
-			goto unlock_and_fail;
+			goto rollback_and_fail;
 		}
 		if (process(walker, lookup_unknown_object(&sha1[20 * i])))
-			goto unlock_and_fail;
+			goto rollback_and_fail;
 	}
 
 	if (loop(walker))
-		goto unlock_and_fail;
+		goto rollback_and_fail;
 
 	if (write_ref_log_details) {
 		msg = xmalloc(strlen(write_ref_log_details) + 12);
@@ -294,19 +288,26 @@ int walker_fetch(struct walker *walker, int targets, char **target,
 	for (i = 0; i < targets; i++) {
 		if (!write_ref || !write_ref[i])
 			continue;
-		ret = write_ref_sha1(lock[i], &sha1[20 * i], msg ? msg : "fetch (unknown)");
-		lock[i] = NULL;
-		if (ret)
-			goto unlock_and_fail;
+		sprintf(ref_name, "refs/%s", write_ref[i]);
+		if (ref_transaction_update(transaction, ref_name,
+					   &sha1[20 * i], NULL,
+					   0, 0))
+			goto rollback_and_fail;
+	}
+
+	if (ref_transaction_commit(transaction, msg ? msg : "fetch (unknown)",
+				   &err)) {
+		error("%s", err.buf);
+		goto rollback_and_fail;
 	}
-	free(msg);
 
+	free(msg);
 	return 0;
 
-unlock_and_fail:
-	for (i = 0; i < targets; i++)
-		if (lock[i])
-			unlock_ref(lock[i]);
+rollback_and_fail:
+	free(msg);
+	strbuf_reset(&err);
+	ref_transaction_free(transaction);
 
 	return -1;
 }
Signature · 1 line
1.9.1.528.g98b8868.dirty
#34 lore raw

PATCH v4 26/27 refs.c: make write_ref_sha1 static

In reply to Ronnie Sahlberg

No external users call write_ref_sha1 any more so lets declare it static.

---
 refs.c | 4 +++-
 refs.h | 3 ---
 2 files changed, 3 insertions(+), 4 deletions(-)
refs.c +3 -1
index add95ba..cb7d69f 100644
@@ -251,6 +251,8 @@ struct ref_entry {
 };
 
 static void read_loose_refs(const char *dirname, struct ref_dir *dir);
+static int write_ref_sha1(struct ref_lock *lock,
+			  const unsigned char *sha1, const char *logmsg);
 
 static struct ref_dir *get_ref_dir(struct ref_entry *entry)
 {
@@ -2798,7 +2800,7 @@ static int is_branch(const char *refname)
 	return !strcmp(refname, "HEAD") || starts_with(refname, "refs/heads/");
 }
 
-int write_ref_sha1(struct ref_lock *lock,
+static int write_ref_sha1(struct ref_lock *lock,
 	const unsigned char *sha1, const char *logmsg)
 {
 	static char term = '\n';
refs.h +0 -3
index fcde43e..bc8a95b 100644
@@ -150,9 +150,6 @@ extern int commit_ref(struct ref_lock *lock);
 /** Release any lock taken but not written. **/
 extern void unlock_ref(struct ref_lock *lock);
 
-/** Writes sha1 into the ref specified by the lock. **/
-extern int write_ref_sha1(struct ref_lock *lock, const unsigned char *sha1, const char *msg);
-
 /** Setup reflog before using. **/
 int log_ref_setup(const char *refname, char *logfile, int bufsize);
 
Signature · 1 line
1.9.1.528.g98b8868.dirty
#35 lore raw

PATCH v4 27/27 refs.c: make lock_ref_sha1 static

In reply to Ronnie Sahlberg

No external callers reference lock_ref_sha1 any more so lets declare it static.

---
 refs.c | 2 +-
 refs.h | 3 ---
 2 files changed, 1 insertion(+), 4 deletions(-)
refs.c +1 -1
index cb7d69f..eebcacb 100644
@@ -2130,7 +2130,7 @@ static struct ref_lock *lock_ref_sha1_basic(const char *refname,
 	return NULL;
 }
 
-struct ref_lock *lock_ref_sha1(const char *refname, const unsigned char *old_sha1)
+static struct ref_lock *lock_ref_sha1(const char *refname, const unsigned char *old_sha1)
 {
 	char refpath[PATH_MAX];
 	if (check_refname_format(refname, 0))
refs.h +0 -3
index bc8a95b..b14fe86 100644
@@ -132,9 +132,6 @@ extern int ref_exists(const char *);
  */
 extern int peel_ref(const char *refname, unsigned char *sha1);
 
-/** Locks a "refs/" ref returning the lock on success and NULL on failure. **/
-extern struct ref_lock *lock_ref_sha1(const char *refname, const unsigned char *old_sha1);
-
 /** Locks any ref (for 'HEAD' type refs). */
 #define REF_NODEREF	0x01
 extern struct ref_lock *lock_any_ref_for_update(const char *refname,
Signature · 1 line
1.9.1.528.g98b8868.dirty
#10 lore raw

Re: [PATCH v4 08/27] refs.c: change ref_transaction_update() to do error checking and return status

In reply to Eric Sunshine
Quoted 60 lines · Eric Sunshine
Quoted 59 lines · Ronnie Sahlberg

Update ref_transaction_update() do some basic error checking and return true on error. Update all callers to check ref_transaction_update() for error.

---
 builtin/update-ref.c | 10 ++++++----
 refs.c               |  9 +++++++--
 refs.h               | 10 +++++-----
 3 files changed, 18 insertions(+), 11 deletions(-)
builtin/update-ref.c +6 -4
index 2bef2a0..59c4d6b 100644
@@ -197,8 +197,9 @@ static const char *parse_cmd_update(struct strbuf *input, const char *next)
        if (*next != line_termination)
                die("update %s: extra input: %s", refname, next);
 
-       ref_transaction_update(transaction, refname, new_sha1, old_sha1,
-                              update_flags, have_old);
+       if (ref_transaction_update(transaction, refname, new_sha1, old_sha1,
+                                  update_flags, have_old))
+               die("update %s: failed", refname);
 
        update_flags = 0;
        free(refname);
@@ -286,8 +287,9 @@ static const char *parse_cmd_verify(struct strbuf *input, const char *next)
        if (*next != line_termination)
                die("verify %s: extra input: %s", refname, next);
 
-       ref_transaction_update(transaction, refname, new_sha1, old_sha1,
-                              update_flags, have_old);
+       if (ref_transaction_update(transaction, refname, new_sha1, old_sha1,
+                                  update_flags, have_old))
+               die("failed transaction update for %s", refname);
 
        update_flags = 0;
        free(refname);
refs.c +5 -2
index 308e13e..1a903fb 100644
@@ -3333,19 +3333,24 @@ static struct ref_update *add_update(struct ref_transaction *transaction,
        return update;
 }
 
-void ref_transaction_update(struct ref_transaction *transaction,
+int ref_transaction_update(struct ref_transaction *transaction,
                            const char *refname,
                            const unsigned char *new_sha1,
                            const unsigned char *old_sha1,
                            int flags, int have_old)
 {
-       struct ref_update *update = add_update(transaction, refname);
+       struct ref_update *update;
+
+       if (have_old && !old_sha1)
+               die("have_old is true but old_sha1 is NULL");
 
Quoted 11 lines

refs.c static struct ref_update *add_update(struct ref_transaction *transaction, · line 3353

Quoted 7 lines
refs.c +2 -0
+       update = add_update(transaction, refname);
        hashcpy(update->new_sha1, new_sha1);
        update->flags = flags;
        update->have_old = have_old;
        if (have_old)
                hashcpy(update->old_sha1, old_sha1);
+       return 0;

Am I misreading? The commit message talks about returning true on error, but this code seems to only ever die() or return 0 (false).

I have updated the commit message to be more precise.
The function returns true on error but there are currently no checks that actually
do return failure in this function. Such checks will be added in the future. Also having it return an int instead of void allows us to use the pattern

if(!transaction ||
ref_transaction_update(transaction, ...) |||
ref_transaction_commit(transaction, ...)) {

eventhough we do not yet have any conditions where _update will fail.

Quoted 26 lines
Quoted 26 lines
refs.c +0 -0
 }
 
 void ref_transaction_create(struct ref_transaction *transaction,
refs.h +5 -6
index bc7715e..0364a3e 100644
@@ -237,11 +237,11 @@ void ref_transaction_rollback(struct ref_transaction *transaction);
  * that the reference should have had before the update, or zeros if
  * it must not have existed beforehand.
  */
-void ref_transaction_update(struct ref_transaction *transaction,
-                           const char *refname,
-                           const unsigned char *new_sha1,
-                           const unsigned char *old_sha1,
-                           int flags, int have_old);
+int ref_transaction_update(struct ref_transaction *transaction,
+                          const char *refname,
+                          const unsigned char *new_sha1,
+                          const unsigned char *old_sha1,
+                          int flags, int have_old);
 
 /*
  * Add a reference creation to transaction.  new_sha1 is the value
--

1.9.1.528.g98b8868.dirty

#16 lore raw

Re: [PATCH v4 12/27] replace.c: use the ref transaction functions for updates

In reply to Eric Sunshine
Quoted 35 lines · Eric Sunshine
Quoted 34 lines · Ronnie Sahlberg

Update replace.c to use ref transactions for updates.

---
 builtin/replace.c | 14 ++++++++------
 1 file changed, 8 insertions(+), 6 deletions(-)
builtin/replace.c +6 -6
index b62420a..b037b29 100644
@@ -129,7 +129,8 @@ static int replace_object(const char *object_ref, const char *replace_ref,
        unsigned char object[20], prev[20], repl[20];
        enum object_type obj_type, repl_type;
        char ref[PATH_MAX];
-       struct ref_lock *lock;
+       struct ref_transaction *transaction;
+       struct strbuf err = STRBUF_INIT;
 
        if (get_sha1(object_ref, object))
                die("Failed to resolve '%s' as a valid ref.", object_ref);
@@ -157,11 +158,12 @@ static int replace_object(const char *object_ref, const char *replace_ref,
        else if (!force)
                die("replace ref '%s' already exists", ref);
 
-       lock = lock_any_ref_for_update(ref, prev, 0, NULL);
-       if (!lock)
-               die("%s: cannot lock the ref", ref);
-       if (write_ref_sha1(lock, repl, NULL) < 0)
-               die("%s: cannot update the ref", ref);
+       transaction = ref_transaction_begin();
+       if (!transaction ||
+           ref_transaction_update(transaction, ref, repl, prev,
+                                  0, !is_null_sha1(prev)) ||
Quoted 8 lines

builtin/replace.c static int replace_object(const char *object_ref, const char *replace_ref, · line 166

Quoted 2 lines
builtin/replace.c +2 -0
+           ref_transaction_commit(transaction, NULL, &err))
+               die(_("%s: failed to replace ref: %s"), ref, err.buf);

Even though 'err' will be empty after this conditional, would strbuf_release(&err) here be warranted to future-proof it? Today's implementation of strbuf will not have allocated any memory, but perhaps a future change might pre-allocate (unlikely though that is), which would leak here.

Thanks.

I have no strong feelings either way.
A previous patch got a comment to remove a strbuf_release() because we knew in that
code path that the string would be empty and thus the call was superfluous.

So one for and one against so far.
I will leave as is until there is more consensus.

Quoted 5 lines
Quoted 5 lines
builtin/replace.c +0 -1
        return 0;
 }
--

1.9.1.528.g98b8868.dirty

#17 lore raw

Re: [PATCH v4 12/27] replace.c: use the ref transaction functions for updates

Quoted 45 lines · Ronnie Sahlberg
Quoted 35 lines · Eric Sunshine
Quoted 34 lines · Ronnie Sahlberg

Update replace.c to use ref transactions for updates.

---
 builtin/replace.c | 14 ++++++++------
 1 file changed, 8 insertions(+), 6 deletions(-)
builtin/replace.c +6 -6
index b62420a..b037b29 100644
@@ -129,7 +129,8 @@ static int replace_object(const char *object_ref, const char *replace_ref,
        unsigned char object[20], prev[20], repl[20];
        enum object_type obj_type, repl_type;
        char ref[PATH_MAX];
-       struct ref_lock *lock;
+       struct ref_transaction *transaction;
+       struct strbuf err = STRBUF_INIT;
 
        if (get_sha1(object_ref, object))
                die("Failed to resolve '%s' as a valid ref.", object_ref);
@@ -157,11 +158,12 @@ static int replace_object(const char *object_ref, const char *replace_ref,
        else if (!force)
                die("replace ref '%s' already exists", ref);
 
-       lock = lock_any_ref_for_update(ref, prev, 0, NULL);
-       if (!lock)
-               die("%s: cannot lock the ref", ref);
-       if (write_ref_sha1(lock, repl, NULL) < 0)
-               die("%s: cannot update the ref", ref);
+       transaction = ref_transaction_begin();
+       if (!transaction ||
+           ref_transaction_update(transaction, ref, repl, prev,
+                                  0, !is_null_sha1(prev)) ||
Quoted 8 lines

builtin/replace.c static int replace_object(const char *object_ref, const char *replace_ref, · line 166

Quoted 2 lines
builtin/replace.c +2 -0
+           ref_transaction_commit(transaction, NULL, &err))
+               die(_("%s: failed to replace ref: %s"), ref, err.buf);

Even though 'err' will be empty after this conditional, would strbuf_release(&err) here be warranted to future-proof it? Today's implementation of strbuf will not have allocated any memory, but perhaps a future change might pre-allocate (unlikely though that is), which would leak here.

Quoted 4 lines

I have no strong feelings either way.
A previous patch got a comment to remove a strbuf_release() because we knew in that
code path that the string would be empty and thus the call was superfluous.

Indeed, I realized later that the reason I gave for possibly adding the strbuf_release() was effectively bogus. Code throughout the project ignores strbuff_release() when it is obvious that the strbuf hasn't been used. Such code looks like this:

func() {
    struct strbuf foo = STRBUF_INIT;
    ...code not touching 'foo'...
    if (...)
        return;
    ...code touching 'foo'...
    strbuf_release(&foo);
}

At the point of early return, it's obvious at a glance that no content has been added to 'foo'.

It was only a little while ago that I came to understand why the code in this patch bothered me:

func() {
    struct strbuf foo = STRBUF_INIT;
    if (bar(&foo))
        die(...);
    ...return or fall off end without releasing 'foo'...
}

The problem is that it's not so easy to see that it's safe to "leak" the strbuf without detouring through the documentation of bar() and possibly its implementation as well, before finally resuming the reading of func(). That extra cost of having to study bar() will likely be paid by most readers of func() who are concerned about the missing strbuf_release(). The cognitive burden is greater.

Quoted 2 lines

So one for and one against so far.
I will leave as is until there is more consensus.

Fair enough. The fact that the variable is named 'err' in this case might be enough to allow one to infer, without detouring through bar(), that the missing strbuf_release() is intentional.

#22 lore raw

Re: [PATCH v4 15/27] fast-import.c: change update_branch to use ref transactions

In reply to Eric Sunshine
Quoted 52 lines · Eric Sunshine
Quoted 51 lines · Ronnie Sahlberg

Change update_branch() to use ref transactions for updates.

---
 fast-import.c | 20 ++++++++++++--------
 1 file changed, 12 insertions(+), 8 deletions(-)
fast-import.c +6 -8
index fb4738d..300c8dc 100644
@@ -1678,36 +1678,40 @@ found_entry:
 static int update_branch(struct branch *b)
 {
        static const char *msg = "fast-import";
-       struct ref_lock *lock;
+       struct ref_transaction *transaction;
        unsigned char old_sha1[20];
+       struct strbuf err = STRBUF_INIT;
 
        if (is_null_sha1(b->sha1))
                return 0;
        if (read_ref(b->name, old_sha1))
                hashclr(old_sha1);
-       lock = lock_any_ref_for_update(b->name, old_sha1, 0, NULL);
-       if (!lock)
-               return error("Unable to lock %s", b->name);
        if (!force_update && !is_null_sha1(old_sha1)) {
                struct commit *old_cmit, *new_cmit;
 
                old_cmit = lookup_commit_reference_gently(old_sha1, 0);
                new_cmit = lookup_commit_reference_gently(b->sha1, 0);
                if (!old_cmit || !new_cmit) {
-                       unlock_ref(lock);
                        return error("Branch %s is missing commits.", b->name);
                }
 
                if (!in_merge_bases(old_cmit, new_cmit)) {
-                       unlock_ref(lock);
                        warning("Not updating %s"
                                " (new tip %s does not contain %s)",
                                b->name, sha1_to_hex(b->sha1), sha1_to_hex(old_sha1));
                        return -1;
                }
        }
-       if (write_ref_sha1(lock, b->sha1, msg) < 0)
-               return error("Unable to update %s", b->name);
+       transaction = ref_transaction_begin();
+       if ((!transaction ||
+           ref_transaction_update(transaction, b->name, b->sha1, old_sha1,
+                                  0, 1)) ||
Quoted 9 lines

fast-import.c found_entry: · line 1713

Quoted 5 lines
fast-import.c +5 -0
+           (ref_transaction_commit(transaction, msg, &err) &&
+            !(transaction = NULL))) {
+               ref_transaction_rollback(transaction);
+               return error("Unable to update branch %s: %s", b->name,
+                            strbuf_detach(&err, NULL));

Iffy strbuf handling. The strbuf content is being leaked here whether detached or not.

Thanks!

I have updated this and all other patches to make sure we do a strbuf_release() any time we have
added to the string.

I also did a quick audit of the strbuf_detach() use in builtin/* (which I based my use on)
and there seems to be quite common that strbuf_detach() is used in a way that will leak memory.

I will make a note and perhaps audit all the other strbuf_detach() calls for a future patch series.

Quoted 6 lines
Quoted 6 lines
fast-import.c +1 -1
+       }
        return 0;
 }
 
--

1.9.1.528.g98b8868.dirty

#23 lore raw

Re: [PATCH v4 15/27] fast-import.c: change update_branch to use ref transactions

In reply to Ronnie Sahlberg

fast-import.c found_entry: · line 1714

Quoted 10 lines · Ronnie Sahlberg
fast-import.c +10 -0
+	transaction = ref_transaction_begin();
+	if ((!transaction ||
+	    ref_transaction_update(transaction, b->name, b->sha1, old_sha1,
+				   0, 1)) ||
+	    (ref_transaction_commit(transaction, msg, &err) &&
+	     !(transaction = NULL))) {
+		ref_transaction_rollback(transaction);
+		return error("Unable to update branch %s: %s", b->name,
+			     strbuf_detach(&err, NULL));
+	}

The assigning of NULL to transaction and always returning true looks very suspicious.

Also, if we couldn't get transaction what happens? I think you wanted to avoid passing NULL to rollback but at the same time I suspect you wanted to fall into that "return error()" part, but apparently you are failing to have that cake and eat it too, no?

#36 lore raw
In reply to Ronnie Sahlberg
Quoted 5 lines · Ronnie Sahlberg

This patch series is based on mhagger/ref-transactions and expands on the transaction API. It converts all external (outside of refs.c) callers to use the transaction API for any writes.
This makes most of the ref updates to become atomic when there are failures locking or writing to a ref.

I think I saw some more comments to be addressed on this round, but I'll try to push it through into 'pu' by attempting to resolve conflicts so that I can ask you to eyeball the result. This series seem to conflict with your own rs/ref-update-check-errors-early topic that is already in 'next'.

If I screwed up the conflict resolution (which is very possible), I may have to ask you to rebase this series on top of acc62aa (which is the merge of rs/ref-update-check-errors-early to 'next'), but I am hoping that conflict resolution I'll push out today will be correct. We'll see.

Thanks.

#37 lore raw
Quoted 14 lines · Junio C Hamano
Quoted 5 lines · Ronnie Sahlberg

This patch series is based on mhagger/ref-transactions and expands on the transaction API. It converts all external (outside of refs.c) callers to use the transaction API for any writes.
This makes most of the ref updates to become atomic when there are failures locking or writing to a ref.

I think I saw some more comments to be addressed on this round, but I'll try to push it through into 'pu' by attempting to resolve conflicts so that I can ask you to eyeball the result. This series seem to conflict with your own rs/ref-update-check-errors-early topic that is already in 'next'.

Quoted 6 lines

If I screwed up the conflict resolution (which is very possible), I may have to ask you to rebase this series on top of acc62aa (which is the merge of rs/ref-update-check-errors-early to 'next'), but I am hoping that conflict resolution I'll push out today will be correct. We'll see.

Thanks.

I just sent v5 of the patch series where I have addressed the comments from Eric and Michael so far.

Otherwise, how hard would it be to drop
rs/ref-update-check-errors-early ?

I can just redo those patches later, and that might be the easiest solution.

Regards
ronnie sahlberg

Quoted 1 line

Thanks.