https://github.com/coreos/etcd/blob/master/Documentation/api.md
Atomic Compare-and-Swap
etcd can be used as a centralized coordination service in a cluster, and CompareAndSwap (CAS) is the most basic operation used to build a distributed lock service.
This command will set the value of a key only if the client-provided conditions are equal to the current conditions.
The current comparable conditions are:
prevValue - checks the previous value of the key.
prevIndex - checks the previous modifiedIndex of the key.
prevExist - checks existence of the key: if prevExist is true, it is an update request; if prevExist is false, it is acreate request.
Here is a simple example. Let's create a key-value pair first: foo=one.
curl http://127.0.0.1:2379/v2/keys/foo -XPUT -d value=one
Now let's try some invalid CompareAndSwap commands.
Trying to set this existing key with prevExist=false fails as expected:
curl http://127.0.0.1:2379/v2/keys/foo?prevExist=false -XPUT -d value=three
The error code explains the problem:
{
"cause": "/foo",
"errorCode": 105,
"index": 39776,
"message": "Key already exists"
}
Now let's provide a prevValue parameter:
curl http://127.0.0.1:2379/v2/keys/foo?prevValue=two -XPUT -d value=three
This will try to compare the previous value of the key and the previous value we provided. If they are equal, the value of the key will change to three.
{
"cause": "[two != one]",
"errorCode": 101,
"index": 8,
"message": "Compare failed"
}
which means CompareAndSwap failed. cause explains why the test failed. Note: the condition prevIndex=0 always passes.
Let'