github.com/m3db/m3@v1.5.0/src/query/api/v1/handler/topic/update.go (about)

     1  // Copyright (c) 2020 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 topic
    22  
    23  import (
    24  	"net/http"
    25  
    26  	clusterclient "github.com/m3db/m3/src/cluster/client"
    27  	"github.com/m3db/m3/src/cluster/placementhandler/handleroptions"
    28  	"github.com/m3db/m3/src/cmd/services/m3query/config"
    29  	"github.com/m3db/m3/src/msg/topic"
    30  	"github.com/m3db/m3/src/query/api/v1/route"
    31  	"github.com/m3db/m3/src/query/generated/proto/admin"
    32  	"github.com/m3db/m3/src/query/util/logging"
    33  	"github.com/m3db/m3/src/x/instrument"
    34  	xhttp "github.com/m3db/m3/src/x/net/http"
    35  
    36  	pkgerrors "github.com/pkg/errors"
    37  	"go.uber.org/zap"
    38  )
    39  
    40  const (
    41  	// UpdateURL is the url for the topic update handler (with the PUT method).
    42  	UpdateURL = route.Prefix + "/topic"
    43  
    44  	// UpdateHTTPMethod is the HTTP method used with this resource.
    45  	UpdateHTTPMethod = http.MethodPut
    46  )
    47  
    48  // UpdateHandler is the handler for topic updates.
    49  type UpdateHandler Handler
    50  
    51  // newUpdateHandler returns a new instance of UpdateHandler. This is used for
    52  // updating a topic in-place, for example to add or remove consumers.
    53  func newUpdateHandler(
    54  	client clusterclient.Client,
    55  	cfg config.Configuration,
    56  	instrumentOpts instrument.Options,
    57  ) http.Handler {
    58  	return &UpdateHandler{
    59  		client:         client,
    60  		cfg:            cfg,
    61  		serviceFn:      Service,
    62  		instrumentOpts: instrumentOpts,
    63  	}
    64  }
    65  
    66  func (h *UpdateHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
    67  	var (
    68  		ctx    = r.Context()
    69  		logger = logging.WithContext(ctx, h.instrumentOpts)
    70  		req    admin.TopicUpdateRequest
    71  	)
    72  
    73  	if rErr := parseRequest(r, &req); rErr != nil {
    74  		logger.Error("unable to parse request", zap.Error(rErr))
    75  		xhttp.WriteError(w, rErr)
    76  		return
    77  	}
    78  
    79  	serviceCfg := handleroptions.ServiceNameAndDefaults{}
    80  	svcOpts := handleroptions.NewServiceOptions(serviceCfg, r.Header, nil)
    81  	service, err := h.serviceFn(h.client, svcOpts)
    82  	if err != nil {
    83  		logger.Error("unable to get service", zap.Error(err))
    84  		xhttp.WriteError(w, err)
    85  		return
    86  	}
    87  
    88  	name := topicName(r.Header)
    89  	svcLogger := logger.With(zap.String("service", name))
    90  	m3Topic, err := service.Get(name)
    91  	if err != nil {
    92  		logger.Error("unable to get topic", zap.Error(err))
    93  		xhttp.WriteError(w, xhttp.NewError(err, http.StatusNotFound))
    94  		return
    95  	}
    96  
    97  	oldConsumers := len(m3Topic.ConsumerServices())
    98  	newConsumers := len(req.ConsumerServices)
    99  
   100  	csvcs := make([]topic.ConsumerService, 0, newConsumers)
   101  	for _, svc := range req.ConsumerServices {
   102  		csvc, err := topic.NewConsumerServiceFromProto(svc)
   103  		if err != nil {
   104  			err := pkgerrors.WithMessagef(err, "error converting consumer service '%s'", svc.String())
   105  			svcLogger.Error("convert consumer service error", zap.Error(err))
   106  			xhttp.WriteError(w, xhttp.NewError(err, http.StatusBadRequest))
   107  			return
   108  		}
   109  
   110  		csvcs = append(csvcs, csvc)
   111  	}
   112  
   113  	m3Topic = m3Topic.SetConsumerServices(csvcs)
   114  	newTopic, err := service.CheckAndSet(m3Topic, int(req.Version))
   115  	if err != nil {
   116  		svcLogger.Error("unable to delete service", zap.Error(err))
   117  		err := pkgerrors.WithMessagef(err, "error deleting service '%s'", name)
   118  		xhttp.WriteError(w, err)
   119  		return
   120  	}
   121  
   122  	svcLogger.Info("updated service in-place", zap.Int("oldConsumers", oldConsumers), zap.Int("newConsumers", newConsumers))
   123  
   124  	pb, err := topic.ToProto(m3Topic)
   125  	if err != nil {
   126  		logger.Error("unable to convert topic to protobuf", zap.Error(err))
   127  		xhttp.WriteError(w, err)
   128  		return
   129  	}
   130  
   131  	resp := &admin.TopicGetResponse{
   132  		Topic:   pb,
   133  		Version: uint32(newTopic.Version()),
   134  	}
   135  	xhttp.WriteProtoMsgJSONResponse(w, resp, logger)
   136  }