github.com/polarismesh/polaris@v1.17.8/service/utils.go (about)

     1  /**
     2   * Tencent is pleased to support the open source community by making Polaris available.
     3   *
     4   * Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved.
     5   *
     6   * Licensed under the BSD 3-Clause License (the "License");
     7   * you may not use this file except in compliance with the License.
     8   * You may obtain a copy of the License at
     9   *
    10   * https://opensource.org/licenses/BSD-3-Clause
    11   *
    12   * Unless required by applicable law or agreed to in writing, software distributed
    13   * under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
    14   * CONDITIONS OF ANY KIND, either express or implied. See the License for the
    15   * specific language governing permissions and limitations under the License.
    16   */
    17  
    18  package service
    19  
    20  import (
    21  	"errors"
    22  	"fmt"
    23  	"regexp"
    24  	"strconv"
    25  	"strings"
    26  
    27  	"github.com/golang/protobuf/proto"
    28  	"github.com/golang/protobuf/ptypes/wrappers"
    29  	apiservice "github.com/polarismesh/specification/source/go/api/v1/service_manage"
    30  
    31  	api "github.com/polarismesh/polaris/common/api/v1"
    32  	commonstore "github.com/polarismesh/polaris/common/store"
    33  	"github.com/polarismesh/polaris/common/utils"
    34  	"github.com/polarismesh/polaris/store"
    35  )
    36  
    37  // some options config
    38  const (
    39  	// QueryDefaultOffset default query offset
    40  	QueryDefaultOffset = 0
    41  	// QueryDefaultLimit default query limit
    42  	QueryDefaultLimit = 100
    43  	// QueryMaxLimit default query max
    44  	QueryMaxLimit = 100
    45  
    46  	// MaxMetadataLength metadata max length
    47  	MaxMetadataLength = 64
    48  
    49  	MaxBusinessLength   = 64
    50  	MaxOwnersLength     = 1024
    51  	MaxDepartmentLength = 1024
    52  	MaxCommentLength    = 1024
    53  
    54  	// service表
    55  	MaxDbServiceNameLength      = 128
    56  	MaxDbServiceNamespaceLength = 64
    57  	MaxDbServicePortsLength     = 8192
    58  	MaxDbServiceBusinessLength  = 128
    59  	MaxDbServiceDeptLength      = 1024
    60  	MaxDbServiceCMDBLength      = 1024
    61  	MaxDbServiceCommentLength   = 1024
    62  	MaxDbServiceOwnerLength     = 1024
    63  	MaxDbServiceToken           = 2048
    64  
    65  	// instance表
    66  	MaxDbInsHostLength     = 128
    67  	MaxDbInsProtocolLength = 32
    68  	MaxDbInsVersionLength  = 32
    69  	MaxDbInsLogicSetLength = 128
    70  
    71  	// circuitbreaker表
    72  	MaxDbCircuitbreakerName       = 128
    73  	MaxDbCircuitbreakerNamespace  = 64
    74  	MaxDbCircuitbreakerBusiness   = 64
    75  	MaxDbCircuitbreakerDepartment = 1024
    76  	MaxDbCircuitbreakerComment    = 1024
    77  	MaxDbCircuitbreakerOwner      = 1024
    78  	MaxDbCircuitbreakerVersion    = 32
    79  
    80  	// platform表
    81  	MaxPlatformIDLength     = 32
    82  	MaxPlatformNameLength   = 128
    83  	MaxPlatformDomainLength = 1024
    84  	MaxPlatformQPS          = 65535
    85  
    86  	MaxRuleName = 64
    87  
    88  	// ratelimit表
    89  	MaxDbRateLimitName = MaxRuleName
    90  
    91  	// MaxDbRoutingName routing_config_v2 表
    92  	MaxDbRoutingName = MaxRuleName
    93  
    94  	// ContextDiscoverParam key for discover parameters in context
    95  	ContextDiscoverParam = utils.StringContext("discover-param")
    96  
    97  	// ParamKeyInstanceId key for parameter key instanceId
    98  	ParamKeyInstanceId = "instanceId"
    99  )
   100  
   101  // checkResourceName 检查资源Name
   102  var resourceNameRE = regexp.MustCompile("^[0-9A-Za-z-./:_]+$")
   103  
   104  func checkResourceName(name *wrappers.StringValue) error {
   105  	if name == nil {
   106  		return errors.New(utils.NilErrString)
   107  	}
   108  
   109  	if len(name.GetValue()) == 0 {
   110  		return errors.New(utils.EmptyErrString)
   111  	}
   112  
   113  	ok := resourceNameRE.MatchString(name.GetValue())
   114  	if !ok {
   115  		return errors.New("name contains invalid character")
   116  	}
   117  
   118  	return nil
   119  }
   120  
   121  // checkInstanceHost 检查服务实例Host
   122  func checkInstanceHost(host *wrappers.StringValue) error {
   123  	if host == nil {
   124  		return errors.New(utils.NilErrString)
   125  	}
   126  
   127  	if host.GetValue() == "" {
   128  		return errors.New(utils.EmptyErrString)
   129  	}
   130  
   131  	return nil
   132  }
   133  
   134  // checkMetadata 检查metadata的个数; 最大是64个
   135  // key/value是否符合要求
   136  func checkMetadata(meta map[string]string) error {
   137  	if meta == nil {
   138  		return nil
   139  	}
   140  
   141  	if len(meta) > MaxMetadataLength {
   142  		return errors.New("metadata is too long")
   143  	}
   144  
   145  	/*regStr := "^[0-9A-Za-z-._*]+$"
   146  	  matchFunc := func(str string) error {
   147  	  	if str == "" {
   148  	  		return nil
   149  	  	}
   150  	  	ok, err := regexp.MatchString(regStr, str)
   151  	  	if err != nil {
   152  	  		log.Errorf("regexp match string(%s) err: %s", str, err.Error())
   153  	  		return err
   154  	  	}
   155  	  	if !ok {
   156  	  		log.Errorf("metadata string(%s) contains invalid character", str)
   157  	  		return errors.New("contain invalid character")
   158  	  	}
   159  	  	return nil
   160  	  }
   161  	  for key, value := range meta {
   162  	  	if err := matchFunc(key); err != nil {
   163  	  		return err
   164  	  	}
   165  	  	if err := matchFunc(value); err != nil {
   166  	  		return err
   167  	  	}
   168  	  }*/
   169  
   170  	return nil
   171  }
   172  
   173  // storeError2Response store code
   174  func storeError2Response(err error) *apiservice.Response {
   175  	if err == nil {
   176  		return nil
   177  	}
   178  	return api.NewResponseWithMsg(commonstore.StoreCode2APICode(err), err.Error())
   179  }
   180  
   181  // storeError2AnyResponse store code
   182  func storeError2AnyResponse(err error, msg proto.Message) *apiservice.Response {
   183  	if err == nil {
   184  		return nil
   185  	}
   186  	if nil == msg {
   187  		return api.NewResponseWithMsg(commonstore.StoreCode2APICode(err), err.Error())
   188  	}
   189  	resp := api.NewAnyDataResponse(commonstore.StoreCode2APICode(err), msg)
   190  	resp.Info = &wrappers.StringValue{Value: err.Error()}
   191  	return resp
   192  }
   193  
   194  // ParseInstanceArgs 解析服务实例的 ip 和 port 查询参数
   195  func ParseInstanceArgs(query map[string]string, meta map[string]string) (*store.InstanceArgs, error) {
   196  	if len(query) == 0 && meta == nil {
   197  		return nil, nil
   198  	}
   199  	res := &store.InstanceArgs{}
   200  	res.Meta = meta
   201  	if len(query) == 0 {
   202  		return res, nil
   203  	}
   204  	hosts, ok := query["host"]
   205  	if !ok {
   206  		return nil, fmt.Errorf("port parameter can not be used alone without host")
   207  	}
   208  	res.Hosts = strings.Split(hosts, ",")
   209  	ports, ok := query["port"]
   210  	if !ok {
   211  		return res, nil
   212  	}
   213  
   214  	portSlices := strings.Split(ports, ",")
   215  	for _, portStr := range portSlices {
   216  		port, err := strconv.ParseUint(portStr, 10, 32)
   217  		if err != nil {
   218  			return nil, fmt.Errorf("%s can not parse as uint, err is %s", portStr, err.Error())
   219  		}
   220  		res.Ports = append(res.Ports, uint32(port))
   221  	}
   222  	return res, nil
   223  }