compare_and_swap_command.go 1011 B

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