Add API call for retrieving db index
Its hard to use the ETCD watch API without knowing the current DB index, so I added it. It works when I test it. Hopefully the method of doing a GET on host/v2/keys just to get the HTTP header is acceptable.
So X-Etcd-Index is tied to an etcd server (so in a cluster, you can have multiple I think, not sure). But the index used in the api is the modifiedIndex stored with a key.
If we take a look at the etcd API description:
node.createdIndex: an index is a unique, monotonically-incrementing integer created for each change to etcd. This specific index reflects the point in the etcd state member at which a given key was created. You may notice that in this example the index is 2 even though it is the first request you sent to the server. This is because there are internal commands that also change the state behind the scenes, like adding and syncing servers.
node.modifiedIndex: like node.createdIndex, this attribute is also an etcd index. Actions that cause the value to change include set, delete, update, create, compareAndSwap and compareAndDelete. Since the get and watch commands do not change state in the store, they do not change the value of node.modifiedIndex.
It's probably best to do an etcdlib_get() before an etcdlib_watch(). If the return value is ETCDLIB_RC_ERROR, you can assume it is 0.
Verifying this locally:
oipo@oipo-X570-AORUS-ELITE:~$ curl http://127.0.0.1:2379/v2/keys/message3
{"errorCode":100,"message":"Key not found","cause":"/message3","index":5266}
oipo@oipo-X570-AORUS-ELITE:~$ curl http://127.0.0.1:2379/v2/keys
{"action":"get","node":{"dir":true,"nodes":[{"key":"/hier","dir":true,"modifiedIndex":13,"createdIndex":13}]}}
I had two factors that led me to wanting this available:
-
When I wrote my db interface code, the first thing I did was setup a directory/key structure then set a watch on the etcd directory containing all those keys. Using the index from the last get always resulted in the watch api being triggered on changes that were made in the past. There was an ugly work around that by writing a key that was outside that dir structure then reading it again, but that was a hack.
-
In the link you gave (etcd v2 api), there's a section down further titled "Watch From Cleared Event Index". It describes a case that could happen in my system - the modified index of the key being over 1000 revisions old. This would break my watch api calls.
It may be possible to have multiple X-Etcd-Index values among a cluster, but I'm assuming that they try to sycn them up asap. That issue doesn't bother me for my system.
If the code doesnt fit for your project, thats OK. Just thought I'd offer it up as its definitely useful for me.