compare_and_swap_command.go 1018 B

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. package v2
  2. import (
  3. "time"
  4. "github.com/coreos/etcd/log"
  5. "github.com/coreos/etcd/store"
  6. "github.com/coreos/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: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(context raft.Context) (interface{}, error) {
  25. s, _ := context.Server().StateMachine().(store.Store)
  26. e, err := s.CompareAndSwap(c.Key, c.PrevValue, c.PrevIndex, c.Value, c.ExpireTime)
  27. if err != nil {
  28. log.Debug(err)
  29. return nil, err
  30. }
  31. return e, nil
  32. }