coreos/etcd — pull request #347 by benbjohnson (2013-11-29 23:58:28+00:00)
Title: WIP: mod/lock

## Overview

This pull request implements a locking module for etcd. The goal is to provide a way for server nodes to be able to easily lock resources while they are in use and then release the lock when it's done. This locking mechanism is similar, in premise, to the distributed lock system that Zookeeper.

Because etcd does not have ephemeral nodes, a simpler TTL-based approach was used to provide a fallback for failed nodes. This approach has the benefit that it can be used in languages that don't easily support multithreading such as BASH scripts.

Adding ephemeral nodes in the future can provide a quicker release of locks acquired by machines that fail completely. However, a TTL should still be used since a failed machine could simply hang and maintain the connection to etcd.

## Usage

### Acquiring a lock

To obtain a lock, simply send a `POST` request to `/mod/lock/`:

```
$ curl -X POST http://localhost:4001/mod/lock/myresource?ttl=60
2
```

This returns the index of the lock: `2`. You can use this index to renew or release the lock later.

If another process already has a lock on `/myresource`, then the request will hang until the other process releases the lock or the TTL causes the lock to expire.

### Renewing a lock

If you have a long, multi-step process you can renew the lock that you originally obtained by using a `PUT` and the lock index:

```
$ curl -X PUT http://localhost:4001/mod/lock/myresource/2?ttl=60
```

This will renew lock index `2` for another 60 seconds if the index still owns the lock. If the lock has been released for some reason, then an error will be returned.

### Releasing a lock

When you're done with your lock, you can release it by using a `DELETE` request with the index:

```
$ curl -X DELETE http://localhost:4001/mod/lock/myresource/2
```

### Checking for lock existence

You can check to see the current index that has the lock by using a `GET`:

```
$ curl http://localhost:4001/mod/lock/myresource
```

However, this is mainly for debugging. Locks can be lost in the time between request and response of the `GET` call.

## Notes

I fixed a bug in the functional tests which caused a bunch of failed assertions. I don't think it's anything serious but I wanted to get this PR in front of you guys so you can review the approach.

Don't check in this PR yet. :)

/cc: @xiangli-cmu @philips