compare_and_swap_command.go 1.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. package v2
  2. import (
  3. "time"
  4. "github.com/coreos/etcd/log"
  5. "github.com/coreos/etcd/store"
  6. "github.com/coreos/go-raft"
  7. )
  8. func init() {
  9. raft.RegisterCommand(&CompareAndSwapCommand{})
  10. }
  11. // The CompareAndSwap performs a conditional update on a key in the store.
  12. type CompareAndSwapCommand struct {
  13. Key string `json:"key"`
  14. Value string `json:"value"`
  15. ExpireTime time.Time `json:"expireTime"`
  16. PrevValue string `json:"prevValue"`
  17. PrevIndex uint64 `json:"prevIndex"`
  18. }
  19. // The name of the testAndSet command in the log
  20. func (c *CompareAndSwapCommand) CommandName() string {
  21. return "etcd:v2:compareAndSwap"
  22. }
  23. // Set the key-value pair if the current value of the key equals to the given prevValue
  24. func (c *CompareAndSwapCommand) Apply(server raft.Server) (interface{}, error) {
  25. s, _ := server.StateMachine().(store.Store)
  26. e, err := s.CompareAndSwap(c.Key, c.PrevValue, c.PrevIndex,
  27. c.Value, c.ExpireTime, server.CommitIndex(), server.Term())
  28. if err != nil {
  29. log.Debug(err)
  30. return nil, err
  31. }
  32. return e, nil
  33. }