github.com/ghodss/etcd@v0.3.1-0.20140417172404-cc329bfa55cb/mod/lock/v2/renew_handler.go (about)

     1  package v2
     2  
     3  import (
     4  	"net/http"
     5  	"path"
     6  	"strconv"
     7  
     8  	etcdErr "github.com/coreos/etcd/error"
     9  	"github.com/coreos/etcd/third_party/github.com/gorilla/mux"
    10  )
    11  
    12  // renewLockHandler attempts to update the TTL on an existing lock.
    13  // Returns a 200 OK if successful. Returns non-200 on error.
    14  func (h *handler) renewLockHandler(w http.ResponseWriter, req *http.Request) error {
    15  	h.client.SyncCluster()
    16  
    17  	// Read the lock path.
    18  	vars := mux.Vars(req)
    19  	keypath := path.Join(prefix, vars["key"])
    20  
    21  	// Parse new TTL parameter.
    22  	ttl, err := strconv.Atoi(req.FormValue("ttl"))
    23  	if err != nil {
    24  		return etcdErr.NewError(etcdErr.EcodeTTLNaN, "Renew", 0)
    25  	}
    26  
    27  	// Read and set defaults for index and value.
    28  	index := req.FormValue("index")
    29  	value := req.FormValue("value")
    30  	if len(index) == 0 && len(value) == 0 {
    31  		return etcdErr.NewError(etcdErr.EcodeIndexOrValueRequired, "Renew", 0)
    32  	}
    33  
    34  	if len(index) == 0 {
    35  		// If index is not specified then look it up by value.
    36  		resp, err := h.client.Get(keypath, true, true)
    37  		if err != nil {
    38  			return err
    39  		}
    40  		nodes := lockNodes{resp.Node.Nodes}
    41  		node, _ := nodes.FindByValue(value)
    42  		if node == nil {
    43  			return etcdErr.NewError(etcdErr.EcodeKeyNotFound, "Renew", 0)
    44  		}
    45  		index = path.Base(node.Key)
    46  
    47  	} else if len(value) == 0 {
    48  		// If value is not specified then default it to the previous value.
    49  		resp, err := h.client.Get(path.Join(keypath, index), true, false)
    50  		if err != nil {
    51  			return err
    52  		}
    53  		value = resp.Node.Value
    54  	}
    55  
    56  	// Renew the lock, if it exists.
    57  	if _, err = h.client.Update(path.Join(keypath, index), value, uint64(ttl)); err != nil {
    58  		return err
    59  	}
    60  
    61  	return nil
    62  }