github.com/m3db/m3@v1.5.0/src/cluster/placementhandler/replace.go (about)

     1  // Copyright (c) 2018 Uber Technologies, Inc.
     2  //
     3  // Permission is hereby granted, free of charge, to any person obtaining a copy
     4  // of this software and associated documentation files (the "Software"), to deal
     5  // in the Software without restriction, including without limitation the rights
     6  // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
     7  // copies of the Software, and to permit persons to whom the Software is
     8  // furnished to do so, subject to the following conditions:
     9  //
    10  // The above copyright notice and this permission notice shall be included in
    11  // all copies or substantial portions of the Software.
    12  //
    13  // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
    14  // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
    15  // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
    16  // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
    17  // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
    18  // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
    19  // THE SOFTWARE.
    20  
    21  package placementhandler
    22  
    23  import (
    24  	"net/http"
    25  	"path"
    26  	"time"
    27  
    28  	"github.com/gogo/protobuf/jsonpb"
    29  	"go.uber.org/zap"
    30  
    31  	"github.com/m3db/m3/src/cluster/placement"
    32  	"github.com/m3db/m3/src/cluster/placementhandler/handleroptions"
    33  	"github.com/m3db/m3/src/query/api/v1/route"
    34  	"github.com/m3db/m3/src/query/generated/proto/admin"
    35  	"github.com/m3db/m3/src/query/util/logging"
    36  	xerrors "github.com/m3db/m3/src/x/errors"
    37  	xhttp "github.com/m3db/m3/src/x/net/http"
    38  )
    39  
    40  const (
    41  	// ReplaceHTTPMethod is the HTTP method for the the replace endpoint.
    42  	ReplaceHTTPMethod = http.MethodPost
    43  
    44  	replacePathName = "replace"
    45  )
    46  
    47  var (
    48  	// M3DBReplaceURL is the url for the m3db replace handler (method POST).
    49  	M3DBReplaceURL = path.Join(route.Prefix,
    50  		M3DBServicePlacementPathName, replacePathName)
    51  
    52  	// M3AggReplaceURL is the url for the m3aggregator replace handler (method
    53  	// POST).
    54  	M3AggReplaceURL = path.Join(route.Prefix,
    55  		M3AggServicePlacementPathName, replacePathName)
    56  
    57  	// M3CoordinatorReplaceURL is the url for the m3coordinator replace handler
    58  	// (method POST).
    59  	M3CoordinatorReplaceURL = path.Join(route.Prefix,
    60  		M3CoordinatorServicePlacementPathName, replacePathName)
    61  )
    62  
    63  // ReplaceHandler is the type for placement replaces.
    64  type ReplaceHandler Handler
    65  
    66  // NewReplaceHandler returns a new ReplaceHandler.
    67  func NewReplaceHandler(opts HandlerOptions) *ReplaceHandler {
    68  	return &ReplaceHandler{HandlerOptions: opts, nowFn: time.Now}
    69  }
    70  
    71  func (h *ReplaceHandler) ServeHTTP(
    72  	svc handleroptions.ServiceNameAndDefaults,
    73  	w http.ResponseWriter,
    74  	r *http.Request,
    75  ) {
    76  	ctx := r.Context()
    77  	logger := logging.WithContext(ctx, h.instrumentOptions)
    78  
    79  	req, pErr := h.parseRequest(r)
    80  	if pErr != nil {
    81  		xhttp.WriteError(w, pErr)
    82  		return
    83  	}
    84  
    85  	placement, err := h.Replace(svc, r, req)
    86  	if err != nil {
    87  		logger.Error("unable to replace instance", zap.Error(err))
    88  		xhttp.WriteError(w, err)
    89  		return
    90  	}
    91  
    92  	placementProto, err := placement.Proto()
    93  	if err != nil {
    94  		logger.Error("unable to get placement protobuf", zap.Error(err))
    95  		xhttp.WriteError(w, err)
    96  		return
    97  	}
    98  
    99  	resp := &admin.PlacementGetResponse{
   100  		Placement: placementProto,
   101  		Version:   int32(placement.Version()),
   102  	}
   103  
   104  	xhttp.WriteProtoMsgJSONResponse(w, resp, logger)
   105  }
   106  
   107  func (h *ReplaceHandler) parseRequest(r *http.Request) (*admin.PlacementReplaceRequest, error) {
   108  	defer r.Body.Close()
   109  
   110  	req := &admin.PlacementReplaceRequest{}
   111  	if err := jsonpb.Unmarshal(r.Body, req); err != nil {
   112  		return nil, xerrors.NewInvalidParamsError(err)
   113  	}
   114  
   115  	return req, nil
   116  }
   117  
   118  // Replace replaces instances.
   119  func (h *ReplaceHandler) Replace(
   120  	svc handleroptions.ServiceNameAndDefaults,
   121  	httpReq *http.Request,
   122  	req *admin.PlacementReplaceRequest,
   123  ) (placement.Placement, error) {
   124  	candidates, err := ConvertInstancesProto(req.Candidates)
   125  	if err != nil {
   126  		return nil, err
   127  	}
   128  
   129  	serviceOpts := handleroptions.NewServiceOptions(svc,
   130  		httpReq.Header, h.m3AggServiceOptions)
   131  
   132  	pcfg, err := Handler(*h).PlacementConfigCopy()
   133  	if err != nil {
   134  		return nil, err
   135  	}
   136  	service, algo, err := ServiceWithAlgo(h.clusterClient,
   137  		serviceOpts, pcfg.ApplyOverride(req.OptionOverride), h.nowFn(), nil)
   138  	if err != nil {
   139  		return nil, err
   140  	}
   141  
   142  	if req.Force {
   143  		newPlacement, _, err := service.ReplaceInstances(req.LeavingInstanceIDs, candidates)
   144  		return newPlacement, err
   145  	}
   146  
   147  	curPlacement, err := service.Placement()
   148  	if err != nil {
   149  		return nil, err
   150  	}
   151  
   152  	// M3Coordinator isn't sharded, can't check if its shards are available.
   153  	if !isStateless(svc.ServiceName) {
   154  		if err := validateAllAvailable(curPlacement); err != nil {
   155  			return nil, err
   156  		}
   157  	}
   158  
   159  	// We use the algorithm directly so that we can CheckAndSet on the placement
   160  	// to make "atomic" forward progress.
   161  	newPlacement, err := algo.ReplaceInstances(curPlacement, req.LeavingInstanceIDs, candidates)
   162  	if err != nil {
   163  		return nil, err
   164  	}
   165  
   166  	// Ensure the placement we're updating is still the one on which we validated
   167  	// all shards are available.
   168  	return service.CheckAndSet(newPlacement, curPlacement.Version())
   169  }