You are viewing a plain text version of this content. The canonical link for it is here.
Posted to dev@servicecomb.apache.org by GitBox <gi...@apache.org> on 2017/12/29 03:09:07 UTC

[GitHub] little-cui commented on a change in pull request #235: SCB-143 Add new rate limiter

little-cui commented on a change in pull request #235: SCB-143 Add new rate limiter
URL: https://github.com/apache/incubator-servicecomb-service-center/pull/235#discussion_r159018119
 
 

 ##########
 File path: pkg/httplimiter/httpratelimiter.go
 ##########
 @@ -0,0 +1,228 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package httplimiter
+
+import (
+	"net/http"
+	"strconv"
+	"strings"
+	"time"
+	"github.com/apache/incubator-servicecomb-service-center/pkg/ratelimiter"
+	"fmt"
+	"sync"
+)
+
+type HTTPErrorMessage struct {
+	Message    string
+	StatusCode int
+}
+
+func (httpErrorMessage *HTTPErrorMessage) Error() string {
+	return fmt.Sprintf("%v: %v", httpErrorMessage.StatusCode, httpErrorMessage.Message)
+}
+
+
+type HttpLimiter struct {
+	HttpMessage    string
+	ContentType    string
+	StatusCode     int
+	RequestLimit   int64
+	TTL            time.Duration
+	IPLookups      []string
+	Methods        []string
+	Headers        map[string][]string
+	BasicAuthUsers []string
+	leakyBuckets   map[string]*ratelimiter.LeakyBucket
+	sync.RWMutex
+}
+
+
+
+func LimitBySegments(limiter *HttpLimiter, keys []string) *HTTPErrorMessage {
+	if limiter.LimitExceeded(strings.Join(keys, "|")) {
+		return &HTTPErrorMessage{Message: limiter.HttpMessage, StatusCode: limiter.StatusCode}
+	}
+
+	return nil
+}
+
+func LimitByRequest(httpLimiter *HttpLimiter, r *http.Request) *HTTPErrorMessage {
+	sliceKeys := BuildSegments(httpLimiter, r)
+
+	for _, keys := range sliceKeys {
+		httpError := LimitBySegments(httpLimiter, keys)
+		if httpError != nil {
+			return httpError
+		}
+	}
+
+	return nil
+}
+
+func BuildSegments(httpLimiter *HttpLimiter, r *http.Request) [][]string {
+	remoteIP := getRemoteIP(httpLimiter.IPLookups, r)
+	urlPath := r.URL.Path
+	sliceKeys := make([][]string, 0)
+
+	if remoteIP == "" {
+		return sliceKeys
+	}
+
+	if httpLimiter.Methods != nil && httpLimiter.Headers != nil && httpLimiter.BasicAuthUsers != nil {
+		if checkExsistence(httpLimiter.Methods, r.Method) {
+			for headerKey, headerValues := range httpLimiter.Headers {
+				if (headerValues == nil || len(headerValues) <= 0) && r.Header.Get(headerKey) != "" {
+					username, _, ok := r.BasicAuth()
+					if ok && checkExsistence(httpLimiter.BasicAuthUsers, username) {
+						sliceKeys = append(sliceKeys, []string{remoteIP, urlPath, r.Method, headerKey, username})
+					}
+
+				} else if len(headerValues) > 0 && r.Header.Get(headerKey) != "" {
+					for _, headerValue := range headerValues {
+						username, _, ok := r.BasicAuth()
+						if ok && checkExsistence(httpLimiter.BasicAuthUsers, username) {
+							sliceKeys = append(sliceKeys, []string{remoteIP, urlPath, r.Method, headerKey, headerValue, username})
+						}
+					}
+				}
+			}
+		}
+
+	} else if httpLimiter.Methods != nil && httpLimiter.Headers != nil {
+		if checkExsistence(httpLimiter.Methods, r.Method) {
+			for headerKey, headerValues := range httpLimiter.Headers {
+				if (headerValues == nil || len(headerValues) <= 0) && r.Header.Get(headerKey) != "" {
+					sliceKeys = append(sliceKeys, []string{remoteIP, urlPath, r.Method, headerKey})
+
+				} else if len(headerValues) > 0 && r.Header.Get(headerKey) != "" {
+					for _, headerValue := range headerValues {
+						sliceKeys = append(sliceKeys, []string{remoteIP, urlPath, r.Method, headerKey, headerValue})
+					}
+				}
+			}
+		}
+
+	} else if httpLimiter.Methods != nil && httpLimiter.BasicAuthUsers != nil {
+		if checkExsistence(httpLimiter.Methods, r.Method) {
+			username, _, ok := r.BasicAuth()
+			if ok && checkExsistence(httpLimiter.BasicAuthUsers, username) {
+				sliceKeys = append(sliceKeys, []string{remoteIP, urlPath, r.Method, username})
+			}
+		}
+
+	} else if httpLimiter.Methods != nil {
+		if checkExsistence(httpLimiter.Methods, r.Method) {
+			sliceKeys = append(sliceKeys, []string{remoteIP, urlPath, r.Method})
+		}
+
+	} else if httpLimiter.Headers != nil {
+		for headerKey, headerValues := range httpLimiter.Headers {
+			if (headerValues == nil || len(headerValues) <= 0) && r.Header.Get(headerKey) != "" {
+				sliceKeys = append(sliceKeys, []string{remoteIP, urlPath, headerKey})
+
+			} else if len(headerValues) > 0 && r.Header.Get(headerKey) != "" {
+				for _, headerValue := range headerValues {
+					sliceKeys = append(sliceKeys, []string{remoteIP, urlPath, headerKey, headerValue})
+				}
+			}
+		}
+
+	} else if httpLimiter.BasicAuthUsers != nil {
+		username, _, ok := r.BasicAuth()
+		if ok && checkExsistence(httpLimiter.BasicAuthUsers, username) {
+			sliceKeys = append(sliceKeys, []string{remoteIP, urlPath, username})
+		}
+	} else {
+		sliceKeys = append(sliceKeys, []string{remoteIP, urlPath})
+	}
+
+	return sliceKeys
+}
+
+func SetResponseHeaders(limiter *HttpLimiter, w http.ResponseWriter) {
+	w.Header().Add("X-Rate-Limit-Limit", strconv.FormatInt(limiter.RequestLimit, 10))
+	w.Header().Add("X-Rate-Limit-Duration", limiter.TTL.String())
+}
+
+func checkExsistence(sliceString []string, needle string) bool {
 
 Review comment:
   checkExsistence -> checkExistence

----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on GitHub and use the
URL above to go to the specific comment.
 
For queries about this service, please contact Infrastructure at:
users@infra.apache.org


With regards,
Apache Git Services