diff --git a/.github/workflows/codecov.yaml b/.github/workflows/codecov.yaml index faa5238ae..33cc822de 100644 --- a/.github/workflows/codecov.yaml +++ b/.github/workflows/codecov.yaml @@ -75,6 +75,8 @@ jobs: export STORE_MODE=sqldb echo "cur STORE MODE=${STORE_MODE}" + # 设置严格模式 + mysql -h127.0.0.1 -P3306 -uroot -p"polaris" -e "set sql_mode='STRICT_TRANS_TABLES,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION'"; # 清空数据 mysql -h127.0.0.1 -P3306 -uroot -p"polaris" -e "DROP DATABASE IF EXISTS polaris_server"; # 初始化 polaris 数据库 @@ -89,6 +91,8 @@ jobs: sleep 10s + # 设置严格模式 + mysql -h127.0.0.1 -P3306 -uroot -p"polaris" -e "set sql_mode='STRICT_TRANS_TABLES,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION'"; # 清空数据 mysql -h127.0.0.1 -P3306 -uroot -p"polaris" -e "DROP DATABASE IF EXISTS polaris_server"; # 初始化 polaris 数据库 @@ -136,5 +140,5 @@ jobs: rm -rf *.cover - - name: Coverage - run: bash <(curl -s https://codecov.io/bash) + - name: Upload coverage reports to Codecov with GitHub Action + uses: codecov/codecov-action@v3 diff --git a/.github/workflows/integration-testing-mysql.yml b/.github/workflows/integration-testing-mysql.yml index 7dec2fbba..70d53073e 100644 --- a/.github/workflows/integration-testing-mysql.yml +++ b/.github/workflows/integration-testing-mysql.yml @@ -89,42 +89,14 @@ jobs: GOARCH: ${{ matrix.goarch }} run: make build - # Run unit tests - - name: run tests - run: | - export STORE_MODE=sqldb - echo "cur STORE MODE=${STORE_MODE}" - - # 清空数据 - mysql -h127.0.0.1 -P3306 -uroot -p"polaris" -e "DROP DATABASE IF EXISTS polaris_server"; - # 初始化 polaris 数据库 - mysql -h127.0.0.1 -P3306 -uroot -p"polaris" < store/sqldb/scripts/polaris_server.sql - # 临时放开 DB 的最大连接数 - mysql -h127.0.0.1 -P3306 -uroot -p"polaris" -e "set GLOBAL max_connections = 3000;" - - pushd ./config - go test -v -timeout 40m - popd - - sleep 10s - - # 清空数据 - mysql -h127.0.0.1 -P3306 -uroot -p"polaris" -e "DROP DATABASE IF EXISTS polaris_server"; - # 初始化 polaris 数据库 - mysql -h127.0.0.1 -P3306 -uroot -p"polaris" < store/sqldb/scripts/polaris_server.sql - # 临时放开 DB 的最大连接数 - mysql -h127.0.0.1 -P3306 -uroot -p"polaris" -e "set GLOBAL max_connections = 3000;" - - pushd ./service - go test -v -timeout 40m - popd - # Run interface tests - name: run discover interface tests run: | export STORE_MODE=sqldb echo "cur STORE MODE=${STORE_MODE}" + # 设置严格模式 + mysql -h127.0.0.1 -P3306 -uroot -p"polaris" -e "set sql_mode='STRICT_TRANS_TABLES,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION'"; # 清空数据 mysql -h127.0.0.1 -P3306 -uroot -p"polaris" -e "DROP DATABASE IF EXISTS polaris_server"; # 初始化 polaris 数据库 @@ -134,6 +106,9 @@ jobs: work_dir=$(ls | grep polaris-server-release | sed -n '1p') echo "work_dir is $work_dir" + + cp -rf ./testdata/polaris-server.yaml $work_dir/ + cd $work_dir ls -alR diff --git a/.github/workflows/standalone.yml b/.github/workflows/standalone.yml index 5e43aad9a..b02b49b9b 100644 --- a/.github/workflows/standalone.yml +++ b/.github/workflows/standalone.yml @@ -4,10 +4,13 @@ on: workflow_dispatch: inputs: server_version: - description: 'tag version for polaris' + description: "tag version for polaris" required: true console_version: - description: 'tag version for polaris-console' + description: "tag version for polaris-console" + required: true + limiter_version: + description: "tag version for polaris-limiter" required: true jobs: @@ -37,15 +40,70 @@ jobs: GOARCH: ${{ matrix.goarch }} SERVER_VERSION: ${{ github.event.inputs.server_version }} CONSOLE_VERSION: ${{ github.event.inputs.console_version }} + LIMITER_VERSION: ${{ github.event.inputs.limiter_version }} run: | if [ ${GOOS} == "kubernetes" ];then set -e + workdir=$(pwd) + + # ---------------------- 出简单 kubernetes 安装包 ---------------------- + cd ${workdir} cd deploy/standalone + + sed -i "s/##POLARIS_SERVER_VERSION##/${SERVER_VERSION}/g" k8s/03-polaris-server.yaml + sed -i "s/##POLARIS_CONSOLE_VERSION##/${CONSOLE_VERSION}/g" k8s/03-polaris-server.yaml + sed -i "s/##POLARIS_PROMETHEUS_VERSION##/${SERVER_VERSION}/g" k8s/04-prometheus.yaml + sed -i "s/##POLARIS_LIMITER_VERSION##/${LIMITER_VERSION}/g" k8s/05-polaris-limiter.yaml + DIR_NAME=polaris-standalone-release_${SERVER_VERSION}.${GOOS} mkdir ${DIR_NAME} pushd ${DIR_NAME} - cp ../k8s/* ./ + cp -rf ../k8s/* ./ + popd + + PACKAGE_NAME=${DIR_NAME}.zip + zip -r ${PACKAGE_NAME} ${DIR_NAME} + rm -rf ${DIR_NAME} + mv ${PACKAGE_NAME} ../../ + + # ---------------------- 出 docker-compose 安装包 ---------------------- + cd ${workdir} + cd deploy/standalone + + sed -i "s/##POLARIS_SERVER_VERSION##/${SERVER_VERSION}/g" docker-compose/docker-compose.yaml + sed -i "s/##POLARIS_CONSOLE_VERSION##/${CONSOLE_VERSION}/g" docker-compose/docker-compose.yaml + sed -i "s/##POLARIS_PROMETHEUS_VERSION##/${SERVER_VERSION}/g" docker-compose/docker-compose.yaml + + DOCKER_COMPOSE_DIR_NAME=polaris-standalone-release_${SERVER_VERSION}.docker-compose + mkdir ${DOCKER_COMPOSE_DIR_NAME} + pushd ${DOCKER_COMPOSE_DIR_NAME} + cp -rf ../docker-compose/* ./ popd + + DOCKER_COMPOSE_PACKAGE_NAME=${DOCKER_COMPOSE_DIR_NAME}.zip + zip -r ${DOCKER_COMPOSE_PACKAGE_NAME} ${DOCKER_COMPOSE_DIR_NAME} + rm -rf ${DOCKER_COMPOSE_DIR_NAME} + mv ${DOCKER_COMPOSE_PACKAGE_NAME} ../../ + + # ---------------------- 出 helm 安装包 ---------------------- + cd ${workdir} + cd deploy + + sed -i "s/##POLARIS_SERVER_VERSION##/${SERVER_VERSION}/g" helm/values.yaml + sed -i "s/##POLARIS_CONSOLE_VERSION##/${CONSOLE_VERSION}/g" helm/values.yaml + sed -i "s/##POLARIS_PROMETHEUS_VERSION##/${SERVER_VERSION}/g" helm/values.yaml + sed -i "s/##POLARIS_LIMITER_VERSION##/${LIMITER_VERSION}/g" helm/values.yaml + + HELM_DIR_NAME=polaris-helm-release_${SERVER_VERSION}.${GOOS} + mkdir ${HELM_DIR_NAME} + pushd ${HELM_DIR_NAME} + cp -rf ../helm/* ./ + popd + + HELM_PACKAGE_NAME=${HELM_DIR_NAME}.zip + zip -r ${HELM_PACKAGE_NAME} ${HELM_DIR_NAME} + rm -rf ${HELM_DIR_NAME} + mv ${HELM_PACKAGE_NAME} ../ else set -e cd deploy/standalone @@ -57,26 +115,29 @@ jobs: wget -T10 -t3 ${POLARIS_GIT_PATH}/polaris/releases/download/${SERVER_VERSION}/${SERVER_PKG_NAME} --no-check-certificate CONSOLE_PKG_NAME=polaris-console-release_${CONSOLE_VERSION}.${GOOS}.${GOARCH}.zip wget -T10 -t3 ${POLARIS_GIT_PATH}/polaris-console/releases/download/${CONSOLE_VERSION}/${CONSOLE_PKG_NAME} --no-check-certificate + LIMITER_PKG_NAME=polaris-limiter-release_${LIMITER_VERSION}.${GOOS}.${GOARCH}.zip + wget -T10 -t3 ${POLARIS_GIT_PATH}/polaris-limiter/releases/download/${LIMITER_VERSION}/${LIMITER_PKG_NAME} --no-check-certificate if [ ${GOOS} == "windows" ];then - wget -T10 -t3 https://github.com/prometheus/prometheus/releases/download/v2.28.0/prometheus-2.28.0.${GOOS}-${GOARCH}.zip - mv ../vm/install-windows.bat ./install.bat - mv ../vm/install-windows.ps1 ./install-windows.ps1 - mv ../vm/uninstall-windows.bat ./uninstall.bat - mv ../vm/uninstall-windows.ps1 ./uninstall-windows.ps1 - mv ../vm/port.properties ./port.properties + wget -T10 -t3 https://github.com/prometheus/prometheus/releases/download/v2.28.0/prometheus-2.28.0.${GOOS}-${GOARCH}.zip + mv ../vm/install-windows.bat ./install.bat + mv ../vm/install-windows.ps1 ./install-windows.ps1 + mv ../vm/uninstall-windows.bat ./uninstall.bat + mv ../vm/uninstall-windows.ps1 ./uninstall-windows.ps1 + mv ../vm/port.properties ./port.properties else - wget -T10 -t3 https://github.com/prometheus/prometheus/releases/download/v2.28.0/prometheus-2.28.0.${GOOS}-${GOARCH}.tar.gz - mv ../vm/install-${GOOS}.sh ./install.sh - mv ../vm/uninstall-${GOOS}.sh ./uninstall.sh - mv ../vm/port.properties ./port.properties + wget -T10 -t3 https://github.com/prometheus/prometheus/releases/download/v2.28.0/prometheus-2.28.0.${GOOS}-${GOARCH}.tar.gz + mv ../vm/install-${GOOS}.sh ./install.sh + mv ../vm/uninstall-${GOOS}.sh ./uninstall.sh + mv ../vm/port.properties ./port.properties + mv ../vm/prometheus-help.sh ./prometheus-help.sh fi popd + PACKAGE_NAME=${DIR_NAME}.zip + zip -r ${PACKAGE_NAME} ${DIR_NAME} + rm -rf ${DIR_NAME} + mv ${PACKAGE_NAME} ../../ + echo ::set-output name=name::${PACKAGE_NAME} fi - PACKAGE_NAME=${DIR_NAME}.zip - zip -r ${PACKAGE_NAME} ${DIR_NAME} - mv ${PACKAGE_NAME} ../../ - echo ::set-output name=name::${PACKAGE_NAME} - - name: Get Release by Tag id: get_release_by_tag @@ -86,12 +147,18 @@ jobs: with: tag_name: ${{ github.event.inputs.server_version }} - - name: Upload asset - uses: actions/upload-release-asset@v1 + # - name: Upload asset + # uses: actions/upload-release-asset@v1 + # env: + # GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + # with: + # upload_url: ${{ steps.get_release_by_tag.outputs.upload_url }} + # asset_path: ./${{ steps.build.outputs.name }} + # asset_name: ${{ steps.build.outputs.name }} + # asset_content_type: application/gzip + - name: Upload env: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} - with: - upload_url: ${{ steps.get_release_by_tag.outputs.upload_url }} - asset_path: ./${{ steps.build.outputs.name }} - asset_name: ${{ steps.build.outputs.name }} - asset_content_type: application/gzip + SERVER_VERSION: ${{ github.event.inputs.server_version }} + run: | + hub release edit $(find . -type f -name "polaris-*.zip" -printf "-a %p ") -m "" "${SERVER_VERSION}" diff --git a/.gitignore b/.gitignore index 3bebf3503..18091ac61 100644 --- a/.gitignore +++ b/.gitignore @@ -10,11 +10,13 @@ log/ .idea .DS_Store -coverage.txt +coverage* *.swp *.code-workspace +__debug_bin + .vscode *.bolt *.bolt.lock diff --git a/README-zh.md b/README-zh.md index 3b6af2b2c..b5b297591 100644 --- a/README-zh.md +++ b/README-zh.md @@ -114,7 +114,8 @@ curl http://127.0.0.1:8090 (1) 基于主流框架开发的微服务接入可参考: -- [Spring Cloud/Spring Boot接入](https://github.com/Tencent/spring-cloud-tencent/tree/main/spring-cloud-tencent-examples/polaris-discovery-example) +- [Spring Cloud接入](https://polarismesh.cn/zh/doc/%E5%BF%AB%E9%80%9F%E5%85%A5%E9%97%A8/SpringCloud%E5%BA%94%E7%94%A8%E6%8E%A5%E5%85%A5.html#%E6%9C%8D%E5%8A%A1%E6%B3%A8%E5%86%8C) +- [Spring Boot接入](https://polarismesh.cn/zh/doc/%E5%BF%AB%E9%80%9F%E5%85%A5%E9%97%A8/SpringBoot%E5%BA%94%E7%94%A8%E6%8E%A5%E5%85%A5.html#%E6%9C%8D%E5%8A%A1%E6%B3%A8%E5%86%8C) - [gRPC-Go接入](https://github.com/polarismesh/grpc-go-polaris/tree/main/examples/quickstart) (2) 主流语言微服务接入可参考: @@ -125,14 +126,13 @@ curl http://127.0.0.1:8090 (3) proxy模式的微服务接入可参考: -- [Envoy接入](https://github.com/polarismesh/examples/tree/main/servicemesh/extended-bookinfo) -- DNS接入(样例开发中) +- [Envoy接入](https://polarismesh.cn/zh/doc/%E5%BF%AB%E9%80%9F%E5%85%A5%E9%97%A8/Envoy%E7%BD%91%E6%A0%BC%E6%8E%A5%E5%85%A5.html#%E5%BF%AB%E9%80%9F%E6%8E%A5%E5%85%A5) #### 服务限流 (1) 基于主流框架开发的微服务接入可参考: -- [Spring Cloud/Spring Boot接入](https://github.com/Tencent/spring-cloud-tencent/tree/main/spring-cloud-tencent-examples/polaris-ratelimit-example) +- [Spring Cloud接入](https://polarismesh.cn/zh/doc/%E5%BF%AB%E9%80%9F%E5%85%A5%E9%97%A8/SpringCloud%E5%BA%94%E7%94%A8%E6%8E%A5%E5%85%A5.html#%E6%9C%8D%E5%8A%A1%E9%99%90%E6%B5%81) - [gRPC-Go接入](https://github.com/polarismesh/grpc-go-polaris/tree/main/examples/ratelimit/local) (2) 主流语言微服务接入可参考: @@ -143,24 +143,23 @@ curl http://127.0.0.1:8090 (3) proxy模式的微服务接入可参考: -- Envoy接入(样例开发中) +- [Nginx接入](https://polarismesh.cn/zh/doc/%E5%BF%AB%E9%80%9F%E5%85%A5%E9%97%A8/Nginx%E7%BD%91%E5%85%B3%E6%8E%A5%E5%85%A5.html#%E8%AE%BF%E9%97%AE%E9%99%90%E6%B5%81) #### 流量调度 (1) 基于主流框架开发的微服务接入可参考: -- [Spring Cloud/Spring Boot接入](https://github.com/Tencent/spring-cloud-tencent/tree/main/spring-cloud-tencent-examples/polaris-router-featureenv-example) +- [Spring Cloud接入](https://polarismesh.cn/zh/doc/%E5%BF%AB%E9%80%9F%E5%85%A5%E9%97%A8/SpringCloud%E5%BA%94%E7%94%A8%E6%8E%A5%E5%85%A5.html#%E6%9C%8D%E5%8A%A1%E8%B7%AF%E7%94%B1) - [gRPC-Go接入](https://github.com/polarismesh/grpc-go-polaris/tree/main/examples/routing/version) (2) 主流语言微服务接入可参考: - [Java语言接入](https://github.com/polarismesh/polaris-java/tree/main/polaris-examples/router-example/router-multienv-example) - [Go语言接入](https://github.com/polarismesh/polaris-go/tree/main/examples/route/dynamic) -- C++语言接入(样例开发中) (3) proxy模式的微服务接入可参考: -- Envoy接入(样例开发中) +- [Envoy接入](https://polarismesh.cn/zh/doc/%E5%BF%AB%E9%80%9F%E5%85%A5%E9%97%A8/Envoy%E7%BD%91%E6%A0%BC%E6%8E%A5%E5%85%A5.html#%E6%B5%81%E9%87%8F%E8%B0%83%E5%BA%A6) #### 配置管理 diff --git a/README.md b/README.md index 3c729ec7a..b01fdbbac 100644 --- a/README.md +++ b/README.md @@ -114,7 +114,8 @@ Polaris supports microservices built with multi-language, multi-framework, multi (1) rpc framework examples: -- [Spring Cloud/Spring Boot Example](https://github.com/Tencent/spring-cloud-tencent/tree/main/spring-cloud-tencent-examples/polaris-discovery-example) +- [Spring Cloud Example](https://polarismesh.cn/zh/doc/%E5%BF%AB%E9%80%9F%E5%85%A5%E9%97%A8/SpringCloud%E5%BA%94%E7%94%A8%E6%8E%A5%E5%85%A5.html#%E6%9C%8D%E5%8A%A1%E6%B3%A8%E5%86%8C) +- [Spring Boot Example](https://polarismesh.cn/zh/doc/%E5%BF%AB%E9%80%9F%E5%85%A5%E9%97%A8/SpringBoot%E5%BA%94%E7%94%A8%E6%8E%A5%E5%85%A5.html#%E6%9C%8D%E5%8A%A1%E6%B3%A8%E5%86%8C) - [gRPC-Go Example](https://github.com/polarismesh/grpc-go-polaris/tree/main/examples/quickstart) (2) multi-language examples: @@ -125,15 +126,13 @@ Polaris supports microservices built with multi-language, multi-framework, multi (3) proxy mode examples: -- [Envoy Example](https://github.com/polarismesh/examples/tree/main/servicemesh/extended-bookinfo) - -- DNS Example (Developing) +- [Envoy Example](https://polarismesh.cn/zh/doc/%E5%BF%AB%E9%80%9F%E5%85%A5%E9%97%A8/Envoy%E7%BD%91%E6%A0%BC%E6%8E%A5%E5%85%A5.html#%E5%BF%AB%E9%80%9F%E6%8E%A5%E5%85%A5) #### RateLimit (1) rpc framework examples: -- [Spring Cloud/Spring Boot Example](https://github.com/Tencent/spring-cloud-tencent/tree/main/spring-cloud-tencent-examples/polaris-ratelimit-example) +- [Spring Cloud Example](https://polarismesh.cn/zh/doc/%E5%BF%AB%E9%80%9F%E5%85%A5%E9%97%A8/SpringCloud%E5%BA%94%E7%94%A8%E6%8E%A5%E5%85%A5.html#%E6%9C%8D%E5%8A%A1%E9%99%90%E6%B5%81) - [gRPC-Go Example](https://github.com/polarismesh/grpc-go-polaris/tree/main/examples/ratelimit/local) (2) multi-language examples: @@ -144,25 +143,23 @@ Polaris supports microservices built with multi-language, multi-framework, multi (3) proxy mode examples: -- Envoy Example (Developing) -- Nginx Example (Developing) +- [Nginx Example](https://polarismesh.cn/zh/doc/%E5%BF%AB%E9%80%9F%E5%85%A5%E9%97%A8/Nginx%E7%BD%91%E5%85%B3%E6%8E%A5%E5%85%A5.html#%E8%AE%BF%E9%97%AE%E9%99%90%E6%B5%81) #### Flow Control (1) rpc framework examples: -- [Spring Cloud/Spring Boot Example](https://github.com/Tencent/spring-cloud-tencent/tree/main/spring-cloud-tencent-examples/polaris-router-featureenv-example) +- [Spring Cloud Example](https://polarismesh.cn/zh/doc/%E5%BF%AB%E9%80%9F%E5%85%A5%E9%97%A8/SpringCloud%E5%BA%94%E7%94%A8%E6%8E%A5%E5%85%A5.html#%E6%9C%8D%E5%8A%A1%E8%B7%AF%E7%94%B1) - [gRPC-Go Example](https://github.com/polarismesh/grpc-go-polaris/tree/main/examples/routing/version) (2) multi-language examples: - [Java Example](https://github.com/polarismesh/polaris-java/tree/main/polaris-examples/router-example/router-multienv-example) - [Go Example](https://github.com/polarismesh/polaris-go/tree/main/examples/route/dynamic) -- C++ Example (Developing) (3) proxy mode examples: -- Envoy Example (Developing) +- [Envoy Example](https://polarismesh.cn/zh/doc/%E5%BF%AB%E9%80%9F%E5%85%A5%E9%97%A8/Envoy%E7%BD%91%E6%A0%BC%E6%8E%A5%E5%85%A5.html#%E6%B5%81%E9%87%8F%E8%B0%83%E5%BA%A6) #### Configuration management diff --git a/apiserver/apiserver.go b/apiserver/apiserver.go index d7bad6fce..b29555301 100644 --- a/apiserver/apiserver.go +++ b/apiserver/apiserver.go @@ -46,17 +46,17 @@ type APIConfig struct { // Apiserver API服务器接口 type Apiserver interface { - // API协议名 + // GetProtocol API协议名 GetProtocol() string - // API的监听端口 + // GetPort API的监听端口 GetPort() uint32 - // API初始化逻辑 + // Initialize API初始化逻辑 Initialize(ctx context.Context, option map[string]interface{}, api map[string]APIConfig) error - // API服务的主逻辑循环 + // Run API服务的主逻辑循环 Run(errCh chan error) - // 停止API端口监听 + // Stop 停止API端口监听 Stop() - // 重启API + // Restart 重启API Restart(option map[string]interface{}, api map[string]APIConfig, errCh chan error) error } diff --git a/apiserver/eurekaserver/eureka_suit_test.go b/apiserver/eurekaserver/eureka_suit_test.go new file mode 100644 index 000000000..8f76776eb --- /dev/null +++ b/apiserver/eurekaserver/eureka_suit_test.go @@ -0,0 +1,204 @@ +/** + * Tencent is pleased to support the open source community by making Polaris available. + * + * Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved. + * + * Licensed under the BSD 3-Clause License (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://opensource.org/licenses/BSD-3-Clause + * + * 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 eurekaserver + +import ( + "context" + "fmt" + "os" + "testing" + "time" + + "github.com/golang/mock/gomock" + "github.com/polarismesh/polaris-server/auth" + "github.com/polarismesh/polaris-server/cache" + commonlog "github.com/polarismesh/polaris-server/common/log" + "github.com/polarismesh/polaris-server/common/utils" + "github.com/polarismesh/polaris-server/namespace" + "github.com/polarismesh/polaris-server/plugin" + "github.com/polarismesh/polaris-server/service" + "github.com/polarismesh/polaris-server/service/batch" + "github.com/polarismesh/polaris-server/service/healthcheck" + "github.com/polarismesh/polaris-server/store" + storemock "github.com/polarismesh/polaris-server/store/mock" + "gopkg.in/yaml.v2" + + "github.com/polarismesh/polaris-server/testdata" + + // 注册相关默认插件 + _ "github.com/polarismesh/polaris-server/plugin/auth/defaultauth" + _ "github.com/polarismesh/polaris-server/plugin/auth/platform" + _ "github.com/polarismesh/polaris-server/plugin/cmdb/memory" + _ "github.com/polarismesh/polaris-server/plugin/discoverevent/local" + _ "github.com/polarismesh/polaris-server/plugin/discoverstat/discoverlocal" + _ "github.com/polarismesh/polaris-server/plugin/healthchecker/heartbeatmemory" + _ "github.com/polarismesh/polaris-server/plugin/healthchecker/heartbeatredis" + _ "github.com/polarismesh/polaris-server/plugin/history/logger" + _ "github.com/polarismesh/polaris-server/plugin/password" + _ "github.com/polarismesh/polaris-server/plugin/ratelimit/lrurate" + _ "github.com/polarismesh/polaris-server/plugin/ratelimit/token" + _ "github.com/polarismesh/polaris-server/plugin/statis/local" + _ "github.com/polarismesh/polaris-server/store/boltdb" + _ "github.com/polarismesh/polaris-server/store/sqldb" +) + +type Bootstrap struct { + Logger map[string]*commonlog.Options +} + +type TestConfig struct { + Bootstrap Bootstrap `yaml:"bootstrap"` + Cache cache.Config `yaml:"cache"` + Namespace namespace.Config `yaml:"namespace"` + Naming service.Config `yaml:"naming"` + HealthChecks healthcheck.Config `yaml:"healthcheck"` + Store store.Config `yaml:"store"` + Auth auth.Config `yaml:"auth"` + Plugin plugin.Config `yaml:"plugin"` +} + +type EurekaTestSuit struct { + cfg *TestConfig + server service.DiscoverServer + healthSvr *healthcheck.Server + namespaceSvr namespace.NamespaceOperateServer + cancelFlag bool + updateCacheInterval time.Duration + cancel context.CancelFunc + storage store.Store +} + +type options func(cfg *TestConfig) + +// 内部初始化函数 +func (d *EurekaTestSuit) initialize(t *testing.T, callback func(t *testing.T, s *storemock.MockStore) error, opts ...options) error { + if err := d.loadConfig(); err != nil { + return err + } + + for i := range opts { + opts[i](d.cfg) + } + + _ = commonlog.Configure(d.cfg.Bootstrap.Logger) + + commonlog.DefaultScope().SetOutputLevel(commonlog.ErrorLevel) + commonlog.NamingScope().SetOutputLevel(commonlog.ErrorLevel) + commonlog.CacheScope().SetOutputLevel(commonlog.ErrorLevel) + commonlog.StoreScope().SetOutputLevel(commonlog.ErrorLevel) + commonlog.AuthScope().SetOutputLevel(commonlog.ErrorLevel) + + plugin.SetPluginConfig(&d.cfg.Plugin) + + ctx, cancel := context.WithCancel(context.Background()) + d.cancel = cancel + + // 初始化存储层 + ctrl := gomock.NewController(t) + s := storemock.NewMockStore(ctrl) + d.storage = s + + if err := callback(t, s); err != nil { + return err + } + + // 初始化缓存模块 + cacheMgn, err := cache.TestCacheInitialize(ctx, &d.cfg.Cache, d.storage) + if err != nil { + return err + } + + // 批量控制器 + namingBatchConfig, err := batch.ParseBatchConfig(d.cfg.Naming.Batch) + if err != nil { + return err + } + healthBatchConfig, err := batch.ParseBatchConfig(d.cfg.HealthChecks.Batch) + if err != nil { + return err + } + + batchConfig := &batch.Config{ + Register: namingBatchConfig.Register, + Deregister: namingBatchConfig.Register, + ClientRegister: namingBatchConfig.ClientRegister, + ClientDeregister: namingBatchConfig.ClientDeregister, + Heartbeat: healthBatchConfig.Heartbeat, + } + + bc, err := batch.NewBatchCtrlWithConfig(d.storage, cacheMgn, batchConfig) + if err != nil { + log.Errorf("new batch ctrl with config err: %s", err.Error()) + return err + } + bc.Start(ctx) + + if len(d.cfg.HealthChecks.LocalHost) == 0 { + d.cfg.HealthChecks.LocalHost = utils.LocalHost // 补充healthCheck的配置 + } + healthCheckServer, err := healthcheck.TestInitialize(ctx, &d.cfg.HealthChecks, d.cfg.Cache.Open, bc, d.storage) + if err != nil { + return err + } + cacheProvider, err := healthCheckServer.CacheProvider() + if err != nil { + return err + } + healthCheckServer.SetServiceCache(cacheMgn.Service()) + healthCheckServer.SetInstanceCache(cacheMgn.Instance()) + + // 为 instance 的 cache 添加 健康检查的 Listener + cacheMgn.AddListener(cache.CacheNameInstance, []cache.Listener{cacheProvider}) + cacheMgn.AddListener(cache.CacheNameClient, []cache.Listener{cacheProvider}) + + d.healthSvr = healthCheckServer + time.Sleep(5 * time.Second) + return nil +} + +// 加载配置 +func (d *EurekaTestSuit) loadConfig() error { + d.cfg = new(TestConfig) + + confFileName := testdata.Path("eureka_apiserver_test.yaml") + if os.Getenv("STORE_MODE") == "sqldb" { + fmt.Printf("run store mode : sqldb\n") + confFileName = testdata.Path("eureka_apiserver_db_test.yaml") + } + file, err := os.Open(confFileName) + if err != nil { + fmt.Printf("[ERROR] %v\n", err) + return err + } + + err = yaml.NewDecoder(file).Decode(d.cfg) + if err != nil { + fmt.Printf("[ERROR] %v\n", err) + return err + } + + return err +} + +func (d *EurekaTestSuit) Destroy() { + d.cancel() + time.Sleep(5 * time.Second) + + d.storage.Destroy() + time.Sleep(5 * time.Second) +} diff --git a/apiserver/eurekaserver/write.go b/apiserver/eurekaserver/write.go index 91f908d66..ebb903f58 100644 --- a/apiserver/eurekaserver/write.go +++ b/apiserver/eurekaserver/write.go @@ -211,7 +211,14 @@ func (h *EurekaServer) updateStatus(ctx context.Context, appId string, instanceI func (h *EurekaServer) renew(ctx context.Context, appId string, instanceId string) uint32 { resp := h.healthCheckServer.Report(ctx, &api.Instance{Id: &wrappers.StringValue{Value: instanceId}}) - return resp.GetCode().GetValue() + code := resp.GetCode().GetValue() + + // 如果目标实例存在,但是没有开启心跳,对于 eureka 来说,仍然属于心跳上报成功 + if code == api.HeartbeatOnDisabledIns { + return api.ExecuteSuccess + } + + return code } func (h *EurekaServer) updateMetadata(ctx context.Context, instanceId string, metadata map[string]string) uint32 { diff --git a/apiserver/eurekaserver/write_test.go b/apiserver/eurekaserver/write_test.go new file mode 100644 index 000000000..8cba577d3 --- /dev/null +++ b/apiserver/eurekaserver/write_test.go @@ -0,0 +1,146 @@ +/** + * Tencent is pleased to support the open source community by making Polaris available. + * + * Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved. + * + * Licensed under the BSD 3-Clause License (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://opensource.org/licenses/BSD-3-Clause + * + * 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 eurekaserver + +import ( + "context" + "testing" + "time" + + "github.com/golang/mock/gomock" + api "github.com/polarismesh/polaris-server/common/api/v1" + "github.com/polarismesh/polaris-server/common/model" + "github.com/polarismesh/polaris-server/common/utils" + "github.com/polarismesh/polaris-server/store/mock" + "github.com/stretchr/testify/assert" + "google.golang.org/protobuf/types/known/wrapperspb" +) + +func TestEurekaServer_renew(t *testing.T) { + + ins := &model.Instance{ + ServiceID: utils.NewUUID(), + Proto: &api.Instance{ + Service: utils.NewStringValue("echo"), + Namespace: utils.NewStringValue("default"), + Host: utils.NewStringValue("127.0.0.1"), + Port: utils.NewUInt32Value(8080), + HealthCheck: &api.HealthCheck{ + Type: api.HealthCheck_HEARTBEAT, + Heartbeat: &api.HeartbeatHealthCheck{ + Ttl: &wrapperspb.UInt32Value{ + Value: 5, + }, + }, + }, + }, + Valid: true, + } + + insId, resp := utils.CheckInstanceTetrad(ins.Proto) + if resp != nil { + t.Fatal(resp.GetInfo().GetValue()) + return + } + + ins.Proto.Id = utils.NewStringValue(insId) + + disableBeatIns := &model.Instance{ + ServiceID: utils.NewUUID(), + Proto: &api.Instance{ + Service: utils.NewStringValue("echo"), + Namespace: utils.NewStringValue("default"), + Host: utils.NewStringValue("127.0.0.2"), + Port: utils.NewUInt32Value(8081), + HealthCheck: &api.HealthCheck{ + Type: api.HealthCheck_HEARTBEAT, + Heartbeat: &api.HeartbeatHealthCheck{ + Ttl: &wrapperspb.UInt32Value{ + Value: 5, + }, + }, + }, + }, + Valid: true, + } + + disableBeatInsId, resp := utils.CheckInstanceTetrad(disableBeatIns.Proto) + if resp != nil { + t.Fatal(resp.GetInfo().GetValue()) + return + } + + disableBeatIns.Proto.Id = utils.NewStringValue(disableBeatInsId) + + eurekaSuit := &EurekaTestSuit{} + if err := eurekaSuit.initialize(t, func(t *testing.T, s *mock.MockStore) error { + s. + EXPECT(). + GetMoreInstances(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()). + AnyTimes(). + Return(map[string]*model.Instance{ + insId: ins, + disableBeatInsId: disableBeatIns, + }, nil) + s. + EXPECT(). + GetMoreServices(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()). + AnyTimes(). + Return(map[string]*model.Service{ + ins.ServiceID: { + ID: ins.ServiceID, + Name: ins.Proto.GetService().GetValue(), + Namespace: ins.Proto.GetNamespace().GetValue(), + }, + }, nil) + + s.EXPECT().GetInstancesCount().AnyTimes().Return(uint32(1), nil) + s.EXPECT().GetUnixSecond().AnyTimes().Return(time.Now().Unix(), nil) + s.EXPECT().Destroy().Return(nil) + return nil + }); err != nil { + t.Fatal(err) + } + + defer eurekaSuit.Destroy() + + t.Run("eureka客户端心跳上报-实例正常且开启心跳", func(t *testing.T) { + svr := &EurekaServer{ + healthCheckServer: eurekaSuit.healthSvr, + } + code := svr.renew(context.Background(), "", insId) + assert.Equalf(t, api.ExecuteSuccess, code, "code need success, actual : %d", code) + }) + + t.Run("eureka客户端心跳上报-实例未开启心跳", func(t *testing.T) { + svr := &EurekaServer{ + healthCheckServer: eurekaSuit.healthSvr, + } + code := svr.renew(context.Background(), "", disableBeatInsId) + assert.Equalf(t, api.ExecuteSuccess, code, "code need success, actual : %d", code) + }) + + t.Run("eureka客户端心跳上报-实例不存在", func(t *testing.T) { + svr := &EurekaServer{ + healthCheckServer: eurekaSuit.healthSvr, + } + code := svr.renew(context.Background(), "", utils.NewUUID()) + assert.Equalf(t, api.NotFoundResource, code, "code need notfound, actual : %d", code) + }) + +} diff --git a/apiserver/grpcserver/base.go b/apiserver/grpcserver/base.go index 82c2ade10..402380559 100644 --- a/apiserver/grpcserver/base.go +++ b/apiserver/grpcserver/base.go @@ -31,9 +31,11 @@ import ( "google.golang.org/grpc/credentials" "google.golang.org/grpc/metadata" "google.golang.org/grpc/peer" + "google.golang.org/grpc/status" api "github.com/polarismesh/polaris-server/common/api/v1" "github.com/polarismesh/polaris-server/common/connlimit" + commonlog "github.com/polarismesh/polaris-server/common/log" "github.com/polarismesh/polaris-server/common/secure" "github.com/polarismesh/polaris-server/common/utils" "github.com/polarismesh/polaris-server/plugin" @@ -61,6 +63,8 @@ type BaseGrpcServer struct { cache Cache convert MessageToCache + + log *commonlog.Scope } // GetPort get the connector listen port value @@ -99,7 +103,7 @@ func (b *BaseGrpcServer) Initialize(ctx context.Context, conf map[string]interfa } if ratelimit := plugin.GetRatelimit(); ratelimit != nil { - log.Infof("[API-Server] %s server open the ratelimit", b.protocol) + b.log.Infof("[API-Server] %s server open the ratelimit", b.protocol) b.ratelimit = ratelimit } @@ -116,7 +120,7 @@ func (b *BaseGrpcServer) Stop(protocol string) { // Run server main loop func (b *BaseGrpcServer) Run(errCh chan error, protocol string, initServer InitServer) { - log.Infof("[API-Server] start %s server", protocol) + b.log.Infof("[API-Server] start %s server", protocol) b.exitCh = make(chan struct{}) b.start = true defer func() { @@ -127,7 +131,7 @@ func (b *BaseGrpcServer) Run(errCh chan error, protocol string, initServer InitS address := fmt.Sprintf("%v:%v", b.listenIP, b.listenPort) listener, err := net.Listen("tcp", address) if err != nil { - log.Error("[API-Server][GRPC] %v", zap.Error(err)) + b.log.Error("[API-Server][GRPC] %v", zap.Error(err)) errCh <- err return } @@ -135,11 +139,11 @@ func (b *BaseGrpcServer) Run(errCh chan error, protocol string, initServer InitS // 如果设置最大连接数 if b.connLimitConfig != nil && b.connLimitConfig.OpenConnLimit { - log.Infof("[API-Server][GRPC] grpc server use max connection limit: %d, grpc max limit: %d", + b.log.Infof("[API-Server][GRPC] grpc server use max connection limit: %d, grpc max limit: %d", b.connLimitConfig.MaxConnPerHost, b.connLimitConfig.MaxConnLimit) listener, err = connlimit.NewListener(listener, protocol, b.connLimitConfig) if err != nil { - log.Error("[API-Server][GRPC] conn limit init", zap.Error(err)) + b.log.Error("[API-Server][GRPC] conn limit init", zap.Error(err)) errCh <- err return } @@ -151,7 +155,7 @@ func (b *BaseGrpcServer) Run(errCh chan error, protocol string, initServer InitS if !b.tlsInfo.IsEmpty() { creds, err = credentials.NewServerTLSFromFile(b.tlsInfo.CertFile, b.tlsInfo.KeyFile) if err != nil { - log.Error("failed to create credentials: %v", zap.Error(err)) + b.log.Error("failed to create credentials: %v", zap.Error(err)) errCh <- err return } @@ -177,12 +181,12 @@ func (b *BaseGrpcServer) Run(errCh chan error, protocol string, initServer InitS b.statis = plugin.GetStatis() if err := server.Serve(listener); err != nil { - log.Errorf("[API-Server][GRPC] %v", err) + b.log.Errorf("[API-Server][GRPC] %v", err) errCh <- err return } - log.Infof("[API-Server] %s server stop", protocol) + b.log.Infof("[API-Server] %s server stop", protocol) } var notPrintableMethods = map[string]bool{ @@ -194,6 +198,7 @@ func (b *BaseGrpcServer) unaryInterceptor(ctx context.Context, req interface{}, stream := newVirtualStream(ctx, WithVirtualStreamBaseServer(b), + WithVirtualStreamLogger(b.log), WithVirtualStreamMethod(info.FullMethod), WithVirtualStreamPreProcessFunc(b.preprocess), WithVirtualStreamPostProcessFunc(b.postprocess), @@ -237,14 +242,27 @@ func (b *BaseGrpcServer) streamInterceptor(srv interface{}, ss grpc.ServerStream ) err = handler(srv, stream) - if err != nil { // 存在非EOF读错误或者写错误 - log.Error("[API-Server][GRPC] handler stream", - zap.String("client-address", stream.ClientAddress), - zap.String("user-agent", stream.UserAgent), - zap.String("request-id", stream.RequestID), - zap.String("method", stream.Method), - zap.Error(err), - ) + if err != nil { + status, ok := status.FromError(err) + if ok && status.Code() == codes.Canceled { + // 存在非EOF读错误或者写错误 + b.log.Info("[API-Server][GRPC] handler stream is canceled by client", + zap.String("client-address", stream.ClientAddress), + zap.String("user-agent", stream.UserAgent), + zap.String("request-id", stream.RequestID), + zap.String("method", stream.Method), + zap.Error(err), + ) + } else { + // 存在非EOF读错误或者写错误 + b.log.Error("[API-Server][GRPC] handler stream", + zap.String("client-address", stream.ClientAddress), + zap.String("user-agent", stream.UserAgent), + zap.String("request-id", stream.RequestID), + zap.String("method", stream.Method), + zap.Error(err), + ) + } _ = b.statis.AddAPICall(stream.Method, "gRPC", stream.Code, 0) } @@ -261,7 +279,7 @@ func (b *BaseGrpcServer) preprocess(stream *VirtualStream, isPrint bool) error { if isPrint { // 打印请求 - log.Info("[API-Server][GRPC] receive request", + b.log.Info("[API-Server][GRPC] receive request", zap.String("client-address", stream.ClientAddress), zap.String("user-agent", stream.UserAgent), zap.String("request-id", stream.RequestID), @@ -284,7 +302,7 @@ func (b *BaseGrpcServer) postprocess(stream *VirtualStream, m interface{}) { // 打印回复 if code != http.StatusOK { - log.Error("[API-Server][GRPC] send response", + b.log.Error("[API-Server][GRPC] send response", zap.String("client-address", stream.ClientAddress), zap.String("user-agent", stream.UserAgent), zap.String("request-id", stream.RequestID), @@ -299,7 +317,7 @@ func (b *BaseGrpcServer) postprocess(stream *VirtualStream, m interface{}) { code = stream.Code // 打印回复 if code != int(codes.OK) { - log.Error("[API-Server][GRPC] send response", + b.log.Error("[API-Server][GRPC] send response", zap.String("client-address", stream.ClientAddress), zap.String("user-agent", stream.UserAgent), zap.String("request-id", stream.RequestID), @@ -315,7 +333,7 @@ func (b *BaseGrpcServer) postprocess(stream *VirtualStream, m interface{}) { // 打印耗时超过1s的请求 if diff > time.Second { - log.Info("[API-Server][GRPC] handling time > 1s", + b.log.Info("[API-Server][GRPC] handling time > 1s", zap.String("client-address", stream.ClientAddress), zap.String("user-agent", stream.UserAgent), zap.String("request-id", stream.RequestID), @@ -329,7 +347,7 @@ func (b *BaseGrpcServer) postprocess(stream *VirtualStream, m interface{}) { // Restart restart gRPC server func (b *BaseGrpcServer) Restart( initialize func() error, run func(), protocol string, option map[string]interface{}) error { - log.Infof("[API-Server][GRPC] restart %s server with new config: %+v", protocol, option) + b.log.Infof("[API-Server][GRPC] restart %s server with new config: %+v", protocol, option) b.restart = true b.Stop(protocol) @@ -337,13 +355,13 @@ func (b *BaseGrpcServer) Restart( <-b.exitCh } - log.Infof("[API-Server][GRPC] old %s server has stopped, begin restarting it", protocol) + b.log.Infof("[API-Server][GRPC] old %s server has stopped, begin restarting it", protocol) if err := initialize(); err != nil { - log.Errorf("restart %s server err: %s", protocol, err.Error()) + b.log.Errorf("restart %s server err: %s", protocol, err.Error()) return err } - log.Infof("[API-Server][GRPC] init %s server successfully, restart it", protocol) + b.log.Infof("[API-Server][GRPC] init %s server successfully, restart it", protocol) b.restart = false go run() @@ -358,13 +376,13 @@ func (b *BaseGrpcServer) EnterRatelimit(ip string, method string) uint32 { // ipRatelimit if ok := b.ratelimit.Allow(plugin.IPRatelimit, ip); !ok { - log.Error("[API-Server][GRPC] ip ratelimit is not allow", zap.String("client-ip", ip), + b.log.Error("[API-Server][GRPC] ip ratelimit is not allow", zap.String("client-ip", ip), zap.String("method", method)) return api.IPRateLimit } // apiRatelimit if ok := b.ratelimit.Allow(plugin.APIRatelimit, method); !ok { - log.Error("[API-Server][GRPC] api rate limit is not allow", zap.String("client-ip", ip), + b.log.Error("[API-Server][GRPC] api rate limit is not allow", zap.String("client-ip", ip), zap.String("method", method)) return api.APIRateLimit } diff --git a/apiserver/grpcserver/cache.go b/apiserver/grpcserver/cache.go index 81c8dcbac..9eb3a5277 100644 --- a/apiserver/grpcserver/cache.go +++ b/apiserver/grpcserver/cache.go @@ -22,7 +22,6 @@ import ( "github.com/gogo/protobuf/proto" lru "github.com/hashicorp/golang-lru" - "go.uber.org/zap" "google.golang.org/grpc" "github.com/polarismesh/polaris-server/plugin" @@ -41,7 +40,7 @@ type Cache interface { // Get Get(cacheType string, key string) *CacheObject // Put - Put(v *CacheObject) *CacheObject + Put(v *CacheObject) (*CacheObject, bool) } // CacheObject @@ -62,7 +61,6 @@ func (c *CacheObject) GetPreparedMessage() *grpc.PreparedMsg { func (c *CacheObject) PrepareMessage(stream grpc.ServerStream) error { pmsg := &grpc.PreparedMsg{} if err := pmsg.Encode(stream, c.OriginVal); err != nil { - log.Error("[Grpc][ProtoCache] prepare message", zap.String("key", c.Key), zap.Error(err)) return err } c.preparedVal = pmsg @@ -123,9 +121,9 @@ func (pc *protobufCache) Get(cacheType string, key string) *CacheObject { } // Put save cache value -func (pc *protobufCache) Put(v *CacheObject) *CacheObject { +func (pc *protobufCache) Put(v *CacheObject) (*CacheObject, bool) { if v == nil { - return nil + return nil, false } cacheType := v.CacheType @@ -133,10 +131,9 @@ func (pc *protobufCache) Put(v *CacheObject) *CacheObject { c, ok := pc.cahceRegistry[cacheType] if !ok { - log.Warn("[Grpc][ProtoCache] put cache ignore", zap.String("cacheType", cacheType)) - return nil + return nil, false } c.Add(key, v) - return v + return v, true } diff --git a/apiserver/grpcserver/config/server.go b/apiserver/grpcserver/config/server.go index 03a66c48c..38d03929e 100644 --- a/apiserver/grpcserver/config/server.go +++ b/apiserver/grpcserver/config/server.go @@ -27,10 +27,14 @@ import ( "github.com/polarismesh/polaris-server/apiserver" "github.com/polarismesh/polaris-server/apiserver/grpcserver" api "github.com/polarismesh/polaris-server/common/api/v1" - "github.com/polarismesh/polaris-server/common/log" + commonlog "github.com/polarismesh/polaris-server/common/log" "github.com/polarismesh/polaris-server/config" ) +var ( + configLog = commonlog.ConfigScope() +) + // ConfigGRPCServer 配置中心 GRPC API 服务器 type ConfigGRPCServer struct { grpcserver.BaseGrpcServer @@ -52,7 +56,10 @@ func (g *ConfigGRPCServer) GetProtocol() string { func (g *ConfigGRPCServer) Initialize(ctx context.Context, option map[string]interface{}, api map[string]apiserver.APIConfig) error { g.openAPI = api - return g.BaseGrpcServer.Initialize(ctx, option, grpcserver.WithProtocol(g.GetProtocol())) + return g.BaseGrpcServer.Initialize(ctx, option, + grpcserver.WithProtocol(g.GetProtocol()), + grpcserver.WithLogger(configLog), + ) } // Run 启动GRPC API服务器 @@ -76,13 +83,13 @@ func (g *ConfigGRPCServer) Run(errCh chan error) { } } default: - log.Errorf("[Config] api %s does not exist in grpcserver", name) + configLog.Errorf("[Config] api %s does not exist in grpcserver", name) return fmt.Errorf("api %s does not exist in grpcserver", name) } } var err error if g.configServer, err = config.GetServer(); err != nil { - log.Errorf("[Config] %v", err) + configLog.Errorf("[Config] %v", err) return err } diff --git a/apiserver/grpcserver/discover/server.go b/apiserver/grpcserver/discover/server.go index cd4df706c..b67bb94f4 100644 --- a/apiserver/grpcserver/discover/server.go +++ b/apiserver/grpcserver/discover/server.go @@ -26,18 +26,23 @@ import ( "github.com/polarismesh/polaris-server/apiserver" "github.com/polarismesh/polaris-server/apiserver/grpcserver" - api "github.com/polarismesh/polaris-server/common/api/v1" - "github.com/polarismesh/polaris-server/common/log" + v1 "github.com/polarismesh/polaris-server/apiserver/grpcserver/discover/v1" + v2 "github.com/polarismesh/polaris-server/apiserver/grpcserver/discover/v2" + apiv1 "github.com/polarismesh/polaris-server/common/api/v1" + apiv2 "github.com/polarismesh/polaris-server/common/api/v2" + commonlog "github.com/polarismesh/polaris-server/common/log" "github.com/polarismesh/polaris-server/service" "github.com/polarismesh/polaris-server/service/healthcheck" ) var ( + namingLog = commonlog.NamingScope() + cacheTypes = map[string]struct{}{ - api.DiscoverResponse_INSTANCE.String(): {}, - api.DiscoverResponse_ROUTING.String(): {}, - api.DiscoverResponse_RATE_LIMIT.String(): {}, - api.DiscoverResponse_CIRCUIT_BREAKER.String(): {}, + apiv1.DiscoverResponse_INSTANCE.String(): {}, + apiv1.DiscoverResponse_ROUTING.String(): {}, + apiv1.DiscoverResponse_RATE_LIMIT.String(): {}, + apiv1.DiscoverResponse_CIRCUIT_BREAKER.String(): {}, } ) @@ -47,6 +52,9 @@ type GRPCServer struct { namingServer service.DiscoverServer healthCheckServer *healthcheck.Server openAPI map[string]apiserver.APIConfig + + v1server *v1.DiscoverServer + v2server *v2.DiscoverServer } // GetPort 获取端口 @@ -65,17 +73,50 @@ func (g *GRPCServer) Initialize(ctx context.Context, option map[string]interface g.openAPI = apiConf - return g.BaseGrpcServer.Initialize(ctx, option, g.buildInitOptions(option)...) + if err := g.BaseGrpcServer.Initialize(ctx, option, g.buildInitOptions(option)...); err != nil { + return err + } + + // 引入功能模块和插件 + var err error + if g.namingServer, err = service.GetServer(); err != nil { + namingLog.Errorf("%v", err) + return err + } + + if g.healthCheckServer, err = healthcheck.GetServer(); err != nil { + namingLog.Errorf("%v", err) + return err + } + + g.v1server = v1.NewDiscoverServer( + v1.WithAllowAccess(g.allowAccess), + v1.WithEnterRateLimit(g.enterRateLimit), + v1.WithHealthCheckerServer(g.healthCheckServer), + v1.WithNamingServer(g.namingServer), + ) + g.v2server = v2.NewDiscoverServer( + v2.WithAllowAccess(g.allowAccess), + v2.WithEnterRateLimit(g.enterRateLimit), + v2.WithHealthCheckerServer(g.healthCheckServer), + v2.WithNamingServer(g.namingServer), + ) + + return nil } // Run 启动GRPC API服务器 func (g *GRPCServer) Run(errCh chan error) { + g.BaseGrpcServer.Run(errCh, g.GetProtocol(), func(server *grpc.Server) error { for name, config := range g.openAPI { switch name { case "client": if config.Enable { - api.RegisterPolarisGRPCServer(server, g) + // 注册 v1 版本的 spec discover server + apiv1.RegisterPolarisGRPCServer(server, g.v1server) + // 注册 v2 版本的 spec discover server + apiv2.RegisterPolarisGRPCServer(server, g.v2server) openMethod, getErr := apiserver.GetClientOpenMethod(config.Include, g.GetProtocol()) if getErr != nil { return getErr @@ -83,22 +124,10 @@ func (g *GRPCServer) Run(errCh chan error) { g.BaseGrpcServer.OpenMethod = openMethod } default: - log.Errorf("[Grpc][Discover] api %s does not exist in grpcserver", name) + namingLog.Errorf("[Grpc][Discover] api %s does not exist in grpcserver", name) return fmt.Errorf("api %s does not exist in grpcserver", name) } } - // 引入功能模块和插件 - var err error - if g.namingServer, err = service.GetServer(); err != nil { - log.Errorf("%v", err) - return err - } - - if g.healthCheckServer, err = healthcheck.GetServer(); err != nil { - log.Errorf("%v", err) - return err - } - return nil }) } @@ -133,6 +162,7 @@ func (g *GRPCServer) allowAccess(method string) bool { func (g *GRPCServer) buildInitOptions(option map[string]interface{}) []grpcserver.InitOption { initOptions := []grpcserver.InitOption{ grpcserver.WithProtocol(g.GetProtocol()), + grpcserver.WithLogger(namingLog), grpcserver.WithMessageToCacheObject(discoverCacheConvert), } @@ -143,7 +173,7 @@ func (g *GRPCServer) buildInitOptions(option map[string]interface{}) []grpcserve cache, err := grpcserver.NewCache(option, types) if err != nil { - log.Warn("[Grpc][Discover] new protobuf cache", zap.Error(err)) + namingLog.Warn("[Grpc][Discover] new protobuf cache", zap.Error(err)) } if cache != nil { @@ -160,13 +190,13 @@ func (g *GRPCServer) buildInitOptions(option map[string]interface{}) []grpcserve // 3. DiscoverResponse_RATE_LIMIT // 4. DiscoverResponse_CIRCUIT_BREAKER func discoverCacheConvert(m interface{}) *grpcserver.CacheObject { - resp, ok := m.(*api.DiscoverResponse) + resp, ok := m.(*apiv1.DiscoverResponse) if !ok { return nil } - if resp.Code.GetValue() != api.ExecuteSuccess { + if resp.Code.GetValue() != apiv1.ExecuteSuccess { return nil } diff --git a/apiserver/grpcserver/discover/client_access.go b/apiserver/grpcserver/discover/v1/client_access.go similarity index 88% rename from apiserver/grpcserver/discover/client_access.go rename to apiserver/grpcserver/discover/v1/client_access.go index 4442f2b11..f783cda56 100644 --- a/apiserver/grpcserver/discover/client_access.go +++ b/apiserver/grpcserver/discover/v1/client_access.go @@ -15,7 +15,7 @@ * specific language governing permissions and limitations under the License. */ -package discover +package v1 import ( "context" @@ -30,17 +30,21 @@ import ( "github.com/polarismesh/polaris-server/apiserver/grpcserver" api "github.com/polarismesh/polaris-server/common/api/v1" - "github.com/polarismesh/polaris-server/common/log" + commonlog "github.com/polarismesh/polaris-server/common/log" "github.com/polarismesh/polaris-server/common/utils" ) +var ( + namingLog = commonlog.NamingScope() +) + // ReportClient 客户端上报 -func (g *GRPCServer) ReportClient(ctx context.Context, in *api.Client) (*api.Response, error) { +func (g *DiscoverServer) ReportClient(ctx context.Context, in *api.Client) (*api.Response, error) { return g.namingServer.ReportClient(grpcserver.ConvertContext(ctx), in), nil } // RegisterInstance 注册服务实例 -func (g *GRPCServer) RegisterInstance(ctx context.Context, in *api.Instance) (*api.Response, error) { +func (g *DiscoverServer) RegisterInstance(ctx context.Context, in *api.Instance) (*api.Response, error) { // 需要记录操作来源,提高效率,只针对特殊接口添加operator rCtx := grpcserver.ConvertContext(ctx) @@ -62,7 +66,7 @@ func (g *GRPCServer) RegisterInstance(ctx context.Context, in *api.Instance) (*a } // DeregisterInstance 反注册服务实例 -func (g *GRPCServer) DeregisterInstance(ctx context.Context, in *api.Instance) (*api.Response, error) { +func (g *DiscoverServer) DeregisterInstance(ctx context.Context, in *api.Instance) (*api.Response, error) { // 需要记录操作来源,提高效率,只针对特殊接口添加operator rCtx := grpcserver.ConvertContext(ctx) rCtx = context.WithValue(rCtx, utils.StringContext("operator"), ParseGrpcOperator(ctx)) @@ -77,7 +81,7 @@ func (g *GRPCServer) DeregisterInstance(ctx context.Context, in *api.Instance) ( } // Discover 统一发现接口 -func (g *GRPCServer) Discover(server api.PolarisGRPC_DiscoverServer) error { +func (g *DiscoverServer) Discover(server api.PolarisGRPC_DiscoverServer) error { ctx := grpcserver.ConvertContext(server.Context()) clientIP, _ := ctx.Value(utils.StringContext("client-ip")).(string) clientAddress, _ := ctx.Value(utils.StringContext("client-address")).(string) @@ -95,7 +99,7 @@ func (g *GRPCServer) Discover(server api.PolarisGRPC_DiscoverServer) error { } msg := fmt.Sprintf("receive grpc discover request: %s", in.Service.String()) - log.Info(msg, + namingLog.Info(msg, zap.String("type", api.DiscoverRequest_DiscoverRequestType_name[int32(in.Type)]), zap.String("client-address", clientAddress), zap.String("user-agent", userAgent), @@ -144,7 +148,7 @@ func (g *GRPCServer) Discover(server api.PolarisGRPC_DiscoverServer) error { } // Heartbeat 上报心跳 -func (g *GRPCServer) Heartbeat(ctx context.Context, in *api.Instance) (*api.Response, error) { +func (g *DiscoverServer) Heartbeat(ctx context.Context, in *api.Instance) (*api.Response, error) { return g.healthCheckServer.Report(grpcserver.ConvertContext(ctx), in), nil } diff --git a/apiserver/grpcserver/discover/v1/server.go b/apiserver/grpcserver/discover/v1/server.go new file mode 100644 index 000000000..08db20a34 --- /dev/null +++ b/apiserver/grpcserver/discover/v1/server.go @@ -0,0 +1,66 @@ +/** + * Tencent is pleased to support the open source community by making Polaris available. + * + * Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved. + * + * Licensed under the BSD 3-Clause License (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://opensource.org/licenses/BSD-3-Clause + * + * 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 v1 + +import ( + "github.com/polarismesh/polaris-server/service" + "github.com/polarismesh/polaris-server/service/healthcheck" +) + +type DiscoverServer struct { + namingServer service.DiscoverServer + healthCheckServer *healthcheck.Server + enterRateLimit func(ip string, method string) uint32 + allowAccess func(method string) bool +} + +func NewDiscoverServer(options ...Option) *DiscoverServer { + s := &DiscoverServer{} + + for i := range options { + options[i](s) + } + + return s +} + +type Option func(s *DiscoverServer) + +func WithNamingServer(svr service.DiscoverServer) Option { + return func(s *DiscoverServer) { + s.namingServer = svr + } +} + +func WithHealthCheckerServer(svr *healthcheck.Server) Option { + return func(s *DiscoverServer) { + s.healthCheckServer = svr + } +} + +func WithEnterRateLimit(f func(ip string, method string) uint32) Option { + return func(s *DiscoverServer) { + s.enterRateLimit = f + } +} + +func WithAllowAccess(f func(method string) bool) Option { + return func(s *DiscoverServer) { + s.allowAccess = f + } +} diff --git a/apiserver/grpcserver/discover/v2/client_access_v2.go b/apiserver/grpcserver/discover/v2/client_access_v2.go new file mode 100644 index 000000000..fa58d5c8f --- /dev/null +++ b/apiserver/grpcserver/discover/v2/client_access_v2.go @@ -0,0 +1,96 @@ +/** + * Tencent is pleased to support the open source community by making Polaris available. + * + * Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved. + * + * Licensed under the BSD 3-Clause License (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://opensource.org/licenses/BSD-3-Clause + * + * 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 v2 + +import ( + "fmt" + "io" + + "github.com/polarismesh/polaris-server/apiserver/grpcserver" + apiv1 "github.com/polarismesh/polaris-server/common/api/v1" + apiv2 "github.com/polarismesh/polaris-server/common/api/v2" + commonlog "github.com/polarismesh/polaris-server/common/log" + "github.com/polarismesh/polaris-server/common/utils" + "go.uber.org/zap" + "google.golang.org/grpc" +) + +var ( + namingLog = commonlog.NamingScope() +) + +// Discover 统一发现接口 +func (g *DiscoverServer) Discover(server apiv2.PolarisGRPC_DiscoverServer) error { + ctx := grpcserver.ConvertContext(server.Context()) + clientIP, _ := ctx.Value(utils.StringContext("client-ip")).(string) + clientAddress, _ := ctx.Value(utils.StringContext("client-address")).(string) + requestID, _ := ctx.Value(utils.StringContext("request-id")).(string) + userAgent, _ := ctx.Value(utils.StringContext("user-agent")).(string) + method, _ := grpc.MethodFromServerStream(server) + + for { + in, err := server.Recv() + if err != nil { + if io.EOF == err { + return nil + } + return err + } + + msg := fmt.Sprintf("receive grpc discover v2 request: %s", in.GetSerivce().String()) + namingLog.Info(msg, + zap.String("type", apiv2.DiscoverRequest_DiscoverRequestType_name[int32(in.Type)]), + zap.String("client-address", clientAddress), + zap.String("user-agent", userAgent), + zap.String("request-id", requestID), + ) + + // 是否允许访问 + if ok := g.allowAccess(method); !ok { + resp := apiv2.NewDiscoverResponse(apiv1.ClientAPINotOpen) + if sendErr := server.Send(resp); sendErr != nil { + return sendErr + } + continue + } + + // stream模式,需要对每个包进行检测 + if code := g.enterRateLimit(clientIP, method); code != apiv1.ExecuteSuccess { + resp := apiv2.NewDiscoverResponse(code) + if err = server.Send(resp); err != nil { + return err + } + continue + } + + var out *apiv2.DiscoverResponse + switch in.Type { + case apiv2.DiscoverRequest_ROUTING: + out = g.namingServer.GetRoutingConfigV2WithCache(ctx, in.GetSerivce()) + case apiv2.DiscoverRequest_CIRCUIT_BREAKER: + out = g.namingServer.GetCircuitBreakerV2WithCache(ctx, in.GetSerivce()) + default: + out = apiv2.NewDiscoverRoutingResponse(apiv1.InvalidDiscoverResource, in.GetSerivce()) + } + + err = server.Send(out) + if err != nil { + return err + } + } +} diff --git a/apiserver/grpcserver/discover/v2/server.go b/apiserver/grpcserver/discover/v2/server.go new file mode 100644 index 000000000..de942b27f --- /dev/null +++ b/apiserver/grpcserver/discover/v2/server.go @@ -0,0 +1,66 @@ +/** + * Tencent is pleased to support the open source community by making Polaris available. + * + * Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved. + * + * Licensed under the BSD 3-Clause License (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://opensource.org/licenses/BSD-3-Clause + * + * 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 v2 + +import ( + "github.com/polarismesh/polaris-server/service" + "github.com/polarismesh/polaris-server/service/healthcheck" +) + +type DiscoverServer struct { + namingServer service.DiscoverServer + healthCheckServer *healthcheck.Server + enterRateLimit func(ip string, method string) uint32 + allowAccess func(method string) bool +} + +func NewDiscoverServer(options ...Option) *DiscoverServer { + s := &DiscoverServer{} + + for i := range options { + options[i](s) + } + + return s +} + +type Option func(s *DiscoverServer) + +func WithNamingServer(svr service.DiscoverServer) Option { + return func(s *DiscoverServer) { + s.namingServer = svr + } +} + +func WithHealthCheckerServer(svr *healthcheck.Server) Option { + return func(s *DiscoverServer) { + s.healthCheckServer = svr + } +} + +func WithEnterRateLimit(f func(ip string, method string) uint32) Option { + return func(s *DiscoverServer) { + s.enterRateLimit = f + } +} + +func WithAllowAccess(f func(method string) bool) Option { + return func(s *DiscoverServer) { + s.allowAccess = f + } +} diff --git a/apiserver/grpcserver/option.go b/apiserver/grpcserver/option.go index 712a97659..d88375551 100644 --- a/apiserver/grpcserver/option.go +++ b/apiserver/grpcserver/option.go @@ -17,6 +17,10 @@ package grpcserver +import ( + commonlog "github.com/polarismesh/polaris-server/common/log" +) + type InitOption func(svr *BaseGrpcServer) // WithProtocol @@ -39,3 +43,10 @@ func WithMessageToCacheObject(convert MessageToCache) InitOption { svr.convert = convert } } + +// WithLogger +func WithLogger(log *commonlog.Scope) InitOption { + return func(svr *BaseGrpcServer) { + svr.log = log + } +} diff --git a/apiserver/grpcserver/stream.go b/apiserver/grpcserver/stream.go index 5388049f0..f1b668154 100644 --- a/apiserver/grpcserver/stream.go +++ b/apiserver/grpcserver/stream.go @@ -23,6 +23,8 @@ import ( "strings" "time" + commonlog "github.com/polarismesh/polaris-server/common/log" + "go.uber.org/zap" "google.golang.org/grpc" "google.golang.org/grpc/metadata" "google.golang.org/grpc/peer" @@ -66,6 +68,13 @@ func WithVirtualStreamBaseServer(server *BaseGrpcServer) initVirtualStream { } } +// WithVirtualStreamLogger 设置 Logger +func WithVirtualStreamLogger(log *commonlog.Scope) initVirtualStream { + return func(vStream *VirtualStream) { + vStream.log = log + } +} + func newVirtualStream(ctx context.Context, initOptions ...initVirtualStream) *VirtualStream { var clientAddress string var clientIP string @@ -130,6 +139,8 @@ type VirtualStream struct { postprocess PostProcessFunc StartTime time.Time + + log *commonlog.Scope } // SetHeader sets the header metadata. It may be called multiple times. @@ -225,10 +236,16 @@ func (v *VirtualStream) handleResponse(stream grpc.ServerStream, m interface{}) } if err := cacheVal.PrepareMessage(stream); err != nil { + v.log.Warn("[Grpc][ProtoCache] prepare message fail, direct send msg", zap.String("key", cacheVal.Key), + zap.Error(err)) return m } - cacheVal = v.server.cache.Put(cacheVal) + cacheVal, ok := v.server.cache.Put(cacheVal) + if !ok { + v.log.Warn("[Grpc][ProtoCache] put cache ignore", zap.String("key", cacheVal.Key), + zap.String("cacheType", cacheVal.CacheType)) + } if cacheVal == nil { return m } diff --git a/apiserver/httpserver/auth.go b/apiserver/httpserver/auth.go index 497a2857f..5cebbf96f 100644 --- a/apiserver/httpserver/auth.go +++ b/apiserver/httpserver/auth.go @@ -23,6 +23,7 @@ import ( "github.com/emicklei/go-restful/v3" "github.com/golang/protobuf/proto" + httpcommon "github.com/polarismesh/polaris-server/apiserver/httpserver/http" api "github.com/polarismesh/polaris-server/common/api/v1" "github.com/polarismesh/polaris-server/common/utils" ) @@ -30,42 +31,42 @@ import ( // GetAuthServer 运维接口 func (h *HTTPServer) GetAuthServer(ws *restful.WebService) error { - ws.Route(ws.GET("/auth/status").To(h.AuthStatus)) + ws.Route(enrichAuthStatusApiDocs(ws.GET("/auth/status").To(h.AuthStatus))) // - ws.Route(ws.POST("/user/login").To(h.Login)) - ws.Route(ws.GET("/users").To(h.GetUsers)) - ws.Route(ws.POST("/users").To(h.CreateUsers)) - ws.Route(ws.POST("/users/delete").To(h.DeleteUsers)) - ws.Route(ws.PUT("/user").To(h.UpdateUser)) - ws.Route(ws.PUT("/user/password").To(h.UpdateUserPassword)) - ws.Route(ws.GET("/user/token").To(h.GetUserToken)) - ws.Route(ws.PUT("/user/token/status").To(h.UpdateUserToken)) - ws.Route(ws.PUT("/user/token/refresh").To(h.ResetUserToken)) + ws.Route(enrichLoginApiDocs(ws.POST("/user/login").To(h.Login))) + ws.Route(enrichGetUsersApiDocs(ws.GET("/users").To(h.GetUsers))) + ws.Route(enrichCreateUsersApiDocs(ws.POST("/users").To(h.CreateUsers))) + ws.Route(enrichDeleteUsersApiDocs(ws.POST("/users/delete").To(h.DeleteUsers))) + ws.Route(enrichUpdateUserApiDocs(ws.PUT("/user").To(h.UpdateUser))) + ws.Route(enrichUpdateUserPasswordApiDocs(ws.PUT("/user/password").To(h.UpdateUserPassword))) + ws.Route(enrichGetUserTokenApiDocs(ws.GET("/user/token").To(h.GetUserToken))) + ws.Route(enrichUpdateUserTokenApiDocs(ws.PUT("/user/token/status").To(h.UpdateUserToken))) + ws.Route(enrichResetUserTokenApiDocs(ws.PUT("/user/token/refresh").To(h.ResetUserToken))) // - ws.Route(ws.POST("/usergroup").To(h.CreateGroup)) - ws.Route(ws.PUT("/usergroups").To(h.UpdateGroups)) - ws.Route(ws.GET("/usergroups").To(h.GetGroups)) - ws.Route(ws.POST("/usergroups/delete").To(h.DeleteGroups)) - ws.Route(ws.GET("/usergroup/detail").To(h.GetGroup)) - ws.Route(ws.GET("/usergroup/token").To(h.GetGroupToken)) - ws.Route(ws.PUT("/usergroup/token/status").To(h.UpdateGroupToken)) - ws.Route(ws.PUT("/usergroup/token/refresh").To(h.ResetGroupToken)) - - ws.Route(ws.POST("/auth/strategy").To(h.CreateStrategy)) - ws.Route(ws.GET("/auth/strategy/detail").To(h.GetStrategy)) - ws.Route(ws.PUT("/auth/strategies").To(h.UpdateStrategies)) - ws.Route(ws.POST("/auth/strategies/delete").To(h.DeleteStrategies)) - ws.Route(ws.GET("/auth/strategies").To(h.GetStrategies)) - ws.Route(ws.GET("/auth/principal/resources").To(h.GetPrincipalResources)) + ws.Route(enrichCreateGroupApiDocs(ws.POST("/usergroup").To(h.CreateGroup))) + ws.Route(enrichUpdateGroupsApiDocs(ws.PUT("/usergroups").To(h.UpdateGroups))) + ws.Route(enrichGetGroupsApiDocs(ws.GET("/usergroups").To(h.GetGroups))) + ws.Route(enrichDeleteGroupsApiDocs(ws.POST("/usergroups/delete").To(h.DeleteGroups))) + ws.Route(enrichGetGroupApiDocs(ws.GET("/usergroup/detail").To(h.GetGroup))) + ws.Route(enrichGetGroupTokenApiDocs(ws.GET("/usergroup/token").To(h.GetGroupToken))) + ws.Route(enrichUpdateGroupTokenApiDocs(ws.PUT("/usergroup/token/status").To(h.UpdateGroupToken))) + ws.Route(enrichResetGroupTokenApiDocs(ws.PUT("/usergroup/token/refresh").To(h.ResetGroupToken))) + + ws.Route(enrichCreateStrategyApiDocs(ws.POST("/auth/strategy").To(h.CreateStrategy))) + ws.Route(enrichGetStrategyApiDocs(ws.GET("/auth/strategy/detail").To(h.GetStrategy))) + ws.Route(enrichUpdateStrategiesApiDocs(ws.PUT("/auth/strategies").To(h.UpdateStrategies))) + ws.Route(enrichDeleteStrategiesApiDocs(ws.POST("/auth/strategies/delete").To(h.DeleteStrategies))) + ws.Route(enrichGetStrategiesApiDocs(ws.GET("/auth/strategies").To(h.GetStrategies))) + ws.Route(enrichGetPrincipalResourcesApiDocs(ws.GET("/auth/principal/resources").To(h.GetPrincipalResources))) return nil } // AuthStatus auth status func (h *HTTPServer) AuthStatus(req *restful.Request, rsp *restful.Response) { - handler := &Handler{req, rsp} + handler := &httpcommon.Handler{req, rsp} checker := h.authServer.GetAuthChecker() @@ -82,7 +83,7 @@ func (h *HTTPServer) AuthStatus(req *restful.Request, rsp *restful.Response) { // Login 登陆函数 func (h *HTTPServer) Login(req *restful.Request, rsp *restful.Response) { - handler := &Handler{req, rsp} + handler := &httpcommon.Handler{req, rsp} loginReq := &api.LoginRequest{} @@ -97,7 +98,7 @@ func (h *HTTPServer) Login(req *restful.Request, rsp *restful.Response) { // CreateUsers 批量创建用户 func (h *HTTPServer) CreateUsers(req *restful.Request, rsp *restful.Response) { - handler := &Handler{req, rsp} + handler := &httpcommon.Handler{req, rsp} var users UserArr @@ -116,7 +117,7 @@ func (h *HTTPServer) CreateUsers(req *restful.Request, rsp *restful.Response) { // UpdateUser 更新用户 func (h *HTTPServer) UpdateUser(req *restful.Request, rsp *restful.Response) { - handler := &Handler{req, rsp} + handler := &httpcommon.Handler{req, rsp} user := &api.User{} @@ -131,7 +132,7 @@ func (h *HTTPServer) UpdateUser(req *restful.Request, rsp *restful.Response) { // UpdateUserPassword 更新用户 func (h *HTTPServer) UpdateUserPassword(req *restful.Request, rsp *restful.Response) { - handler := &Handler{req, rsp} + handler := &httpcommon.Handler{req, rsp} user := &api.ModifyUserPassword{} @@ -146,7 +147,7 @@ func (h *HTTPServer) UpdateUserPassword(req *restful.Request, rsp *restful.Respo // DeleteUsers 批量删除用户 func (h *HTTPServer) DeleteUsers(req *restful.Request, rsp *restful.Response) { - handler := &Handler{req, rsp} + handler := &httpcommon.Handler{req, rsp} var users UserArr @@ -165,9 +166,9 @@ func (h *HTTPServer) DeleteUsers(req *restful.Request, rsp *restful.Response) { // GetUsers 查询用户 func (h *HTTPServer) GetUsers(req *restful.Request, rsp *restful.Response) { - handler := &Handler{req, rsp} + handler := &httpcommon.Handler{req, rsp} - queryParams := utils.ParseQueryParams(req) + queryParams := httpcommon.ParseQueryParams(req) ctx := handler.ParseHeaderContext() handler.WriteHeaderAndProto(h.authServer.GetUsers(ctx, queryParams)) @@ -175,8 +176,8 @@ func (h *HTTPServer) GetUsers(req *restful.Request, rsp *restful.Response) { // GetUserToken 获取这个用户所关联的所有用户组列表信息,支持翻页 func (h *HTTPServer) GetUserToken(req *restful.Request, rsp *restful.Response) { - handler := &Handler{req, rsp} - queryParams := utils.ParseQueryParams(req) + handler := &httpcommon.Handler{req, rsp} + queryParams := httpcommon.ParseQueryParams(req) user := &api.User{ Id: utils.NewStringValue(queryParams["id"]), @@ -187,7 +188,7 @@ func (h *HTTPServer) GetUserToken(req *restful.Request, rsp *restful.Response) { // UpdateUserToken 更改用户的token func (h *HTTPServer) UpdateUserToken(req *restful.Request, rsp *restful.Response) { - handler := &Handler{req, rsp} + handler := &httpcommon.Handler{req, rsp} user := &api.User{} @@ -202,7 +203,7 @@ func (h *HTTPServer) UpdateUserToken(req *restful.Request, rsp *restful.Response // ResetUserToken 重置用户 token func (h *HTTPServer) ResetUserToken(req *restful.Request, rsp *restful.Response) { - handler := &Handler{req, rsp} + handler := &httpcommon.Handler{req, rsp} user := &api.User{} @@ -217,7 +218,7 @@ func (h *HTTPServer) ResetUserToken(req *restful.Request, rsp *restful.Response) // CreateGroup 创建用户组 func (h *HTTPServer) CreateGroup(req *restful.Request, rsp *restful.Response) { - handler := &Handler{req, rsp} + handler := &httpcommon.Handler{req, rsp} group := &api.UserGroup{} @@ -232,7 +233,7 @@ func (h *HTTPServer) CreateGroup(req *restful.Request, rsp *restful.Response) { // UpdateGroups 更新用户组 func (h *HTTPServer) UpdateGroups(req *restful.Request, rsp *restful.Response) { - handler := &Handler{req, rsp} + handler := &httpcommon.Handler{req, rsp} var groups ModifyGroupArr @@ -251,7 +252,7 @@ func (h *HTTPServer) UpdateGroups(req *restful.Request, rsp *restful.Response) { // DeleteGroups 删除用户组 func (h *HTTPServer) DeleteGroups(req *restful.Request, rsp *restful.Response) { - handler := &Handler{req, rsp} + handler := &httpcommon.Handler{req, rsp} var groups GroupArr @@ -270,9 +271,9 @@ func (h *HTTPServer) DeleteGroups(req *restful.Request, rsp *restful.Response) { // GetGroups 获取用户组列表 func (h *HTTPServer) GetGroups(req *restful.Request, rsp *restful.Response) { - handler := &Handler{req, rsp} + handler := &httpcommon.Handler{req, rsp} - queryParams := utils.ParseQueryParams(req) + queryParams := httpcommon.ParseQueryParams(req) ctx := handler.ParseHeaderContext() handler.WriteHeaderAndProto(h.authServer.GetGroups(ctx, queryParams)) @@ -280,9 +281,9 @@ func (h *HTTPServer) GetGroups(req *restful.Request, rsp *restful.Response) { // GetGroup 获取用户组详细 func (h *HTTPServer) GetGroup(req *restful.Request, rsp *restful.Response) { - handler := &Handler{req, rsp} + handler := &httpcommon.Handler{req, rsp} - queryParams := utils.ParseQueryParams(req) + queryParams := httpcommon.ParseQueryParams(req) ctx := handler.ParseHeaderContext() group := &api.UserGroup{ @@ -294,9 +295,9 @@ func (h *HTTPServer) GetGroup(req *restful.Request, rsp *restful.Response) { // GetGroupToken 获取用户组 token func (h *HTTPServer) GetGroupToken(req *restful.Request, rsp *restful.Response) { - handler := &Handler{req, rsp} + handler := &httpcommon.Handler{req, rsp} - queryParams := utils.ParseQueryParams(req) + queryParams := httpcommon.ParseQueryParams(req) ctx := handler.ParseHeaderContext() group := &api.UserGroup{ @@ -308,7 +309,7 @@ func (h *HTTPServer) GetGroupToken(req *restful.Request, rsp *restful.Response) // UpdateGroupToken 更新用户组 token func (h *HTTPServer) UpdateGroupToken(req *restful.Request, rsp *restful.Response) { - handler := &Handler{req, rsp} + handler := &httpcommon.Handler{req, rsp} group := &api.UserGroup{} @@ -323,7 +324,7 @@ func (h *HTTPServer) UpdateGroupToken(req *restful.Request, rsp *restful.Respons // ResetGroupToken 重置用户组 token func (h *HTTPServer) ResetGroupToken(req *restful.Request, rsp *restful.Response) { - handler := &Handler{req, rsp} + handler := &httpcommon.Handler{req, rsp} group := &api.UserGroup{} @@ -338,7 +339,7 @@ func (h *HTTPServer) ResetGroupToken(req *restful.Request, rsp *restful.Response // CreateStrategy 创建鉴权策略 func (h *HTTPServer) CreateStrategy(req *restful.Request, rsp *restful.Response) { - handler := &Handler{req, rsp} + handler := &httpcommon.Handler{req, rsp} strategy := &api.AuthStrategy{} @@ -353,7 +354,7 @@ func (h *HTTPServer) CreateStrategy(req *restful.Request, rsp *restful.Response) // UpdateStrategies 更新鉴权策略 func (h *HTTPServer) UpdateStrategies(req *restful.Request, rsp *restful.Response) { - handler := &Handler{req, rsp} + handler := &httpcommon.Handler{req, rsp} var strategies ModifyStrategyArr @@ -372,7 +373,7 @@ func (h *HTTPServer) UpdateStrategies(req *restful.Request, rsp *restful.Respons // DeleteStrategies 批量删除鉴权策略 func (h *HTTPServer) DeleteStrategies(req *restful.Request, rsp *restful.Response) { - handler := &Handler{req, rsp} + handler := &httpcommon.Handler{req, rsp} var strategies StrategyArr @@ -391,9 +392,9 @@ func (h *HTTPServer) DeleteStrategies(req *restful.Request, rsp *restful.Respons // GetStrategies 批量获取鉴权策略 func (h *HTTPServer) GetStrategies(req *restful.Request, rsp *restful.Response) { - handler := &Handler{req, rsp} + handler := &httpcommon.Handler{req, rsp} - queryParams := utils.ParseQueryParams(req) + queryParams := httpcommon.ParseQueryParams(req) ctx := handler.ParseHeaderContext() handler.WriteHeaderAndProto(h.authServer.GetStrategies(ctx, queryParams)) @@ -401,9 +402,9 @@ func (h *HTTPServer) GetStrategies(req *restful.Request, rsp *restful.Response) // GetStrategy 获取鉴权策略详细 func (h *HTTPServer) GetStrategy(req *restful.Request, rsp *restful.Response) { - handler := &Handler{req, rsp} + handler := &httpcommon.Handler{req, rsp} - queryParams := utils.ParseQueryParams(req) + queryParams := httpcommon.ParseQueryParams(req) ctx := handler.ParseHeaderContext() strategy := &api.AuthStrategy{ @@ -415,9 +416,9 @@ func (h *HTTPServer) GetStrategy(req *restful.Request, rsp *restful.Response) { // GetPrincipalResources 获取鉴权策略详细 func (h *HTTPServer) GetPrincipalResources(req *restful.Request, rsp *restful.Response) { - handler := &Handler{req, rsp} + handler := &httpcommon.Handler{req, rsp} - queryParams := utils.ParseQueryParams(req) + queryParams := httpcommon.ParseQueryParams(req) ctx := handler.ParseHeaderContext() handler.WriteHeaderAndProto(h.authServer.GetPrincipalResources(ctx, queryParams)) diff --git a/apiserver/httpserver/auth_apidoc.go b/apiserver/httpserver/auth_apidoc.go new file mode 100644 index 000000000..7d28e0232 --- /dev/null +++ b/apiserver/httpserver/auth_apidoc.go @@ -0,0 +1,241 @@ +/** + * Tencent is pleased to support the open source community by making Polaris available. + * + * Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved. + * + * Licensed under the BSD 3-Clause License (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://opensource.org/licenses/BSD-3-Clause + * + * 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 httpserver + +import ( + "github.com/emicklei/go-restful/v3" + restfulspec "github.com/polarismesh/go-restful-openapi/v2" + + api "github.com/polarismesh/polaris-server/common/api/v1" +) + +var ( + authApiTags = []string{"Auth"} + usersApiTags = []string{"Users"} + userGroupApiTags = []string{"UserGroup"} +) + +func enrichAuthStatusApiDocs(r *restful.RouteBuilder) *restful.RouteBuilder { + return r. + Doc("查询鉴权开关信息"). + Metadata(restfulspec.KeyOpenAPITags, authApiTags). + Notes(enrichAuthStatusApiNotes) +} + +func enrichCreateStrategyApiDocs(r *restful.RouteBuilder) *restful.RouteBuilder { + return r. + Doc("创建鉴权策略"). + Metadata(restfulspec.KeyOpenAPITags, authApiTags). + Reads(api.AuthStrategy{}, "create auth strategy"). + Notes(enrichCreateStrategyApiNotes) +} + +func enrichUpdateStrategiesApiDocs(r *restful.RouteBuilder) *restful.RouteBuilder { + return r. + Doc("更新鉴权策略"). + Metadata(restfulspec.KeyOpenAPITags, authApiTags). + Reads(api.AuthStrategy{}, "update auth strategy"). + Notes(enrichUpdateStrategiesApiNotes) +} + +func enrichGetStrategiesApiDocs(r *restful.RouteBuilder) *restful.RouteBuilder { + return r. + Doc("查询鉴权策略列表"). + Metadata(restfulspec.KeyOpenAPITags, authApiTags). + Param(restful.QueryParameter("id", "策略ID").DataType("string").Required(false)). + Param(restful.QueryParameter("name", "策略名称, 当前仅提供全模糊搜索").DataType("string").Required(false)). + Param(restful.QueryParameter("default", "“0” 查询自定义策略;“1” 查询默认策略;不填则为查询(默认+自定义)鉴权策略").DataType("string").Required(false)). + Param(restful.QueryParameter("res_id", "资源ID").DataType("string").Required(false)). + Param(restful.QueryParameter("res_type", "资源类型, namespace、service、config_group").DataType("string").Required(false)). + Param(restful.QueryParameter("principal_id", "成员ID").DataType("string").Required(false)). + Param(restful.QueryParameter("principal_type", "成员类型, user、group").DataType("string").Required(false)). + Param(restful.QueryParameter("show_detail", "是否显示策略详细").DataType("boolean").Required(false)). + Param(restful.QueryParameter("offset", "查询偏移量, 默认为0").DataType("integer").Required(false).DefaultValue("0")). + Param(restful.QueryParameter("limit", "本次查询条数, 最大为100").DataType("integer").Required(false)). + Notes(enrichGetStrategiesApiNotes) +} + +func enrichGetPrincipalResourcesApiDocs(r *restful.RouteBuilder) *restful.RouteBuilder { + return r. + Doc("获取鉴权策略详细"). + Metadata(restfulspec.KeyOpenAPITags, authApiTags). + Param(restful.QueryParameter("principal_id", "策略ID").DataType("string").Required(true)). + Param(restful.QueryParameter("principal_type", "Principal类别,user/group").DataType("string").Required(true)). + Notes(enrichGetPrincipalResourcesApiNotes) +} + +func enrichGetStrategyApiDocs(r *restful.RouteBuilder) *restful.RouteBuilder { + return r. + Doc("获取鉴权策略详细"). + Metadata(restfulspec.KeyOpenAPITags, authApiTags). + Param(restful.QueryParameter("id", "策略ID").DataType("string").Required(true)). + Notes(enrichGetStrategyApiNotes) +} + +func enrichDeleteStrategiesApiDocs(r *restful.RouteBuilder) *restful.RouteBuilder { + return r. + Doc("删除鉴权策略"). + Metadata(restfulspec.KeyOpenAPITags, authApiTags). + Reads(api.AuthStrategy{}, "delete auth strategy"). + Notes(enrichDeleteStrategiesApiNotes) +} + +func enrichLoginApiDocs(r *restful.RouteBuilder) *restful.RouteBuilder { + return r. + Doc("用户登录"). + Metadata(restfulspec.KeyOpenAPITags, usersApiTags). + Reads(api.LoginRequest{}, "用户登录接口"). + Notes(enrichLoginApiNotes) +} + +func enrichGetUsersApiDocs(r *restful.RouteBuilder) *restful.RouteBuilder { + return r. + Doc("获取用户"). + Metadata(restfulspec.KeyOpenAPITags, usersApiTags). + Param(restful.QueryParameter("id", "用户ID").DataType("string").Required(false)). + Param(restful.QueryParameter("name", "用户名称, 当前仅提供全模糊搜索").DataType("string").Required(false)). + Param(restful.QueryParameter("source", "用户来源").DataType("string").Required(false)). + Param(restful.QueryParameter("group_id", "用户组ID, 用于查询某个用户组下用户列表").DataType("string").Required(false)). + Param(restful.QueryParameter("offset", "查询偏移量, 默认为0").DataType("integer").Required(false).DefaultValue("0")). + Param(restful.QueryParameter("limit", "本次查询条数, 最大为100").DataType("integer").Required(false)). + Notes(enrichGetUsersApiNotes) +} + +func enrichCreateUsersApiDocs(r *restful.RouteBuilder) *restful.RouteBuilder { + return r. + Doc("创建用户"). + Metadata(restfulspec.KeyOpenAPITags, usersApiTags). + Reads(api.User{}, "create user"). + Notes(enrichCreateUsersApiNotes) +} + +func enrichDeleteUsersApiDocs(r *restful.RouteBuilder) *restful.RouteBuilder { + return r. + Doc("删除用户"). + Metadata(restfulspec.KeyOpenAPITags, usersApiTags). + Reads(api.User{}, "delete user"). + Notes(enrichDeleteUsersApiNotes) +} + +func enrichUpdateUserApiDocs(r *restful.RouteBuilder) *restful.RouteBuilder { + return r. + Doc("更新用户"). + Metadata(restfulspec.KeyOpenAPITags, usersApiTags). + Reads(api.User{}, "update user"). + Notes(enrichUpdateUserApiNotes) +} + +func enrichUpdateUserPasswordApiDocs(r *restful.RouteBuilder) *restful.RouteBuilder { + return r. + Doc("更新用户密码"). + Metadata(restfulspec.KeyOpenAPITags, usersApiTags). + Reads(api.ModifyUserPassword{}, "update user password"). + Notes(enrichUpdateUserPasswordApiNotes) +} + +func enrichGetUserTokenApiDocs(r *restful.RouteBuilder) *restful.RouteBuilder { + return r. + Doc("获取用户Token"). + Metadata(restfulspec.KeyOpenAPITags, usersApiTags). + Param(restful.QueryParameter("id", "用户ID").DataType("string").Required(true)). + Notes(enrichGetUserTokenApiNotes) +} + +func enrichUpdateUserTokenApiDocs(r *restful.RouteBuilder) *restful.RouteBuilder { + return r. + Doc("更新用户Token"). + Metadata(restfulspec.KeyOpenAPITags, usersApiTags). + Reads(api.User{}, "update user token"). + Notes(enrichUpdateUserTokenApiNotes) +} + +func enrichResetUserTokenApiDocs(r *restful.RouteBuilder) *restful.RouteBuilder { + return r. + Doc("重置用户Token"). + Metadata(restfulspec.KeyOpenAPITags, usersApiTags). + Reads(api.User{}, "reset user token"). + Notes(enrichResetUserTokenApiNotes) +} + +func enrichCreateGroupApiDocs(r *restful.RouteBuilder) *restful.RouteBuilder { + return r. + Doc("创建用户组"). + Metadata(restfulspec.KeyOpenAPITags, userGroupApiTags). + Reads(api.UserGroup{}, "create group"). + Notes(enrichCreateGroupApiNotes) +} + +func enrichUpdateGroupsApiDocs(r *restful.RouteBuilder) *restful.RouteBuilder { + return r. + Doc("更新用户组"). + Metadata(restfulspec.KeyOpenAPITags, userGroupApiTags). + Reads(api.UserGroup{}, "update group"). + Notes(enrichUpdateGroupsApiNotes) +} + +func enrichGetGroupsApiDocs(r *restful.RouteBuilder) *restful.RouteBuilder { + return r. + Doc("查询用户组列表"). + Metadata(restfulspec.KeyOpenAPITags, userGroupApiTags). + Param(restful.QueryParameter("id", "用户组ID").DataType("string").Required(false)). + Param(restful.QueryParameter("name", "用户组名称, 当前仅提供全模糊搜索").DataType("string").Required(false)). + Param(restful.QueryParameter("user_id", "用户ID, 用于查询某个用户关联的用户组列表").DataType("string").Required(false)). + Param(restful.QueryParameter("offset", "查询偏移量, 默认为0").DataType("integer").Required(false).DefaultValue("0")). + Param(restful.QueryParameter("limit", "本次查询条数, 最大为100").DataType("integer").Required(false)). + Notes(enrichGetGroupsApiNotes) +} + +func enrichGetGroupApiDocs(r *restful.RouteBuilder) *restful.RouteBuilder { + return r. + Doc("获取用户组详情"). + Metadata(restfulspec.KeyOpenAPITags, userGroupApiTags). + Param(restful.QueryParameter("id", "用户组ID").DataType("integer").Required(true)). + Notes(enrichGetGroupApiNotes) +} + +func enrichGetGroupTokenApiDocs(r *restful.RouteBuilder) *restful.RouteBuilder { + return r. + Doc("获取用户组 token"). + Metadata(restfulspec.KeyOpenAPITags, userGroupApiTags). + Param(restful.QueryParameter("id", "用户组ID").DataType("integer").Required(true)). + Notes(enrichGetGroupTokenApiNotes) +} + +func enrichDeleteGroupsApiDocs(r *restful.RouteBuilder) *restful.RouteBuilder { + return r. + Doc("删除用户组"). + Metadata(restfulspec.KeyOpenAPITags, userGroupApiTags). + Reads(api.UserGroup{}, "delete group"). + Notes(enrichDeleteGroupsApiNotes) +} + +func enrichUpdateGroupTokenApiDocs(r *restful.RouteBuilder) *restful.RouteBuilder { + return r. + Doc("更新用户组 token"). + Metadata(restfulspec.KeyOpenAPITags, userGroupApiTags). + Reads(api.UserGroup{}, "update user group token"). + Notes(enrichUpdateGroupTokenApiNotes) +} + +func enrichResetGroupTokenApiDocs(r *restful.RouteBuilder) *restful.RouteBuilder { + return r. + Doc("重置用户组 token"). + Metadata(restfulspec.KeyOpenAPITags, userGroupApiTags). + Reads(api.UserGroup{}, "reset user group token"). + Notes(enrichResetGroupTokenApiNotes) +} diff --git a/apiserver/httpserver/auth_apinotes.go b/apiserver/httpserver/auth_apinotes.go new file mode 100644 index 000000000..1df200d4b --- /dev/null +++ b/apiserver/httpserver/auth_apinotes.go @@ -0,0 +1,1015 @@ +/** + * Tencent is pleased to support the open source community by making Polaris available. + * + * Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved. + * + * Licensed under the BSD 3-Clause License (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://opensource.org/licenses/BSD-3-Clause + * + * 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 httpserver + +const ( + enrichAuthStatusApiNotes = ` + +请求示例: + +~~~ +GET /core/v1/auth/status +~~~ + + + +响应示例: + +~~~ +{ + "code": 200000, + "info": "execute success", + "optionSwitch": + { + "auth": "true" + } +} +~~~ +` + + enrichCreateStrategyApiNotes = ` +请求示例: + +~~~ +POST /core/v1/auth/strategy +Header X-Polaris-Token: {访问凭据} +~~~ + +~~~json +{ + "name": "xxx", + "comment": "xxx", + "principals": { + "users": [ + { + "id": "xxx" + } + ], + "groups": [ + { + "id": "xxx" + } + ] + }, + "resources": { + "namespaces": [ + { + "id": "Polaris" + } + ], + "services": [ + { + "id": "Polaris" + } + ], + "config_groups": [ + { + "id": "Polaris" + } + ] + } +} +~~~ + +响应示例: + +~~~json +{ + "code": 200000, + "info": "execute success" +} +~~~ +` + + enrichUpdateStrategiesApiNotes = ` +请求示例: + +~~~ +PUT /core/v1/auth/strategies +Header X-Polaris-Token: {访问凭据} +~~~ + +~~~json +[ + { + "id": "xxx", + "comment": "xxx", + "add_principals": { + "users": [{ + "id": "xxx" + },{ + "id": "xxx" + }], + "groups": [{ + "id": "xxx" + }] + }, + "remove_principals": { + "users": [{"id": "xxx"}], + "groups": [{ + "id": "xxx" + }] + }, + "add_resources": { + "namespaces": [ + { + "id":"xxx" + }], + "services": [{ + "id":"xxx" + }], + "config_groups": [ + { + "id":"xxx" + }] + }, + "remove_resources": { + "namespaces": [ + { + "id": "xxx" + } + ], + "services": [], + "config_groups": [] + } + } +] +~~~ + +响应示例: + +~~~json +{ + "code": 200000, + "info": "execute success", + "size": 1, + "responses": [ + { + "code": 200000, + "info": "execute success" + } + ] +} +~~~ +` + + enrichGetStrategiesApiNotes = ` +请求示例: + +~~~ +GET /core/v1/auth/strategies?{key}={value} +Header X-Polaris-Token: {访问凭据} +~~~ + +支持的URL参数 + +| 参数名 | 类型 | 描述 | 是否必填 | +|----------------|--------|---------------------------------------------------------------------|---------| +| id | string | 策略ID | 否 | +| name | string | 策略名称, 当前仅提供全模糊搜索 | 否 | +| default | string | “0” 查询自定义策略;“1” 查询默认策略;不填则为查询(默认+自定义)鉴权策略 | 否 | +| res_id | string | 资源ID | 否 | +| res_type | string | 资源类型, namespace、service、config_group | 否 | +| principal_id | string | 成员ID | 否 | +| principal_type | string | 成员类型, user、group | 否 | +| show_detail | bool | 是否显示策略详细 | 否 | +| offset | int | 查询偏移量, 默认为0 | 否 | +| limit | int | 本次查询条数, 最大为100 | 否 | + + +响应示例: + +~~~json +{ + "code": 200000, + "info": "execute success", + "amount": 1, + "size": 1, + "authStrategies": [ + { + "id": "xxx", + "name": "xxx", + "principals": { + "users": [ + { + "id": "xxx", + "name": "xxx" + } + ], + "groups": [ + { + "id": "xxx", + "name": "xxx" + } + ] + }, + "resources": { + "strategy_id": null, + "namespaces": [], + "services": [ + { + "id": "xxx", + "namespace": "default", + "name": "Demo-1" + }, + { + "id": "xxx", + "namespace": "default", + "name": "Demo-2" + } + ], + "config_groups": [] + }, + "action": "READ_WRITE", + "comment": "Default Strategy", + "ctime": "2022-02-09 19:48:53", + "mtime": "2022-02-09 19:48:53", + "default_strategy": true + }, + ] +} +~~~ +` + + enrichGetPrincipalResourcesApiNotes = ` +请求示例: + +~~~ +GET /core/v1/auth/principal/resources?principal_id=xxx&principal_type=user +Header X-Polaris-Token: {访问凭据} +~~~ + +| 参数名 | 类型 | 描述 | 是否必填 | +|----------------|--------|------------------------|---------| +| principal_id | string | 策略ID | 是 | +| principal_type | string | Principal类别,user/group | 是 | + + +响应示例: + +~~~json +{ + "code": 200000, + "info": "execute success", + "resources": { + "namespaces": [ + { + "id": "xxx", + "namespace": "xxx", + "name": "xxx" + } + ], + "services": [ + { + "id": "xxx", + "namespace": "Polaris", + "name": "xxx" + } + ], + "config_groups": [{ + "id": "xxx", + "namespace": "xxx", + "name": "xxx" + } + ] + } +} +~~~ +` + + enrichGetStrategyApiNotes = ` +根据策略ID查询该策略的具体详细信息 + +请求示例: + +~~~ +GET /core/v1/auth/strategy/detail?id=xxx +Header X-Polaris-Token: {访问凭据} +~~~ + +| 参数名 | 类型 | 描述 | 是否必填 | +|--------|--------|------|---------| +| id | string | 策略ID | 是 | + + + +响应示例: + +~~~json +{ + "code": 200000, + "info": "execute success", + "authStrategy": { + "id": "xxx", + "name": "xxx", + "principals": { + "users": [ + { + "id": "xxx", + "name": "xxx" + } + ], + "groups": [] + }, + "resources": { + "namespaces": [], + "services": [ + { + "id": "xxx", + "namespace": "default", + "name": "Demo-1" + }, + { + "id": "xxx", + "namespace": "default", + "name": "Demo-2" + } + ], + "config_groups": [] + }, + "action": "READ_WRITE", + "comment": "Default Strategy", + "ctime": "2022-02-09 19:43:26", + "mtime": "2022-02-15 23:20:48", + "default_strategy": true + } +} +~~~ +` + + enrichDeleteStrategiesApiNotes = ` +请求示例: + +~~~ +POST /core/v1/auth/strategies/delete +Header X-Polaris-Token: {访问凭据} +~~~ + +~~~json +[ + { + "id": "xxx" + } +] +~~~ + +响应示例: + +~~~json +{ + "code": 200000, + "info": "execute success", + "size": 1, + "responses": [ + { + "code": 200000, + "info": "execute success" + } + ] +} +~~~ +` + enrichLoginApiNotes = ` +用于控制台进行用户登陆操作 + +请求示例: + +~~~ +POST /core/v1/user/login +~~~ + +| 参数名 | 类型 | 描述 | 是否必填 | +|----------|--------|--------|---------| +| name | string | 用户名 | 是 | +| password | string | 用户密码 | 是 | + + +应答示例: + +~~~json +{ + "code": 200000, + "info": "execute success", + "loginResponse": { + "token": "xxx", + "name": "xxx", + "user_id": "xxx", + "role": "xxx" + } +} +~~~ + +| 参数名 | | 类型 | 描述 | +|---------------|---------|--------|-------------------------------------------------------| +| code | | uint32 | 六位返回码 | +| info | | string | 返回信息 | +| loginResponse | | | 命名空间 | +| | token | string | 用户Token, 用于接口请求访问 | +| | name | string | 用户名 | +| | role | string | 当前用户角色, (admin:超级账户, main:主账户, sub:子账户) | +| | user_id | string | 当前用户ID | + +` + + enrichGetUsersApiNotes = ` +根据相关条件对用户列表进行查询 + +请求示例: + +~~~ +GET /core/v1/users?id=xxx&name=xxx&source=xxx&group_id=xxx&offset=xxx&limit=xxx +Header X-Polaris-Token: {访问凭据} +~~~ + +| 参数名 | 类型 | 描述 | 是否必填 | +|----------|--------|--------------------------------------|---------| +| id | string | 用户ID | 否 | +| name | string | 用户名称, 当前仅提供全模糊搜索 | 否 | +| source | string | 用户来源 | 否 | +| group_id | string | 用户组ID, 用于查询某个用户组下用户列表 | 否 | +| offset | int | 查询偏移量, 默认为0 | 否 | +| limit | int | 本次查询条数, 最大为100 | 否 | + + +响应示例: + +~~~json +{ + "code": 200000, + "info": "execute success", + "amount": 1, + "size": 1, + "users": [ + { + "id": "xxx", + "name": "xxx", + "source": "", + "auth_token": "", + "token_enable": true, + "comment": "", + "ctime": "2022-02-09 19:48:53", + "mtime": "2022-02-09 19:48:53", + } + ] +} +~~~ +` + + enrichCreateUsersApiNotes = ` +批量创建用户至北极星 + +请求示例: + +~~~ +POST /core/v1/users +Header X-Polaris-Token: {访问凭据} +~~~ + +~~~json +[ + { + "name": "polarismesh", + "password": "polarismesh", + "comment": "polarismesh", + "source": "Polaris" + } +] +~~~ + +| 参数名 | 类型 | 描述 | 是否必填 | +|----------|--------|--------|---------| +| name | string | 用户名 | 是 | +| password | string | 用户密码 | 是 | +| comment | string | 用户备注 | 否 | +| source | string | 用户来源 | 否 | + + +应答示例: + +~~~json +{ + "code": 200000, + "info": "execute success", + "size": 1, + "responses": [ + { + "code": 200000, + "info": "execute success" + } + ] +} +~~~ + +数据结构: + +> user + +| 参数名 | 类型 | 描述 | +|--------------|--------|--------------------| +| id | string | 用户ID | +| name | string | 用户名称 | +| password | string | 用户密码 | +| source | string | 用户来源 | +| auth_token | string | 用户访问凭据 | +| token_enable | bool | 用户访问凭据是否可用 | +| comment | string | 用户备注信息 | +| ctime | string | 用户创建时间 | +| mtime | string | 用户修改时间 | +` + + enrichDeleteUsersApiNotes = ` +批量删除北极星中的用户 + +请求示例 + +~~~ +POST /core/v1/users/delete +Header X-Polaris-Token: {访问凭据} +~~~ + +~~~json +[ + { + "id": "xxx" + } +] +~~~ + +| 参数名 | 类型 | 描述 | 是否必填 | +|--------|--------|------|---------| +| id | string | 用户ID | 是 | + + +响应示例: + +~~~json +{ + "code": 200000, + "info": "execute success", + "responses": [ + { + "code": 200000, + "info": "execute success" + } + ] +} +~~~ +` + + enrichUpdateUserApiNotes = ` +更新用户的备注信息数据 + +请求示例: + +~~~ +PUT /core/v1/user +Header X-Polaris-Token: {访问凭据} +~~~ + +~~~json +{ + "id": "xxx", + "comment": "polarismesh" +} +~~~ + +| 参数名 | 类型 | 描述 | 是否必填 | +|---------|--------|--------|---------| +| id | string | 用户ID | 是 | +| comment | string | 用户备注 | 否 | +` + + enrichUpdateUserPasswordApiNotes = ` +用户重新更新密码, 如果密码更新成功, 则会一并更新对应用户的访问凭据 + +请求示例: + +~~~ +PUT /core/v1/user/password +Header X-Polaris-Token: {访问凭据} +~~~ + +~~~json +{ + "id": "xxx", + "old_password": "xxx", + "new_password": "xxx" +} +~~~ + +| 参数名 | 类型 | 描述 | 是否必填 | +|--------------|--------|------|---------| +| id | string | 用户ID | 是 | +| old_password | string | 旧密码 | 否 | +| new_password | string | 新密码 | 否 | + + +响应示例: +` + + enrichGetUserTokenApiNotes = ` +查询用户的Token凭据信息,通过用户ID或者用户名进行查询 + +请求示例: + +~~~ +GET /core/v1/user/token?id=xxx +Header X-Polaris-Token: {访问凭据} +~~~ + +| 参数名 | 类型 | 描述 | 是否必填 | +|--------|--------|------|---------| +| id | string | 用户ID | 是 | + +响应示例: + +~~~json +{ + "code": 200000, + "info": "execute success", + "user": { + "id": "xxx", + "auth_token": "xxx", + "token_enable": true + } +} +~~~ +` + + enrichUpdateUserTokenApiNotes = ` +对用户Token的使用状态进行修改, 如果用户的Token被设置为禁用状态, 则该Token后续无法用于访问北极星接口以及资源, 需使用主账户或者超级账户进行解封 + +请求示例: + +~~~ +PUT /core/v1/user/token/status +Header X-Polaris-Token: {访问凭据} +~~~ + +~~~json +{ + "id": "xxx", + "token_enable": false +} +~~~ + +| 参数名 | 类型 | 描述 | 是否必填 | +|--------------|--------|------------------------------------------|---------| +| id | string | 用户ID | 是 | +| token_enable | bool | 当前Token可用状态, true为启用, false为禁用 | 是 | + + +响应示例: + +~~~json +{ + "code": 200000, + "info": "execute success" +} +~~~ +` + + enrichResetUserTokenApiNotes = ` +重置用户的Token, 当Token重置之后,原先的Token失效并且无法进行访问北极星接口以及资源 + +请求示例: + +~~~ +PUT /core/v1/user/token/refresh +Header X-Polaris-Token: {访问凭据} +~~~ + +~~~json +{ + "id": "xxx" +} +~~~ + +| 参数名 | 类型 | 描述 | 是否必填 | +|--------|--------|------|---------| +| id | string | 用户ID | 是 | + + +响应示例: + +~~~json +{ + "code": 200000, + "info": "execute success" +} +~~~ +` + + enrichCreateGroupApiNotes = ` +请求示例: + +~~~ +POST /core/v1/usergroup +Header X-Polaris-Token: {访问凭据} +~~~ + +~~~json +{ + "name": "GROUP_1", + "comment": "", + "relation": { + "users": [ + { + "id": "xxx" + }, { + "id": "xxx" + } + ] + } +} +~~~ + +| 参数名 | 类型 | 描述 | +|----------|----------|----------------------| +| name | string | 用户组名称 | +| comment | string | 用户组备注信息 | +| relation | user列表 | 当前用户组关联的用户ID | + +响应示例: + +~~~json +{ + "code": 200000, + "info": "execute success" +} +~~~ +` + + enrichUpdateGroupsApiNotes = ` +请求示例: + +~~~ +PUT /core/v1/usergroup +Header X-Polaris-Token: {访问凭据} +~~~ + +~~~json +[ + { + "id": "xxx", + "comment": "xxx", + "add_relations": { + "users": [{ + "id": "xxx" + }, { + "id": "xxx" + }] + }, + "remove_relations": { + "users": [{ + "id": "xxx" + }, { + "id": "xxx" + }] + } + } +] +~~~ + +| 参数名 | 类型 | 描述 | +|-----------------|----------|--------------------------| +| id | string | 用户组ID | +| comment | string | 用户组备注信息 | +| add_relation | user列表 | 当前用户组追加关联的用户ID | +| remove_relation | user列表 | 当前用户组移除关联的用户ID | + +响应示例: + +~~~json +{ + "code": 200000, + "info": "execute success", + "size": 1, + "responses": [ + { + "code": 200000, + "info": "execute success" + } + ] +} +~~~ +` + + enrichGetGroupsApiNotes = ` +请求示例: + +~~~ +GET /core/v1/usergroups?{key}={value} +Header X-Polaris-Token: {访问凭据} +~~~ + +支持的URL参数 + +| 参数名 | 类型 | 描述 | 是否必填 | +|---------|--------|----------------------------------------|---------| +| id | string | 用户组ID | 否 | +| name | string | 用户组名称, 当前仅提供全模糊搜索 | 否 | +| user_id | string | 用户ID, 用于查询某个用户关联的用户组列表 | 否 | +| offset | int | 查询偏移量, 默认为0 | 否 | +| limit | int | 本次查询条数, 最大为100 | 否 | + + +响应示例: + +~~~json +{ + "code": 200000, + "info": "execute success", + "amount": 1, + "size": 1, + "userGroups": [ + { + "id": "xxx", + "name": "xxx", + "auth_token": null, + "token_enable": true, + "comment": "", + "ctime": "2022-02-09 21:46:33", + "mtime": "2022-02-09 21:46:33", + "user_count": 1 + } + ] +} +~~~ + +数据结构: + +> userGroups + +| 参数名 | 类型 | 描述 | +|--------------|--------|----------------------| +| id | string | 用户组ID | +| name | string | 用户组名称 | +| auth_token | string | 用户组访问凭据 | +| token_enable | bool | 用户组访问凭据是否可用 | +| comment | string | 用户组备注信息 | +| ctime | string | 用户组创建时间 | +| mtime | string | 用户组修改时间 | +| user_count | int | 当前用户组下用户的数量 | +` + + enrichGetGroupApiNotes = ` +请求示例: + +~~~ +GET /core/v1/usergroup/detail?id=xxx +Header X-Polaris-Token: {访问凭据} +~~~ + + +响应示例: + +~~~json +{ + "code": 200000, + "info": "execute success", + "userGroup": { + "id": "xxx", + "name": "xxx", + "token_enable": true, + "comment": "", + "ctime": "2022-02-09 21:46:33", + "mtime": "2022-02-09 21:46:33", + "relation": { + "users": [ + { + "id": "xxx", + "name": "xxx", + "source": "", + "token_enable": true, + "comment": "", + "ctime": "2022-02-09 19:48:53", + "mtime": "2022-02-09 19:48:53", + } + ] + }, + "user_count": 1 + } +} +~~~ +` + + enrichGetGroupTokenApiNotes = ` +请求示例: + +~~~ +GET /core/v1/usergroup/token?id=xxx +Header X-Polaris-Token: {访问凭据} +~~~ + +响应示例: + +~~~json +{ + "code": 200000, + "info": "execute success", + "userGroup": { + "id": "xxx", + "auth_token": "xxx", + "token_enable": true + } +} +~~~ +` + + enrichDeleteGroupsApiNotes = ` +请求示例: + +~~~ +POST /core/v1/usergroups/delete +Header X-Polaris-Token: {访问凭据} +~~~ + +~~~json +[ + { + "id": "xxx" + } +] +~~~ + +响应示例: + +~~~json +{ + "code": 200000, + "info": "execute success", + "responses": [ + { + "code": 200000, + "info": "execute success" + } + ] +} +~~~ +` + + enrichUpdateGroupTokenApiNotes = ` +请求示例: + +~~~ +PUT /core/v1/usergroup/token/status +Header X-Polaris-Token: {访问凭据} +~~~ + +~~~json +{ + "id": "xxx", + "token_enable": false +} +~~~ + +响应示例: + +~~~json +{ + "code": 200000, + "info": "execute success" +} +~~~ +` + + enrichResetGroupTokenApiNotes = ` +请求示例: + +~~~ +PUT /core/v1/usergroup/token/refresh +Header X-Polaris-Token: {访问凭据} +~~~ + +~~~json +{ + "id": "xxx" +} +~~~ + +响应示例: + +~~~json +{ + "code": 200000, + "info": "execute success" +} +~~~ +` +) diff --git a/apiserver/httpserver/client.go b/apiserver/httpserver/client.go index 5d61ddc2e..29b6f0444 100644 --- a/apiserver/httpserver/client.go +++ b/apiserver/httpserver/client.go @@ -19,8 +19,7 @@ package httpserver import ( "github.com/emicklei/go-restful/v3" - - "github.com/polarismesh/polaris-server/common/utils" + httpcommon "github.com/polarismesh/polaris-server/apiserver/httpserver/http" ) func (h *HTTPServer) GetClientServer(ws *restful.WebService) error { @@ -31,9 +30,9 @@ func (h *HTTPServer) GetClientServer(ws *restful.WebService) error { func (h *HTTPServer) GetReportClients(req *restful.Request, rsp *restful.Response) { - handler := &utils.Handler{req, rsp} + handler := &httpcommon.Handler{req, rsp} - queryParams := utils.ParseQueryParams(req) + queryParams := httpcommon.ParseQueryParams(req) ctx := handler.ParseHeaderContext() ret := h.namingServer.GetReportClientWithCache(ctx, queryParams) diff --git a/apiserver/httpserver/config_client_access.go b/apiserver/httpserver/config_client_access.go index 94547b250..aa698da2f 100644 --- a/apiserver/httpserver/config_client_access.go +++ b/apiserver/httpserver/config_client_access.go @@ -23,11 +23,12 @@ import ( "github.com/emicklei/go-restful/v3" "google.golang.org/protobuf/types/known/wrapperspb" + httpcommon "github.com/polarismesh/polaris-server/apiserver/httpserver/http" api "github.com/polarismesh/polaris-server/common/api/v1" ) func (h *HTTPServer) getConfigFile(req *restful.Request, rsp *restful.Response) { - handler := &Handler{req, rsp} + handler := &httpcommon.Handler{req, rsp} version, err := strconv.ParseUint(handler.QueryParameter("version"), 10, 64) if err != nil { @@ -47,7 +48,7 @@ func (h *HTTPServer) getConfigFile(req *restful.Request, rsp *restful.Response) } func (h *HTTPServer) watchConfigFile(req *restful.Request, rsp *restful.Response) { - handler := &Handler{req, rsp} + handler := &httpcommon.Handler{req, rsp} // 1. 解析出客户端监听的配置文件列表 watchConfigFileRequest := &api.ClientWatchConfigFileRequest{} diff --git a/apiserver/httpserver/config_console_access.go b/apiserver/httpserver/config_console_access.go index 4eece1a32..7059111a0 100644 --- a/apiserver/httpserver/config_console_access.go +++ b/apiserver/httpserver/config_console_access.go @@ -24,13 +24,14 @@ import ( "github.com/golang/protobuf/proto" "go.uber.org/zap" + httpcommon "github.com/polarismesh/polaris-server/apiserver/httpserver/http" api "github.com/polarismesh/polaris-server/common/api/v1" "github.com/polarismesh/polaris-server/common/utils" ) // CreateConfigFileGroup 创建配置文件组 func (h *HTTPServer) CreateConfigFileGroup(req *restful.Request, rsp *restful.Response) { - handler := &Handler{req, rsp} + handler := &httpcommon.Handler{req, rsp} configFileGroup := &api.ConfigFileGroup{} ctx, err := handler.Parse(configFileGroup) @@ -49,7 +50,7 @@ func (h *HTTPServer) CreateConfigFileGroup(req *restful.Request, rsp *restful.Re // QueryConfigFileGroups 查询配置文件组,group 模糊搜索 func (h *HTTPServer) QueryConfigFileGroups(req *restful.Request, rsp *restful.Response) { - handler := &Handler{req, rsp} + handler := &httpcommon.Handler{req, rsp} namespace := handler.QueryParameter("namespace") group := handler.QueryParameter("group") @@ -65,7 +66,7 @@ func (h *HTTPServer) QueryConfigFileGroups(req *restful.Request, rsp *restful.Re // DeleteConfigFileGroup 删除配置文件组 func (h *HTTPServer) DeleteConfigFileGroup(req *restful.Request, rsp *restful.Response) { - handler := &Handler{req, rsp} + handler := &httpcommon.Handler{req, rsp} namespace := handler.QueryParameter("namespace") group := handler.QueryParameter("group") @@ -76,7 +77,7 @@ func (h *HTTPServer) DeleteConfigFileGroup(req *restful.Request, rsp *restful.Re // UpdateConfigFileGroup 更新配置文件组,只能更新 comment func (h *HTTPServer) UpdateConfigFileGroup(req *restful.Request, rsp *restful.Response) { - handler := &Handler{req, rsp} + handler := &httpcommon.Handler{req, rsp} configFileGroup := &api.ConfigFileGroup{} ctx, err := handler.Parse(configFileGroup) @@ -95,7 +96,7 @@ func (h *HTTPServer) UpdateConfigFileGroup(req *restful.Request, rsp *restful.Re // CreateConfigFile 创建配置文件 func (h *HTTPServer) CreateConfigFile(req *restful.Request, rsp *restful.Response) { - handler := &Handler{req, rsp} + handler := &httpcommon.Handler{req, rsp} configFile := &api.ConfigFile{} ctx, err := handler.Parse(configFile) @@ -114,7 +115,7 @@ func (h *HTTPServer) CreateConfigFile(req *restful.Request, rsp *restful.Respons // GetConfigFile 获取单个配置文件 func (h *HTTPServer) GetConfigFile(req *restful.Request, rsp *restful.Response) { - handler := &Handler{req, rsp} + handler := &httpcommon.Handler{req, rsp} namespace := handler.QueryParameter("namespace") group := handler.QueryParameter("group") @@ -125,7 +126,7 @@ func (h *HTTPServer) GetConfigFile(req *restful.Request, rsp *restful.Response) } func (h *HTTPServer) QueryConfigFilesByGroup(req *restful.Request, rsp *restful.Response) { - handler := &Handler{req, rsp} + handler := &httpcommon.Handler{req, rsp} namespace := handler.QueryParameter("namespace") group := handler.QueryParameter("group") @@ -139,7 +140,7 @@ func (h *HTTPServer) QueryConfigFilesByGroup(req *restful.Request, rsp *restful. // SearchConfigFile 按照 group 和 name 模糊搜索配置文件,按照 tag 搜索,多个tag之间或的关系 func (h *HTTPServer) SearchConfigFile(req *restful.Request, rsp *restful.Response) { - handler := &Handler{req, rsp} + handler := &httpcommon.Handler{req, rsp} namespace := handler.QueryParameter("namespace") group := handler.QueryParameter("group") @@ -156,7 +157,7 @@ func (h *HTTPServer) SearchConfigFile(req *restful.Request, rsp *restful.Respons // UpdateConfigFile 更新配置文件 func (h *HTTPServer) UpdateConfigFile(req *restful.Request, rsp *restful.Response) { - handler := &Handler{req, rsp} + handler := &httpcommon.Handler{req, rsp} configFile := &api.ConfigFile{} ctx, err := handler.Parse(configFile) @@ -174,7 +175,7 @@ func (h *HTTPServer) UpdateConfigFile(req *restful.Request, rsp *restful.Respons // DeleteConfigFile 删除单个配置文件,删除配置文件也会删除配置文件发布内容,客户端将获取不到配置文件 func (h *HTTPServer) DeleteConfigFile(req *restful.Request, rsp *restful.Response) { - handler := &Handler{req, rsp} + handler := &httpcommon.Handler{req, rsp} namespace := handler.QueryParameter("namespace") group := handler.QueryParameter("group") @@ -187,7 +188,7 @@ func (h *HTTPServer) DeleteConfigFile(req *restful.Request, rsp *restful.Respons // BatchDeleteConfigFile 批量删除配置文件 func (h *HTTPServer) BatchDeleteConfigFile(req *restful.Request, rsp *restful.Response) { - handler := &Handler{req, rsp} + handler := &httpcommon.Handler{req, rsp} operator := handler.QueryParameter("deleteBy") @@ -208,7 +209,7 @@ func (h *HTTPServer) BatchDeleteConfigFile(req *restful.Request, rsp *restful.Re // PublishConfigFile 发布配置文件 func (h *HTTPServer) PublishConfigFile(req *restful.Request, rsp *restful.Response) { - handler := &Handler{req, rsp} + handler := &httpcommon.Handler{req, rsp} configFile := &api.ConfigFileRelease{} ctx, err := handler.Parse(configFile) @@ -227,7 +228,7 @@ func (h *HTTPServer) PublishConfigFile(req *restful.Request, rsp *restful.Respon // GetConfigFileRelease 获取配置文件最后一次发布内容 func (h *HTTPServer) GetConfigFileRelease(req *restful.Request, rsp *restful.Response) { - handler := &Handler{req, rsp} + handler := &httpcommon.Handler{req, rsp} namespace := handler.QueryParameter("namespace") group := handler.QueryParameter("group") @@ -240,7 +241,7 @@ func (h *HTTPServer) GetConfigFileRelease(req *restful.Request, rsp *restful.Res // GetConfigFileReleaseHistory 获取配置文件发布历史,按照发布时间倒序排序 func (h *HTTPServer) GetConfigFileReleaseHistory(req *restful.Request, rsp *restful.Response) { - handler := &Handler{req, rsp} + handler := &httpcommon.Handler{req, rsp} namespace := handler.QueryParameter("namespace") group := handler.QueryParameter("group") @@ -263,7 +264,7 @@ func (h *HTTPServer) GetConfigFileReleaseHistory(req *restful.Request, rsp *rest // GetAllConfigFileTemplates get all config file template func (h *HTTPServer) GetAllConfigFileTemplates(req *restful.Request, rsp *restful.Response) { - handler := &Handler{req, rsp} + handler := &httpcommon.Handler{req, rsp} response := h.configServer.GetAllConfigFileTemplates(handler.ParseHeaderContext()) @@ -272,7 +273,7 @@ func (h *HTTPServer) GetAllConfigFileTemplates(req *restful.Request, rsp *restfu // CreateConfigFileTemplate create config file template func (h *HTTPServer) CreateConfigFileTemplate(req *restful.Request, rsp *restful.Response) { - handler := &Handler{req, rsp} + handler := &httpcommon.Handler{req, rsp} configFileTemplate := &api.ConfigFileTemplate{} ctx, err := handler.Parse(configFileTemplate) diff --git a/apiserver/httpserver/config_server.go b/apiserver/httpserver/config_server.go index f15456309..ccb8fee80 100644 --- a/apiserver/httpserver/config_server.go +++ b/apiserver/httpserver/config_server.go @@ -60,35 +60,35 @@ func (h *HTTPServer) GetConfigAccessServer(include []string) (*restful.WebServic func (h *HTTPServer) bindConfigConsoleEndpoint(ws *restful.WebService) { // 配置文件组 - ws.Route(ws.POST("/configfilegroups").To(h.CreateConfigFileGroup)) - ws.Route(ws.GET("/configfilegroups").To(h.QueryConfigFileGroups)) - ws.Route(ws.DELETE("/configfilegroups").To(h.DeleteConfigFileGroup)) - ws.Route(ws.PUT("/configfilegroups").To(h.UpdateConfigFileGroup)) + ws.Route(enrichCreateConfigFileGroupApiDocs(ws.POST("/configfilegroups").To(h.CreateConfigFileGroup))) + ws.Route(enrichQueryConfigFileGroupsApiDocs(ws.GET("/configfilegroups").To(h.QueryConfigFileGroups))) + ws.Route(enrichDeleteConfigFileGroupApiDocs(ws.DELETE("/configfilegroups").To(h.DeleteConfigFileGroup))) + ws.Route(enrichUpdateConfigFileGroupApiDocs(ws.PUT("/configfilegroups").To(h.UpdateConfigFileGroup))) // 配置文件 - ws.Route(ws.POST("/configfiles").To(h.CreateConfigFile)) - ws.Route(ws.GET("/configfiles").To(h.GetConfigFile)) - ws.Route(ws.GET("/configfiles/by-group").To(h.QueryConfigFilesByGroup)) - ws.Route(ws.GET("/configfiles/search").To(h.SearchConfigFile)) - ws.Route(ws.PUT("/configfiles").To(h.UpdateConfigFile)) - ws.Route(ws.DELETE("/configfiles").To(h.DeleteConfigFile)) - ws.Route(ws.POST("/configfiles/batchdelete").To(h.BatchDeleteConfigFile)) + ws.Route(enrichCreateConfigFileApiDocs(ws.POST("/configfiles").To(h.CreateConfigFile))) + ws.Route(enrichGetConfigFileApiDocs(ws.GET("/configfiles").To(h.GetConfigFile))) + ws.Route(enrichQueryConfigFilesByGroupApiDocs(ws.GET("/configfiles/by-group").To(h.QueryConfigFilesByGroup))) + ws.Route(enrichSearchConfigFileApiDocs(ws.GET("/configfiles/search").To(h.SearchConfigFile))) + ws.Route(enrichUpdateConfigFileApiDocs(ws.PUT("/configfiles").To(h.UpdateConfigFile))) + ws.Route(enrichDeleteConfigFileApiDocs(ws.DELETE("/configfiles").To(h.DeleteConfigFile))) + ws.Route(enrichBatchDeleteConfigFileApiDocs(ws.POST("/configfiles/batchdelete").To(h.BatchDeleteConfigFile))) // 配置文件发布 - ws.Route(ws.POST("/configfiles/release").To(h.PublishConfigFile)) - ws.Route(ws.GET("/configfiles/release").To(h.GetConfigFileRelease)) + ws.Route(enrichPublishConfigFileApiDocs(ws.POST("/configfiles/release").To(h.PublishConfigFile))) + ws.Route(enrichGetConfigFileReleaseApiDocs(ws.GET("/configfiles/release").To(h.GetConfigFileRelease))) // 配置文件发布历史 - ws.Route(ws.GET("/configfiles/releasehistory").To(h.GetConfigFileReleaseHistory)) + ws.Route(enrichGetConfigFileReleaseHistoryApiDocs(ws.GET("/configfiles/releasehistory").To(h.GetConfigFileReleaseHistory))) // config file template - ws.Route(ws.GET("/configfiletemplates").To(h.GetAllConfigFileTemplates)) - ws.Route(ws.POST("/configfiletemplates").To(h.CreateConfigFileTemplate)) + ws.Route(enrichGetAllConfigFileTemplatesApiDocs(ws.GET("/configfiletemplates").To(h.GetAllConfigFileTemplates))) + ws.Route(enrichCreateConfigFileTemplateApiDocs(ws.POST("/configfiletemplates").To(h.CreateConfigFileTemplate))) } func (h *HTTPServer) bindConfigClientEndpoint(ws *restful.WebService) { - ws.Route(ws.GET("/GetConfigFile").To(h.getConfigFile)) - ws.Route(ws.POST("/WatchConfigFile").To(h.watchConfigFile)) + ws.Route(enrichGetConfigFileForClientApiDocs(ws.GET("/GetConfigFile").To(h.getConfigFile))) + ws.Route(enrichWatchConfigFileForClientApiDocs(ws.POST("/WatchConfigFile").To(h.watchConfigFile))) } // StopConfigServer 停止配置中心模块 diff --git a/apiserver/httpserver/config_server_apidoc.go b/apiserver/httpserver/config_server_apidoc.go new file mode 100644 index 000000000..b43160c9f --- /dev/null +++ b/apiserver/httpserver/config_server_apidoc.go @@ -0,0 +1,182 @@ +/** + * Tencent is pleased to support the open source community by making Polaris available. + * + * Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved. + * + * Licensed under the BSD 3-Clause License (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://opensource.org/licenses/BSD-3-Clause + * + * 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 httpserver + +import ( + "github.com/emicklei/go-restful/v3" + restfulspec "github.com/polarismesh/go-restful-openapi/v2" + + api "github.com/polarismesh/polaris-server/common/api/v1" +) + +var ( + configConsoleApiTags = []string{"ConfigConsole"} + configClientApiTags = []string{"ConfigClient"} +) + +func enrichCreateConfigFileGroupApiDocs(r *restful.RouteBuilder) *restful.RouteBuilder { + return r. + Doc("创建配置文件组"). + Metadata(restfulspec.KeyOpenAPITags, configConsoleApiTags). + Reads(api.ConfigFileGroup{}, "开启北极星服务端针对控制台接口鉴权开关后,需要添加下面的 header\nHeader X-Polaris-Token: {访问凭据}\n ```\n{\n \"name\":\"someGroup\",\n \"namespace\":\"someNamespace\",\n \"comment\":\"some comment\",\n \"createBy\":\"ledou\"\n}\n```") +} + +func enrichQueryConfigFileGroupsApiDocs(r *restful.RouteBuilder) *restful.RouteBuilder { + return r. + Doc("搜索配置文件组"). + Metadata(restfulspec.KeyOpenAPITags, configConsoleApiTags). + Param(restful.QueryParameter("namespace", "命名空间,不填表示全部命名空间").DataType("string").Required(false)). + Param(restful.QueryParameter("group", "配置文件分组名,模糊搜索").DataType("string").Required(false)). + Param(restful.QueryParameter("fileName", "配置文件名称,模糊搜索").DataType("string").Required(false)). + Param(restful.QueryParameter("offset", "翻页偏移量 默认为 0").DataType("integer").Required(false).DefaultValue("0")). + Param(restful.QueryParameter("limit", "一页大小,最大为 100").DataType("integer").Required(true).DefaultValue("100")) +} + +func enrichDeleteConfigFileGroupApiDocs(r *restful.RouteBuilder) *restful.RouteBuilder { + return r. + Doc("删除配置文件"). + Metadata(restfulspec.KeyOpenAPITags, configConsoleApiTags). + Param(restful.QueryParameter("namespace", "命名空间").DataType("string").Required(true)). + Param(restful.QueryParameter("group", "配置文件分组").DataType("string").Required(true)) +} + +func enrichUpdateConfigFileGroupApiDocs(r *restful.RouteBuilder) *restful.RouteBuilder { + return r. + Doc("更新配置文件组"). + Metadata(restfulspec.KeyOpenAPITags, configConsoleApiTags). + Reads(api.ConfigFileGroup{}, "开启北极星服务端针对控制台接口鉴权开关后,需要添加下面的 header\nHeader X-Polaris-Token: {访问凭据}\n ```\n{\n \"name\":\"someGroup\",\n \"namespace\":\"someNamespace\",\n \"comment\":\"some comment\",\n \"createBy\":\"ledou\"\n}\n```") +} + +func enrichCreateConfigFileApiDocs(r *restful.RouteBuilder) *restful.RouteBuilder { + return r. + Doc("创建配置文件"). + Metadata(restfulspec.KeyOpenAPITags, configConsoleApiTags). + Reads(api.ConfigFile{}, "开启北极星服务端针对控制台接口鉴权开关后,需要添加下面的 header\nHeader X-Polaris-Token: {访问凭据}\n ```{\n \"name\":\"application.properties\",\n \"namespace\":\"someNamespace\",\n \"group\":\"someGroup\",\n \"content\":\"redis.cache.age=10\",\n \"comment\":\"第一个配置文件\",\n \"tags\":[{\"key\":\"service\", \"value\":\"helloService\"}],\n \"createBy\":\"ledou\",\n \"format\":\"properties\"\n}\n```\n") +} + +func enrichGetConfigFileApiDocs(r *restful.RouteBuilder) *restful.RouteBuilder { + return r. + Doc("拉取配置"). + Metadata(restfulspec.KeyOpenAPITags, configConsoleApiTags). + Param(restful.QueryParameter("namespace", "命名空间").DataType("string").Required(true)). + Param(restful.QueryParameter("group", "配置文件分组").DataType("string").Required(true)). + Param(restful.QueryParameter("name", "配置文件名").DataType("string").Required(true)) +} + +func enrichQueryConfigFilesByGroupApiDocs(r *restful.RouteBuilder) *restful.RouteBuilder { + return r. + Doc("搜索配置文件"). + Metadata(restfulspec.KeyOpenAPITags, configConsoleApiTags). + Param(restful.QueryParameter("namespace", "命名空间").DataType("string").Required(false)). + Param(restful.QueryParameter("group", "配置文件分组").DataType("string").Required(false)). + Param(restful.QueryParameter("offset", "翻页偏移量 默认为 0").DataType("integer").Required(false).DefaultValue("0")). + Param(restful.QueryParameter("limit", "一页大小,最大为 100").DataType("integer").Required(true).DefaultValue("100")) +} + +func enrichSearchConfigFileApiDocs(r *restful.RouteBuilder) *restful.RouteBuilder { + return r. + Doc("搜索配置文件"). + Metadata(restfulspec.KeyOpenAPITags, configConsoleApiTags). + Param(restful.QueryParameter("namespace", "命名空间").DataType("string").Required(false)). + Param(restful.QueryParameter("group", "配置文件分组").DataType("string").Required(false)). + Param(restful.QueryParameter("name", "配置文件").DataType("string").Required(false)). + Param(restful.QueryParameter("tags", "格式:key1,value1,key2,value2").DataType("string").Required(false)). + Param(restful.QueryParameter("offset", "翻页偏移量 默认为 0").DataType("integer").Required(false).DefaultValue("0")). + Param(restful.QueryParameter("limit", "一页大小,最大为 100").DataType("integer").Required(true).DefaultValue("100")) +} + +func enrichUpdateConfigFileApiDocs(r *restful.RouteBuilder) *restful.RouteBuilder { + return r. + Doc("创建配置文件"). + Metadata(restfulspec.KeyOpenAPITags, configConsoleApiTags). + Reads(api.ConfigFile{}, "开启北极星服务端针对控制台接口鉴权开关后,需要添加下面的 header\nHeader X-Polaris-Token: {访问凭据}\n ```{\n \"name\":\"application.properties\",\n \"namespace\":\"someNamespace\",\n \"group\":\"someGroup\",\n \"content\":\"redis.cache.age=10\",\n \"comment\":\"第一个配置文件\",\n \"tags\":[{\"key\":\"service\", \"value\":\"helloService\"}],\n \"createBy\":\"ledou\",\n \"format\":\"properties\"\n}\n```\n") +} + +func enrichDeleteConfigFileApiDocs(r *restful.RouteBuilder) *restful.RouteBuilder { + return r. + Doc("创建配置文件"). + Metadata(restfulspec.KeyOpenAPITags, configConsoleApiTags). + Param(restful.QueryParameter("namespace", "命名空间").DataType("string").Required(true)). + Param(restful.QueryParameter("group", "配置文件分组").DataType("string").Required(true)). + Param(restful.QueryParameter("name", "配置文件").DataType("string").Required(true)). + Param(restful.QueryParameter("deleteBy", "操作人").DataType("string").Required(false)) +} + +func enrichBatchDeleteConfigFileApiDocs(r *restful.RouteBuilder) *restful.RouteBuilder { + return r. + Doc("批量删除配置文件"). + Metadata(restfulspec.KeyOpenAPITags, configConsoleApiTags). + Param(restful.QueryParameter("deleteBy", "操作人").DataType("string").Required(false)). + Reads(api.ConfigFile{}, "开启北极星服务端针对控制台接口鉴权开关后,需要添加下面的 header\nHeader X-Polaris-Token: {访问凭据}\n```[\n {\n \"name\":\"application.properties\",\n \"namespace\":\"someNamespace\",\n \"group\":\"someGroup\"\n }\n]\n```") +} + +func enrichPublishConfigFileApiDocs(r *restful.RouteBuilder) *restful.RouteBuilder { + return r. + Doc("发布配置文件"). + Metadata(restfulspec.KeyOpenAPITags, configConsoleApiTags). + Reads(api.ConfigFileRelease{}, "开启北极星服务端针对控制台接口鉴权开关后,需要添加下面的 header\nHeader X-Polaris-Token: {访问凭据}\n```{\n \"name\":\"release-002\",\n \"fileName\":\"application.properties\",\n \"namespace\":\"someNamespace\",\n \"group\":\"someGroup\",\n \"comment\":\"发布第一个配置文件\",\n \"createBy\":\"ledou\"\n}\n```") +} + +func enrichGetConfigFileReleaseApiDocs(r *restful.RouteBuilder) *restful.RouteBuilder { + return r. + Doc("获取配置文件最后一次全量发布信息"). + Metadata(restfulspec.KeyOpenAPITags, configConsoleApiTags). + Param(restful.QueryParameter("namespace", "命名空间").DataType("string").Required(true)). + Param(restful.QueryParameter("group", "配置文件分组").DataType("string").Required(true)). + Param(restful.QueryParameter("name", "配置文件").DataType("string").Required(true)) +} + +func enrichGetConfigFileReleaseHistoryApiDocs(r *restful.RouteBuilder) *restful.RouteBuilder { + return r. + Doc("获取配置文件发布历史记录"). + Metadata(restfulspec.KeyOpenAPITags, configConsoleApiTags). + Param(restful.QueryParameter("namespace", "命名空间").DataType("string").Required(true)). + Param(restful.QueryParameter("group", "配置文件分组").DataType("string").Required(false)). + Param(restful.QueryParameter("name", "配置文件").DataType("string").Required(false)). + Param(restful.QueryParameter("offset", "翻页偏移量 默认为 0").DataType("integer").Required(false).DefaultValue("0")). + Param(restful.QueryParameter("limit", "一页大小,最大为 100").DataType("integer").Required(true).DefaultValue("100")) +} + +func enrichGetAllConfigFileTemplatesApiDocs(r *restful.RouteBuilder) *restful.RouteBuilder { + return r. + Doc("获取配置模板"). + Metadata(restfulspec.KeyOpenAPITags, configConsoleApiTags) +} + +func enrichCreateConfigFileTemplateApiDocs(r *restful.RouteBuilder) *restful.RouteBuilder { + return r. + Doc("创建配置模板"). + Metadata(restfulspec.KeyOpenAPITags, configConsoleApiTags) +} + +func enrichGetConfigFileForClientApiDocs(r *restful.RouteBuilder) *restful.RouteBuilder { + return r. + Doc("拉取配置"). + Metadata(restfulspec.KeyOpenAPITags, configClientApiTags). + Param(restful.QueryParameter("namespace", "命名空间").DataType("string").Required(true)). + Param(restful.QueryParameter("group", "配置文件分组").DataType("string").Required(true)). + Param(restful.QueryParameter("fileName", "配置文件名").DataType("string").Required(true)). + Param(restful.QueryParameter("version", "配置文件客户端版本号,刚启动时设置为 0").DataType("integer").Required(true)) +} + +func enrichWatchConfigFileForClientApiDocs(r *restful.RouteBuilder) *restful.RouteBuilder { + return r. + Doc("监听配置"). + Metadata(restfulspec.KeyOpenAPITags, configClientApiTags). + Reads(api.ClientWatchConfigFileRequest{}, "通过 Http LongPolling 机制订阅配置变更。") +} diff --git a/apiserver/httpserver/core_console_access.go b/apiserver/httpserver/core_console_access.go index 56e9a90c2..3b8d73b6e 100644 --- a/apiserver/httpserver/core_console_access.go +++ b/apiserver/httpserver/core_console_access.go @@ -23,8 +23,13 @@ import ( "github.com/emicklei/go-restful/v3" ) +const ( + defaultReadAccess string = "default-read" + defaultAccess string = "default" +) + // GetCoreConsoleAccessServer 增加配置中心模块之后,namespace 作为两个模块的公共模块需要独立, restful path 以 /core 开头 -func (h *HTTPServer) GetCoreConsoleAccessServer(ws *restful.WebService, include []string) error { +func (h *HTTPServer) GetCoreV1ConsoleAccessServer(ws *restful.WebService, include []string) error { consoleAccess := []string{defaultAccess} if len(include) == 0 { @@ -55,15 +60,15 @@ func (h *HTTPServer) GetCoreConsoleAccessServer(ws *restful.WebService, include } func (h *HTTPServer) addCoreDefaultReadAccess(ws *restful.WebService) { - ws.Route(ws.GET("/namespaces").To(h.GetNamespaces)) - ws.Route(ws.GET("/namespaces/token").To(h.GetNamespaceToken)) + ws.Route(enrichGetNamespacesApiDocs(ws.GET("/namespaces").To(h.v1Server.GetNamespaces).Operation("CoreGetNamespaces"))) + ws.Route(enrichGetNamespaceTokenApiDocs(ws.GET("/namespaces/token").To(h.v1Server.GetNamespaceToken).Operation("CoreGetNamespaceToken"))) } func (h *HTTPServer) addCoreDefaultAccess(ws *restful.WebService) { - ws.Route(ws.POST("/namespaces").To(h.CreateNamespaces)) - ws.Route(ws.POST("/namespaces/delete").To(h.DeleteNamespaces)) - ws.Route(ws.PUT("/namespaces").To(h.UpdateNamespaces)) - ws.Route(ws.GET("/namespaces").To(h.GetNamespaces)) - ws.Route(ws.GET("/namespaces/token").To(h.GetNamespaceToken)) - ws.Route(ws.PUT("/namespaces/token").To(h.UpdateNamespaceToken)) + ws.Route(enrichCreateNamespacesApiDocs(ws.POST("/namespaces").To(h.v1Server.CreateNamespaces).Operation("CoreCreateNamespaces"))) + ws.Route(enrichDeleteNamespacesApiDocs(ws.POST("/namespaces/delete").To(h.v1Server.DeleteNamespaces).Operation("CoreDeleteNamespaces"))) + ws.Route(enrichUpdateNamespacesApiDocs(ws.PUT("/namespaces").To(h.v1Server.UpdateNamespaces).Operation("CoreUpdateNamespaces"))) + ws.Route(enrichGetNamespacesApiDocs(ws.GET("/namespaces").To(h.v1Server.GetNamespaces).Operation("CoreGetNamespaces"))) + ws.Route(enrichGetNamespaceTokenApiDocs(ws.GET("/namespaces/token").To(h.v1Server.GetNamespaceToken).Operation("CoreGetNamespaceToken"))) + ws.Route(enrichUpdateNamespaceTokenApiDocs(ws.PUT("/namespaces/token").To(h.v1Server.UpdateNamespaceToken).Operation("CoreUpdateNamespaceToken"))) } diff --git a/apiserver/httpserver/core_console_apidoc.go b/apiserver/httpserver/core_console_apidoc.go new file mode 100644 index 000000000..f22f852df --- /dev/null +++ b/apiserver/httpserver/core_console_apidoc.go @@ -0,0 +1,75 @@ +/** + * Tencent is pleased to support the open source community by making Polaris available. + * + * Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved. + * + * Licensed under the BSD 3-Clause License (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://opensource.org/licenses/BSD-3-Clause + * + * 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 httpserver + +import ( + "github.com/emicklei/go-restful/v3" + restfulspec "github.com/polarismesh/go-restful-openapi/v2" + + v1 "github.com/polarismesh/polaris-server/common/api/v1" +) + +var ( + namespaceApiTags = []string{"Namespaces"} +) + +func enrichGetNamespacesApiDocs(r *restful.RouteBuilder) *restful.RouteBuilder { + return r. + Doc("查询命名空间列表"). + Metadata(restfulspec.KeyOpenAPITags, namespaceApiTags). + Param(restful.QueryParameter("name", "命名空间唯一名称").DataType("string").Required(true)). + Param(restful.QueryParameter("offset", "查询偏移量").DataType("integer").Required(false).DefaultValue("0")). + Param(restful.QueryParameter("limit", "查询条数,**最多查询100条**").DataType("integer").Required(false)). + Notes(enrichGetNamespacesApiNotes) +} + +func enrichCreateNamespacesApiDocs(r *restful.RouteBuilder) *restful.RouteBuilder { + return r. + Doc("创建命名空间"). + Metadata(restfulspec.KeyOpenAPITags, namespaceApiTags). + Reads([]v1.Namespace{}, "create namespaces"). + Notes(enrichCreateNamespacesApiNotes) +} + +func enrichDeleteNamespacesApiDocs(r *restful.RouteBuilder) *restful.RouteBuilder { + return r. + Doc("删除命名空间"). + Metadata(restfulspec.KeyOpenAPITags, namespaceApiTags). + Reads([]v1.Namespace{}, "delete namespaces"). + Notes(enrichDeleteNamespacesApiNotes) +} + +func enrichUpdateNamespacesApiDocs(r *restful.RouteBuilder) *restful.RouteBuilder { + return r. + Doc("更新命名空间"). + Metadata(restfulspec.KeyOpenAPITags, namespaceApiTags). + Reads([]v1.Namespace{}, "update namespaces"). + Notes(enrichUpdateNamespacesApiNotes) +} + +func enrichGetNamespaceTokenApiDocs(r *restful.RouteBuilder) *restful.RouteBuilder { + return r. + Doc("查询命名空间Token"). + Metadata(restfulspec.KeyOpenAPITags, namespaceApiTags).Deprecate() +} + +func enrichUpdateNamespaceTokenApiDocs(r *restful.RouteBuilder) *restful.RouteBuilder { + return r. + Doc("更新命名空间Token"). + Metadata(restfulspec.KeyOpenAPITags, namespaceApiTags).Deprecate() +} diff --git a/apiserver/httpserver/core_console_apinotes.go b/apiserver/httpserver/core_console_apinotes.go new file mode 100644 index 000000000..8e36c43b4 --- /dev/null +++ b/apiserver/httpserver/core_console_apinotes.go @@ -0,0 +1,174 @@ +/** + * Tencent is pleased to support the open source community by making Polaris available. + * + * Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved. + * + * Licensed under the BSD 3-Clause License (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://opensource.org/licenses/BSD-3-Clause + * + * 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 httpserver + +const ( + enrichGetNamespacesApiNotes = ` +| 参数名 | 类型 | 描述 | 是否必填 | +| ------ | ------ | ------------------------------------------------ | -------- | +| name | string | 命名空间唯一名称 | 是 | +| offset | uint | 查询偏移量 | 否 | +| limit | uint | 查询条数,**最多查询100条** | 否 | + + +请求示例: + +~~~ +GET /{core|naming}/v1/namespaces?name=&offset=&limit= + +# 开启北极星服务端针对控制台接口鉴权开关后,需要添加下面的 header +Header X-Polaris-Token: {访问凭据} +~~~ + +应答示例: +~~~json +{ + "code": 200000, + "info": "execute success", + "amount": 0, + "size": 3, + "namespaces": [ + { + "name": "...", + "comment": "", + "ctime": "2021-11-22 23:50:52", + "mtime": "2021-11-22 23:50:52" + }, + { + "name": "...", + "comment": "", + "ctime": "2021-11-22 23:50:52", + "mtime": "2021-11-22 23:50:52" + } + ] +} +~~~ +` + enrichCreateNamespacesApiNotes = ` +| 参数名 | 类型 | 描述 | 是否必填 | +| ---------------- | -------- | ---------------------------------------------------------- | -------- | +| name | string | 命名空间唯一名称 | 是 | +| comment | string | 描述 | 否 | +| user_ids | []string | 可以操作该资源的用户,**仅当开启北极星鉴权时生效** | 否 | +| group_ids | []string | 可以操作该资源的用户组,,**仅当开启北极星鉴权时生效** | 否 | +| remove_user_ids | []string | 被移除的可操作该资源的用户,**仅当开启北极星鉴权时生效** | 否 | +| remove_group_ids | []string | 被移除的可操作该资源的用户组,**仅当开启北极星鉴权时生效** | 否 | + + +请求示例: + +~~~ +POST /{core|naming}/v1/namespaces + +# 开启北极星服务端针对控制台接口鉴权开关后,需要添加下面的 header +Header X-Polaris-Token: {访问凭据} + +[ + { + "name": "...", + "comment": "..." + } +] +~~~ + +应答示例: +~~~json +{ + "code":200000, + "info":"...", + "size":1, + "responses":[ + { + "code":200000, + "info":"execute success", + "namespace":{ + "name":"...", + "token":"..." + } + } + ] +} +~~~ +` + enrichUpdateNamespacesApiNotes = ` +| 参数名 | 类型 | 描述 | 是否必填 | +| ---------------- | -------- | ---------------------------------------------------------- | -------- | +| name | string | 命名空间唯一名称 | 是 | +| comment | string | 描述 | 否 | +| token | string | 命名空间的token,用于权限鉴定 | 是 | +| user_ids | []string | 可以操作该资源的用户,**仅当开启北极星鉴权时生效** | 否 | +| group_ids | []string | 可以操作该资源的用户组,,**仅当开启北极星鉴权时生效** | 否 | +| remove_user_ids | []string | 被移除的可操作该资源的用户,**仅当开启北极星鉴权时生效** | 否 | +| remove_group_ids | []string | 被移除的可操作该资源的用户组,**仅当开启北极星鉴权时生效** | 否 | + +请求示例: + +~~~ +PUT /{core|naming}/v1/namespaces + +# 开启北极星服务端针对控制台接口鉴权开关后,需要添加下面的 header +Header X-Polaris-Token: {访问凭据} + +[ + { + "name": "...", + "comment": "..." + } +] +~~~ + +应答示例: +~~~json +{ + "code": 200000, + "info": "execute success", + "size": 0 +} +~~~ +` + enrichDeleteNamespacesApiNotes = ` +| 参数名 | 类型 | 描述 | 是否必填 | +| ------ | ------ | ----------------------------- | -------- | +| name | string | 命名空间唯一名称 | 是 | +| token | string | 命名空间的token,用于权限鉴定 | 是 | + +请求示例: + +~~~ +POST /{core|naming}/v1/namespaces/delete + +# 开启北极星服务端针对控制台接口鉴权开关后,需要添加下面的 header +Header X-Polaris-Token: {访问凭据} + +[ + { + "name": "...", + } +] +~~~ + +应答示例: +~~~json +{ + "code": 200000, + "info": "execute success", + "size": 0 +} +~~~ +` +) diff --git a/apiserver/httpserver/handler.go b/apiserver/httpserver/http/handler.go similarity index 83% rename from apiserver/httpserver/handler.go rename to apiserver/httpserver/http/handler.go index cb5aaf4d1..3ac474aa5 100644 --- a/apiserver/httpserver/handler.go +++ b/apiserver/httpserver/http/handler.go @@ -15,7 +15,7 @@ * specific language governing permissions and limitations under the License. */ -package httpserver +package http import ( "context" @@ -32,6 +32,8 @@ import ( "github.com/polarismesh/polaris-server/apiserver/httpserver/i18n" api "github.com/polarismesh/polaris-server/common/api/v1" + apiv2 "github.com/polarismesh/polaris-server/common/api/v2" + "github.com/polarismesh/polaris-server/common/log" "github.com/polarismesh/polaris-server/common/utils" ) @@ -178,6 +180,30 @@ func (h *Handler) WriteHeaderAndProto(obj api.ResponseMessage) { } } +// WriteHeaderAndProto 返回Code和Proto +func (h *Handler) WriteHeaderAndProtoV2(obj apiv2.ResponseMessage) { + requestID := h.Request.HeaderParameter(utils.PolarisRequestID) + h.Request.SetAttribute(utils.PolarisCode, obj.GetCode()) + status := apiv2.CalcCode(obj) + + if status != http.StatusOK { + log.Error(obj.String(), zap.String("request-id", requestID)) + } + if code := obj.GetCode(); code != api.ExecuteSuccess { + h.Response.AddHeader(utils.PolarisCode, fmt.Sprintf("%d", code)) + h.Response.AddHeader(utils.PolarisMessage, api.Code2Info(code)) + } + + h.Response.AddHeader(utils.PolarisRequestID, requestID) + h.Response.WriteHeader(status) + + m := jsonpb.Marshaler{Indent: " ", EmitDefaults: true} + err := m.Marshal(h.Response, obj) + if err != nil { + log.Error(err.Error(), zap.String("request-id", requestID)) + } +} + // HTTPResponse http答复简单封装 func HTTPResponse(req *restful.Request, rsp *restful.Response, code uint32) { handler := &Handler{req, rsp} @@ -191,15 +217,27 @@ func HTTPResponse(req *restful.Request, rsp *restful.Response, code uint32) { func (h *Handler) i18n(obj api.ResponseMessage) api.ResponseMessage { hMsg := h.Response.Header().Get(utils.PolarisMessage) info := obj.GetInfo() - if hMsg != info.Value { + if hMsg != info.GetValue() { return obj } code := obj.GetCode() msg, err := i18n.Translate( - code.Value, h.Request.QueryParameter("lang"), h.Request.HeaderParameter("Accept-Language")) + code.GetValue(), h.Request.QueryParameter("lang"), h.Request.HeaderParameter("Accept-Language")) if msg == "" || err != nil { return obj } *info = wrappers.StringValue{Value: msg} return obj } + +// parseQueryParams 解析并获取HTTP的query params +func ParseQueryParams(req *restful.Request) map[string]string { + queryParams := make(map[string]string) + for key, value := range req.Request.URL.Query() { + if len(value) > 0 { + queryParams[key] = value[0] // 暂时默认只支持一个查询 + } + } + + return queryParams +} diff --git a/apiserver/httpserver/handler_test.go b/apiserver/httpserver/http/handler_test.go similarity index 96% rename from apiserver/httpserver/handler_test.go rename to apiserver/httpserver/http/handler_test.go index 0eebb9cbf..001585e85 100644 --- a/apiserver/httpserver/handler_test.go +++ b/apiserver/httpserver/http/handler_test.go @@ -15,7 +15,7 @@ * specific language governing permissions and limitations under the License. */ -package httpserver +package http import ( "net/http" @@ -31,8 +31,8 @@ import ( ) func init() { - i18n.LoadI18nMessageFile("i18n/en.toml") - i18n.LoadI18nMessageFile("i18n/zh.toml") + i18n.LoadI18nMessageFile("../i18n/en.toml") + i18n.LoadI18nMessageFile("../i18n/zh.toml") } func Test_i18n(t *testing.T) { diff --git a/apiserver/httpserver/i18n/cmd/gen.go b/apiserver/httpserver/i18n/cmd/gen.go index 30f943a33..233acbbb2 100644 --- a/apiserver/httpserver/i18n/cmd/gen.go +++ b/apiserver/httpserver/i18n/cmd/gen.go @@ -81,7 +81,7 @@ func generateI18nMessageSrc(fileName string) { func getSrcCodeInfo() []errCodeItem { fset := token.NewFileSet() - f, err := parser.ParseFile(fset, "../../../common/api/v1/codeinfo.go", nil, parser.ParseComments) + f, err := parser.ParseFile(fset, "../../../../common/api/v1/codeinfo.go", nil, parser.ParseComments) if err != nil { panic(err) } diff --git a/apiserver/httpserver/i18n/en.toml b/apiserver/httpserver/i18n/en.toml index 78d7c369c..0ebb5fc78 100644 --- a/apiserver/httpserver/i18n/en.toml +++ b/apiserver/httpserver/i18n/en.toml @@ -1,152 +1,158 @@ -200000 = "execute success" #ExecuteSuccess -200001 = "discover data is no change" #DataNoChange -200002 = "update data is no change, no need to update" #NoNeedUpdate -400000 = "bad request" #BadRequest -400001 = "request decode failed" #ParseException -400002 = "empty request" #EmptyRequest -400003 = "batch size over the limit" #BatchSizeOverLimit -400004 = "invalid discover resource" #InvalidDiscoverResource -400100 = "invalid request id" #InvalidRequestID -400101 = "invalid user name" #InvalidUserName -400102 = "invalid user token" #InvalidUserToken -400103 = "invalid parameter" #InvalidParameter -400104 = "query instance parameter is empty" #EmptyQueryParameter -400105 = "query instance, (service,namespace) or host is required" #InvalidQueryInsParameter -400110 = "invalid namespace name" #InvalidNamespaceName -400111 = "invalid namespace owners" #InvalidNamespaceOwners -400112 = "invalid namespace token" #InvalidNamespaceToken -400120 = "invalid service name" #InvalidServiceName -400121 = "invalid service owners" #InvalidServiceOwners -400122 = "invalid service token" #InvalidServiceToken -400123 = "invalid service metadata" #InvalidServiceMetadata -400124 = "invalid service ports" #InvalidServicePorts -400125 = "invalid service business" #InvalidServiceBusiness -400126 = "invalid service department" #InvalidServiceDepartment -400127 = "invalid service CMDB" #InvalidServiceCMDB -400128 = "invalid service comment" #InvalidServiceComment -400129 = "invalid service alias comment" #InvalidServiceAliasComment -400130 = "invalid instance id" #InvalidInstanceID -400131 = "invalid instance host" #InvalidInstanceHost -400132 = "invalid instance port" #InvalidInstancePort -400133 = "invalid service alias" #InvalidServiceAlias -400134 = "request namespace is not allow to create sid type alias" #InvalidNamespaceWithAlias -400135 = "invalid service alias owners" #InvalidServiceAliasOwners -400136 = "invalid instance protocol" #InvalidInstanceProtocol -400137 = "invalid instance version" #InvalidInstanceVersion -400138 = "invalid instance logic set" #InvalidInstanceLogicSet -400139 = "invalid instance isolate" #InvalidInstanceIsolate -400140 = "server not open health check" #HealthCheckNotOpen -400141 = "heartbeat on disabled instance" #HeartbeatOnDisabledIns -400142 = "instance can only heartbeat 1 time per second" #HeartbeatExceedLimit -400143 = "heartbeat type not found" #HeartbeatTypeNotFound -400150 = "the length of metadata is too long or metadata contains invalid characters" #InvalidMetadata -400151 = "invalid rate limit id" #InvalidRateLimitID -400152 = "invalid rate limit labels" #InvalidRateLimitLabels -400153 = "invalid rate limit amounts" #InvalidRateLimitAmounts -400154 = "invalid rate limit name" #InvalidRateLimitName -400160 = "invalid circuit breaker id" #InvalidCircuitBreakerID -400161 = "invalid circuit breaker version" #InvalidCircuitBreakerVersion -400162 = "invalid circuit breaker name" #InvalidCircuitBreakerName -400163 = "invalid circuit breaker namespace" #InvalidCircuitBreakerNamespace -400164 = "invalid circuit breaker owners" #InvalidCircuitBreakerOwners -400165 = "invalid circuit breaker token" #InvalidCircuitBreakerToken -400166 = "invalid circuit breaker business" #InvalidCircuitBreakerBusiness -400167 = "invalid circuit breaker department" #InvalidCircuitBreakerDepartment -400168 = "invalid circuit breaker comment" #InvalidCircuitBreakerComment -400170 = "services existed mesh" #ServicesExistedMesh -400171 = "resources existed mesh" #ResourcesExistedMesh -400172 = "invalid mesh parameter" #InvalidMeshParameter -400180 = "invalid platform id" #InvalidPlatformID -400181 = "invalid platform name" #InvalidPlatformName -400182 = "invalid platform domain" #InvalidPlatformDomain -400183 = "invalid platform qps" #InvalidPlatformQPS -400184 = "invalid platform token" #InvalidPlatformToken -400185 = "invalid platform owner" #InvalidPlatformOwner -400186 = "invalid platform department" #InvalidPlatformDepartment -400187 = "invalid platform comment" #InvalidPlatformComment -400188 = "not found platform" #NotFoundPlatform -400190 = "invalid flux ratelimit id" #InvalidFluxRateLimitId -400191 = "invalid flux ratelimit qps" #InvalidFluxRateLimitQps -400192 = "invalid flux ratelimit key" #InvalidFluxRateLimitSetKey -400201 = "existed resource" #ExistedResource -400202 = "not found resource" #NotFoundResource -400203 = "some services existed in namespace" #NamespaceExistedServices -400204 = "some instances existed in service" #ServiceExistedInstances -400205 = "some routings existed in service" #ServiceExistedRoutings -400206 = "some rate limits existed in service" #ServiceExistedRateLimits -400207 = "exist released config" #ExistReleasedConfig -400208 = "the same instance request" #SameInstanceRequest -400209 = "some circuit breakers existed in service" #ServiceExistedCircuitBreakers -400210 = "some aliases existed in service" #ServiceExistedAlias -400211 = "some mesh resources existed in namespace" #NamespaceExistedMeshResources -400212 = "some circuit breakers existed in namespace" #NamespaceExistedCircuitBreakers -400213 = "service subscribed by some mesh" #ServiceSubscribedByMeshes -400214 = "service existed flux rate limits" #ServiceExistedFluxRateLimits -400215 = "exist user" #UserExisted -400216 = "exist usergroup" #UserGroupExisted -400217 = "exist auth strategy rule" #AuthStrategyRuleExisted -400218 = "some sub-account existed in owner" #SubAccountExisted -400301 = "not found service" #NotFoundService -400302 = "not found routing" #NotFoundRouting -400303 = "not found instances" #NotFoundInstance -400304 = "not found service alias" #NotFoundServiceAlias -400305 = "not found namespace" #NotFoundNamespace -400306 = "not found the source service link with the alias" #NotFoundSourceService -400307 = "not found rate limit" #NotFoundRateLimit -400308 = "not found circuit breaker" #NotFoundCircuitBreaker -400309 = "not found master config" #NotFoundMasterConfig -400310 = "not found tag config" #NotFoundTagConfig -400311 = "not found tag config or service, or relation already exists" #NotFoundTagConfigOrService -400312 = "not found user" #NotFoundUser -400313 = "not found owner user" #NotFoundOwnerUser -400314 = "not found usergroup" #NotFoundUserGroup -400315 = "not found auth strategy rule" #NotFoundAuthStrategyRule -400401 = "client api is not open" #ClientAPINotOpen -400402 = "not allow requesting business service" #NotAllowBusinessService -400410 = "invalid user owners" #InvalidUserOwners -400411 = "invalid user-id" #InvalidUserID -400412 = "invalid user password" #InvalidUserPassword -400413 = "invalid user mobile" #InvalidUserMobile -400414 = "invalid user email" #InvalidUserEmail -400420 = "invalid usergroup owner attribute" #InvalidUserGroupOwners -400421 = "invalid usergroup id" #InvalidUserGroupID -400430 = "invalid auth strategy rule owner" #InvalidAuthStrategyOwners -400431 = "invalid auth strategy rule name" #InvalidAuthStrategyName -400432 = "invalid auth strategy id" #InvalidAuthStrategyID -400440 = "invalid principal type" #InvalidPrincipalType -400501 = "not allow service alias updating" #NotAllowAliasUpdate -400502 = "not allow service alias creating instance" #NotAllowAliasCreateInstance -400503 = "not allow service alias creating routing config" #NotAllowAliasCreateRouting -400504 = "only source service can create alias" #NotAllowCreateAliasForAlias -400505 = "not allow service alias creating rate limit" #NotAllowAliasCreateRateLimit -400506 = "not allow service alias binding rule" #NotAllowAliasBindRule -400507 = "not allow different namespace binding rule" #NotAllowDifferentNamespaceBindRule -400508 = "not allow modify default strategy principal" #NotAllowModifyDefaultStrategyPrincipal -400801 = "invalid config file group name" #InvalidConfigFileGroupName -400802 = "invalid config file name" #InvalidConfigFileName -400803 = "config file content too long" #InvalidConfigFileContentLength -400804 = "invalid config file format, support json,xml,html,properties,text,yaml" #InvalidConfigFileFormat -400805 = "invalid config file tags, tags should be pair, like key1,value1,key2,value2. and key,value should not blank" #InvalidConfigFileTags -400806 = "invalid watch config file format" #InvalidWatchConfigFileFormat -400807 = "config file not existed" #NotFoundResourceConfigFile -400808 = "invalid config file template name" #InvalidConfigFileTemplateName -401000 = "unauthorized" #Unauthorized -401001 = "access is not approved" #NotAllowedAccess -401002 = "auth token empty" #EmptyAutToken -401003 = "token already disabled" #TokenDisabled -401004 = "token not existed" #TokenNotExisted -403001 = "server limit the ip access" #IPRateLimit -403002 = "server limit the api access" #APIRateLimit -404001 = "not found the host cmdb" #CMDBNotFindHost -409000 = "data is conflict, please try again" #DataConflict -429001 = "your instance has too many requests" #InstanceTooManyRequests -500000 = "execute exception" #ExecuteException -500001 = "store layer exception" #StoreLayerException -500002 = "cmdb plugin exception" #CMDBPluginException -500004 = "parsing routing failed" #ParseRoutingException -500005 = "parse rate limit failed" #ParseRateLimitException -500006 = "parse circuit breaker failed" #ParseCircuitBreakerException -500007 = "heartbeat execute exception" #HeartbeatException -500008 = "instance async regist timeout" #InstanceRegisTimeout -500100 = "token verify exception" #AuthTokenVerifyException -500101 = "operation role exception" #OperationRoleException +200000 = "execute success" #ExecuteSuccess +200001 = "discover data is no change" #DataNoChange +200002 = "update data is no change, no need to update" #NoNeedUpdate +400000 = "bad request" #BadRequest +400001 = "request decode failed" #ParseException +400002 = "empty request" #EmptyRequest +400003 = "batch size over the limit" #BatchSizeOverLimit +400004 = "invalid discover resource" #InvalidDiscoverResource +400100 = "invalid request id" #InvalidRequestID +400101 = "invalid user name" #InvalidUserName +400102 = "invalid user token" #InvalidUserToken +400103 = "invalid parameter" #InvalidParameter +400104 = "query instance parameter is empty" #EmptyQueryParameter +400105 = "query instance, (service,namespace) or host is required" #InvalidQueryInsParameter +400110 = "invalid namespace name" #InvalidNamespaceName +400111 = "invalid namespace owners" #InvalidNamespaceOwners +400112 = "invalid namespace token" #InvalidNamespaceToken +400120 = "invalid service name" #InvalidServiceName +400121 = "invalid service owners" #InvalidServiceOwners +400122 = "invalid service token" #InvalidServiceToken +400123 = "invalid service metadata" #InvalidServiceMetadata +400124 = "invalid service ports" #InvalidServicePorts +400125 = "invalid service business" #InvalidServiceBusiness +400126 = "invalid service department" #InvalidServiceDepartment +400127 = "invalid service CMDB" #InvalidServiceCMDB +400128 = "invalid service comment" #InvalidServiceComment +400129 = "invalid service alias comment" #InvalidServiceAliasComment +400130 = "invalid instance id" #InvalidInstanceID +400131 = "invalid instance host" #InvalidInstanceHost +400132 = "invalid instance port" #InvalidInstancePort +400133 = "invalid service alias" #InvalidServiceAlias +400134 = "request namespace is not allow to create sid type alias" #InvalidNamespaceWithAlias +400135 = "invalid service alias owners" #InvalidServiceAliasOwners +400136 = "invalid instance protocol" #InvalidInstanceProtocol +400137 = "invalid instance version" #InvalidInstanceVersion +400138 = "invalid instance logic set" #InvalidInstanceLogicSet +400139 = "invalid instance isolate" #InvalidInstanceIsolate +400140 = "server not open health check" #HealthCheckNotOpen +400141 = "heartbeat on disabled instance" #HeartbeatOnDisabledIns +400142 = "instance can only heartbeat 1 time per second" #HeartbeatExceedLimit +400143 = "" #HeartbeatTypeNotFound +400150 = "the length of metadata is too long or metadata contains invalid characters" #InvalidMetadata +400151 = "invalid rate limit id" #InvalidRateLimitID +400152 = "invalid rate limit labels" #InvalidRateLimitLabels +400153 = "invalid rate limit amounts" #InvalidRateLimitAmounts +400154 = "" #InvalidRateLimitName +400160 = "invalid circuit breaker id" #InvalidCircuitBreakerID +400161 = "invalid circuit breaker version" #InvalidCircuitBreakerVersion +400162 = "invalid circuit breaker name" #InvalidCircuitBreakerName +400163 = "invalid circuit breaker namespace" #InvalidCircuitBreakerNamespace +400164 = "invalid circuit breaker owners" #InvalidCircuitBreakerOwners +400165 = "invalid circuit breaker token" #InvalidCircuitBreakerToken +400166 = "invalid circuit breaker business" #InvalidCircuitBreakerBusiness +400167 = "invalid circuit breaker department" #InvalidCircuitBreakerDepartment +400168 = "invalid circuit breaker comment" #InvalidCircuitBreakerComment +400170 = "services existed mesh" #ServicesExistedMesh +400171 = "resources existed mesh" #ResourcesExistedMesh +400172 = "invalid mesh parameter" #InvalidMeshParameter +400180 = "invalid platform id" #InvalidPlatformID +400181 = "invalid platform name" #InvalidPlatformName +400182 = "invalid platform domain" #InvalidPlatformDomain +400183 = "invalid platform qps" #InvalidPlatformQPS +400184 = "invalid platform token" #InvalidPlatformToken +400185 = "invalid platform owner" #InvalidPlatformOwner +400186 = "invalid platform department" #InvalidPlatformDepartment +400187 = "invalid platform comment" #InvalidPlatformComment +400188 = "not found platform" #NotFoundPlatform +400190 = "invalid flux ratelimit id" #InvalidFluxRateLimitId +400191 = "invalid flux ratelimit qps" #InvalidFluxRateLimitQps +400192 = "invalid flux ratelimit key" #InvalidFluxRateLimitSetKey +400201 = "existed resource" #ExistedResource +400202 = "not found resource" #NotFoundResource +400203 = "some services existed in namespace" #NamespaceExistedServices +400204 = "some instances existed in service" #ServiceExistedInstances +400205 = "some routings existed in service" #ServiceExistedRoutings +400206 = "some rate limits existed in service" #ServiceExistedRateLimits +400207 = "exist released config" #ExistReleasedConfig +400208 = "the same instance request" #SameInstanceRequest +400209 = "some circuit breakers existed in service" #ServiceExistedCircuitBreakers +400210 = "some aliases existed in service" #ServiceExistedAlias +400211 = "some mesh resources existed in namespace" #NamespaceExistedMeshResources +400212 = "some circuit breakers existed in namespace" #NamespaceExistedCircuitBreakers +400213 = "service subscribed by some mesh" #ServiceSubscribedByMeshes +400214 = "" #ServiceExistedFluxRateLimits +400215 = "exist user" #UserExisted +400216 = "exist usergroup" #UserGroupExisted +400217 = "exist auth strategy rule" #AuthStrategyRuleExisted +400218 = "some sub-account existed in owner" #SubAccountExisted +400219 = "some config group existed in namespace" #NamespaceExistedConfigGroups +400301 = "not found service" #NotFoundService +400302 = "not found routing" #NotFoundRouting +400303 = "not found instances" #NotFoundInstance +400304 = "not found service alias" #NotFoundServiceAlias +400305 = "not found namespace" #NotFoundNamespace +400306 = "not found the source service link with the alias" #NotFoundSourceService +400307 = "not found rate limit" #NotFoundRateLimit +400308 = "not found circuit breaker" #NotFoundCircuitBreaker +400309 = "not found master config" #NotFoundMasterConfig +400310 = "not found tag config" #NotFoundTagConfig +400311 = "not found tag config or service, or relation already exists" #NotFoundTagConfigOrService +400312 = "not found user" #NotFoundUser +400313 = "not found owner user" #NotFoundOwnerUser +400314 = "not found usergroup" #NotFoundUserGroup +400315 = "not found auth strategy rule" #NotFoundAuthStrategyRule +400401 = "client api is not open" #ClientAPINotOpen +400402 = "not allow requesting business service" #NotAllowBusinessService +400410 = "" #InvalidUserOwners +400411 = "invalid user-id" #InvalidUserID +400412 = "invalid user password" #InvalidUserPassword +400413 = "" #InvalidUserMobile +400414 = "" #InvalidUserEmail +400420 = "invalid usergroup owner attribute" #InvalidUserGroupOwners +400421 = "" #InvalidUserGroupID +400430 = "invalid auth strategy rule owner" #InvalidAuthStrategyOwners +400431 = "invalid auth strategy rule name" #InvalidAuthStrategyName +400432 = "" #InvalidAuthStrategyID +400440 = "invalid principal type" #InvalidPrincipalType +400501 = "not allow service alias updating" #NotAllowAliasUpdate +400502 = "not allow service alias creating instance" #NotAllowAliasCreateInstance +400503 = "not allow service alias creating routing config" #NotAllowAliasCreateRouting +400504 = "only source service can create alias" #NotAllowCreateAliasForAlias +400505 = "not allow service alias creating rate limit" #NotAllowAliasCreateRateLimit +400506 = "not allow service alias binding rule" #NotAllowAliasBindRule +400507 = "not allow different namespace binding rule" #NotAllowDifferentNamespaceBindRule +400508 = "not allow modify default strategy principal" #NotAllowModifyDefaultStrategyPrincipal +400509 = "not allow modify main account default strategy" #NotAllowModifyOwnerDefaultStrategy +400700 = "invalid routing id" #InvalidRoutingID +400701 = "invalid routing policy, only support (RulePolicy,MetadataPolicy)" #InvalidRoutingPolicy +400702 = "invalid routing name" #InvalidRoutingName +400703 = "invalid routing priority, only support [0, 10]" #InvalidRoutingPriority +400801 = "invalid config file group name" #InvalidConfigFileGroupName +400802 = "invalid config file name" #InvalidConfigFileName +400803 = "config file content too long" #InvalidConfigFileContentLength +400804 = "invalid config file format, support json,xml,html,properties,text,yaml" #InvalidConfigFileFormat +400805 = "invalid config file tags, tags should be pair, like key1,value1,key2,value2. and key,value should not blank" #InvalidConfigFileTags +400806 = "invalid watch config file format" #InvalidWatchConfigFileFormat +400807 = "config file not existed" #NotFoundResourceConfigFile +400808 = "invalid config file template name" #InvalidConfigFileTemplateName +401000 = "unauthorized" #Unauthorized +401001 = "access is not approved" #NotAllowedAccess +401002 = "auth token empty" #EmptyAutToken +401003 = "token already disabled" #TokenDisabled +401004 = "token not existed" #TokenNotExisted +403001 = "server limit the ip access" #IPRateLimit +403002 = "server limit the api access" #APIRateLimit +404001 = "not found the host cmdb" #CMDBNotFindHost +409000 = "data is conflict, please try again" #DataConflict +429001 = "your instance has too many requests" #InstanceTooManyRequests +500000 = "execute exception" #ExecuteException +500001 = "store layer exception" #StoreLayerException +500002 = "cmdb plugin exception" #CMDBPluginException +500004 = "parsing routing failed" #ParseRoutingException +500005 = "parse rate limit failed" #ParseRateLimitException +500006 = "parse circuit breaker failed" #ParseCircuitBreakerException +500007 = "heartbeat execute exception" #HeartbeatException +500008 = "instance async regist timeout" #InstanceRegisTimeout +500100 = "token verify exception" #AuthTokenVerifyException +500101 = "operation role exception" #OperationRoleException \ No newline at end of file diff --git a/apiserver/httpserver/i18n/messages.genearate.go b/apiserver/httpserver/i18n/messages.genearate.go index 4a071d593..0d75d3a8d 100644 --- a/apiserver/httpserver/i18n/messages.genearate.go +++ b/apiserver/httpserver/i18n/messages.genearate.go @@ -16,169 +16,174 @@ * specific language governing permissions and limitations under the License. */ -package i18n + package i18n -import ( - "fmt" - - ii18n "github.com/nicksnyder/go-i18n/v2/i18n" - - api "github.com/polarismesh/polaris-server/common/api/v1" -) - -func init() { - i18nMsgCache = map[uint32]*ii18n.Message{ - api.ExecuteSuccess: {ID: fmt.Sprint(api.ExecuteSuccess)}, - api.DataNoChange: {ID: fmt.Sprint(api.DataNoChange)}, - api.NoNeedUpdate: {ID: fmt.Sprint(api.NoNeedUpdate)}, - api.BadRequest: {ID: fmt.Sprint(api.BadRequest)}, - api.ParseException: {ID: fmt.Sprint(api.ParseException)}, - api.EmptyRequest: {ID: fmt.Sprint(api.EmptyRequest)}, - api.BatchSizeOverLimit: {ID: fmt.Sprint(api.BatchSizeOverLimit)}, - api.InvalidDiscoverResource: {ID: fmt.Sprint(api.InvalidDiscoverResource)}, - api.InvalidRequestID: {ID: fmt.Sprint(api.InvalidRequestID)}, - api.InvalidUserName: {ID: fmt.Sprint(api.InvalidUserName)}, - api.InvalidUserToken: {ID: fmt.Sprint(api.InvalidUserToken)}, - api.InvalidParameter: {ID: fmt.Sprint(api.InvalidParameter)}, - api.EmptyQueryParameter: {ID: fmt.Sprint(api.EmptyQueryParameter)}, - api.InvalidQueryInsParameter: {ID: fmt.Sprint(api.InvalidQueryInsParameter)}, - api.InvalidNamespaceName: {ID: fmt.Sprint(api.InvalidNamespaceName)}, - api.InvalidNamespaceOwners: {ID: fmt.Sprint(api.InvalidNamespaceOwners)}, - api.InvalidNamespaceToken: {ID: fmt.Sprint(api.InvalidNamespaceToken)}, - api.InvalidServiceName: {ID: fmt.Sprint(api.InvalidServiceName)}, - api.InvalidServiceOwners: {ID: fmt.Sprint(api.InvalidServiceOwners)}, - api.InvalidServiceToken: {ID: fmt.Sprint(api.InvalidServiceToken)}, - api.InvalidServiceMetadata: {ID: fmt.Sprint(api.InvalidServiceMetadata)}, - api.InvalidServicePorts: {ID: fmt.Sprint(api.InvalidServicePorts)}, - api.InvalidServiceBusiness: {ID: fmt.Sprint(api.InvalidServiceBusiness)}, - api.InvalidServiceDepartment: {ID: fmt.Sprint(api.InvalidServiceDepartment)}, - api.InvalidServiceCMDB: {ID: fmt.Sprint(api.InvalidServiceCMDB)}, - api.InvalidServiceComment: {ID: fmt.Sprint(api.InvalidServiceComment)}, - api.InvalidServiceAliasComment: {ID: fmt.Sprint(api.InvalidServiceAliasComment)}, - api.InvalidInstanceID: {ID: fmt.Sprint(api.InvalidInstanceID)}, - api.InvalidInstanceHost: {ID: fmt.Sprint(api.InvalidInstanceHost)}, - api.InvalidInstancePort: {ID: fmt.Sprint(api.InvalidInstancePort)}, - api.InvalidServiceAlias: {ID: fmt.Sprint(api.InvalidServiceAlias)}, - api.InvalidNamespaceWithAlias: {ID: fmt.Sprint(api.InvalidNamespaceWithAlias)}, - api.InvalidServiceAliasOwners: {ID: fmt.Sprint(api.InvalidServiceAliasOwners)}, - api.InvalidInstanceProtocol: {ID: fmt.Sprint(api.InvalidInstanceProtocol)}, - api.InvalidInstanceVersion: {ID: fmt.Sprint(api.InvalidInstanceVersion)}, - api.InvalidInstanceLogicSet: {ID: fmt.Sprint(api.InvalidInstanceLogicSet)}, - api.InvalidInstanceIsolate: {ID: fmt.Sprint(api.InvalidInstanceIsolate)}, - api.HealthCheckNotOpen: {ID: fmt.Sprint(api.HealthCheckNotOpen)}, - api.HeartbeatOnDisabledIns: {ID: fmt.Sprint(api.HeartbeatOnDisabledIns)}, - api.HeartbeatExceedLimit: {ID: fmt.Sprint(api.HeartbeatExceedLimit)}, - api.HeartbeatTypeNotFound: {ID: fmt.Sprint(api.HeartbeatTypeNotFound)}, - api.InvalidMetadata: {ID: fmt.Sprint(api.InvalidMetadata)}, - api.InvalidRateLimitID: {ID: fmt.Sprint(api.InvalidRateLimitID)}, - api.InvalidRateLimitLabels: {ID: fmt.Sprint(api.InvalidRateLimitLabels)}, - api.InvalidRateLimitAmounts: {ID: fmt.Sprint(api.InvalidRateLimitAmounts)}, - api.InvalidRateLimitName: {ID: fmt.Sprint(api.InvalidRateLimitName)}, - api.InvalidCircuitBreakerID: {ID: fmt.Sprint(api.InvalidCircuitBreakerID)}, - api.InvalidCircuitBreakerVersion: {ID: fmt.Sprint(api.InvalidCircuitBreakerVersion)}, - api.InvalidCircuitBreakerName: {ID: fmt.Sprint(api.InvalidCircuitBreakerName)}, - api.InvalidCircuitBreakerNamespace: {ID: fmt.Sprint(api.InvalidCircuitBreakerNamespace)}, - api.InvalidCircuitBreakerOwners: {ID: fmt.Sprint(api.InvalidCircuitBreakerOwners)}, - api.InvalidCircuitBreakerToken: {ID: fmt.Sprint(api.InvalidCircuitBreakerToken)}, - api.InvalidCircuitBreakerBusiness: {ID: fmt.Sprint(api.InvalidCircuitBreakerBusiness)}, - api.InvalidCircuitBreakerDepartment: {ID: fmt.Sprint(api.InvalidCircuitBreakerDepartment)}, - api.InvalidCircuitBreakerComment: {ID: fmt.Sprint(api.InvalidCircuitBreakerComment)}, - api.ServicesExistedMesh: {ID: fmt.Sprint(api.ServicesExistedMesh)}, - api.ResourcesExistedMesh: {ID: fmt.Sprint(api.ResourcesExistedMesh)}, - api.InvalidMeshParameter: {ID: fmt.Sprint(api.InvalidMeshParameter)}, - api.InvalidPlatformID: {ID: fmt.Sprint(api.InvalidPlatformID)}, - api.InvalidPlatformName: {ID: fmt.Sprint(api.InvalidPlatformName)}, - api.InvalidPlatformDomain: {ID: fmt.Sprint(api.InvalidPlatformDomain)}, - api.InvalidPlatformQPS: {ID: fmt.Sprint(api.InvalidPlatformQPS)}, - api.InvalidPlatformToken: {ID: fmt.Sprint(api.InvalidPlatformToken)}, - api.InvalidPlatformOwner: {ID: fmt.Sprint(api.InvalidPlatformOwner)}, - api.InvalidPlatformDepartment: {ID: fmt.Sprint(api.InvalidPlatformDepartment)}, - api.InvalidPlatformComment: {ID: fmt.Sprint(api.InvalidPlatformComment)}, - api.NotFoundPlatform: {ID: fmt.Sprint(api.NotFoundPlatform)}, - api.InvalidFluxRateLimitId: {ID: fmt.Sprint(api.InvalidFluxRateLimitId)}, - api.InvalidFluxRateLimitQps: {ID: fmt.Sprint(api.InvalidFluxRateLimitQps)}, - api.InvalidFluxRateLimitSetKey: {ID: fmt.Sprint(api.InvalidFluxRateLimitSetKey)}, - api.ExistedResource: {ID: fmt.Sprint(api.ExistedResource)}, - api.NotFoundResource: {ID: fmt.Sprint(api.NotFoundResource)}, - api.NamespaceExistedServices: {ID: fmt.Sprint(api.NamespaceExistedServices)}, - api.ServiceExistedInstances: {ID: fmt.Sprint(api.ServiceExistedInstances)}, - api.ServiceExistedRoutings: {ID: fmt.Sprint(api.ServiceExistedRoutings)}, - api.ServiceExistedRateLimits: {ID: fmt.Sprint(api.ServiceExistedRateLimits)}, - api.ExistReleasedConfig: {ID: fmt.Sprint(api.ExistReleasedConfig)}, - api.SameInstanceRequest: {ID: fmt.Sprint(api.SameInstanceRequest)}, - api.ServiceExistedCircuitBreakers: {ID: fmt.Sprint(api.ServiceExistedCircuitBreakers)}, - api.ServiceExistedAlias: {ID: fmt.Sprint(api.ServiceExistedAlias)}, - api.NamespaceExistedMeshResources: {ID: fmt.Sprint(api.NamespaceExistedMeshResources)}, - api.NamespaceExistedCircuitBreakers: {ID: fmt.Sprint(api.NamespaceExistedCircuitBreakers)}, - api.ServiceSubscribedByMeshes: {ID: fmt.Sprint(api.ServiceSubscribedByMeshes)}, - api.ServiceExistedFluxRateLimits: {ID: fmt.Sprint(api.ServiceExistedFluxRateLimits)}, - api.UserExisted: {ID: fmt.Sprint(api.UserExisted)}, - api.UserGroupExisted: {ID: fmt.Sprint(api.UserGroupExisted)}, - api.AuthStrategyRuleExisted: {ID: fmt.Sprint(api.AuthStrategyRuleExisted)}, - api.SubAccountExisted: {ID: fmt.Sprint(api.SubAccountExisted)}, - api.NotFoundService: {ID: fmt.Sprint(api.NotFoundService)}, - api.NotFoundRouting: {ID: fmt.Sprint(api.NotFoundRouting)}, - api.NotFoundInstance: {ID: fmt.Sprint(api.NotFoundInstance)}, - api.NotFoundServiceAlias: {ID: fmt.Sprint(api.NotFoundServiceAlias)}, - api.NotFoundNamespace: {ID: fmt.Sprint(api.NotFoundNamespace)}, - api.NotFoundSourceService: {ID: fmt.Sprint(api.NotFoundSourceService)}, - api.NotFoundRateLimit: {ID: fmt.Sprint(api.NotFoundRateLimit)}, - api.NotFoundCircuitBreaker: {ID: fmt.Sprint(api.NotFoundCircuitBreaker)}, - api.NotFoundMasterConfig: {ID: fmt.Sprint(api.NotFoundMasterConfig)}, - api.NotFoundTagConfig: {ID: fmt.Sprint(api.NotFoundTagConfig)}, - api.NotFoundTagConfigOrService: {ID: fmt.Sprint(api.NotFoundTagConfigOrService)}, - api.NotFoundUser: {ID: fmt.Sprint(api.NotFoundUser)}, - api.NotFoundOwnerUser: {ID: fmt.Sprint(api.NotFoundOwnerUser)}, - api.NotFoundUserGroup: {ID: fmt.Sprint(api.NotFoundUserGroup)}, - api.NotFoundAuthStrategyRule: {ID: fmt.Sprint(api.NotFoundAuthStrategyRule)}, - api.ClientAPINotOpen: {ID: fmt.Sprint(api.ClientAPINotOpen)}, - api.NotAllowBusinessService: {ID: fmt.Sprint(api.NotAllowBusinessService)}, - api.InvalidUserOwners: {ID: fmt.Sprint(api.InvalidUserOwners)}, - api.InvalidUserID: {ID: fmt.Sprint(api.InvalidUserID)}, - api.InvalidUserPassword: {ID: fmt.Sprint(api.InvalidUserPassword)}, - api.InvalidUserMobile: {ID: fmt.Sprint(api.InvalidUserMobile)}, - api.InvalidUserEmail: {ID: fmt.Sprint(api.InvalidUserEmail)}, - api.InvalidUserGroupOwners: {ID: fmt.Sprint(api.InvalidUserGroupOwners)}, - api.InvalidUserGroupID: {ID: fmt.Sprint(api.InvalidUserGroupID)}, - api.InvalidAuthStrategyOwners: {ID: fmt.Sprint(api.InvalidAuthStrategyOwners)}, - api.InvalidAuthStrategyName: {ID: fmt.Sprint(api.InvalidAuthStrategyName)}, - api.InvalidAuthStrategyID: {ID: fmt.Sprint(api.InvalidAuthStrategyID)}, - api.InvalidPrincipalType: {ID: fmt.Sprint(api.InvalidPrincipalType)}, - api.NotAllowAliasUpdate: {ID: fmt.Sprint(api.NotAllowAliasUpdate)}, - api.NotAllowAliasCreateInstance: {ID: fmt.Sprint(api.NotAllowAliasCreateInstance)}, - api.NotAllowAliasCreateRouting: {ID: fmt.Sprint(api.NotAllowAliasCreateRouting)}, - api.NotAllowCreateAliasForAlias: {ID: fmt.Sprint(api.NotAllowCreateAliasForAlias)}, - api.NotAllowAliasCreateRateLimit: {ID: fmt.Sprint(api.NotAllowAliasCreateRateLimit)}, - api.NotAllowAliasBindRule: {ID: fmt.Sprint(api.NotAllowAliasBindRule)}, - api.NotAllowDifferentNamespaceBindRule: {ID: fmt.Sprint(api.NotAllowDifferentNamespaceBindRule)}, - api.NotAllowModifyDefaultStrategyPrincipal: {ID: fmt.Sprint(api.NotAllowModifyDefaultStrategyPrincipal)}, - api.InvalidConfigFileGroupName: {ID: fmt.Sprint(api.InvalidConfigFileGroupName)}, - api.InvalidConfigFileName: {ID: fmt.Sprint(api.InvalidConfigFileName)}, - api.InvalidConfigFileContentLength: {ID: fmt.Sprint(api.InvalidConfigFileContentLength)}, - api.InvalidConfigFileFormat: {ID: fmt.Sprint(api.InvalidConfigFileFormat)}, - api.InvalidConfigFileTags: {ID: fmt.Sprint(api.InvalidConfigFileTags)}, - api.InvalidWatchConfigFileFormat: {ID: fmt.Sprint(api.InvalidWatchConfigFileFormat)}, - api.NotFoundResourceConfigFile: {ID: fmt.Sprint(api.NotFoundResourceConfigFile)}, - api.InvalidConfigFileTemplateName: {ID: fmt.Sprint(api.InvalidConfigFileTemplateName)}, - api.Unauthorized: {ID: fmt.Sprint(api.Unauthorized)}, - api.NotAllowedAccess: {ID: fmt.Sprint(api.NotAllowedAccess)}, - api.EmptyAutToken: {ID: fmt.Sprint(api.EmptyAutToken)}, - api.TokenDisabled: {ID: fmt.Sprint(api.TokenDisabled)}, - api.TokenNotExisted: {ID: fmt.Sprint(api.TokenNotExisted)}, - api.IPRateLimit: {ID: fmt.Sprint(api.IPRateLimit)}, - api.APIRateLimit: {ID: fmt.Sprint(api.APIRateLimit)}, - api.CMDBNotFindHost: {ID: fmt.Sprint(api.CMDBNotFindHost)}, - api.DataConflict: {ID: fmt.Sprint(api.DataConflict)}, - api.InstanceTooManyRequests: {ID: fmt.Sprint(api.InstanceTooManyRequests)}, - api.ExecuteException: {ID: fmt.Sprint(api.ExecuteException)}, - api.StoreLayerException: {ID: fmt.Sprint(api.StoreLayerException)}, - api.CMDBPluginException: {ID: fmt.Sprint(api.CMDBPluginException)}, - api.ParseRoutingException: {ID: fmt.Sprint(api.ParseRoutingException)}, - api.ParseRateLimitException: {ID: fmt.Sprint(api.ParseRateLimitException)}, - api.ParseCircuitBreakerException: {ID: fmt.Sprint(api.ParseCircuitBreakerException)}, - api.HeartbeatException: {ID: fmt.Sprint(api.HeartbeatException)}, - api.InstanceRegisTimeout: {ID: fmt.Sprint(api.InstanceRegisTimeout)}, - api.AuthTokenVerifyException: {ID: fmt.Sprint(api.AuthTokenVerifyException)}, - api.OperationRoleException: {ID: fmt.Sprint(api.OperationRoleException)}, - } -} + import ( + "fmt" + + ii18n "github.com/nicksnyder/go-i18n/v2/i18n" + api "github.com/polarismesh/polaris-server/common/api/v1" + ) + + func init() { + i18nMsgCache = map[uint32]*ii18n.Message{ + api.ExecuteSuccess: {ID: fmt.Sprint(api.ExecuteSuccess)}, + api.DataNoChange: {ID: fmt.Sprint(api.DataNoChange)}, + api.NoNeedUpdate: {ID: fmt.Sprint(api.NoNeedUpdate)}, + api.BadRequest: {ID: fmt.Sprint(api.BadRequest)}, + api.ParseException: {ID: fmt.Sprint(api.ParseException)}, + api.EmptyRequest: {ID: fmt.Sprint(api.EmptyRequest)}, + api.BatchSizeOverLimit: {ID: fmt.Sprint(api.BatchSizeOverLimit)}, + api.InvalidDiscoverResource: {ID: fmt.Sprint(api.InvalidDiscoverResource)}, + api.InvalidRequestID: {ID: fmt.Sprint(api.InvalidRequestID)}, + api.InvalidUserName: {ID: fmt.Sprint(api.InvalidUserName)}, + api.InvalidUserToken: {ID: fmt.Sprint(api.InvalidUserToken)}, + api.InvalidParameter: {ID: fmt.Sprint(api.InvalidParameter)}, + api.EmptyQueryParameter: {ID: fmt.Sprint(api.EmptyQueryParameter)}, + api.InvalidQueryInsParameter: {ID: fmt.Sprint(api.InvalidQueryInsParameter)}, + api.InvalidNamespaceName: {ID: fmt.Sprint(api.InvalidNamespaceName)}, + api.InvalidNamespaceOwners: {ID: fmt.Sprint(api.InvalidNamespaceOwners)}, + api.InvalidNamespaceToken: {ID: fmt.Sprint(api.InvalidNamespaceToken)}, + api.InvalidServiceName: {ID: fmt.Sprint(api.InvalidServiceName)}, + api.InvalidServiceOwners: {ID: fmt.Sprint(api.InvalidServiceOwners)}, + api.InvalidServiceToken: {ID: fmt.Sprint(api.InvalidServiceToken)}, + api.InvalidServiceMetadata: {ID: fmt.Sprint(api.InvalidServiceMetadata)}, + api.InvalidServicePorts: {ID: fmt.Sprint(api.InvalidServicePorts)}, + api.InvalidServiceBusiness: {ID: fmt.Sprint(api.InvalidServiceBusiness)}, + api.InvalidServiceDepartment: {ID: fmt.Sprint(api.InvalidServiceDepartment)}, + api.InvalidServiceCMDB: {ID: fmt.Sprint(api.InvalidServiceCMDB)}, + api.InvalidServiceComment: {ID: fmt.Sprint(api.InvalidServiceComment)}, + api.InvalidServiceAliasComment: {ID: fmt.Sprint(api.InvalidServiceAliasComment)}, + api.InvalidInstanceID: {ID: fmt.Sprint(api.InvalidInstanceID)}, + api.InvalidInstanceHost: {ID: fmt.Sprint(api.InvalidInstanceHost)}, + api.InvalidInstancePort: {ID: fmt.Sprint(api.InvalidInstancePort)}, + api.InvalidServiceAlias: {ID: fmt.Sprint(api.InvalidServiceAlias)}, + api.InvalidNamespaceWithAlias: {ID: fmt.Sprint(api.InvalidNamespaceWithAlias)}, + api.InvalidServiceAliasOwners: {ID: fmt.Sprint(api.InvalidServiceAliasOwners)}, + api.InvalidInstanceProtocol: {ID: fmt.Sprint(api.InvalidInstanceProtocol)}, + api.InvalidInstanceVersion: {ID: fmt.Sprint(api.InvalidInstanceVersion)}, + api.InvalidInstanceLogicSet: {ID: fmt.Sprint(api.InvalidInstanceLogicSet)}, + api.InvalidInstanceIsolate: {ID: fmt.Sprint(api.InvalidInstanceIsolate)}, + api.HealthCheckNotOpen: {ID: fmt.Sprint(api.HealthCheckNotOpen)}, + api.HeartbeatOnDisabledIns: {ID: fmt.Sprint(api.HeartbeatOnDisabledIns)}, + api.HeartbeatExceedLimit: {ID: fmt.Sprint(api.HeartbeatExceedLimit)}, + api.HeartbeatTypeNotFound: {ID: fmt.Sprint(api.HeartbeatTypeNotFound)}, + api.InvalidMetadata: {ID: fmt.Sprint(api.InvalidMetadata)}, + api.InvalidRateLimitID: {ID: fmt.Sprint(api.InvalidRateLimitID)}, + api.InvalidRateLimitLabels: {ID: fmt.Sprint(api.InvalidRateLimitLabels)}, + api.InvalidRateLimitAmounts: {ID: fmt.Sprint(api.InvalidRateLimitAmounts)}, + api.InvalidRateLimitName: {ID: fmt.Sprint(api.InvalidRateLimitName)}, + api.InvalidCircuitBreakerID: {ID: fmt.Sprint(api.InvalidCircuitBreakerID)}, + api.InvalidCircuitBreakerVersion: {ID: fmt.Sprint(api.InvalidCircuitBreakerVersion)}, + api.InvalidCircuitBreakerName: {ID: fmt.Sprint(api.InvalidCircuitBreakerName)}, + api.InvalidCircuitBreakerNamespace: {ID: fmt.Sprint(api.InvalidCircuitBreakerNamespace)}, + api.InvalidCircuitBreakerOwners: {ID: fmt.Sprint(api.InvalidCircuitBreakerOwners)}, + api.InvalidCircuitBreakerToken: {ID: fmt.Sprint(api.InvalidCircuitBreakerToken)}, + api.InvalidCircuitBreakerBusiness: {ID: fmt.Sprint(api.InvalidCircuitBreakerBusiness)}, + api.InvalidCircuitBreakerDepartment: {ID: fmt.Sprint(api.InvalidCircuitBreakerDepartment)}, + api.InvalidCircuitBreakerComment: {ID: fmt.Sprint(api.InvalidCircuitBreakerComment)}, + api.ServicesExistedMesh: {ID: fmt.Sprint(api.ServicesExistedMesh)}, + api.ResourcesExistedMesh: {ID: fmt.Sprint(api.ResourcesExistedMesh)}, + api.InvalidMeshParameter: {ID: fmt.Sprint(api.InvalidMeshParameter)}, + api.InvalidPlatformID: {ID: fmt.Sprint(api.InvalidPlatformID)}, + api.InvalidPlatformName: {ID: fmt.Sprint(api.InvalidPlatformName)}, + api.InvalidPlatformDomain: {ID: fmt.Sprint(api.InvalidPlatformDomain)}, + api.InvalidPlatformQPS: {ID: fmt.Sprint(api.InvalidPlatformQPS)}, + api.InvalidPlatformToken: {ID: fmt.Sprint(api.InvalidPlatformToken)}, + api.InvalidPlatformOwner: {ID: fmt.Sprint(api.InvalidPlatformOwner)}, + api.InvalidPlatformDepartment: {ID: fmt.Sprint(api.InvalidPlatformDepartment)}, + api.InvalidPlatformComment: {ID: fmt.Sprint(api.InvalidPlatformComment)}, + api.NotFoundPlatform: {ID: fmt.Sprint(api.NotFoundPlatform)}, + api.InvalidFluxRateLimitId: {ID: fmt.Sprint(api.InvalidFluxRateLimitId)}, + api.InvalidFluxRateLimitQps: {ID: fmt.Sprint(api.InvalidFluxRateLimitQps)}, + api.InvalidFluxRateLimitSetKey: {ID: fmt.Sprint(api.InvalidFluxRateLimitSetKey)}, + api.ExistedResource: {ID: fmt.Sprint(api.ExistedResource)}, + api.NotFoundResource: {ID: fmt.Sprint(api.NotFoundResource)}, + api.NamespaceExistedServices: {ID: fmt.Sprint(api.NamespaceExistedServices)}, + api.ServiceExistedInstances: {ID: fmt.Sprint(api.ServiceExistedInstances)}, + api.ServiceExistedRoutings: {ID: fmt.Sprint(api.ServiceExistedRoutings)}, + api.ServiceExistedRateLimits: {ID: fmt.Sprint(api.ServiceExistedRateLimits)}, + api.ExistReleasedConfig: {ID: fmt.Sprint(api.ExistReleasedConfig)}, + api.SameInstanceRequest: {ID: fmt.Sprint(api.SameInstanceRequest)}, + api.ServiceExistedCircuitBreakers: {ID: fmt.Sprint(api.ServiceExistedCircuitBreakers)}, + api.ServiceExistedAlias: {ID: fmt.Sprint(api.ServiceExistedAlias)}, + api.NamespaceExistedMeshResources: {ID: fmt.Sprint(api.NamespaceExistedMeshResources)}, + api.NamespaceExistedCircuitBreakers: {ID: fmt.Sprint(api.NamespaceExistedCircuitBreakers)}, + api.ServiceSubscribedByMeshes: {ID: fmt.Sprint(api.ServiceSubscribedByMeshes)}, + api.ServiceExistedFluxRateLimits: {ID: fmt.Sprint(api.ServiceExistedFluxRateLimits)}, + api.UserExisted: {ID: fmt.Sprint(api.UserExisted)}, + api.UserGroupExisted: {ID: fmt.Sprint(api.UserGroupExisted)}, + api.AuthStrategyRuleExisted: {ID: fmt.Sprint(api.AuthStrategyRuleExisted)}, + api.SubAccountExisted: {ID: fmt.Sprint(api.SubAccountExisted)}, + api.NotFoundService: {ID: fmt.Sprint(api.NotFoundService)}, + api.NotFoundRouting: {ID: fmt.Sprint(api.NotFoundRouting)}, + api.NotFoundInstance: {ID: fmt.Sprint(api.NotFoundInstance)}, + api.NotFoundServiceAlias: {ID: fmt.Sprint(api.NotFoundServiceAlias)}, + api.NotFoundNamespace: {ID: fmt.Sprint(api.NotFoundNamespace)}, + api.NotFoundSourceService: {ID: fmt.Sprint(api.NotFoundSourceService)}, + api.NotFoundRateLimit: {ID: fmt.Sprint(api.NotFoundRateLimit)}, + api.NotFoundCircuitBreaker: {ID: fmt.Sprint(api.NotFoundCircuitBreaker)}, + api.NotFoundMasterConfig: {ID: fmt.Sprint(api.NotFoundMasterConfig)}, + api.NotFoundTagConfig: {ID: fmt.Sprint(api.NotFoundTagConfig)}, + api.NotFoundTagConfigOrService: {ID: fmt.Sprint(api.NotFoundTagConfigOrService)}, + api.NotFoundUser: {ID: fmt.Sprint(api.NotFoundUser)}, + api.NotFoundOwnerUser: {ID: fmt.Sprint(api.NotFoundOwnerUser)}, + api.NotFoundUserGroup: {ID: fmt.Sprint(api.NotFoundUserGroup)}, + api.NotFoundAuthStrategyRule: {ID: fmt.Sprint(api.NotFoundAuthStrategyRule)}, + api.ClientAPINotOpen: {ID: fmt.Sprint(api.ClientAPINotOpen)}, + api.NotAllowBusinessService: {ID: fmt.Sprint(api.NotAllowBusinessService)}, + api.InvalidUserOwners: {ID: fmt.Sprint(api.InvalidUserOwners)}, + api.InvalidUserID: {ID: fmt.Sprint(api.InvalidUserID)}, + api.InvalidUserPassword: {ID: fmt.Sprint(api.InvalidUserPassword)}, + api.InvalidUserMobile: {ID: fmt.Sprint(api.InvalidUserMobile)}, + api.InvalidUserEmail: {ID: fmt.Sprint(api.InvalidUserEmail)}, + api.InvalidUserGroupOwners: {ID: fmt.Sprint(api.InvalidUserGroupOwners)}, + api.InvalidUserGroupID: {ID: fmt.Sprint(api.InvalidUserGroupID)}, + api.InvalidAuthStrategyOwners: {ID: fmt.Sprint(api.InvalidAuthStrategyOwners)}, + api.InvalidAuthStrategyName: {ID: fmt.Sprint(api.InvalidAuthStrategyName)}, + api.InvalidAuthStrategyID: {ID: fmt.Sprint(api.InvalidAuthStrategyID)}, + api.InvalidPrincipalType: {ID: fmt.Sprint(api.InvalidPrincipalType)}, + api.NotAllowAliasUpdate: {ID: fmt.Sprint(api.NotAllowAliasUpdate)}, + api.NotAllowAliasCreateInstance: {ID: fmt.Sprint(api.NotAllowAliasCreateInstance)}, + api.NotAllowAliasCreateRouting: {ID: fmt.Sprint(api.NotAllowAliasCreateRouting)}, + api.NotAllowCreateAliasForAlias: {ID: fmt.Sprint(api.NotAllowCreateAliasForAlias)}, + api.NotAllowAliasCreateRateLimit: {ID: fmt.Sprint(api.NotAllowAliasCreateRateLimit)}, + api.NotAllowAliasBindRule: {ID: fmt.Sprint(api.NotAllowAliasBindRule)}, + api.NotAllowDifferentNamespaceBindRule: {ID: fmt.Sprint(api.NotAllowDifferentNamespaceBindRule)}, + api.NotAllowModifyDefaultStrategyPrincipal: {ID: fmt.Sprint(api.NotAllowModifyDefaultStrategyPrincipal)}, + api.NotAllowModifyOwnerDefaultStrategy: {ID: fmt.Sprint(api.NotAllowModifyOwnerDefaultStrategy)}, + api.InvalidRoutingID: {ID: fmt.Sprint(api.InvalidRoutingID)}, + api.InvalidRoutingPolicy: {ID: fmt.Sprint(api.InvalidRoutingPolicy)}, + api.InvalidRoutingPriority: {ID: fmt.Sprint(api.InvalidRoutingPriority)}, + api.InvalidRoutingName: {ID: fmt.Sprint(api.InvalidRoutingName)}, + api.InvalidConfigFileGroupName: {ID: fmt.Sprint(api.InvalidConfigFileGroupName)}, + api.InvalidConfigFileName: {ID: fmt.Sprint(api.InvalidConfigFileName)}, + api.InvalidConfigFileContentLength: {ID: fmt.Sprint(api.InvalidConfigFileContentLength)}, + api.InvalidConfigFileFormat: {ID: fmt.Sprint(api.InvalidConfigFileFormat)}, + api.InvalidConfigFileTags: {ID: fmt.Sprint(api.InvalidConfigFileTags)}, + api.InvalidWatchConfigFileFormat: {ID: fmt.Sprint(api.InvalidWatchConfigFileFormat)}, + api.NotFoundResourceConfigFile: {ID: fmt.Sprint(api.NotFoundResourceConfigFile)}, + api.InvalidConfigFileTemplateName: {ID: fmt.Sprint(api.InvalidConfigFileTemplateName)}, + api.Unauthorized: {ID: fmt.Sprint(api.Unauthorized)}, + api.NotAllowedAccess: {ID: fmt.Sprint(api.NotAllowedAccess)}, + api.EmptyAutToken: {ID: fmt.Sprint(api.EmptyAutToken)}, + api.TokenDisabled: {ID: fmt.Sprint(api.TokenDisabled)}, + api.TokenNotExisted: {ID: fmt.Sprint(api.TokenNotExisted)}, + api.IPRateLimit: {ID: fmt.Sprint(api.IPRateLimit)}, + api.APIRateLimit: {ID: fmt.Sprint(api.APIRateLimit)}, + api.CMDBNotFindHost: {ID: fmt.Sprint(api.CMDBNotFindHost)}, + api.DataConflict: {ID: fmt.Sprint(api.DataConflict)}, + api.InstanceTooManyRequests: {ID: fmt.Sprint(api.InstanceTooManyRequests)}, + api.ExecuteException: {ID: fmt.Sprint(api.ExecuteException)}, + api.StoreLayerException: {ID: fmt.Sprint(api.StoreLayerException)}, + api.CMDBPluginException: {ID: fmt.Sprint(api.CMDBPluginException)}, + api.ParseRoutingException: {ID: fmt.Sprint(api.ParseRoutingException)}, + api.ParseRateLimitException: {ID: fmt.Sprint(api.ParseRateLimitException)}, + api.ParseCircuitBreakerException: {ID: fmt.Sprint(api.ParseCircuitBreakerException)}, + api.HeartbeatException: {ID: fmt.Sprint(api.HeartbeatException)}, + api.InstanceRegisTimeout: {ID: fmt.Sprint(api.InstanceRegisTimeout)}, + api.AuthTokenVerifyException: {ID: fmt.Sprint(api.AuthTokenVerifyException)}, + api.OperationRoleException: {ID: fmt.Sprint(api.OperationRoleException)}, + } + } + \ No newline at end of file diff --git a/apiserver/httpserver/i18n/zh.toml b/apiserver/httpserver/i18n/zh.toml index f06c54253..8fc94ccd5 100644 --- a/apiserver/httpserver/i18n/zh.toml +++ b/apiserver/httpserver/i18n/zh.toml @@ -1,152 +1,157 @@ -200000 = "执行成功" #ExecuteSuccess -200001 = "服务发现数据无变化" #DataNoChange -200002 = "数据没有变化, 无需更新" #NoNeedUpdate -400000 = "请求错误" #BadRequest -400001 = "请求解析失败" #ParseException -400002 = "空请求" #EmptyRequest -400003 = "批量数据超过限制" #BatchSizeOverLimit -400004 = "服务发现资源非法" #InvalidDiscoverResource -400100 = "请求ID非法" #InvalidRequestID -400101 = "用户名非法" #InvalidUserName -400102 = "用户token非法" #InvalidUserToken -400103 = "参数非法" #InvalidParameter -400104 = "查询实例参数为空" #EmptyQueryParameter -400105 = "查询实例, 需要(服务,命名空间)或主机作为参数" #InvalidQueryInsParameter -400110 = "命名空间名称非法" #InvalidNamespaceName -400111 = "命名空间拥有人非法" #InvalidNamespaceOwners -400112 = "命名空间token非法" #InvalidNamespaceToken -400120 = "服务名称非法" #InvalidServiceName -400121 = "服务拥有人非法" #InvalidServiceOwners -400122 = "服务token非法" #InvalidServiceToken -400123 = "服务元数据非法" #InvalidServiceMetadata -400124 = "服务端口非法" #InvalidServicePorts -400125 = "服务所属业务非法" #InvalidServiceBusiness -400126 = "服务所属部门非法" #InvalidServiceDepartment -400127 = "服务cmdb非法" #InvalidServiceCMDB -400128 = "服务备注非法" #InvalidServiceComment -400129 = "服务别名备注非法" #InvalidServiceAliasComment -400130 = "实例ID非法" #InvalidInstanceID -400131 = "实例Host非法" #InvalidInstanceHost -400132 = "实例端口非法" #InvalidInstancePort -400133 = "实例别名非法" #InvalidServiceAlias -400134 = "当前命名空间不运行创建sid类型别名" #InvalidNamespaceWithAlias -400135 = "服务别名拥有者非法" #InvalidServiceAliasOwners -400136 = "实例协议非法" #InvalidInstanceProtocol -400137 = "实例版本非法" #InvalidInstanceVersion -400138 = "实例逻辑集合非法" #InvalidInstanceLogicSet -400139 = "实例隔离设置非法" #InvalidInstanceIsolate -400140 = "服务端未开启健康检查" #HealthCheckNotOpen -400141 = "在已被禁用的实例上进行心跳" #HeartbeatOnDisabledIns -400142 = "心跳超限, 实例仅支持每秒1次心跳" #HeartbeatExceedLimit -400143 = "未找到心跳类型" #HeartbeatTypeNotFound -400150 = "元数据长度过长或包含非法字符" #InvalidMetadata -400151 = "限频ID非法" #InvalidRateLimitID -400152 = "限频标签非法" #InvalidRateLimitLabels -400153 = "限频数量非法" #InvalidRateLimitAmounts -400154 = "限流名称非法" #InvalidRateLimitName -400160 = "熔断ID非法" #InvalidCircuitBreakerID -400161 = "熔断版本非法" #InvalidCircuitBreakerVersion -400162 = "熔断名称非法" #InvalidCircuitBreakerName -400163 = "熔断命名空间ID非法" #InvalidCircuitBreakerNamespace -400164 = "熔断所属人ID非法" #InvalidCircuitBreakerOwners -400165 = "熔断token非法" #InvalidCircuitBreakerToken -400166 = "熔断所属业务非法" #InvalidCircuitBreakerBusiness -400167 = "熔断所属部门非法" #InvalidCircuitBreakerDepartment -400168 = "熔断备注非法" #InvalidCircuitBreakerComment -400170 = "服务有已存在的网格" #ServicesExistedMesh -400171 = "当前资源有已存在的网格" #ResourcesExistedMesh -400172 = "网格参数非法" #InvalidMeshParameter -400180 = "平台ID非法" #InvalidPlatformID -400181 = "平台名称非法" #InvalidPlatformName -400182 = "平台域名非法" #InvalidPlatformDomain -400183 = "平台qps非法" #InvalidPlatformQPS -400184 = "平台token非法" #InvalidPlatformToken -400185 = "平台拥有人非法" #InvalidPlatformOwner -400186 = "平台所属部们非法" #InvalidPlatformDepartment -400187 = "平台备注非法" #InvalidPlatformComment -400188 = "未找到平台" #NotFoundPlatform -400190 = "限流ID非法" #InvalidFluxRateLimitId -400191 = "限流qps非法" #InvalidFluxRateLimitQps -400192 = "限流标识非法" #InvalidFluxRateLimitSetKey -400201 = "资源已存在" #ExistedResource -400202 = "未找到资源" #NotFoundResource -400203 = "某些服务在当前命名空间已存在" #NamespaceExistedServices -400204 = "某些实例在当前服务已存在" #ServiceExistedInstances -400205 = "某些路由在当前服务已存在" #ServiceExistedRoutings -400206 = "某些限流在当前服务已存在" #ServiceExistedRateLimits -400207 = "存在已发布配置" #ExistReleasedConfig -400208 = "实例请求重复" #SameInstanceRequest -400209 = "某些熔断在当前服务已存在" #ServiceExistedCircuitBreakers -400210 = "某些别名在当前服务已存在" #ServiceExistedAlias -400211 = "某些网格资源在当前命名空间已存在" #NamespaceExistedMeshResources -400212 = "某些熔断在当前命名空间已存在" #NamespaceExistedCircuitBreakers -400213 = "服务已被某些网格订阅" #ServiceSubscribedByMeshes -400214 = "服务已存在限流配置" #ServiceExistedFluxRateLimits -400215 = "用户已存在" #UserExisted -400216 = "用户组已存在" #UserGroupExisted -400217 = "鉴权策略规则已存在" #AuthStrategyRuleExisted -400218 = "某些子账号已属当前拥有人" #SubAccountExisted -400301 = "服务未找到" #NotFoundService -400302 = "路由未找到" #NotFoundRouting -400303 = "示例未找到" #NotFoundInstance -400304 = "服务别名未找到" #NotFoundServiceAlias -400305 = "命名空间未找到" #NotFoundNamespace -400306 = "未找到和当前服务别名关联的服务" #NotFoundSourceService -400307 = "限流规则未找到" #NotFoundRateLimit -400308 = "熔断规则未找到" #NotFoundCircuitBreaker -400309 = "主配置未找到" #NotFoundMasterConfig -400310 = "标签配置未找到" #NotFoundTagConfig -400311 = "未找到标签或服务, 或者关系已存在" #NotFoundTagConfigOrService -400312 = "用户未找到" #NotFoundUser -400313 = "拥有人用户未找到" #NotFoundOwnerUser -400314 = "用户组未找到" #NotFoundUserGroup -400315 = "鉴权策略规则未找到" #NotFoundAuthStrategyRule -400401 = "客户端API未开放" #ClientAPINotOpen -400402 = "不允许请求当前业务服务" #NotAllowBusinessService -400410 = "用户所有人非法" #InvalidUserOwners -400411 = "用户ID非法" #InvalidUserID -400412 = "用户密码非法" #InvalidUserPassword -400413 = "用户手机号非法" #InvalidUserMobile -400414 = "用户邮件非法" #InvalidUserEmail -400420 = "用户组所有人的属性非法" #InvalidUserGroupOwners -400421 = "用户组ID非法" #InvalidUserGroupID -400430 = "鉴权策略规则拥有人非法" #InvalidAuthStrategyOwners -400431 = "鉴权策略规则名称非法" #InvalidAuthStrategyName -400432 = "鉴权策略ID非法" #InvalidAuthStrategyID -400440 = "principal类型非法" #InvalidPrincipalType -400501 = "服务别名不允许更新" #NotAllowAliasUpdate -400502 = "服务别名不允许创建实例" #NotAllowAliasCreateInstance -400503 = "服务别名不允许创建路由规则" #NotAllowAliasCreateRouting -400504 = "仅允许源服务可以创建别名" #NotAllowCreateAliasForAlias -400505 = "服务别名不允许创建限流规则" #NotAllowAliasCreateRateLimit -400506 = "服务别名不允许绑定规则" #NotAllowAliasBindRule -400507 = "不允许不同的命名空间绑定同一规则" #NotAllowDifferentNamespaceBindRule -400508 = "不允许修改默认策略" #NotAllowModifyDefaultStrategyPrincipal -400801 = "配置文件组名非法" #InvalidConfigFileGroupName -400802 = "配置文件名称非法" #InvalidConfigFileName -400803 = "配置文件内容过长" #InvalidConfigFileContentLength -400804 = "非法的配置文件格式,支持的格式有: json,xml,html,properties,text,yaml" #InvalidConfigFileFormat -400805 = "配置文件标签非法, 标签应该是成对的, 比如key1,value1,key2,value2, 并且key,value应是非空白字符" #InvalidConfigFileTags -400806 = "监视配置文件格式非法" #InvalidWatchConfigFileFormat -400807 = "无法找到配置文件" #NotFoundResourceConfigFile -400808 = "invalid config file template name" #InvalidConfigFileTemplateName -401000 = "未经授权" #Unauthorized -401001 = "权限不被允许" #NotAllowedAccess -401002 = "鉴权token为空" #EmptyAutToken -401003 = "token已被禁用" #TokenDisabled -401004 = "token不存在" #TokenNotExisted -403001 = "ip达到服务端限制" #IPRateLimit -403002 = "api达到服务端限制" #APIRateLimit -404001 = "无法找到主机的cmdb" #CMDBNotFindHost -409000 = "数据有冲突, 请再次重试" #DataConflict -429001 = "你的实例请求过多" #InstanceTooManyRequests -500000 = "执行异常" #ExecuteException -500001 = "存储层异常" #StoreLayerException -500002 = "cmdb插件异常" #CMDBPluginException -500004 = "解析路由规则失败" #ParseRoutingException -500005 = "解析限频规则失败" #ParseRateLimitException -500006 = "解析熔断规则失败" #ParseCircuitBreakerException -500007 = "心跳异常" #HeartbeatException -500008 = "实例异步注册超时" #InstanceRegisTimeout -500100 = "token验证异常" #AuthTokenVerifyException -500101 = "角色操作异常" #OperationRoleException +200000 = "执行成功" #ExecuteSuccess +200001 = "服务发现数据无变化" #DataNoChange +200002 = "数据没有变化, 无需更新" #NoNeedUpdate +400000 = "请求错误" #BadRequest +400001 = "请求解析失败" #ParseException +400002 = "空请求" #EmptyRequest +400003 = "批量数据超过限制" #BatchSizeOverLimit +400004 = "服务发现资源非法" #InvalidDiscoverResource +400100 = "请求ID非法" #InvalidRequestID +400101 = "用户名非法" #InvalidUserName +400102 = "用户token非法" #InvalidUserToken +400103 = "参数非法" #InvalidParameter +400104 = "查询实例参数为空" #EmptyQueryParameter +400105 = "查询实例, 需要(服务,命名空间)或主机作为参数" #InvalidQueryInsParameter +400110 = "命名空间名称非法" #InvalidNamespaceName +400111 = "命名空间拥有人非法" #InvalidNamespaceOwners +400112 = "命名空间token非法" #InvalidNamespaceToken +400120 = "服务名称非法" #InvalidServiceName +400121 = "服务拥有人非法" #InvalidServiceOwners +400122 = "服务token非法" #InvalidServiceToken +400123 = "服务元数据非法" #InvalidServiceMetadata +400124 = "服务端口非法" #InvalidServicePorts +400125 = "服务所属业务非法" #InvalidServiceBusiness +400126 = "服务所属部门非法" #InvalidServiceDepartment +400127 = "服务cmdb非法" #InvalidServiceCMDB +400128 = "服务备注非法" #InvalidServiceComment +400129 = "服务别名备注非法" #InvalidServiceAliasComment +400130 = "实例ID非法" #InvalidInstanceID +400131 = "实例Host非法" #InvalidInstanceHost +400132 = "实例端口非法" #InvalidInstancePort +400133 = "实例别名非法" #InvalidServiceAlias +400134 = "当前命名空间不运行创建sid类型别名" #InvalidNamespaceWithAlias +400135 = "服务别名拥有者非法" #InvalidServiceAliasOwners +400136 = "实例协议非法" #InvalidInstanceProtocol +400137 = "实例版本非法" #InvalidInstanceVersion +400138 = "实例逻辑集合非法" #InvalidInstanceLogicSet +400139 = "实例隔离设置非法" #InvalidInstanceIsolate +400140 = "服务端未开启健康检查" #HealthCheckNotOpen +400141 = "在已被禁用的实例上进行心跳" #HeartbeatOnDisabledIns +400142 = "心跳超限, 实例仅支持每秒1次心跳" #HeartbeatExceedLimit +400143 = "未找到心跳类型" #HeartbeatTypeNotFound +400150 = "元数据长度过长或包含非法字符" #InvalidMetadata +400151 = "限频ID非法" #InvalidRateLimitID +400152 = "限频标签非法" #InvalidRateLimitLabels +400153 = "限频数量非法" #InvalidRateLimitAmounts +400154 = "限流名称非法" #InvalidRateLimitName +400160 = "熔断ID非法" #InvalidCircuitBreakerID +400161 = "熔断版本非法" #InvalidCircuitBreakerVersion +400162 = "熔断名称非法" #InvalidCircuitBreakerName +400163 = "熔断命名空间ID非法" #InvalidCircuitBreakerNamespace +400164 = "熔断所属人ID非法" #InvalidCircuitBreakerOwners +400165 = "熔断token非法" #InvalidCircuitBreakerToken +400166 = "熔断所属业务非法" #InvalidCircuitBreakerBusiness +400167 = "熔断所属部门非法" #InvalidCircuitBreakerDepartment +400168 = "熔断备注非法" #InvalidCircuitBreakerComment +400170 = "服务有已存在的网格" #ServicesExistedMesh +400171 = "当前资源有已存在的网格" #ResourcesExistedMesh +400172 = "网格参数非法" #InvalidMeshParameter +400180 = "平台ID非法" #InvalidPlatformID +400181 = "平台名称非法" #InvalidPlatformName +400182 = "平台域名非法" #InvalidPlatformDomain +400183 = "平台qps非法" #InvalidPlatformQPS +400184 = "平台token非法" #InvalidPlatformToken +400185 = "平台拥有人非法" #InvalidPlatformOwner +400186 = "平台所属部们非法" #InvalidPlatformDepartment +400187 = "平台备注非法" #InvalidPlatformComment +400188 = "未找到平台" #NotFoundPlatform +400190 = "限流ID非法" #InvalidFluxRateLimitId +400191 = "限流qps非法" #InvalidFluxRateLimitQps +400192 = "限流标识非法" #InvalidFluxRateLimitSetKey +400201 = "资源已存在" #ExistedResource +400202 = "未找到资源" #NotFoundResource +400203 = "当前服务存在服务,请先删除服务,再删除命名空间" #NamespaceExistedServices +400204 = "当前服务存在实例,请先删除实例,再删除服务" #ServiceExistedInstances +400205 = "当前服务存在路由规则,请先删除路由规则,再删除服务" #ServiceExistedRoutings +400206 = "当前服务存在限流规则,请先删除限流规则,再删除服务" #ServiceExistedRateLimits +400207 = "存在已发布配置" #ExistReleasedConfig +400208 = "实例请求重复" #SameInstanceRequest +400209 = "当前服务存在熔断规则,请先删除熔断规则,再删除服务" #ServiceExistedCircuitBreakers +400210 = "当前服务存在服务别名,请先删除服务别名,再删除服务" #ServiceExistedAlias +400211 = "某些网格资源在当前命名空间已存在" #NamespaceExistedMeshResources +400212 = "某些熔断在当前命名空间已存在" #NamespaceExistedCircuitBreakers +400213 = "服务已被某些网格订阅" #ServiceSubscribedByMeshes +400214 = "服务已存在限流配置" #ServiceExistedFluxRateLimits +400215 = "用户已存在" #UserExisted +400216 = "用户组已存在" #UserGroupExisted +400217 = "鉴权策略规则已存在" #AuthStrategyRuleExisted +400218 = "某些子账号已属当前拥有人" #SubAccountExisted +400219 = "当前命名空间存在配置分组,请先删除配置分组,再删除命名空间" #NamespaceExistedConfigGroups +400301 = "服务未找到" #NotFoundService +400302 = "路由未找到" #NotFoundRouting +400303 = "示例未找到" #NotFoundInstance +400304 = "服务别名未找到" #NotFoundServiceAlias +400305 = "命名空间未找到" #NotFoundNamespace +400306 = "未找到和当前服务别名关联的服务" #NotFoundSourceService +400307 = "限流规则未找到" #NotFoundRateLimit +400308 = "熔断规则未找到" #NotFoundCircuitBreaker +400309 = "主配置未找到" #NotFoundMasterConfig +400310 = "标签配置未找到" #NotFoundTagConfig +400311 = "未找到标签或服务, 或者关系已存在" #NotFoundTagConfigOrService +400312 = "用户未找到" #NotFoundUser +400313 = "拥有人用户未找到" #NotFoundOwnerUser +400314 = "用户组未找到" #NotFoundUserGroup +400315 = "鉴权策略规则未找到" #NotFoundAuthStrategyRule +400401 = "客户端API未开放" #ClientAPINotOpen +400402 = "不允许请求当前业务服务" #NotAllowBusinessService +400410 = "用户所有人非法" #InvalidUserOwners +400411 = "用户ID非法" #InvalidUserID +400412 = "用户密码非法" #InvalidUserPassword +400413 = "用户手机号非法" #InvalidUserMobile +400414 = "用户邮件非法" #InvalidUserEmail +400420 = "用户组所有人的属性非法" #InvalidUserGroupOwners +400421 = "用户组ID非法" #InvalidUserGroupID +400430 = "鉴权策略规则拥有人非法" #InvalidAuthStrategyOwners +400431 = "鉴权策略规则名称非法" #InvalidAuthStrategyName +400432 = "鉴权策略ID非法" #InvalidAuthStrategyID +400440 = "鉴权策略用户主体类型非法" #InvalidPrincipalType +400501 = "服务别名不允许更新" #NotAllowAliasUpdate +400502 = "服务别名不允许创建实例" #NotAllowAliasCreateInstance +400503 = "服务别名不允许创建路由规则" #NotAllowAliasCreateRouting +400504 = "仅允许源服务可以创建别名" #NotAllowCreateAliasForAlias +400505 = "服务别名不允许创建限流规则" #NotAllowAliasCreateRateLimit +400506 = "服务别名不允许绑定规则" #NotAllowAliasBindRule +400507 = "不允许不同的命名空间绑定同一规则" #NotAllowDifferentNamespaceBindRule +400508 = "不允许修改默认策略" #NotAllowModifyDefaultStrategyPrincipal +400700 = "路由规则ID非法" #InvalidRoutingID +400701 = "路由规则类型非法,只支持 (RulePolicy,MetadataPolicy)" #InvalidRoutingPolicy +400702 = "路由名称非法" #InvalidRoutingName +400703 = "路由优先级非法,只支持[0, 10]" #InvalidRoutingPriority +400801 = "配置文件组名非法" #InvalidConfigFileGroupName +400802 = "配置文件名称非法" #InvalidConfigFileName +400803 = "配置文件内容过长" #InvalidConfigFileContentLength +400804 = "非法的配置文件格式,支持的格式有: json,xml,html,properties,text,yaml" #InvalidConfigFileFormat +400805 = "配置文件标签非法, 标签应该是成对的, 比如key1,value1,key2,value2, 并且key,value应是非空白字符" #InvalidConfigFileTags +400806 = "监视配置文件格式非法" #InvalidWatchConfigFileFormat +400807 = "无法找到配置文件" #NotFoundResourceConfigFile +400808 = "配置模板名称非法" #InvalidConfigFileTemplateName +401000 = "未经授权" #Unauthorized +401001 = "权限不被允许" #NotAllowedAccess +401002 = "鉴权token为空" #EmptyAutToken +401003 = "token已被禁用" #TokenDisabled +401004 = "token不存在" #TokenNotExisted +403001 = "ip达到服务端限制" #IPRateLimit +403002 = "api达到服务端限制" #APIRateLimit +404001 = "无法找到主机的cmdb" #CMDBNotFindHost +409000 = "数据有冲突, 请再次重试" #DataConflict +429001 = "你的实例请求过多" #InstanceTooManyRequests +500000 = "执行异常" #ExecuteException +500001 = "存储层异常" #StoreLayerException +500002 = "cmdb插件异常" #CMDBPluginException +500004 = "解析路由规则失败" #ParseRoutingException +500005 = "解析限频规则失败" #ParseRateLimitException +500006 = "解析熔断规则失败" #ParseCircuitBreakerException +500007 = "心跳异常" #HeartbeatException +500008 = "实例异步注册超时" #InstanceRegisTimeout +500100 = "token验证异常" #AuthTokenVerifyException +500101 = "角色操作异常" #OperationRoleException diff --git a/apiserver/httpserver/log.go b/apiserver/httpserver/log.go index 386ffa1f9..d1863d3fc 100644 --- a/apiserver/httpserver/log.go +++ b/apiserver/httpserver/log.go @@ -22,6 +22,7 @@ import ( ) var ( - log = commonlog.NamingScope() + log = commonlog.APIServerScope() + namingLog = commonlog.NamingScope() configLog = commonlog.ConfigScope() ) diff --git a/apiserver/httpserver/maintain_access.go b/apiserver/httpserver/maintain_access.go index 05605c3ab..cf8f4a806 100644 --- a/apiserver/httpserver/maintain_access.go +++ b/apiserver/httpserver/maintain_access.go @@ -26,6 +26,7 @@ import ( "github.com/emicklei/go-restful/v3" + httpcommon "github.com/polarismesh/polaris-server/apiserver/httpserver/http" api "github.com/polarismesh/polaris-server/common/api/v1" "github.com/polarismesh/polaris-server/common/utils" "github.com/polarismesh/polaris-server/maintain" @@ -52,7 +53,7 @@ func (h *HTTPServer) GetMaintainAccessServer() *restful.WebService { // host,可选,查看指定host func (h *HTTPServer) GetServerConnections(req *restful.Request, rsp *restful.Response) { ctx := initContext(req) - params := utils.ParseQueryParams(req) + params := httpcommon.ParseQueryParams(req) connReq := maintain.ConnReq{ Protocol: params["protocol"], Host: params["host"], @@ -69,7 +70,7 @@ func (h *HTTPServer) GetServerConnections(req *restful.Request, rsp *restful.Res // GetServerConnStats 获取连接缓存里面的统计信息 func (h *HTTPServer) GetServerConnStats(req *restful.Request, rsp *restful.Response) { ctx := initContext(req) - params := utils.ParseQueryParams(req) + params := httpcommon.ParseQueryParams(req) var amount int = 0 if amountStr, ok := params["amount"]; ok { @@ -132,7 +133,7 @@ func (h *HTTPServer) FreeOSMemory(req *restful.Request, rsp *restful.Response) { // CleanInstance 彻底清理flag=1的实例运维接口 // 支持一个个清理 func (h *HTTPServer) CleanInstance(req *restful.Request, rsp *restful.Response) { - handler := &Handler{req, rsp} + handler := &httpcommon.Handler{req, rsp} instance := &api.Instance{} ctx, err := handler.Parse(instance) @@ -147,8 +148,8 @@ func (h *HTTPServer) CleanInstance(req *restful.Request, rsp *restful.Response) // GetLastHeartbeat 获取实例,上一次心跳的时间 func (h *HTTPServer) GetLastHeartbeat(req *restful.Request, rsp *restful.Response) { ctx := initContext(req) - handler := &Handler{req, rsp} - params := utils.ParseQueryParams(req) + handler := &httpcommon.Handler{req, rsp} + params := httpcommon.ParseQueryParams(req) instance := &api.Instance{} if id, ok := params["id"]; ok && id != "" { instance.Id = utils.NewStringValue(id) diff --git a/apiserver/httpserver/proto.go b/apiserver/httpserver/proto.go index 14676db5f..aefd4587b 100644 --- a/apiserver/httpserver/proto.go +++ b/apiserver/httpserver/proto.go @@ -35,66 +35,6 @@ func (m *NamespaceArr) String() string { return proto.CompactTextString(m) } // ProtoMessage return proto message func (*NamespaceArr) ProtoMessage() {} -// ServiceArr 服务数组定义 -type ServiceArr []*api.Service - -// Reset 重置初始化 -func (m *ServiceArr) Reset() { *m = ServiceArr{} } - -// String return string -func (m *ServiceArr) String() string { return proto.CompactTextString(m) } - -// ProtoMessage return proto message -func (*ServiceArr) ProtoMessage() {} - -// InstanceArr 服务实例数组定义 -type InstanceArr []*api.Instance - -// Reset reset initialization -func (m *InstanceArr) Reset() { *m = InstanceArr{} } - -// String -func (m *InstanceArr) String() string { return proto.CompactTextString(m) } - -// ProtoMessage return proto message -func (*InstanceArr) ProtoMessage() {} - -// RoutingArr 路由规则数组定义 -type RoutingArr []*api.Routing - -// Reset reset initialization -func (m *RoutingArr) Reset() { *m = RoutingArr{} } - -// String return string -func (m *RoutingArr) String() string { return proto.CompactTextString(m) } - -// ProtoMessage return proto message -func (*RoutingArr) ProtoMessage() {} - -// RateLimitArr 限流规则数组定义 -type RateLimitArr []*api.Rule - -// Reset reset initialization -func (m *RateLimitArr) Reset() { *m = RateLimitArr{} } - -// String -func (m *RateLimitArr) String() string { return proto.CompactTextString(m) } - -// ProtoMessage return proto message -func (*RateLimitArr) ProtoMessage() {} - -// CircuitBreakerArr 熔断规则数组定义 -type CircuitBreakerArr []*api.CircuitBreaker - -// Reset reset initialization -func (m *CircuitBreakerArr) Reset() { *m = CircuitBreakerArr{} } - -// String -func (m *CircuitBreakerArr) String() string { return proto.CompactTextString(m) } - -// ProtoMessage return proto message -func (*CircuitBreakerArr) ProtoMessage() {} - // ConfigReleaseArr 发布规则数组定义 type ConfigReleaseArr []*api.ConfigRelease diff --git a/apiserver/httpserver/server.go b/apiserver/httpserver/server.go index 94366327a..2b8f48f5a 100644 --- a/apiserver/httpserver/server.go +++ b/apiserver/httpserver/server.go @@ -31,9 +31,13 @@ import ( "go.uber.org/zap" "github.com/polarismesh/polaris-server/apiserver" + httpcommon "github.com/polarismesh/polaris-server/apiserver/httpserver/http" + v1 "github.com/polarismesh/polaris-server/apiserver/httpserver/v1" + v2 "github.com/polarismesh/polaris-server/apiserver/httpserver/v2" "github.com/polarismesh/polaris-server/auth" api "github.com/polarismesh/polaris-server/common/api/v1" "github.com/polarismesh/polaris-server/common/connlimit" + commonlog "github.com/polarismesh/polaris-server/common/log" "github.com/polarismesh/polaris-server/common/metrics" "github.com/polarismesh/polaris-server/common/secure" "github.com/polarismesh/polaris-server/common/utils" @@ -58,7 +62,8 @@ type HTTPServer struct { restart bool exitCh chan struct{} - enablePprof bool + enablePprof bool + enableSwagger bool server *http.Server maintainServer maintain.MaintainOperateServer @@ -70,6 +75,9 @@ type HTTPServer struct { statis plugin.Statis auth plugin.Auth + v1Server v1.HTTPServerV1 + v2Server v2.HTTPServerV2 + authServer auth.AuthServer } @@ -96,6 +104,7 @@ func (h *HTTPServer) Initialize(_ context.Context, option map[string]interface{} h.listenIP = option["listenIP"].(string) h.listenPort = uint32(option["listenPort"].(int)) h.enablePprof, _ = option["enablePprof"].(bool) + h.enableSwagger, _ = option["enableSwagger"].(bool) // 连接数限制的配置 if raw, _ := option["connLimit"].(map[interface{}]interface{}); raw != nil { connLimitConfig, err := connlimit.ParseConnLimitConfig(raw) @@ -190,6 +199,9 @@ func (h *HTTPServer) Run(errCh chan error) { return } + h.v1Server = *v1.NewV1Server(h.namespaceServer, h.namingServer, h.healthCheckServer) + h.v2Server = *v2.NewV2Server(h.namespaceServer, h.namingServer, h.healthCheckServer) + // 初始化http server address := fmt.Sprintf("%v:%v", h.listenIP, h.listenPort) @@ -320,16 +332,22 @@ func (h *HTTPServer) createRestfulContainer() (*restful.Container, error) { } case "console": if config.Enable { - namingService, err := h.GetNamingConsoleAccessServer(config.Include) + namingServiceV1, err := h.v1Server.GetNamingConsoleAccessServer(config.Include) + if err != nil { + return nil, err + } + wsContainer.Add(namingServiceV1) + + namingServiceV2, err := h.v2Server.GetNamingConsoleAccessServer(config.Include) if err != nil { return nil, err } - wsContainer.Add(namingService) + wsContainer.Add(namingServiceV2) ws := new(restful.WebService) ws.Path("/core/v1").Consumes(restful.MIME_JSON).Produces(restful.MIME_JSON) - if err := h.GetCoreConsoleAccessServer(ws, config.Include); err != nil { + if err := h.GetCoreV1ConsoleAccessServer(ws, config.Include); err != nil { return nil, err } if err := h.GetAuthServer(ws); err != nil { @@ -340,11 +358,17 @@ func (h *HTTPServer) createRestfulContainer() (*restful.Container, error) { } case "client": if config.Enable { - service, err := h.GetClientAccessServer(config.Include) + serviceV1, err := h.v1Server.GetClientAccessServer(config.Include) + if err != nil { + return nil, err + } + wsContainer.Add(serviceV1) + + serviceV2, err := h.v2Server.GetClientAccessServer(config.Include) if err != nil { return nil, err } - wsContainer.Add(service) + wsContainer.Add(serviceV2) } case "config": if config.Enable { @@ -364,6 +388,10 @@ func (h *HTTPServer) createRestfulContainer() (*restful.Container, error) { h.enablePprofAccess(wsContainer) } + if h.enableSwagger { + h.enableSwaggerAPI(wsContainer) + } + statis := plugin.GetStatis() if _, ok := statis.(*local.StatisWorker); ok { h.enablePrometheusAccess(wsContainer) @@ -415,8 +443,15 @@ func (h *HTTPServer) preprocess(req *restful.Request, rsp *restful.Response) err platformID := req.HeaderParameter("Platform-Id") requestURL := req.Request.URL.String() if !strings.Contains(requestURL, Discover) { + var scope *commonlog.Scope + if strings.Contains(requestURL, "naming") { + scope = namingLog + } else { + scope = configLog + } + // 打印请求 - log.Info("receive request", + scope.Info("receive request", zap.String("client-address", req.Request.RemoteAddr), zap.String("user-agent", req.HeaderParameter("User-Agent")), zap.String("request-id", requestID), @@ -465,7 +500,14 @@ func (h *HTTPServer) postProcess(req *restful.Request, rsp *restful.Response) { diff := now.Sub(startTime) // 打印耗时超过1s的请求 if diff > time.Second { - log.Info("handling time > 1s", + var scope *commonlog.Scope + if strings.Contains(path, "naming") { + scope = namingLog + } else { + scope = configLog + } + + scope.Info("handling time > 1s", zap.String("client-address", req.Request.RemoteAddr), zap.String("user-agent", req.HeaderParameter("User-Agent")), zap.String("request-id", req.HeaderParameter("Request-Id")), @@ -503,7 +545,7 @@ func (h *HTTPServer) enterAuth(req *restful.Request, rsp *restful.Response) erro zap.String("request-id", rid), zap.String("platform-id", pid), zap.String("platform-token", pToken)) - HTTPResponse(req, rsp, api.NotAllowedAccess) + httpcommon.HTTPResponse(req, rsp, api.NotAllowedAccess) return errors.New("http access is not allowed") } return nil @@ -527,7 +569,7 @@ func (h *HTTPServer) enterRateLimit(req *restful.Request, rsp *restful.Response) if ok := h.rateLimit.Allow(plugin.IPRatelimit, segments[0]); !ok { log.Error("ip ratelimit is not allow", zap.String("client", address), zap.String("request-id", rid)) - HTTPResponse(req, rsp, api.IPRateLimit) + httpcommon.HTTPResponse(req, rsp, api.IPRateLimit) return errors.New("ip ratelimit is not allow") } @@ -537,7 +579,7 @@ func (h *HTTPServer) enterRateLimit(req *restful.Request, rsp *restful.Response) if ok := h.rateLimit.Allow(plugin.APIRatelimit, apiName); !ok { log.Error("api ratelimit is not allow", zap.String("client", address), zap.String("request-id", rid), zap.String("api", apiName)) - HTTPResponse(req, rsp, api.APIRateLimit) + httpcommon.HTTPResponse(req, rsp, api.APIRateLimit) return errors.New("api ratelimit is not allow") } diff --git a/apiserver/httpserver/swagger_access.go b/apiserver/httpserver/swagger_access.go new file mode 100644 index 000000000..2c1335bd7 --- /dev/null +++ b/apiserver/httpserver/swagger_access.go @@ -0,0 +1,110 @@ +/** + * Tencent is pleased to support the open source community by making Polaris available. + * + * Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved. + * + * Licensed under the BSD 3-Clause License (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://opensource.org/licenses/BSD-3-Clause + * + * 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 httpserver + +import ( + "github.com/emicklei/go-restful/v3" + "github.com/go-openapi/spec" + restfulspec "github.com/polarismesh/go-restful-openapi/v2" + "github.com/polarismesh/polaris-server/common/version" +) + +func (h *HTTPServer) enableSwaggerAPI(wsContainer *restful.Container) { + log.Infof("[HTTPServer] open http access for swagger API") + config := restfulspec.Config{ + WebServices: wsContainer.RegisteredWebServices(), // you control what services are visible + APIPath: "/apidocs.json", + PostBuildSwaggerObjectHandler: enrichSwaggerObject, + } + + wsContainer.Add(restfulspec.NewOpenAPIService(config)) +} + +func enrichSwaggerObject(swo *spec.Swagger) { + swo.Info = &spec.Info{ + InfoProps: spec.InfoProps{ + Title: "Polaris Server", + Description: "一个支持多语言、多框架的云原生服务发现和治理中心\n\n提供高性能SDK和无侵入Sidecar两种接入方式\n\n", + Contact: &spec.ContactInfo{ + ContactInfoProps: spec.ContactInfoProps{ + Name: "Polaris Mesh", + //Email: "polaris@qq.com", + URL: "https://polarismesh.cn/", + }, + }, + License: &spec.License{ + LicenseProps: spec.LicenseProps{ + Name: "BSD 3-Clause", + URL: "https://github.com/polarismesh/polaris/blob/main/LICENSE", + }, + }, + Version: version.GetRevision(), + }, + } + swo.Tags = []spec.Tag{ + {TagProps: spec.TagProps{ + Name: "Alias", + Description: "服务别名管理"}}, + {TagProps: spec.TagProps{ + Name: "Auth", + Description: "鉴权管理"}}, + {TagProps: spec.TagProps{ + Name: "ConfigClient", + Description: "客户端API接口"}}, + {TagProps: spec.TagProps{ + Name: "ConfigConsole", + Description: "服务端接口"}}, + {TagProps: spec.TagProps{ + Name: "Client", + Description: "客户端"}}, + {TagProps: spec.TagProps{ + Name: "Instances", + Description: "实例管理"}}, + {TagProps: spec.TagProps{ + Name: "Namespaces", + Description: "命名空间管理"}}, + {TagProps: spec.TagProps{ + Name: "Routing", + Description: "路由规则管理"}}, + {TagProps: spec.TagProps{ + Name: "RateLimits", + Description: "限流规则管理"}}, + {TagProps: spec.TagProps{ + Name: "RegisterInstance", + Description: "服务发现"}}, + {TagProps: spec.TagProps{ + Name: "Services", + Description: "服务管理"}}, + {TagProps: spec.TagProps{ + Name: "Users", + Description: "用户管理"}}, + {TagProps: spec.TagProps{ + Name: "UserGroup", + Description: "用户组"}}, + } + + swo.SecurityDefinitions = map[string]*spec.SecurityScheme{ + "api_key": spec.APIKeyAuth("X-Polaris-Token", "header"), + } + + var securitySetting []map[string][]string + apiKey := make(map[string][]string, 0) + apiKey["api_key"] = []string{} + securitySetting = append(securitySetting, apiKey) + swo.Security = securitySetting +} diff --git a/apiserver/grpcserver/log.go b/apiserver/httpserver/v1/log.go similarity index 85% rename from apiserver/grpcserver/log.go rename to apiserver/httpserver/v1/log.go index a837bceef..e779ea0dc 100644 --- a/apiserver/grpcserver/log.go +++ b/apiserver/httpserver/v1/log.go @@ -15,10 +15,14 @@ * specific language governing permissions and limitations under the License. */ -package grpcserver +package v1 import ( commonlog "github.com/polarismesh/polaris-server/common/log" ) -var log = commonlog.NamingScope() +var ( + log = commonlog.APIServerScope() + namingLog = commonlog.NamingScope() + configLog = commonlog.ConfigScope() +) diff --git a/apiserver/httpserver/naming_client_access.go b/apiserver/httpserver/v1/naming_client_access.go similarity index 72% rename from apiserver/httpserver/naming_client_access.go rename to apiserver/httpserver/v1/naming_client_access.go index 1ea6efc96..40a1cb043 100644 --- a/apiserver/httpserver/naming_client_access.go +++ b/apiserver/httpserver/v1/naming_client_access.go @@ -15,20 +15,22 @@ * specific language governing permissions and limitations under the License. */ -package httpserver +package v1 import ( "fmt" "github.com/emicklei/go-restful/v3" + restfulspec "github.com/polarismesh/go-restful-openapi/v2" "go.uber.org/zap" "github.com/polarismesh/polaris-server/apiserver" + httpcommon "github.com/polarismesh/polaris-server/apiserver/httpserver/http" api "github.com/polarismesh/polaris-server/common/api/v1" ) // GetClientAccessServer get client access server -func (h *HTTPServer) GetClientAccessServer(include []string) (*restful.WebService, error) { +func (h *HTTPServerV1) GetClientAccessServer(include []string) (*restful.WebService, error) { clientAccess := []string{apiserver.DiscoverAccess, apiserver.RegisterAccess, apiserver.HealthcheckAccess} ws := new(restful.WebService) @@ -59,25 +61,39 @@ func (h *HTTPServer) GetClientAccessServer(include []string) (*restful.WebServic } // addDiscoverAccess 增加服务发现接口 -func (h *HTTPServer) addDiscoverAccess(ws *restful.WebService) { - ws.Route(ws.POST("/ReportClient").To(h.ReportClient)) - ws.Route(ws.POST("/Discover").To(h.Discover)) +func (h *HTTPServerV1) addDiscoverAccess(ws *restful.WebService) { + tags := []string{"DiscoverAccess"} + ws.Route(ws.POST("/ReportClient").To(h.ReportClient). + Doc("上报客户端"). + Writes(&api.Client{}). + Metadata(restfulspec.KeyOpenAPITags, tags)) + ws.Route(ws.POST("/Discover").To(h.Discover). + Doc("服务发现"). + Metadata(restfulspec.KeyOpenAPITags, tags)) } // addRegisterAccess 增加注册/反注册接口 -func (h *HTTPServer) addRegisterAccess(ws *restful.WebService) { - ws.Route(ws.POST("/RegisterInstance").To(h.RegisterInstance)) - ws.Route(ws.POST("/DeregisterInstance").To(h.DeregisterInstance)) +func (h *HTTPServerV1) addRegisterAccess(ws *restful.WebService) { + tags := []string{"Instances", "RegisterAccess"} + ws.Route(ws.POST("/RegisterInstance"). + Doc("注册实例"). + Metadata(restfulspec.KeyOpenAPITags, tags). + To(h.RegisterInstance)) + + ws.Route(ws.POST("/DeregisterInstance"). + Doc("移除注册实例"). + Metadata(restfulspec.KeyOpenAPITags, tags). + To(h.DeregisterInstance)) } // addHealthCheckAccess 增加健康检查接口 -func (h *HTTPServer) addHealthCheckAccess(ws *restful.WebService) { +func (h *HTTPServerV1) addHealthCheckAccess(ws *restful.WebService) { ws.Route(ws.POST("/Heartbeat").To(h.Heartbeat)) } // ReportClient 客户端上报信息 -func (h *HTTPServer) ReportClient(req *restful.Request, rsp *restful.Response) { - handler := &Handler{req, rsp} +func (h *HTTPServerV1) ReportClient(req *restful.Request, rsp *restful.Response) { + handler := &httpcommon.Handler{req, rsp} client := &api.Client{} ctx, err := handler.Parse(client) if err != nil { @@ -89,8 +105,8 @@ func (h *HTTPServer) ReportClient(req *restful.Request, rsp *restful.Response) { } // RegisterInstance 注册服务实例 -func (h *HTTPServer) RegisterInstance(req *restful.Request, rsp *restful.Response) { - handler := &Handler{req, rsp} +func (h *HTTPServerV1) RegisterInstance(req *restful.Request, rsp *restful.Response) { + handler := &httpcommon.Handler{req, rsp} instance := &api.Instance{} ctx, err := handler.Parse(instance) @@ -103,8 +119,8 @@ func (h *HTTPServer) RegisterInstance(req *restful.Request, rsp *restful.Respons } // DeregisterInstance 反注册服务实例 -func (h *HTTPServer) DeregisterInstance(req *restful.Request, rsp *restful.Response) { - handler := &Handler{req, rsp} +func (h *HTTPServerV1) DeregisterInstance(req *restful.Request, rsp *restful.Response) { + handler := &httpcommon.Handler{req, rsp} instance := &api.Instance{} ctx, err := handler.Parse(instance) @@ -117,8 +133,8 @@ func (h *HTTPServer) DeregisterInstance(req *restful.Request, rsp *restful.Respo } // Discover 统一发现接口 -func (h *HTTPServer) Discover(req *restful.Request, rsp *restful.Response) { - handler := &Handler{req, rsp} +func (h *HTTPServerV1) Discover(req *restful.Request, rsp *restful.Response) { + handler := &httpcommon.Handler{req, rsp} discoverRequest := &api.DiscoverRequest{} ctx, err := handler.Parse(discoverRequest) @@ -128,7 +144,7 @@ func (h *HTTPServer) Discover(req *restful.Request, rsp *restful.Response) { } msg := fmt.Sprintf("receive http discover request: %s", discoverRequest.Service.String()) - log.Info(msg, + namingLog.Info(msg, zap.String("type", api.DiscoverRequest_DiscoverRequestType_name[int32(discoverRequest.Type)]), zap.String("client-address", req.Request.RemoteAddr), zap.String("user-agent", req.HeaderParameter("User-Agent")), @@ -155,8 +171,8 @@ func (h *HTTPServer) Discover(req *restful.Request, rsp *restful.Response) { } // Heartbeat 服务实例心跳 -func (h *HTTPServer) Heartbeat(req *restful.Request, rsp *restful.Response) { - handler := &Handler{req, rsp} +func (h *HTTPServerV1) Heartbeat(req *restful.Request, rsp *restful.Response) { + handler := &httpcommon.Handler{req, rsp} instance := &api.Instance{} ctx, err := handler.Parse(instance) diff --git a/apiserver/httpserver/naming_console_access.go b/apiserver/httpserver/v1/naming_console_access.go similarity index 73% rename from apiserver/httpserver/naming_console_access.go rename to apiserver/httpserver/v1/naming_console_access.go index d143ab365..7ee80f6f0 100644 --- a/apiserver/httpserver/naming_console_access.go +++ b/apiserver/httpserver/v1/naming_console_access.go @@ -15,7 +15,7 @@ * specific language governing permissions and limitations under the License. */ -package httpserver +package v1 import ( "context" @@ -24,7 +24,9 @@ import ( "github.com/emicklei/go-restful/v3" "github.com/golang/protobuf/proto" + restfulspec "github.com/polarismesh/go-restful-openapi/v2" + httpcommon "github.com/polarismesh/polaris-server/apiserver/httpserver/http" api "github.com/polarismesh/polaris-server/common/api/v1" "github.com/polarismesh/polaris-server/common/utils" ) @@ -35,7 +37,7 @@ const ( ) // GetNamingConsoleAccessServer 注册管理端接口 -func (h *HTTPServer) GetNamingConsoleAccessServer(include []string) (*restful.WebService, error) { +func (h *HTTPServerV1) GetNamingConsoleAccessServer(include []string) (*restful.WebService, error) { consoleAccess := []string{defaultAccess} ws := new(restful.WebService) @@ -63,18 +65,24 @@ func (h *HTTPServer) GetNamingConsoleAccessServer(include []string) (*restful.We case defaultAccess: h.addDefaultAccess(ws) default: - log.Errorf("method %s does not exist in httpserver console access", item) - return nil, fmt.Errorf("method %s does not exist in httpserver console access", item) + log.Errorf("method %s does not exist in HTTPServerV1 console access", item) + return nil, fmt.Errorf("method %s does not exist in HTTPServerV1 console access", item) } } return ws, nil } // addDefaultReadAccess 增加默认读接口 -func (h *HTTPServer) addDefaultReadAccess(ws *restful.WebService) { +func (h *HTTPServerV1) addDefaultReadAccess(ws *restful.WebService) { // 管理端接口:只包含读接口 - ws.Route(ws.GET("/namespaces").To(h.GetNamespaces)) - ws.Route(ws.GET("/namespace/token").To(h.GetNamespaceToken)) + nsTags := []string{"Namespaces"} + ws.Route(ws.GET("/namespaces").To(h.GetNamespaces). + Doc("get namespaces"). + Metadata(restfulspec.KeyOpenAPITags, nsTags)) + + ws.Route(ws.GET("/namespace/token").To(h.GetNamespaceToken). + Doc("get namespaces token"). + Metadata(restfulspec.KeyOpenAPITags, nsTags)) ws.Route(ws.GET("/services").To(h.GetServices)) ws.Route(ws.GET("/services/count").To(h.GetServicesCount)) @@ -98,13 +106,10 @@ func (h *HTTPServer) addDefaultReadAccess(ws *restful.WebService) { ws.Route(ws.GET("/circuitbreakers/master").To(h.GetMasterCircuitBreakers)) ws.Route(ws.GET("/circuitbreakers/release").To(h.GetReleaseCircuitBreakers)) ws.Route(ws.GET("/circuitbreaker/token").To(h.GetCircuitBreakerToken)) - - ws.Route(ws.GET("/platforms").To(h.GetPlatforms)) - ws.Route(ws.GET("/platform/token").To(h.GetPlatformToken)) } // addDefaultAccess 增加默认接口 -func (h *HTTPServer) addDefaultAccess(ws *restful.WebService) { +func (h *HTTPServerV1) addDefaultAccess(ws *restful.WebService) { // 管理端接口:增删改查请求全部操作存储层 ws.Route(ws.POST("/namespaces").To(h.CreateNamespaces)) ws.Route(ws.POST("/namespaces/delete").To(h.DeleteNamespaces)) @@ -134,6 +139,7 @@ func (h *HTTPServer) addDefaultAccess(ws *restful.WebService) { ws.Route(ws.PUT("/instances/isolate/host").To(h.UpdateInstancesIsolate)) ws.Route(ws.GET("/instances").To(h.GetInstances)) ws.Route(ws.GET("/instances/count").To(h.GetInstancesCount)) + ws.Route(ws.GET("/instances/labels").To(h.GetInstanceLabels)) ws.Route(ws.POST("/routings").To(h.CreateRoutings)) ws.Route(ws.POST("/routings/delete").To(h.DeleteRoutings)) @@ -157,18 +163,11 @@ func (h *HTTPServer) addDefaultAccess(ws *restful.WebService) { ws.Route(ws.GET("/circuitbreakers/master").To(h.GetMasterCircuitBreakers)) ws.Route(ws.GET("/circuitbreakers/release").To(h.GetReleaseCircuitBreakers)) ws.Route(ws.GET("/circuitbreaker/token").To(h.GetCircuitBreakerToken)) - - ws.Route(ws.POST("/platforms").To(h.CreatePlatforms)) - ws.Route(ws.POST("/platforms/delete").To(h.DeletePlatforms)) - ws.Route(ws.PUT("/platforms").To(h.UpdatePlatforms)) - ws.Route(ws.GET("/platforms").To(h.GetPlatforms)) - ws.Route(ws.GET("/platform/token").To(h.GetPlatformToken)) - } // CreateNamespaces 创建命名空间 -func (h *HTTPServer) CreateNamespaces(req *restful.Request, rsp *restful.Response) { - handler := &Handler{req, rsp} +func (h *HTTPServerV1) CreateNamespaces(req *restful.Request, rsp *restful.Response) { + handler := &httpcommon.Handler{req, rsp} var namespaces NamespaceArr ctx, err := handler.ParseArray(func() proto.Message { @@ -185,8 +184,8 @@ func (h *HTTPServer) CreateNamespaces(req *restful.Request, rsp *restful.Respons } // DeleteNamespaces 删除命名空间 -func (h *HTTPServer) DeleteNamespaces(req *restful.Request, rsp *restful.Response) { - handler := &Handler{req, rsp} +func (h *HTTPServerV1) DeleteNamespaces(req *restful.Request, rsp *restful.Response) { + handler := &httpcommon.Handler{req, rsp} var namespaces NamespaceArr ctx, err := handler.ParseArray(func() proto.Message { @@ -209,8 +208,8 @@ func (h *HTTPServer) DeleteNamespaces(req *restful.Request, rsp *restful.Respons } // UpdateNamespaces 修改命名空间 -func (h *HTTPServer) UpdateNamespaces(req *restful.Request, rsp *restful.Response) { - handler := &Handler{req, rsp} +func (h *HTTPServerV1) UpdateNamespaces(req *restful.Request, rsp *restful.Response) { + handler := &httpcommon.Handler{req, rsp} var namespaces NamespaceArr ctx, err := handler.ParseArray(func() proto.Message { @@ -233,21 +232,21 @@ func (h *HTTPServer) UpdateNamespaces(req *restful.Request, rsp *restful.Respons } // GetNamespaces 查询命名空间 -func (h *HTTPServer) GetNamespaces(req *restful.Request, rsp *restful.Response) { - handler := &Handler{req, rsp} +func (h *HTTPServerV1) GetNamespaces(req *restful.Request, rsp *restful.Response) { + handler := &httpcommon.Handler{req, rsp} ret := h.namespaceServer.GetNamespaces(handler.ParseHeaderContext(), req.Request.URL.Query()) handler.WriteHeaderAndProto(ret) } // GetNamespaceToken 命名空间token的获取 -func (h *HTTPServer) GetNamespaceToken(req *restful.Request, rsp *restful.Response) { - handler := &Handler{req, rsp} +func (h *HTTPServerV1) GetNamespaceToken(req *restful.Request, rsp *restful.Response) { + handler := &httpcommon.Handler{req, rsp} token := req.HeaderParameter("Polaris-Token") ctx := context.WithValue(context.Background(), utils.StringContext("polaris-token"), token) - queryParams := utils.ParseQueryParams(req) + queryParams := httpcommon.ParseQueryParams(req) namespace := &api.Namespace{ Name: utils.NewStringValue(queryParams["name"]), Token: utils.NewStringValue(queryParams["token"]), @@ -258,8 +257,8 @@ func (h *HTTPServer) GetNamespaceToken(req *restful.Request, rsp *restful.Respon } // UpdateNamespaceToken 更新命名空间的token -func (h *HTTPServer) UpdateNamespaceToken(req *restful.Request, rsp *restful.Response) { - handler := &Handler{req, rsp} +func (h *HTTPServerV1) UpdateNamespaceToken(req *restful.Request, rsp *restful.Response) { + handler := &httpcommon.Handler{req, rsp} var namespace api.Namespace ctx, err := handler.Parse(&namespace) @@ -273,8 +272,8 @@ func (h *HTTPServer) UpdateNamespaceToken(req *restful.Request, rsp *restful.Res } // CreateServices 创建服务 -func (h *HTTPServer) CreateServices(req *restful.Request, rsp *restful.Response) { - handler := &Handler{req, rsp} +func (h *HTTPServerV1) CreateServices(req *restful.Request, rsp *restful.Response) { + handler := &httpcommon.Handler{req, rsp} var services ServiceArr ctx, err := handler.ParseArray(func() proto.Message { @@ -291,8 +290,8 @@ func (h *HTTPServer) CreateServices(req *restful.Request, rsp *restful.Response) } // DeleteServices 删除服务 -func (h *HTTPServer) DeleteServices(req *restful.Request, rsp *restful.Response) { - handler := &Handler{req, rsp} +func (h *HTTPServerV1) DeleteServices(req *restful.Request, rsp *restful.Response) { + handler := &httpcommon.Handler{req, rsp} var services ServiceArr ctx, err := handler.ParseArray(func() proto.Message { @@ -315,8 +314,8 @@ func (h *HTTPServer) DeleteServices(req *restful.Request, rsp *restful.Response) } // UpdateServices 修改服务 -func (h *HTTPServer) UpdateServices(req *restful.Request, rsp *restful.Response) { - handler := &Handler{req, rsp} +func (h *HTTPServerV1) UpdateServices(req *restful.Request, rsp *restful.Response) { + handler := &httpcommon.Handler{req, rsp} var services ServiceArr ctx, err := handler.ParseArray(func() proto.Message { @@ -338,29 +337,29 @@ func (h *HTTPServer) UpdateServices(req *restful.Request, rsp *restful.Response) } // GetServices 查询服务 -func (h *HTTPServer) GetServices(req *restful.Request, rsp *restful.Response) { - handler := &Handler{req, rsp} +func (h *HTTPServerV1) GetServices(req *restful.Request, rsp *restful.Response) { + handler := &httpcommon.Handler{req, rsp} - queryParams := utils.ParseQueryParams(req) + queryParams := httpcommon.ParseQueryParams(req) ctx := handler.ParseHeaderContext() ret := h.namingServer.GetServices(ctx, queryParams) handler.WriteHeaderAndProto(ret) } // GetServicesCount 查询服务总数 -func (h *HTTPServer) GetServicesCount(req *restful.Request, rsp *restful.Response) { - handler := &Handler{req, rsp} +func (h *HTTPServerV1) GetServicesCount(req *restful.Request, rsp *restful.Response) { + handler := &httpcommon.Handler{req, rsp} ret := h.namingServer.GetServicesCount(handler.ParseHeaderContext()) handler.WriteHeaderAndProto(ret) } // GetServiceToken 获取服务token -func (h *HTTPServer) GetServiceToken(req *restful.Request, rsp *restful.Response) { - handler := &Handler{req, rsp} +func (h *HTTPServerV1) GetServiceToken(req *restful.Request, rsp *restful.Response) { + handler := &httpcommon.Handler{req, rsp} token := req.HeaderParameter("Polaris-Token") ctx := context.WithValue(context.Background(), utils.StringContext("polaris-token"), token) - queryParams := utils.ParseQueryParams(req) + queryParams := httpcommon.ParseQueryParams(req) service := &api.Service{ Name: utils.NewStringValue(queryParams["name"]), Namespace: utils.NewStringValue(queryParams["namespace"]), @@ -372,8 +371,8 @@ func (h *HTTPServer) GetServiceToken(req *restful.Request, rsp *restful.Response } // UpdateServiceToken 更新服务token -func (h *HTTPServer) UpdateServiceToken(req *restful.Request, rsp *restful.Response) { - handler := &Handler{req, rsp} +func (h *HTTPServerV1) UpdateServiceToken(req *restful.Request, rsp *restful.Response) { + handler := &httpcommon.Handler{req, rsp} var service api.Service ctx, err := handler.Parse(&service) @@ -386,8 +385,8 @@ func (h *HTTPServer) UpdateServiceToken(req *restful.Request, rsp *restful.Respo } // CreateServiceAlias service alias -func (h *HTTPServer) CreateServiceAlias(req *restful.Request, rsp *restful.Response) { - handler := &Handler{req, rsp} +func (h *HTTPServerV1) CreateServiceAlias(req *restful.Request, rsp *restful.Response) { + handler := &httpcommon.Handler{req, rsp} var alias api.ServiceAlias ctx, err := handler.Parse(&alias) @@ -400,8 +399,8 @@ func (h *HTTPServer) CreateServiceAlias(req *restful.Request, rsp *restful.Respo } // UpdateServiceAlias 修改服务别名 -func (h *HTTPServer) UpdateServiceAlias(req *restful.Request, rsp *restful.Response) { - handler := &Handler{req, rsp} +func (h *HTTPServerV1) UpdateServiceAlias(req *restful.Request, rsp *restful.Response) { + handler := &httpcommon.Handler{req, rsp} var alias api.ServiceAlias ctx, err := handler.Parse(&alias) @@ -420,8 +419,8 @@ func (h *HTTPServer) UpdateServiceAlias(req *restful.Request, rsp *restful.Respo } // DeleteServiceAliases 删除服务别名 -func (h *HTTPServer) DeleteServiceAliases(req *restful.Request, rsp *restful.Response) { - handler := &Handler{req, rsp} +func (h *HTTPServerV1) DeleteServiceAliases(req *restful.Request, rsp *restful.Response) { + handler := &httpcommon.Handler{req, rsp} var aliases ServiceAliasArr ctx, err := handler.ParseArray(func() proto.Message { @@ -443,17 +442,17 @@ func (h *HTTPServer) DeleteServiceAliases(req *restful.Request, rsp *restful.Res } // GetServiceAliases 根据源服务获取服务别名 -func (h *HTTPServer) GetServiceAliases(req *restful.Request, rsp *restful.Response) { - handler := &Handler{req, rsp} +func (h *HTTPServerV1) GetServiceAliases(req *restful.Request, rsp *restful.Response) { + handler := &httpcommon.Handler{req, rsp} - queryParams := utils.ParseQueryParams(req) + queryParams := httpcommon.ParseQueryParams(req) ret := h.namingServer.GetServiceAliases(handler.ParseHeaderContext(), queryParams) handler.WriteHeaderAndProto(ret) } // CreateInstances 创建服务实例 -func (h *HTTPServer) CreateInstances(req *restful.Request, rsp *restful.Response) { - handler := &Handler{req, rsp} +func (h *HTTPServerV1) CreateInstances(req *restful.Request, rsp *restful.Response) { + handler := &httpcommon.Handler{req, rsp} var instances InstanceArr ctx, err := handler.ParseArray(func() proto.Message { @@ -470,8 +469,8 @@ func (h *HTTPServer) CreateInstances(req *restful.Request, rsp *restful.Response } // DeleteInstances 删除服务实例 -func (h *HTTPServer) DeleteInstances(req *restful.Request, rsp *restful.Response) { - handler := &Handler{req, rsp} +func (h *HTTPServerV1) DeleteInstances(req *restful.Request, rsp *restful.Response) { + handler := &httpcommon.Handler{req, rsp} var instances InstanceArr ctx, err := handler.ParseArray(func() proto.Message { @@ -494,8 +493,8 @@ func (h *HTTPServer) DeleteInstances(req *restful.Request, rsp *restful.Response } // DeleteInstancesByHost 根据host删除服务实例 -func (h *HTTPServer) DeleteInstancesByHost(req *restful.Request, rsp *restful.Response) { - handler := &Handler{req, rsp} +func (h *HTTPServerV1) DeleteInstancesByHost(req *restful.Request, rsp *restful.Response) { + handler := &httpcommon.Handler{req, rsp} var instances InstanceArr ctx, err := handler.ParseArray(func() proto.Message { @@ -518,8 +517,8 @@ func (h *HTTPServer) DeleteInstancesByHost(req *restful.Request, rsp *restful.Re } // UpdateInstances 修改服务实例 -func (h *HTTPServer) UpdateInstances(req *restful.Request, rsp *restful.Response) { - handler := &Handler{req, rsp} +func (h *HTTPServerV1) UpdateInstances(req *restful.Request, rsp *restful.Response) { + handler := &httpcommon.Handler{req, rsp} var instances InstanceArr ctx, err := handler.ParseArray(func() proto.Message { @@ -542,8 +541,8 @@ func (h *HTTPServer) UpdateInstances(req *restful.Request, rsp *restful.Response } // UpdateInstancesIsolate 修改服务实例的隔离状态 -func (h *HTTPServer) UpdateInstancesIsolate(req *restful.Request, rsp *restful.Response) { - handler := &Handler{req, rsp} +func (h *HTTPServerV1) UpdateInstancesIsolate(req *restful.Request, rsp *restful.Response) { + handler := &httpcommon.Handler{req, rsp} var instances InstanceArr ctx, err := handler.ParseArray(func() proto.Message { @@ -566,25 +565,33 @@ func (h *HTTPServer) UpdateInstancesIsolate(req *restful.Request, rsp *restful.R } // GetInstances 查询服务实例 -func (h *HTTPServer) GetInstances(req *restful.Request, rsp *restful.Response) { - handler := &Handler{req, rsp} +func (h *HTTPServerV1) GetInstances(req *restful.Request, rsp *restful.Response) { + handler := &httpcommon.Handler{req, rsp} - queryParams := utils.ParseQueryParams(req) + queryParams := httpcommon.ParseQueryParams(req) ret := h.namingServer.GetInstances(handler.ParseHeaderContext(), queryParams) handler.WriteHeaderAndProto(ret) } // GetInstancesCount 查询服务实例 -func (h *HTTPServer) GetInstancesCount(req *restful.Request, rsp *restful.Response) { - handler := &Handler{req, rsp} +func (h *HTTPServerV1) GetInstancesCount(req *restful.Request, rsp *restful.Response) { + handler := &httpcommon.Handler{req, rsp} ret := h.namingServer.GetInstancesCount(handler.ParseHeaderContext()) handler.WriteHeaderAndProto(ret) } +// GetInstanceLabels 查询某个服务下所有实例的标签信息 +func (h *HTTPServerV1) GetInstanceLabels(req *restful.Request, rsp *restful.Response) { + handler := &httpcommon.Handler{req, rsp} + + ret := h.namingServer.GetInstanceLabels(handler.ParseHeaderContext(), httpcommon.ParseQueryParams(req)) + handler.WriteHeaderAndProto(ret) +} + // CreateRoutings 创建规则路由 -func (h *HTTPServer) CreateRoutings(req *restful.Request, rsp *restful.Response) { - handler := &Handler{req, rsp} +func (h *HTTPServerV1) CreateRoutings(req *restful.Request, rsp *restful.Response) { + handler := &httpcommon.Handler{req, rsp} var routings RoutingArr ctx, err := handler.ParseArray(func() proto.Message { @@ -602,8 +609,8 @@ func (h *HTTPServer) CreateRoutings(req *restful.Request, rsp *restful.Response) } // DeleteRoutings 删除规则路由 -func (h *HTTPServer) DeleteRoutings(req *restful.Request, rsp *restful.Response) { - handler := &Handler{req, rsp} +func (h *HTTPServerV1) DeleteRoutings(req *restful.Request, rsp *restful.Response) { + handler := &httpcommon.Handler{req, rsp} var routings RoutingArr ctx, err := handler.ParseArray(func() proto.Message { @@ -626,8 +633,8 @@ func (h *HTTPServer) DeleteRoutings(req *restful.Request, rsp *restful.Response) } // UpdateRoutings 修改规则路由 -func (h *HTTPServer) UpdateRoutings(req *restful.Request, rsp *restful.Response) { - handler := &Handler{req, rsp} +func (h *HTTPServerV1) UpdateRoutings(req *restful.Request, rsp *restful.Response) { + handler := &httpcommon.Handler{req, rsp} var routings RoutingArr ctx, err := handler.ParseArray(func() proto.Message { @@ -650,17 +657,17 @@ func (h *HTTPServer) UpdateRoutings(req *restful.Request, rsp *restful.Response) } // GetRoutings 查询规则路由 -func (h *HTTPServer) GetRoutings(req *restful.Request, rsp *restful.Response) { - handler := &Handler{req, rsp} +func (h *HTTPServerV1) GetRoutings(req *restful.Request, rsp *restful.Response) { + handler := &httpcommon.Handler{req, rsp} - queryParams := utils.ParseQueryParams(req) + queryParams := httpcommon.ParseQueryParams(req) ret := h.namingServer.GetRoutingConfigs(handler.ParseHeaderContext(), queryParams) handler.WriteHeaderAndProto(ret) } // CreateRateLimits 创建限流规则 -func (h *HTTPServer) CreateRateLimits(req *restful.Request, rsp *restful.Response) { - handler := &Handler{req, rsp} +func (h *HTTPServerV1) CreateRateLimits(req *restful.Request, rsp *restful.Response) { + handler := &httpcommon.Handler{req, rsp} var rateLimits RateLimitArr ctx, err := handler.ParseArray(func() proto.Message { @@ -677,8 +684,8 @@ func (h *HTTPServer) CreateRateLimits(req *restful.Request, rsp *restful.Respons } // DeleteRateLimits 删除限流规则 -func (h *HTTPServer) DeleteRateLimits(req *restful.Request, rsp *restful.Response) { - handler := &Handler{req, rsp} +func (h *HTTPServerV1) DeleteRateLimits(req *restful.Request, rsp *restful.Response) { + handler := &httpcommon.Handler{req, rsp} var rateLimits RateLimitArr ctx, err := handler.ParseArray(func() proto.Message { @@ -700,8 +707,8 @@ func (h *HTTPServer) DeleteRateLimits(req *restful.Request, rsp *restful.Respons } // EnableRateLimits 激活限流规则 -func (h *HTTPServer) EnableRateLimits(req *restful.Request, rsp *restful.Response) { - handler := &Handler{req, rsp} +func (h *HTTPServerV1) EnableRateLimits(req *restful.Request, rsp *restful.Response) { + handler := &httpcommon.Handler{req, rsp} var rateLimits RateLimitArr ctx, err := handler.ParseArray(func() proto.Message { msg := &api.Rule{} @@ -722,8 +729,8 @@ func (h *HTTPServer) EnableRateLimits(req *restful.Request, rsp *restful.Respons } // UpdateRateLimits 修改限流规则 -func (h *HTTPServer) UpdateRateLimits(req *restful.Request, rsp *restful.Response) { - handler := &Handler{req, rsp} +func (h *HTTPServerV1) UpdateRateLimits(req *restful.Request, rsp *restful.Response) { + handler := &httpcommon.Handler{req, rsp} var rateLimits RateLimitArr ctx, err := handler.ParseArray(func() proto.Message { @@ -746,17 +753,17 @@ func (h *HTTPServer) UpdateRateLimits(req *restful.Request, rsp *restful.Respons } // GetRateLimits 查询限流规则 -func (h *HTTPServer) GetRateLimits(req *restful.Request, rsp *restful.Response) { - handler := &Handler{req, rsp} +func (h *HTTPServerV1) GetRateLimits(req *restful.Request, rsp *restful.Response) { + handler := &httpcommon.Handler{req, rsp} - queryParams := utils.ParseQueryParams(req) + queryParams := httpcommon.ParseQueryParams(req) ret := h.namingServer.GetRateLimits(handler.ParseHeaderContext(), queryParams) handler.WriteHeaderAndProto(ret) } // CreateCircuitBreakers 创建熔断规则 -func (h *HTTPServer) CreateCircuitBreakers(req *restful.Request, rsp *restful.Response) { - handler := &Handler{req, rsp} +func (h *HTTPServerV1) CreateCircuitBreakers(req *restful.Request, rsp *restful.Response) { + handler := &httpcommon.Handler{req, rsp} var circuitBreakers CircuitBreakerArr ctx, err := handler.ParseArray(func() proto.Message { @@ -774,8 +781,8 @@ func (h *HTTPServer) CreateCircuitBreakers(req *restful.Request, rsp *restful.Re } // CreateCircuitBreakerVersions 创建熔断规则版本 -func (h *HTTPServer) CreateCircuitBreakerVersions(req *restful.Request, rsp *restful.Response) { - handler := &Handler{req, rsp} +func (h *HTTPServerV1) CreateCircuitBreakerVersions(req *restful.Request, rsp *restful.Response) { + handler := &httpcommon.Handler{req, rsp} var circuitBreakers CircuitBreakerArr ctx, err := handler.ParseArray(func() proto.Message { @@ -792,8 +799,8 @@ func (h *HTTPServer) CreateCircuitBreakerVersions(req *restful.Request, rsp *res } // DeleteCircuitBreakers 删除熔断规则 -func (h *HTTPServer) DeleteCircuitBreakers(req *restful.Request, rsp *restful.Response) { - handler := &Handler{req, rsp} +func (h *HTTPServerV1) DeleteCircuitBreakers(req *restful.Request, rsp *restful.Response) { + handler := &httpcommon.Handler{req, rsp} var circuitBreakers CircuitBreakerArr ctx, err := handler.ParseArray(func() proto.Message { @@ -815,8 +822,8 @@ func (h *HTTPServer) DeleteCircuitBreakers(req *restful.Request, rsp *restful.Re } // UpdateCircuitBreakers 修改熔断规则 -func (h *HTTPServer) UpdateCircuitBreakers(req *restful.Request, rsp *restful.Response) { - handler := &Handler{req, rsp} +func (h *HTTPServerV1) UpdateCircuitBreakers(req *restful.Request, rsp *restful.Response) { + handler := &httpcommon.Handler{req, rsp} var circuitBreakers CircuitBreakerArr ctx, err := handler.ParseArray(func() proto.Message { @@ -838,8 +845,8 @@ func (h *HTTPServer) UpdateCircuitBreakers(req *restful.Request, rsp *restful.Re } // ReleaseCircuitBreakers 发布熔断规则 -func (h *HTTPServer) ReleaseCircuitBreakers(req *restful.Request, rsp *restful.Response) { - handler := &Handler{req, rsp} +func (h *HTTPServerV1) ReleaseCircuitBreakers(req *restful.Request, rsp *restful.Response) { + handler := &httpcommon.Handler{req, rsp} var configRelease ConfigReleaseArr ctx, err := handler.ParseArray(func() proto.Message { @@ -861,8 +868,8 @@ func (h *HTTPServer) ReleaseCircuitBreakers(req *restful.Request, rsp *restful.R } // UnBindCircuitBreakers 解绑熔断规则 -func (h *HTTPServer) UnBindCircuitBreakers(req *restful.Request, rsp *restful.Response) { - handler := &Handler{req, rsp} +func (h *HTTPServerV1) UnBindCircuitBreakers(req *restful.Request, rsp *restful.Response) { + handler := &httpcommon.Handler{req, rsp} var configRelease ConfigReleaseArr ctx, err := handler.ParseArray(func() proto.Message { @@ -884,53 +891,53 @@ func (h *HTTPServer) UnBindCircuitBreakers(req *restful.Request, rsp *restful.Re } // GetCircuitBreaker 根据id和version获取熔断规则 -func (h *HTTPServer) GetCircuitBreaker(req *restful.Request, rsp *restful.Response) { - handler := &Handler{req, rsp} +func (h *HTTPServerV1) GetCircuitBreaker(req *restful.Request, rsp *restful.Response) { + handler := &httpcommon.Handler{req, rsp} - queryParams := utils.ParseQueryParams(req) + queryParams := httpcommon.ParseQueryParams(req) ret := h.namingServer.GetCircuitBreaker(handler.ParseHeaderContext(), queryParams) handler.WriteHeaderAndProto(ret) } // GetCircuitBreakerVersions 查询熔断规则的所有版本 -func (h *HTTPServer) GetCircuitBreakerVersions(req *restful.Request, rsp *restful.Response) { - handler := &Handler{req, rsp} +func (h *HTTPServerV1) GetCircuitBreakerVersions(req *restful.Request, rsp *restful.Response) { + handler := &httpcommon.Handler{req, rsp} - queryParams := utils.ParseQueryParams(req) + queryParams := httpcommon.ParseQueryParams(req) ret := h.namingServer.GetCircuitBreakerVersions(handler.ParseHeaderContext(), queryParams) handler.WriteHeaderAndProto(ret) } // GetMasterCircuitBreakers 查询master熔断规则 -func (h *HTTPServer) GetMasterCircuitBreakers(req *restful.Request, rsp *restful.Response) { - handler := &Handler{req, rsp} +func (h *HTTPServerV1) GetMasterCircuitBreakers(req *restful.Request, rsp *restful.Response) { + handler := &httpcommon.Handler{req, rsp} - queryParams := utils.ParseQueryParams(req) + queryParams := httpcommon.ParseQueryParams(req) ret := h.namingServer.GetMasterCircuitBreakers(handler.ParseHeaderContext(), queryParams) handler.WriteHeaderAndProto(ret) } // GetReleaseCircuitBreakers 根据规则id查询已发布的熔断规则 -func (h *HTTPServer) GetReleaseCircuitBreakers(req *restful.Request, rsp *restful.Response) { - handler := &Handler{req, rsp} +func (h *HTTPServerV1) GetReleaseCircuitBreakers(req *restful.Request, rsp *restful.Response) { + handler := &httpcommon.Handler{req, rsp} - queryParams := utils.ParseQueryParams(req) + queryParams := httpcommon.ParseQueryParams(req) ret := h.namingServer.GetReleaseCircuitBreakers(handler.ParseHeaderContext(), queryParams) handler.WriteHeaderAndProto(ret) } // GetCircuitBreakerByService 根据服务查询绑定熔断规则 -func (h *HTTPServer) GetCircuitBreakerByService(req *restful.Request, rsp *restful.Response) { - handler := &Handler{req, rsp} +func (h *HTTPServerV1) GetCircuitBreakerByService(req *restful.Request, rsp *restful.Response) { + handler := &httpcommon.Handler{req, rsp} - queryParams := utils.ParseQueryParams(req) + queryParams := httpcommon.ParseQueryParams(req) ret := h.namingServer.GetCircuitBreakerByService(handler.ParseHeaderContext(), queryParams) handler.WriteHeaderAndProto(ret) } // GetServiceOwner 根据服务获取服务负责人 -func (h *HTTPServer) GetServiceOwner(req *restful.Request, rsp *restful.Response) { - handler := &Handler{req, rsp} +func (h *HTTPServerV1) GetServiceOwner(req *restful.Request, rsp *restful.Response) { + handler := &httpcommon.Handler{req, rsp} var services ServiceArr ctx, err := handler.ParseArray(func() proto.Message { @@ -947,12 +954,12 @@ func (h *HTTPServer) GetServiceOwner(req *restful.Request, rsp *restful.Response } // GetCircuitBreakerToken 获取熔断规则token -func (h *HTTPServer) GetCircuitBreakerToken(req *restful.Request, rsp *restful.Response) { - handler := &Handler{req, rsp} +func (h *HTTPServerV1) GetCircuitBreakerToken(req *restful.Request, rsp *restful.Response) { + handler := &httpcommon.Handler{req, rsp} token := req.HeaderParameter("Polaris-Token") ctx := context.WithValue(context.Background(), utils.StringContext("polaris-token"), token) - queryParams := utils.ParseQueryParams(req) + queryParams := httpcommon.ParseQueryParams(req) circuitBreaker := &api.CircuitBreaker{ Id: utils.NewStringValue(queryParams["id"]), Version: utils.NewStringValue("master"), @@ -961,93 +968,3 @@ func (h *HTTPServer) GetCircuitBreakerToken(req *restful.Request, rsp *restful.R ret := h.namingServer.GetCircuitBreakerToken(ctx, circuitBreaker) handler.WriteHeaderAndProto(ret) } - -// CreatePlatforms 创建平台 -func (h *HTTPServer) CreatePlatforms(req *restful.Request, rsp *restful.Response) { - handler := &Handler{req, rsp} - - var platforms PlatformArr - ctx, err := handler.ParseArray(func() proto.Message { - msg := &api.Platform{} - platforms = append(platforms, msg) - return msg - }) - if err != nil { - handler.WriteHeaderAndProto(api.NewBatchWriteResponseWithMsg(api.ParseException, err.Error())) - return - } - - handler.WriteHeaderAndProto(h.namingServer.CreatePlatforms(ctx, platforms)) -} - -// UpdatePlatforms 修改平台 -func (h *HTTPServer) UpdatePlatforms(req *restful.Request, rsp *restful.Response) { - handler := &Handler{req, rsp} - - var platforms PlatformArr - ctx, err := handler.ParseArray(func() proto.Message { - msg := &api.Platform{} - platforms = append(platforms, msg) - return msg - }) - if err != nil { - handler.WriteHeaderAndProto(api.NewBatchWriteResponseWithMsg(api.ParseException, err.Error())) - return - } - - ret := h.namingServer.UpdatePlatforms(ctx, platforms) - if code := api.CalcCode(ret); code != http.StatusOK { - handler.WriteHeaderAndProto(ret) - return - } - - handler.WriteHeaderAndProto(ret) -} - -// DeletePlatforms 删除平台 -func (h *HTTPServer) DeletePlatforms(req *restful.Request, rsp *restful.Response) { - handler := &Handler{req, rsp} - - var platforms PlatformArr - ctx, err := handler.ParseArray(func() proto.Message { - msg := &api.Platform{} - platforms = append(platforms, msg) - return msg - }) - if err != nil { - handler.WriteHeaderAndProto(api.NewBatchQueryResponseWithMsg(api.ParseException, err.Error())) - return - } - ret := h.namingServer.DeletePlatforms(ctx, platforms) - if code := api.CalcCode(ret); code != http.StatusOK { - handler.WriteHeaderAndProto(ret) - return - } - - handler.WriteHeaderAndProto(ret) -} - -// GetPlatforms 查询平台 -func (h *HTTPServer) GetPlatforms(req *restful.Request, rsp *restful.Response) { - handler := &Handler{req, rsp} - - queryParams := utils.ParseQueryParams(req) - ret := h.namingServer.GetPlatforms(handler.ParseHeaderContext(), queryParams) - handler.WriteHeaderAndProto(ret) -} - -// GetPlatformToken 查询平台Token -func (h *HTTPServer) GetPlatformToken(req *restful.Request, rsp *restful.Response) { - handler := &Handler{req, rsp} - token := req.HeaderParameter("Polaris-Token") - ctx := context.WithValue(context.Background(), utils.StringContext("polaris-token"), token) - - queryParams := utils.ParseQueryParams(req) - platform := &api.Platform{ - Id: utils.NewStringValue(queryParams["id"]), - Token: utils.NewStringValue(queryParams["token"]), - } - - ret := h.namingServer.GetPlatformToken(ctx, platform) - handler.WriteHeaderAndProto(ret) -} diff --git a/apiserver/httpserver/v1/proto.go b/apiserver/httpserver/v1/proto.go new file mode 100644 index 000000000..e5228af05 --- /dev/null +++ b/apiserver/httpserver/v1/proto.go @@ -0,0 +1,120 @@ +/** + * Tencent is pleased to support the open source community by making Polaris available. + * + * Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved. + * + * Licensed under the BSD 3-Clause License (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://opensource.org/licenses/BSD-3-Clause + * + * 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 v1 + +import ( + "github.com/golang/protobuf/proto" + + api "github.com/polarismesh/polaris-server/common/api/v1" +) + +// NamespaceArr 命名空间数组定义 +type NamespaceArr []*api.Namespace + +// Reset 重置初始化 +func (m *NamespaceArr) Reset() { *m = NamespaceArr{} } + +// String return string +func (m *NamespaceArr) String() string { return proto.CompactTextString(m) } + +// ProtoMessage return proto message +func (*NamespaceArr) ProtoMessage() {} + +// ServiceArr 服务数组定义 +type ServiceArr []*api.Service + +// Reset 重置初始化 +func (m *ServiceArr) Reset() { *m = ServiceArr{} } + +// String return string +func (m *ServiceArr) String() string { return proto.CompactTextString(m) } + +// ProtoMessage return proto message +func (*ServiceArr) ProtoMessage() {} + +// InstanceArr 服务实例数组定义 +type InstanceArr []*api.Instance + +// Reset reset initialization +func (m *InstanceArr) Reset() { *m = InstanceArr{} } + +// String +func (m *InstanceArr) String() string { return proto.CompactTextString(m) } + +// ProtoMessage return proto message +func (*InstanceArr) ProtoMessage() {} + +// RoutingArr 路由规则数组定义 +type RoutingArr []*api.Routing + +// Reset reset initialization +func (m *RoutingArr) Reset() { *m = RoutingArr{} } + +// String return string +func (m *RoutingArr) String() string { return proto.CompactTextString(m) } + +// ProtoMessage return proto message +func (*RoutingArr) ProtoMessage() {} + +// RateLimitArr 限流规则数组定义 +type RateLimitArr []*api.Rule + +// Reset reset initialization +func (m *RateLimitArr) Reset() { *m = RateLimitArr{} } + +// String +func (m *RateLimitArr) String() string { return proto.CompactTextString(m) } + +// ProtoMessage return proto message +func (*RateLimitArr) ProtoMessage() {} + +// CircuitBreakerArr 熔断规则数组定义 +type CircuitBreakerArr []*api.CircuitBreaker + +// Reset reset initialization +func (m *CircuitBreakerArr) Reset() { *m = CircuitBreakerArr{} } + +// String +func (m *CircuitBreakerArr) String() string { return proto.CompactTextString(m) } + +// ProtoMessage return proto message +func (*CircuitBreakerArr) ProtoMessage() {} + +// ConfigReleaseArr 发布规则数组定义 +type ConfigReleaseArr []*api.ConfigRelease + +// Reset reset initialization +func (m *ConfigReleaseArr) Reset() { *m = ConfigReleaseArr{} } + +// String return string +func (m *ConfigReleaseArr) String() string { return proto.CompactTextString(m) } + +// ProtoMessage return proto message +func (*ConfigReleaseArr) ProtoMessage() {} + +// ServiceAliasArr 服务实例数组定义 +type ServiceAliasArr []*api.ServiceAlias + +// Reset reset initialization +func (m *ServiceAliasArr) Reset() { *m = ServiceAliasArr{} } + +// String return string +func (m *ServiceAliasArr) String() string { return proto.CompactTextString(m) } + +// ProtoMessage proto message +func (*ServiceAliasArr) ProtoMessage() {} diff --git a/apiserver/httpserver/v1/server.go b/apiserver/httpserver/v1/server.go new file mode 100644 index 000000000..230d6eddd --- /dev/null +++ b/apiserver/httpserver/v1/server.go @@ -0,0 +1,42 @@ +/** + * Tencent is pleased to support the open source community by making Polaris available. + * + * Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved. + * + * Licensed under the BSD 3-Clause License (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://opensource.org/licenses/BSD-3-Clause + * + * 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 v1 + +import ( + "github.com/polarismesh/polaris-server/namespace" + "github.com/polarismesh/polaris-server/service" + "github.com/polarismesh/polaris-server/service/healthcheck" +) + +type HTTPServerV1 struct { + namespaceServer namespace.NamespaceOperateServer + namingServer service.DiscoverServer + healthCheckServer *healthcheck.Server +} + +func NewV1Server( + namespaceServer namespace.NamespaceOperateServer, + namingServer service.DiscoverServer, + healthCheckServer *healthcheck.Server) *HTTPServerV1 { + + return &HTTPServerV1{ + namespaceServer: namespaceServer, + namingServer: namingServer, + healthCheckServer: healthCheckServer, + } +} diff --git a/store/sqldb/scripts/delta/v180-v1110.sql b/apiserver/httpserver/v2/log.go similarity index 63% rename from store/sqldb/scripts/delta/v180-v1110.sql rename to apiserver/httpserver/v2/log.go index 95b1a191c..0b90e05a6 100644 --- a/store/sqldb/scripts/delta/v180-v1110.sql +++ b/apiserver/httpserver/v2/log.go @@ -1,26 +1,28 @@ -/* - * Tencent is pleased to support the open source community by making Polaris available. - * - * Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved. - * - * Licensed under the BSD 3-Clause License (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://opensource.org/licenses/BSD-3-Clause - * - * 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. - */ --- --- Database: `polaris_server` --- - -USE `polaris_server`; - -ALTER TABLE `ratelimit_config` CHANGE `cluster_id` `name` varchar(64) NOT NULL; -ALTER TABLE `ratelimit_config` ADD COLUMN `disable` tinyint(4) NOT NULL DEFAULT '0'; -ALTER TABLE `ratelimit_config` ADD COLUMN `etime` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP; -ALTER TABLE `ratelimit_config` ADD COLUMN `method` varchar(512) NOT NULL; \ No newline at end of file +/** + * Tencent is pleased to support the open source community by making Polaris available. + * + * Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved. + * + * Licensed under the BSD 3-Clause License (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://opensource.org/licenses/BSD-3-Clause + * + * 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 v2 + +import ( + commonlog "github.com/polarismesh/polaris-server/common/log" +) + +var ( + log = commonlog.APIServerScope() + namingLog = commonlog.NamingScope() + configLog = commonlog.ConfigScope() +) diff --git a/apiserver/httpserver/v2/naming_client_access.go b/apiserver/httpserver/v2/naming_client_access.go new file mode 100644 index 000000000..c8408d606 --- /dev/null +++ b/apiserver/httpserver/v2/naming_client_access.go @@ -0,0 +1,93 @@ +/** + * Tencent is pleased to support the open source community by making Polaris available. + * + * Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved. + * + * Licensed under the BSD 3-Clause License (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://opensource.org/licenses/BSD-3-Clause + * + * 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 v2 + +import ( + "fmt" + + "github.com/emicklei/go-restful/v3" + restfulspec "github.com/polarismesh/go-restful-openapi/v2" + "go.uber.org/zap" + + "github.com/polarismesh/polaris-server/apiserver" + httpcommon "github.com/polarismesh/polaris-server/apiserver/httpserver/http" + api "github.com/polarismesh/polaris-server/common/api/v1" + apiv2 "github.com/polarismesh/polaris-server/common/api/v2" +) + +// GetClientAccessServer get client access server +func (h *HTTPServerV2) GetClientAccessServer(include []string) (*restful.WebService, error) { + clientAccess := []string{apiserver.DiscoverAccess, apiserver.RegisterAccess, apiserver.HealthcheckAccess} + + ws := new(restful.WebService) + + ws.Path("/v2").Consumes(restful.MIME_JSON).Produces(restful.MIME_JSON) + + // 如果为空,则开启全部接口 + if len(include) == 0 { + include = clientAccess + } + + // 客户端接口:增删改请求操作存储层,查请求访问缓存 + for _, item := range include { + switch item { + case apiserver.DiscoverAccess: + h.addDiscoverAccess(ws) + } + } + + return ws, nil +} + +// addDiscoverAccess 增加服务发现接口 +func (h *HTTPServerV2) addDiscoverAccess(ws *restful.WebService) { + tags := []string{"DiscoverAccess"} + ws.Route(ws.POST("/Discover").To(h.Discover). + Doc("服务发现"). + Metadata(restfulspec.KeyOpenAPITags, tags)) +} + +// Discover 统一发现接口 +func (h *HTTPServerV2) Discover(req *restful.Request, rsp *restful.Response) { + handler := &httpcommon.Handler{req, rsp} + + discoverRequest := &apiv2.DiscoverRequest{} + ctx, err := handler.Parse(discoverRequest) + if err != nil { + handler.WriteHeaderAndProto(api.NewResponseWithMsg(api.ParseException, err.Error())) + return + } + + msg := fmt.Sprintf("receive http discover request: %s", discoverRequest.GetSerivce().String()) + namingLog.Info(msg, + zap.String("type", api.DiscoverRequest_DiscoverRequestType_name[int32(discoverRequest.Type)]), + zap.String("client-address", req.Request.RemoteAddr), + zap.String("user-agent", req.HeaderParameter("User-Agent")), + zap.String("request-id", req.HeaderParameter("Request-Id")), + ) + + var ret *apiv2.DiscoverResponse + switch discoverRequest.Type { + case apiv2.DiscoverRequest_ROUTING: + ret = h.namingServer.GetRoutingConfigV2WithCache(ctx, discoverRequest.GetSerivce()) + default: + ret = apiv2.NewDiscoverRoutingResponse(api.InvalidDiscoverResource, discoverRequest.GetSerivce()) + } + + handler.WriteHeaderAndProtoV2(ret) +} diff --git a/apiserver/httpserver/v2/naming_console_access.go b/apiserver/httpserver/v2/naming_console_access.go new file mode 100644 index 000000000..ddf9714d9 --- /dev/null +++ b/apiserver/httpserver/v2/naming_console_access.go @@ -0,0 +1,170 @@ +/** + * Tencent is pleased to support the open source community by making Polaris available. + * + * Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved. + * + * Licensed under the BSD 3-Clause License (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://opensource.org/licenses/BSD-3-Clause + * + * 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 v2 + +import ( + "fmt" + + "github.com/emicklei/go-restful/v3" + "github.com/golang/protobuf/proto" + + httpcommon "github.com/polarismesh/polaris-server/apiserver/httpserver/http" + apiv1 "github.com/polarismesh/polaris-server/common/api/v1" + apiv2 "github.com/polarismesh/polaris-server/common/api/v2" +) + +const ( + defaultReadAccess string = "default-read" + defaultAccess string = "default" +) + +// GetNamingConsoleAccessServer 注册管理端接口 +func (h *HTTPServerV2) GetNamingConsoleAccessServer(include []string) (*restful.WebService, error) { + consoleAccess := []string{defaultAccess} + + ws := new(restful.WebService) + + ws.Path("/naming/v2").Consumes(restful.MIME_JSON).Produces(restful.MIME_JSON) + + // 如果为空,则开启全部接口 + if len(include) == 0 { + include = consoleAccess + } + + var hasDefault = false + for _, item := range include { + if item == defaultAccess { + hasDefault = true + break + } + } + for _, item := range include { + switch item { + case defaultReadAccess: + if !hasDefault { + h.addDefaultReadAccess(ws) + } + case defaultAccess: + h.addDefaultAccess(ws) + default: + log.Errorf("method %s does not exist in HTTPServerV2 console access", item) + return nil, fmt.Errorf("method %s does not exist in HTTPServerV2 console access", item) + } + } + return ws, nil +} + +// addDefaultReadAccess 增加默认读接口 +func (h *HTTPServerV2) addDefaultReadAccess(ws *restful.WebService) { + ws.Route(ws.POST("/routings").To(h.CreateRoutings)) + ws.Route(ws.GET("/routings").To(h.GetRoutings)) +} + +// addDefaultAccess 增加默认接口 +func (h *HTTPServerV2) addDefaultAccess(ws *restful.WebService) { + ws.Route(ws.POST("/routings").To(h.CreateRoutings)) + ws.Route(ws.POST("/routings/delete").To(h.DeleteRoutings)) + ws.Route(ws.PUT("/routings").To(h.UpdateRoutings)) + ws.Route(ws.GET("/routings").To(h.GetRoutings)) + ws.Route(ws.PUT("/routings/enable").To(h.EnableRoutings)) +} + +// CreateRoutings 创建规则路由 +func (h *HTTPServerV2) CreateRoutings(req *restful.Request, rsp *restful.Response) { + handler := &httpcommon.Handler{req, rsp} + + var routings RoutingArr + ctx, err := handler.ParseArray(func() proto.Message { + msg := &apiv2.Routing{} + routings = append(routings, msg) + return msg + }) + if err != nil { + handler.WriteHeaderAndProtoV2(apiv2.NewBatchWriteResponseWithMsg(apiv1.ParseException, err.Error())) + return + } + + ret := h.namingServer.CreateRoutingConfigsV2(ctx, routings) + handler.WriteHeaderAndProtoV2(ret) +} + +// DeleteRoutings 删除规则路由 +func (h *HTTPServerV2) DeleteRoutings(req *restful.Request, rsp *restful.Response) { + handler := &httpcommon.Handler{req, rsp} + + var routings RoutingArr + ctx, err := handler.ParseArray(func() proto.Message { + msg := &apiv2.Routing{} + routings = append(routings, msg) + return msg + }) + if err != nil { + handler.WriteHeaderAndProtoV2(apiv2.NewBatchWriteResponseWithMsg(apiv1.ParseException, err.Error())) + return + } + + ret := h.namingServer.DeleteRoutingConfigsV2(ctx, routings) + handler.WriteHeaderAndProtoV2(ret) +} + +// UpdateRoutings 修改规则路由 +func (h *HTTPServerV2) UpdateRoutings(req *restful.Request, rsp *restful.Response) { + handler := &httpcommon.Handler{req, rsp} + + var routings RoutingArr + ctx, err := handler.ParseArray(func() proto.Message { + msg := &apiv2.Routing{} + routings = append(routings, msg) + return msg + }) + if err != nil { + handler.WriteHeaderAndProtoV2(apiv2.NewBatchWriteResponseWithMsg(apiv1.ParseException, err.Error())) + return + } + + ret := h.namingServer.UpdateRoutingConfigsV2(ctx, routings) + handler.WriteHeaderAndProtoV2(ret) +} + +// GetRoutings 查询规则路由 +func (h *HTTPServerV2) GetRoutings(req *restful.Request, rsp *restful.Response) { + handler := &httpcommon.Handler{req, rsp} + + queryParams := httpcommon.ParseQueryParams(req) + ret := h.namingServer.GetRoutingConfigsV2(handler.ParseHeaderContext(), queryParams) + handler.WriteHeaderAndProtoV2(ret) +} + +// EnableRoutings 查询规则路由 +func (h *HTTPServerV2) EnableRoutings(req *restful.Request, rsp *restful.Response) { + handler := &httpcommon.Handler{req, rsp} + + var routings RoutingArr + ctx, err := handler.ParseArray(func() proto.Message { + msg := &apiv2.Routing{} + routings = append(routings, msg) + return msg + }) + if err != nil { + handler.WriteHeaderAndProtoV2(apiv2.NewBatchWriteResponseWithMsg(apiv1.ParseException, err.Error())) + return + } + + ret := h.namingServer.EnableRoutings(ctx, routings) + handler.WriteHeaderAndProtoV2(ret) +} diff --git a/apiserver/httpserver/v2/proto.go b/apiserver/httpserver/v2/proto.go new file mode 100644 index 000000000..716386bf1 --- /dev/null +++ b/apiserver/httpserver/v2/proto.go @@ -0,0 +1,36 @@ +/** + * Tencent is pleased to support the open source community by making Polaris available. + * + * Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved. + * + * Licensed under the BSD 3-Clause License (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://opensource.org/licenses/BSD-3-Clause + * + * 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 v2 + +import ( + "github.com/golang/protobuf/proto" + + api "github.com/polarismesh/polaris-server/common/api/v2" +) + +// RoutingArr 路由规则数组定义 +type RoutingArr []*api.Routing + +// Reset reset initialization +func (m *RoutingArr) Reset() { *m = RoutingArr{} } + +// String return string +func (m *RoutingArr) String() string { return proto.CompactTextString(m) } + +// ProtoMessage return proto message +func (*RoutingArr) ProtoMessage() {} diff --git a/apiserver/httpserver/v2/server.go b/apiserver/httpserver/v2/server.go new file mode 100644 index 000000000..90a9537f7 --- /dev/null +++ b/apiserver/httpserver/v2/server.go @@ -0,0 +1,44 @@ +/** + * Tencent is pleased to support the open source community by making Polaris available. + * + * Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved. + * + * Licensed under the BSD 3-Clause License (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://opensource.org/licenses/BSD-3-Clause + * + * 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 v2 + +import ( + "github.com/polarismesh/polaris-server/namespace" + "github.com/polarismesh/polaris-server/service" + "github.com/polarismesh/polaris-server/service/healthcheck" +) + +// HTTPServerV2 +type HTTPServerV2 struct { + namespaceServer namespace.NamespaceOperateServer + namingServer service.DiscoverServer + healthCheckServer *healthcheck.Server +} + +// NewV2Server +func NewV2Server( + namespaceServer namespace.NamespaceOperateServer, + namingServer service.DiscoverServer, + healthCheckServer *healthcheck.Server) *HTTPServerV2 { + + return &HTTPServerV2{ + namespaceServer: namespaceServer, + namingServer: namingServer, + healthCheckServer: healthCheckServer, + } +} diff --git a/apiserver/l5pbserver/naming.go b/apiserver/l5pbserver/naming.go index 1763ef8b0..db686e2a0 100644 --- a/apiserver/l5pbserver/naming.go +++ b/apiserver/l5pbserver/naming.go @@ -29,7 +29,7 @@ import ( "go.uber.org/zap" "github.com/polarismesh/polaris-server/common/api/l5" - "github.com/polarismesh/polaris-server/common/utils" + l5common "github.com/polarismesh/polaris-server/common/cl5" ) type l5Code uint32 @@ -115,8 +115,8 @@ func (l *L5pbserver) handleRequest(req *cl5Request, requestData []byte) l5Code { // handleSyncByAgentCmd 根据SID列表获取路由信息 func (l *L5pbserver) handleSyncByAgentCmd(conn net.Conn, iPkg *l5.Cl5Pkg) l5Code { ctx := context.Background() - ctx = context.WithValue(ctx, utils.Cl5ServerCluster{}, l.clusterName) - ctx = context.WithValue(ctx, utils.Cl5ServerProtocol{}, l.GetProtocol()) + ctx = context.WithValue(ctx, l5common.Cl5ServerCluster{}, l.clusterName) + ctx = context.WithValue(ctx, l5common.Cl5ServerProtocol{}, l.GetProtocol()) syncByAgentAck, err := l.namingServer.SyncByAgentCmd(ctx, iPkg.GetSyncByAgentCmd()) if err != nil { log.Errorf("%v", err) diff --git a/apiserver/prometheussd/prometheus_access.go b/apiserver/prometheussd/prometheus_access.go index ecd025490..84b2c1986 100644 --- a/apiserver/prometheussd/prometheus_access.go +++ b/apiserver/prometheussd/prometheus_access.go @@ -18,12 +18,12 @@ package prometheussd import ( - "github.com/emicklei/go-restful/v3" + "context" - "github.com/polarismesh/polaris-server/common/utils" + "github.com/emicklei/go-restful/v3" ) -// GetPrometheusDiscoveryServer 注册用于promethesu服务发现的接口 +// GetPrometheusDiscoveryServer 注册用于prometheus服务发现的接口 func (h *PrometheusServer) GetPrometheusDiscoveryServer(include []string) (*restful.WebService, error) { ws := new(restful.WebService) @@ -38,6 +38,7 @@ func (h *PrometheusServer) addPrometheusDefaultAccess(ws *restful.WebService) { ws.Route(ws.GET("/clients").To(h.GetPrometheusClients)) } +// GetPrometheusClients 对接 prometheus 基于 http 的 service discovery // [ // { // "targets": [ "", ... ], @@ -47,14 +48,22 @@ func (h *PrometheusServer) addPrometheusDefaultAccess(ws *restful.WebService) { // }, // ... // ] -// GetPrometheusClients 对接 prometheus 基于 http 的 service discovery func (h *PrometheusServer) GetPrometheusClients(req *restful.Request, rsp *restful.Response) { - handler := &utils.Handler{req, rsp} - - queryParams := utils.ParseQueryParams(req) - ctx := handler.ParseHeaderContext() - ret := h.namingServer.GetReportClientWithCache(ctx, queryParams) + queryParams := ParseQueryParams(req) + ret := h.namingServer.GetReportClientWithCache(context.Background(), queryParams) _ = rsp.WriteAsJson(ret.Response) } + +// parseQueryParams 解析并获取HTTP的query params +func ParseQueryParams(req *restful.Request) map[string]string { + queryParams := make(map[string]string) + for key, value := range req.Request.URL.Query() { + if len(value) > 0 { + queryParams[key] = value[0] // 暂时默认只支持一个查询 + } + } + + return queryParams +} diff --git a/apiserver/xdsserverv3/callback.go b/apiserver/xdsserverv3/callback.go new file mode 100644 index 000000000..b86a93731 --- /dev/null +++ b/apiserver/xdsserverv3/callback.go @@ -0,0 +1,114 @@ +/** + * Tencent is pleased to support the open source community by making Polaris available. + * + * Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved. + * + * Licensed under the BSD 3-Clause License (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://opensource.org/licenses/BSD-3-Clause + * + * 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 xdsserverv3 + +import ( + "context" + + discovery "github.com/envoyproxy/go-control-plane/envoy/service/discovery/v3" + "github.com/gogo/protobuf/jsonpb" + commonlog "github.com/polarismesh/polaris-server/common/log" +) + +type Callbacks struct { + log *commonlog.Scope +} + +func (cb *Callbacks) Report() { + +} + +func (cb *Callbacks) OnStreamOpen(_ context.Context, id int64, typ string) error { + if cb.log.DebugEnabled() { + cb.log.Debugf("stream %d open for %s", id, typ) + } + return nil +} + +func (cb *Callbacks) OnStreamClosed(id int64) { + if cb.log.DebugEnabled() { + cb.log.Debugf("stream %d closed", id) + } +} + +func (cb *Callbacks) OnDeltaStreamOpen(_ context.Context, id int64, typ string) error { + if cb.log.DebugEnabled() { + cb.log.Debugf("delta stream %d open for %s", id, typ) + } + return nil +} + +func (cb *Callbacks) OnDeltaStreamClosed(id int64) { + if cb.log.DebugEnabled() { + cb.log.Debugf("delta stream %d closed", id) + } +} + +func (cb *Callbacks) OnStreamRequest(id int64, req *discovery.DiscoveryRequest) error { + if cb.log.DebugEnabled() { + marshaler := jsonpb.Marshaler{} + str, _ := marshaler.MarshalToString(req) + cb.log.Debugf("on stream %d type %s request %s ", id, req.TypeUrl, str) + } + return nil +} + +func (cb *Callbacks) OnStreamResponse(_ context.Context, id int64, req *discovery.DiscoveryRequest, resp *discovery.DiscoveryResponse) { + if cb.log.DebugEnabled() { + marshaler := jsonpb.Marshaler{} + reqstr, _ := marshaler.MarshalToString(req) + respstr, _ := marshaler.MarshalToString(resp) + cb.log.Debugf("on stream %d type %s request %s response %s", id, req.TypeUrl, reqstr, respstr) + } +} + +func (cb *Callbacks) OnStreamDeltaResponse(id int64, req *discovery.DeltaDiscoveryRequest, resp *discovery.DeltaDiscoveryResponse) { + if cb.log.DebugEnabled() { + marshaler := jsonpb.Marshaler{} + reqstr, _ := marshaler.MarshalToString(req) + respstr, _ := marshaler.MarshalToString(resp) + cb.log.Debugf("on delta stream %d type %s request %s response %s", id, req.TypeUrl, reqstr, respstr) + } +} + +func (cb *Callbacks) OnStreamDeltaRequest(id int64, req *discovery.DeltaDiscoveryRequest) error { + if cb.log.DebugEnabled() { + marshaler := jsonpb.Marshaler{} + str, _ := marshaler.MarshalToString(req) + cb.log.Debugf("on stream %d delta type %s request %s", id, req.TypeUrl, str) + } + return nil +} + +func (cb *Callbacks) OnFetchRequest(_ context.Context, req *discovery.DiscoveryRequest) error { + if cb.log.DebugEnabled() { + marshaler := jsonpb.Marshaler{} + str, _ := marshaler.MarshalToString(req) + cb.log.Debugf("on fetch type %s request %s ", req.TypeUrl, str) + } + return nil +} + +func (cb *Callbacks) OnFetchResponse(req *discovery.DiscoveryRequest, resp *discovery.DiscoveryResponse) { + if cb.log.DebugEnabled() { + marshaler := jsonpb.Marshaler{} + reqstr, _ := marshaler.MarshalToString(req) + respstr, _ := marshaler.MarshalToString(resp) + cb.log.Debugf("on fetch type %s request %s response %s", req.TypeUrl, reqstr, respstr) + } +} diff --git a/apiserver/xdsserverv3/server.go b/apiserver/xdsserverv3/server.go index 02158f583..7892eb9ed 100644 --- a/apiserver/xdsserverv3/server.go +++ b/apiserver/xdsserverv3/server.go @@ -47,12 +47,10 @@ import ( cachev3 "github.com/envoyproxy/go-control-plane/pkg/cache/v3" "github.com/envoyproxy/go-control-plane/pkg/resource/v3" serverv3 "github.com/envoyproxy/go-control-plane/pkg/server/v3" - testv3 "github.com/envoyproxy/go-control-plane/pkg/test/v3" "github.com/golang/protobuf/ptypes" _struct "github.com/golang/protobuf/ptypes/struct" "github.com/golang/protobuf/ptypes/wrappers" "go.uber.org/atomic" - "go.uber.org/zap" "google.golang.org/grpc" "google.golang.org/protobuf/types/known/anypb" @@ -60,6 +58,7 @@ import ( "github.com/polarismesh/polaris-server/cache" api "github.com/polarismesh/polaris-server/common/api/v1" "github.com/polarismesh/polaris-server/common/connlimit" + commonlog "github.com/polarismesh/polaris-server/common/log" "github.com/polarismesh/polaris-server/common/model" "github.com/polarismesh/polaris-server/namespace" "github.com/polarismesh/polaris-server/service" @@ -96,6 +95,140 @@ type XDSServer struct { RatelimitConfigGetter RatelimitConfigGetter } +// Initialize 初始化 +func (x *XDSServer) Initialize(ctx context.Context, option map[string]interface{}, + api map[string]apiserver.APIConfig, +) error { + x.cache = cachev3.NewSnapshotCache(false, PolarisNodeHash{}, commonlog.XDSV3Scope()) + x.registryInfo = make(map[string][]*ServiceInfo) + x.listenPort = uint32(option["listenPort"].(int)) + x.listenIP = option["listenIP"].(string) + + x.versionNum = atomic.NewUint64(0) + var err error + + x.namingServer, err = service.GetServer() + if err != nil { + log.Errorf("%v", err) + return err + } + + if raw, _ := option["connLimit"].(map[interface{}]interface{}); raw != nil { + connConfig, err := connlimit.ParseConnLimitConfig(raw) + if err != nil { + return err + } + x.connLimitConfig = connConfig + } + + err = x.initRegistryInfo() + if err != nil { + log.Errorf("%v", err) + return err + } + + err = x.getRegistryInfoWithCache(ctx, x.registryInfo) + if err != nil { + log.Errorf("%v", err) + return err + } + + err = x.pushRegistryInfoToXDSCache(x.registryInfo) + if err != nil { + log.Errorf("%v", err) + return err + } + + x.startSynTask(ctx) + + return nil +} + +// Run 启动运行 +func (x *XDSServer) Run(errCh chan error) { + // 启动 grpc server + ctx := context.Background() + cb := &Callbacks{log: commonlog.XDSV3Scope()} + srv := serverv3.NewServer(ctx, x.cache, cb) + var grpcOptions []grpc.ServerOption + grpcOptions = append(grpcOptions, grpc.MaxConcurrentStreams(1000)) + grpcServer := grpc.NewServer(grpcOptions...) + x.server = grpcServer + address := fmt.Sprintf("%v:%v", x.listenIP, x.listenPort) + listener, err := net.Listen("tcp", address) + if err != nil { + log.Errorf("%v", err) + errCh <- err + return + } + + if x.connLimitConfig != nil && x.connLimitConfig.OpenConnLimit { + log.Infof("grpc server use max connection limit: %d, grpc max limit: %d", + x.connLimitConfig.MaxConnPerHost, x.connLimitConfig.MaxConnLimit) + listener, err = connlimit.NewListener(listener, x.GetProtocol(), x.connLimitConfig) + if err != nil { + log.Errorf("conn limit init err: %s", err.Error()) + errCh <- err + return + } + + } + + registerServer(grpcServer, srv) + + log.Infof("management server listening on %d\n", x.listenPort) + + if err = grpcServer.Serve(listener); err != nil { + log.Errorf("%v", err) + errCh <- err + return + } + + log.Info("xds server stop") +} + +func registerServer(grpcServer *grpc.Server, server serverv3.Server) { + // register services + discoverygrpc.RegisterAggregatedDiscoveryServiceServer(grpcServer, server) + endpointservice.RegisterEndpointDiscoveryServiceServer(grpcServer, server) + clusterservice.RegisterClusterDiscoveryServiceServer(grpcServer, server) + routeservice.RegisterRouteDiscoveryServiceServer(grpcServer, server) + listenerservice.RegisterListenerDiscoveryServiceServer(grpcServer, server) + secretservice.RegisterSecretDiscoveryServiceServer(grpcServer, server) + runtimeservice.RegisterRuntimeDiscoveryServiceServer(grpcServer, server) +} + +// Stop 停止服务 +func (x *XDSServer) Stop() { + connlimit.RemoveLimitListener(x.GetProtocol()) + if x.server != nil { + x.server.Stop() + } +} + +// Restart 重启服务 +func (x *XDSServer) Restart(option map[string]interface{}, api map[string]apiserver.APIConfig, errCh chan error) error { + log.Infof("restart xds server with new config: +%v", option) + + x.restart = true + x.Stop() + if x.start { + <-x.exitCh + } + + log.Info("old xds server has stopped, begin restarting it") + if err := x.Initialize(context.Background(), option, api); err != nil { + log.Errorf("restart grpc server err: %s", err.Error()) + return err + } + + log.Info("init grpc server successfully, restart it") + x.restart = false + go x.Run(errCh) + + return nil +} + type RatelimitConfigGetter func(serviceID string) []*model.RateLimit // PolarisNodeHash 存放 hash 方法 @@ -312,7 +445,8 @@ func makeRoutes(serviceInfo *ServiceInfo) []*route.Route { // 使用 sources 生成 routeMatch for _, source := range inbound.Sources { if source.Metadata == nil || len(source.Metadata) == 0 { - continue + matchAll = true + break } for name := range source.Metadata { if name == "*" { @@ -346,7 +480,17 @@ func makeRoutes(serviceInfo *ServiceInfo) []*route.Route { StringMatch: &v32.StringMatcher{MatchPattern: &v32.StringMatcher_Exact{Exact: matchString.GetValue().GetValue()}}, }, } - } else { + } + if matchString.Type == api.MatchString_NOT_EQUALS { + headerMatch = &route.HeaderMatcher{ + Name: headerSubName, + HeaderMatchSpecifier: &route.HeaderMatcher_StringMatch{ + StringMatch: &v32.StringMatcher{MatchPattern: &v32.StringMatcher_Exact{Exact: matchString.GetValue().GetValue()}}, + }, + InvertMatch: true, + } + } + if matchString.Type == api.MatchString_REGEX { headerMatch = &route.HeaderMatcher{ Name: headerSubName, HeaderMatchSpecifier: &route.HeaderMatcher_StringMatch{ @@ -371,7 +515,8 @@ func makeRoutes(serviceInfo *ServiceInfo) []*route.Route { StringMatch: &v32.StringMatcher{MatchPattern: &v32.StringMatcher_Exact{Exact: matchString.GetValue().GetValue()}}, }, } - } else { + } + if matchString.Type == api.MatchString_REGEX { queryMatcher = &route.QueryParameterMatcher{ Name: querySubName, QueryParameterMatchSpecifier: &route.QueryParameterMatcher_StringMatch{ @@ -813,59 +958,6 @@ func (x *XDSServer) initRegistryInfo() error { return nil } -// Initialize 初始化 -func (x *XDSServer) Initialize(ctx context.Context, option map[string]interface{}, - api map[string]apiserver.APIConfig, -) error { - logger, _ := zap.NewDevelopment() - defer logger.Sync() // flushes buffer, if any - l := logger.Sugar() - - x.cache = cachev3.NewSnapshotCache(false, PolarisNodeHash{}, l) - x.registryInfo = make(map[string][]*ServiceInfo) - x.listenPort = uint32(option["listenPort"].(int)) - x.listenIP = option["listenIP"].(string) - - x.versionNum = atomic.NewUint64(0) - var err error - - x.namingServer, err = service.GetServer() - if err != nil { - log.Errorf("%v", err) - return err - } - - if raw, _ := option["connLimit"].(map[interface{}]interface{}); raw != nil { - connConfig, err := connlimit.ParseConnLimitConfig(raw) - if err != nil { - return err - } - x.connLimitConfig = connConfig - } - - err = x.initRegistryInfo() - if err != nil { - log.Errorf("%v", err) - return err - } - - err = x.getRegistryInfoWithCache(ctx, x.registryInfo) - if err != nil { - log.Errorf("%v", err) - return err - } - - err = x.pushRegistryInfoToXDSCache(x.registryInfo) - if err != nil { - log.Errorf("%v", err) - return err - } - - x.startSynTask(ctx) - - return nil -} - func (x *XDSServer) startSynTask(ctx context.Context) error { // 读取 polaris 缓存数据 synXdsConfFunc := func() { @@ -958,88 +1050,3 @@ func (x *XDSServer) checkUpdate(curServiceInfo, cacheServiceInfo []*ServiceInfo) return false } - -// Run 启动运行 -func (x *XDSServer) Run(errCh chan error) { - // 启动 grpc server - ctx := context.Background() - cb := &testv3.Callbacks{Debug: true} - srv := serverv3.NewServer(ctx, x.cache, cb) - var grpcOptions []grpc.ServerOption - grpcOptions = append(grpcOptions, grpc.MaxConcurrentStreams(1000)) - grpcServer := grpc.NewServer(grpcOptions...) - x.server = grpcServer - address := fmt.Sprintf("%v:%v", x.listenIP, x.listenPort) - listener, err := net.Listen("tcp", address) - if err != nil { - log.Errorf("%v", err) - errCh <- err - return - } - - if x.connLimitConfig != nil && x.connLimitConfig.OpenConnLimit { - log.Infof("grpc server use max connection limit: %d, grpc max limit: %d", - x.connLimitConfig.MaxConnPerHost, x.connLimitConfig.MaxConnLimit) - listener, err = connlimit.NewListener(listener, x.GetProtocol(), x.connLimitConfig) - if err != nil { - log.Errorf("conn limit init err: %s", err.Error()) - errCh <- err - return - } - - } - - registerServer(grpcServer, srv) - - log.Infof("management server listening on %d\n", x.listenPort) - - if err = grpcServer.Serve(listener); err != nil { - log.Errorf("%v", err) - errCh <- err - return - } - - log.Info("xds server stop") -} - -func registerServer(grpcServer *grpc.Server, server serverv3.Server) { - // register services - discoverygrpc.RegisterAggregatedDiscoveryServiceServer(grpcServer, server) - endpointservice.RegisterEndpointDiscoveryServiceServer(grpcServer, server) - clusterservice.RegisterClusterDiscoveryServiceServer(grpcServer, server) - routeservice.RegisterRouteDiscoveryServiceServer(grpcServer, server) - listenerservice.RegisterListenerDiscoveryServiceServer(grpcServer, server) - secretservice.RegisterSecretDiscoveryServiceServer(grpcServer, server) - runtimeservice.RegisterRuntimeDiscoveryServiceServer(grpcServer, server) -} - -// Stop 停止服务 -func (x *XDSServer) Stop() { - connlimit.RemoveLimitListener(x.GetProtocol()) - if x.server != nil { - x.server.Stop() - } -} - -// Restart 重启服务 -func (x *XDSServer) Restart(option map[string]interface{}, api map[string]apiserver.APIConfig, errCh chan error) error { - log.Infof("restart xds server with new config: +%v", option) - - x.restart = true - x.Stop() - if x.start { - <-x.exitCh - } - - log.Info("old xds server has stopped, begin restarting it") - if err := x.Initialize(context.Background(), option, api); err != nil { - log.Errorf("restart grpc server err: %s", err.Error()) - return err - } - - log.Info("init grpc server successfully, restart it") - x.restart = false - go x.Run(errCh) - - return nil -} diff --git a/auth/api.go b/auth/api.go index 2a4fe2caf..41472e91d 100644 --- a/auth/api.go +++ b/auth/api.go @@ -57,7 +57,7 @@ type AuthServer interface { type AuthChecker interface { // Initialize 执行初始化动作 Initialize(options *Config, cacheMgn *cache.CacheManager) error - // VerifyToken 验证令牌 + // VerifyCredential 验证令牌 VerifyCredential(preCtx *model.AcquireContext) error // CheckClientPermission 执行检查客户端动作判断是否有权限,并且对 RequestContext 注入操作者数据 CheckClientPermission(preCtx *model.AcquireContext) (bool, error) diff --git a/auth/defaultauth/auth_mgn_core_test.go b/auth/defaultauth/auth_mgn_core_test.go index 361e5edec..131a913a5 100644 --- a/auth/defaultauth/auth_mgn_core_test.go +++ b/auth/defaultauth/auth_mgn_core_test.go @@ -65,18 +65,15 @@ func Test_defaultAuthChecker_VerifyCredential(t *testing.T) { storage.EXPECT().GetGroupsForCache(gomock.Any(), gomock.Any()).AnyTimes().Return([]*model.UserGroupDetail{}, nil) ctx, cancel := context.WithCancel(context.Background()) - if err := cache.TestCacheInitialize(ctx, &cache.Config{ + cacheMgn, err := cache.TestCacheInitialize(ctx, &cache.Config{ Open: true, Resources: []cache.ConfigEntry{ { Name: "users", }, }, - }, storage); err != nil { - t.Fatal(err) - } + }, storage) - cacheMgn, err := cache.GetCacheManager() if err != nil { t.Fatal(err) } @@ -229,15 +226,12 @@ func Test_defaultAuthChecker_CheckPermission_Write_NoStrict(t *testing.T) { storage.EXPECT().GetMoreServices(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()).AnyTimes().Return(serviceMap, nil) ctx, cancel := context.WithCancel(context.Background()) - if err := cache.TestCacheInitialize(ctx, cfg, storage); err != nil { - t.Fatal(err) - } - - cacheMgn, err := cache.GetCacheManager() + cacheMgn, err := cache.TestCacheInitialize(ctx, cfg, storage) if err != nil { t.Fatal(err) } + defer func() { cancel() cacheMgn.Clear() @@ -473,15 +467,12 @@ func Test_defaultAuthChecker_CheckPermission_Write_Strict(t *testing.T) { storage.EXPECT().GetMoreServices(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()).AnyTimes().Return(serviceMap, nil) ctx, cancel := context.WithCancel(context.Background()) - if err := cache.TestCacheInitialize(ctx, cfg, storage); err != nil { - t.Fatal(err) - } - - cacheMgn, err := cache.GetCacheManager() + cacheMgn, err := cache.TestCacheInitialize(ctx, cfg, storage) if err != nil { t.Fatal(err) } + defer func() { cancel() cacheMgn.Clear() @@ -667,15 +658,12 @@ func Test_defaultAuthChecker_CheckPermission_Read_NoStrict(t *testing.T) { storage.EXPECT().GetMoreServices(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()).AnyTimes().Return(serviceMap, nil) ctx, cancel := context.WithCancel(context.Background()) - if err := cache.TestCacheInitialize(ctx, cfg, storage); err != nil { - t.Fatal(err) - } - - cacheMgn, err := cache.GetCacheManager() + cacheMgn, err := cache.TestCacheInitialize(ctx, cfg, storage) if err != nil { t.Fatal(err) } + defer func() { cancel() cacheMgn.Clear() @@ -881,15 +869,12 @@ func Test_defaultAuthChecker_CheckPermission_Read_Strict(t *testing.T) { storage.EXPECT().GetMoreServices(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()).AnyTimes().Return(serviceMap, nil) ctx, cancel := context.WithCancel(context.Background()) - if err := cache.TestCacheInitialize(ctx, cfg, storage); err != nil { - t.Fatal(err) - } - - cacheMgn, err := cache.GetCacheManager() + cacheMgn, err := cache.TestCacheInitialize(ctx, cfg, storage) if err != nil { t.Fatal(err) } + defer func() { cancel() cacheMgn.Clear() diff --git a/auth/defaultauth/group.go b/auth/defaultauth/group.go index cb91407d0..9f115699c 100644 --- a/auth/defaultauth/group.go +++ b/auth/defaultauth/group.go @@ -28,6 +28,7 @@ import ( "github.com/polarismesh/polaris-server/common/model" commontime "github.com/polarismesh/polaris-server/common/time" "github.com/polarismesh/polaris-server/common/utils" + authcommon "github.com/polarismesh/polaris-server/common/auth" ) type ( @@ -168,7 +169,7 @@ func (svr *server) DeleteGroup(ctx context.Context, req *api.UserGroup) *api.Res return api.NewGroupResponse(api.ExecuteSuccess, req) } - if utils.ParseUserRole(ctx) != model.AdminUserRole { + if authcommon.ParseUserRole(ctx) != model.AdminUserRole { if group.Owner != userID { return api.NewResponse(api.NotAllowedAccess) } @@ -235,7 +236,7 @@ func parseGroupSearchArgs(ctx context.Context, query map[string]string) (map[str } // 如果当前不是管理员角色的话,只能查询该用户所关联的用户组列表以及自己创建的用户组 - if utils.ParseUserRole(ctx) != model.AdminUserRole { + if authcommon.ParseUserRole(ctx) != model.AdminUserRole { if !utils.ParseIsOwner(ctx) { searchFilters["user_id"] = utils.ParseUserID(ctx) } @@ -256,7 +257,7 @@ func (svr *server) GetGroup(ctx context.Context, req *api.UserGroup) *api.Respon return errResp } - if utils.ParseUserRole(ctx) != model.AdminUserRole { + if authcommon.ParseUserRole(ctx) != model.AdminUserRole { userID := utils.ParseUserID(ctx) isGroupOwner := group.Owner == userID _, find := group.UserIds[userID] @@ -282,7 +283,7 @@ func (svr *server) GetGroupToken(ctx context.Context, req *api.UserGroup) *api.R return errResp } - if utils.ParseUserRole(ctx) != model.AdminUserRole { + if authcommon.ParseUserRole(ctx) != model.AdminUserRole { userID := utils.ParseUserID(ctx) isGroupOwner := groupCache.Owner == userID _, find := groupCache.UserIds[userID] @@ -312,7 +313,7 @@ func (svr *server) UpdateGroupToken(ctx context.Context, req *api.UserGroup) *ap return errResp } - if utils.ParseUserRole(ctx) != model.AdminUserRole { + if authcommon.ParseUserRole(ctx) != model.AdminUserRole { userID := utils.ParseUserID(ctx) if group.Owner != userID { return api.NewResponse(api.NotAllowedAccess) @@ -475,7 +476,7 @@ func (svr *server) checkUpdateGroup(ctx context.Context, req *api.ModifyUserGrou // 1.管理员 // 2.自己在这个用户组里面 // 3.自己是这个用户组的owner角色 - if utils.ParseUserRole(ctx) != model.AdminUserRole { + if authcommon.ParseUserRole(ctx) != model.AdminUserRole { _, inGroup := group.UserIds[userID] if !inGroup && group.Owner != userID { return api.NewResponse(api.NotAllowedAccess) diff --git a/auth/defaultauth/group_test.go b/auth/defaultauth/group_test.go index cf316f589..b06e4e564 100644 --- a/auth/defaultauth/group_test.go +++ b/auth/defaultauth/group_test.go @@ -85,15 +85,12 @@ func newGroupTest(t *testing.T) *GroupTest { } ctx, cancel := context.WithCancel(context.Background()) - if err := cache.TestCacheInitialize(ctx, cfg, storage); err != nil { - t.Fatal(err) - } - - cacheMgn, err := cache.GetCacheManager() + cacheMgn, err := cache.TestCacheInitialize(ctx, cfg, storage) if err != nil { t.Fatal(err) } + time.Sleep(time.Second) checker := &defaultAuthChecker{} diff --git a/auth/defaultauth/strategy.go b/auth/defaultauth/strategy.go index b55d1088d..c681d57db 100644 --- a/auth/defaultauth/strategy.go +++ b/auth/defaultauth/strategy.go @@ -26,6 +26,7 @@ import ( "go.uber.org/zap" api "github.com/polarismesh/polaris-server/common/api/v1" + authcommon "github.com/polarismesh/polaris-server/common/auth" "github.com/polarismesh/polaris-server/common/log" "github.com/polarismesh/polaris-server/common/model" commontime "github.com/polarismesh/polaris-server/common/time" @@ -95,6 +96,7 @@ func (svr *server) UpdateStrategies(ctx context.Context, reqs []*api.ModifyAuthS // UpdateStrategy 实现鉴权策略的变更 // Case 1. 修改的是默认鉴权策略的话,只能修改资源,不能添加、删除用户 or 用户组 // Case 2. 鉴权策略只能被自己的 owner 对应的用户修改 +// Case 3. 主账户的默认策略不得修改 func (svr *server) UpdateStrategy(ctx context.Context, req *api.ModifyAuthStrategy) *api.Response { requestID := utils.ParseRequestID(ctx) @@ -267,7 +269,7 @@ func parseStrategySearchArgs(ctx context.Context, searchFilters map[string]strin } } - if utils.ParseUserRole(ctx) != model.AdminUserRole { + if authcommon.ParseUserRole(ctx) != model.AdminUserRole { // 如果当前账户不是 admin 角色,既不是走资源视角查看,也不是指定principal查看,那么只能查询当前操作用户被关联到的鉴权策略, if _, ok := searchFilters["res_id"]; !ok { // 设置 owner 参数,只能查看对应 owner 下的策略 @@ -311,7 +313,7 @@ func (svr *server) GetStrategy(ctx context.Context, req *api.AuthStrategy) *api. var canView bool if isOwner { // 是否是本鉴权策略的 owner 账户, 或者是否是超级管理员, 是的话则快速跳过下面的检查 - canView = (ret.Owner == userId) || utils.ParseUserRole(ctx) == model.AdminUserRole + canView = (ret.Owner == userId) || authcommon.ParseUserRole(ctx) == model.AdminUserRole } // 判断是否在该策略所属的成员列表中,如果自己在某个用户组,而该用户组又在这个策略的成员中,则也是可以查看的 @@ -698,7 +700,7 @@ func (svr *server) checkCreateStrategy(req *api.AuthStrategy) *api.Response { func (svr *server) checkUpdateStrategy(ctx context.Context, req *api.ModifyAuthStrategy, saved *model.StrategyDetail) *api.Response { userId := utils.ParseUserID(ctx) - if utils.ParseUserRole(ctx) != model.AdminUserRole { + if authcommon.ParseUserRole(ctx) != model.AdminUserRole { if !utils.ParseIsOwner(ctx) || userId != saved.Owner { log.AuthScope().Error("[Auth][Strategy] modify strategy denied, current user not owner", utils.ZapRequestID(utils.ParseRequestID(ctx)), @@ -716,6 +718,13 @@ func (svr *server) checkUpdateStrategy(ctx context.Context, req *api.ModifyAuthS len(req.RemovePrincipals.Users) != 0 { return api.NewModifyAuthStrategyResponse(api.NotAllowModifyDefaultStrategyPrincipal, req) } + + // 主账户的默认策略禁止编辑 + if len(saved.Principals) == 1 && saved.Principals[0].PrincipalRole == model.PrincipalUser { + if saved.Principals[0].PrincipalID == utils.ParseOwnerID(ctx) { + return api.NewResponse(api.NotAllowModifyOwnerDefaultStrategy) + } + } } // 检查用户是否存在 diff --git a/auth/defaultauth/strategy_test.go b/auth/defaultauth/strategy_test.go index ec8511737..976bf2c4b 100644 --- a/auth/defaultauth/strategy_test.go +++ b/auth/defaultauth/strategy_test.go @@ -94,15 +94,12 @@ func newStrategyTest(t *testing.T) *StrategyTest { cfg, _ := initCache(ctrl) ctx, cancel := context.WithCancel(context.Background()) - if err := cache.TestCacheInitialize(ctx, cfg, storage); err != nil { - t.Fatal(err) - } - - cacheMgn, err := cache.GetCacheManager() + cacheMgn, err := cache.TestCacheInitialize(ctx, cfg, storage) if err != nil { t.Fatal(err) } + time.Sleep(2 * time.Second) checker := &defaultAuthChecker{} diff --git a/auth/defaultauth/user.go b/auth/defaultauth/user.go index 307b63daa..20d877ad3 100644 --- a/auth/defaultauth/user.go +++ b/auth/defaultauth/user.go @@ -31,6 +31,7 @@ import ( "github.com/polarismesh/polaris-server/common/model" commontime "github.com/polarismesh/polaris-server/common/time" "github.com/polarismesh/polaris-server/common/utils" + authcommon "github.com/polarismesh/polaris-server/common/auth" ) type ( @@ -76,7 +77,7 @@ func (svr *server) CreateUser(ctx context.Context, req *api.User) *api.Response } // 如果创建的目标账户类型是非子账户,则 ownerId 需要设置为 “” - if convertCreateUserRole(utils.ParseUserRole(ctx)) != model.SubAccountUserRole { + if convertCreateUserRole(authcommon.ParseUserRole(ctx)) != model.SubAccountUserRole { ownerID = "" } @@ -112,7 +113,7 @@ func (svr *server) CreateUser(ctx context.Context, req *api.User) *api.Response func (svr *server) createUser(ctx context.Context, req *api.User) *api.Response { requestID := utils.ParseRequestID(ctx) - data, err := createUserModel(req, utils.ParseUserRole(ctx)) + data, err := createUserModel(req, authcommon.ParseUserRole(ctx)) if err != nil { log.AuthScope().Error("[Auth][User] create user model", utils.ZapRequestID(requestID), zap.Error(err)) @@ -198,8 +199,8 @@ func (svr *server) UpdateUserPassword(ctx context.Context, req *api.ModifyUserPa return api.NewResponse(api.NotAllowedAccess) } - ignoreOrign := utils.ParseUserRole(ctx) == model.AdminUserRole || utils.ParseUserRole(ctx) == model.OwnerUserRole - data, needUpdate, err := updateUserPasswordAttribute(ignoreOrign, user, req) + ignoreOrigin := authcommon.ParseUserRole(ctx) == model.AdminUserRole || authcommon.ParseUserRole(ctx) == model.OwnerUserRole + data, needUpdate, err := updateUserPasswordAttribute(ignoreOrigin, user, req) if err != nil { log.AuthScope().Error("[Auth][User] compute user update attribute", zap.Error(err), zap.String("user", req.GetId().GetValue())) @@ -312,7 +313,7 @@ func (svr *server) GetUsers(ctx context.Context, query map[string]string) *api.B searchFilters["hide_admin"] = strconv.FormatBool(true) // 如果不是超级管理员,查看数据有限制 - if utils.ParseUserRole(ctx) != model.AdminUserRole { + if authcommon.ParseUserRole(ctx) != model.AdminUserRole { // 设置 owner 参数,只能查看对应 owner 下的用户 searchFilters["owner"] = utils.ParseOwnerID(ctx) } @@ -403,7 +404,7 @@ func (svr *server) UpdateUserToken(ctx context.Context, req *api.User) *api.Resp return api.NewUserResponse(api.NotAllowedAccess, req) } - if utils.ParseUserRole(ctx) != model.AdminUserRole { + if authcommon.ParseUserRole(ctx) != model.AdminUserRole { if user.Type != model.SubAccountUserRole { return api.NewUserResponseWithMsg(api.NotAllowedAccess, "only disable sub-account token", req) } @@ -472,7 +473,7 @@ func (svr *server) ResetUserToken(ctx context.Context, req *api.User) *api.Respo // Case 2: 如果是主账户操作自己的子账户,通过 // Case 3: 如果是超级账户,通过 func checkUserViewPermission(ctx context.Context, user *model.User) bool { - role := utils.ParseUserRole(ctx) + role := authcommon.ParseUserRole(ctx) if role == model.AdminUserRole { log.AuthScope().Debug("check user view permission", utils.ZapRequestIDByCtx(ctx), zap.Bool("admin", true)) return true @@ -587,6 +588,14 @@ func checkUpdateUser(req *api.User) *api.Response { return api.NewUserResponse(api.BadRequest, req) } + if err := checkMobile(req.Mobile); err != nil { + return api.NewUserResponse(api.InvalidUserMobile, req) + } + + if err := checkEmail(req.Email); err != nil { + return api.NewUserResponse(api.InvalidUserEmail, req) + } + return nil } diff --git a/auth/defaultauth/user_test.go b/auth/defaultauth/user_test.go index ad6787d5c..8036eab82 100644 --- a/auth/defaultauth/user_test.go +++ b/auth/defaultauth/user_test.go @@ -96,15 +96,12 @@ func newUserTest(t *testing.T) *UserTest { } ctx, cancel := context.WithCancel(context.Background()) - if err := cache.TestCacheInitialize(ctx, cfg, storage); err != nil { - t.Fatal(err) - } - - cacheMgn, err := cache.GetCacheManager() + cacheMgn, err := cache.TestCacheInitialize(ctx, cfg, storage) if err != nil { t.Fatal(err) } + time.Sleep(5 * time.Second) checker := &defaultAuthChecker{} @@ -181,7 +178,6 @@ func Test_server_CreateUsers(t *testing.T) { resp := userTest.svr.CreateUsers(reqCtx, createUsersReq) t.Logf("CreateUsers resp : %+v", resp) - assert.Equal(t, api.ExecuteException, resp.Code.GetValue(), "create users must fail") assert.Equal(t, api.InvalidUserName, resp.Responses[0].Code.GetValue(), "create users must fail") }) @@ -198,7 +194,6 @@ func Test_server_CreateUsers(t *testing.T) { resp := userTest.svr.CreateUsers(reqCtx, createUsersReq) t.Logf("CreateUsers resp : %+v", resp) - assert.Equal(t, api.ExecuteException, resp.Code.GetValue(), "create users must fail") assert.Equal(t, api.InvalidUserPassword, resp.Responses[0].Code.GetValue(), "create users must fail") }) @@ -217,7 +212,6 @@ func Test_server_CreateUsers(t *testing.T) { resp := userTest.svr.CreateUsers(reqCtx, createUsersReq) t.Logf("CreateUsers resp : %+v", resp) - assert.Equal(t, api.ExecuteException, resp.Code.GetValue(), "create users must fail") assert.Equal(t, api.UserExisted, resp.Responses[0].Code.GetValue(), "create users must fail") }) @@ -236,7 +230,6 @@ func Test_server_CreateUsers(t *testing.T) { resp := userTest.svr.CreateUsers(reqCtx, createUsersReq) t.Logf("CreateUsers resp : %+v", resp) - assert.Equal(t, api.ExecuteException, resp.Code.GetValue(), "create users must fail") assert.Equal(t, api.UserExisted, resp.Responses[0].Code.GetValue(), "create users must fail") }) @@ -251,7 +244,6 @@ func Test_server_CreateUsers(t *testing.T) { resp := userTest.svr.CreateUsers(context.Background(), createUsersReq) t.Logf("CreateUsers resp : %+v", resp) - assert.Equal(t, api.ExecuteException, resp.Code.GetValue(), "create users must fail") assert.Equal(t, api.EmptyAutToken, resp.Responses[0].Code.GetValue(), "create users must fail") }) @@ -267,7 +259,6 @@ func Test_server_CreateUsers(t *testing.T) { reqCtx := context.WithValue(context.Background(), utils.ContextAuthTokenKey, "utils.ContextAuthTokenKey") resp := userTest.svr.CreateUsers(reqCtx, createUsersReq) t.Logf("CreateUsers resp : %+v", resp) - assert.Equal(t, api.ExecuteException, resp.Code.GetValue(), "create users must fail") assert.Equal(t, api.AuthTokenVerifyException, resp.Responses[0].Code.GetValue(), "create users must fail") }) @@ -288,7 +279,6 @@ func Test_server_CreateUsers(t *testing.T) { resp := userTest.svr.CreateUsers(reqCtx, createUsersReq) t.Logf("CreateUsers resp : %+v", resp) - assert.Equal(t, api.ExecuteException, resp.Code.GetValue(), "create users must fail") assert.Equal(t, api.TokenDisabled, resp.Responses[0].Code.GetValue(), "create users must fail") userTest.users[0].TokenEnable = true @@ -308,7 +298,6 @@ func Test_server_CreateUsers(t *testing.T) { resp := userTest.svr.CreateUsers(reqCtx, createUsersReq) t.Logf("CreateUsers resp : %+v", resp) - assert.Equal(t, api.ExecuteException, resp.Code.GetValue(), "create users must fail") assert.Equal(t, api.OperationRoleException, resp.Responses[0].Code.GetValue(), "create users must fail") }) @@ -325,7 +314,6 @@ func Test_server_CreateUsers(t *testing.T) { resp := userTest.svr.CreateUsers(reqCtx, createUsersReq) t.Logf("CreateUsers resp : %+v", resp) - assert.Equal(t, api.ExecuteException, resp.Code.GetValue(), "create users must fail") assert.Equal(t, api.OperationRoleException, resp.Responses[0].Code.GetValue(), "create users must fail") }) } diff --git a/bootstrap/server.go b/bootstrap/server.go index 9c49fa709..984c0b178 100644 --- a/bootstrap/server.go +++ b/bootstrap/server.go @@ -26,6 +26,7 @@ import ( "time" "github.com/golang/protobuf/ptypes/wrappers" + "gopkg.in/yaml.v2" "github.com/polarismesh/polaris-server/apiserver" "github.com/polarismesh/polaris-server/auth" @@ -63,7 +64,12 @@ func Start(configFilePath string) { return } - fmt.Printf("[INFO] %+v\n", *cfg) + c, err := yaml.Marshal(cfg) + if err != nil { + fmt.Printf("[ERROR] config yaml marshal fail\n") + return + } + fmt.Printf(string(c)) // 初始化日志打印 err = log.Configure(cfg.Bootstrap.Logger) @@ -188,7 +194,7 @@ func StartComponents(ctx context.Context, cfg *boot_config.Config) error { } // 最后启动 cache - if err := cache.Run(ctx); err != nil { + if err := cache.Run(cacheMgn, ctx); err != nil { return err } @@ -240,6 +246,7 @@ func StartDiscoverComponents(ctx context.Context, cfg *boot_config.Config, s sto return err } healthCheckServer.SetServiceCache(cacheMgn.Service()) + healthCheckServer.SetInstanceCache(cacheMgn.Instance()) // 为 instance 的 cache 添加 健康检查的 Listener cacheMgn.AddListener(cache.CacheNameInstance, []cache.Listener{cacheProvider}) @@ -256,7 +263,7 @@ func StartDiscoverComponents(ctx context.Context, cfg *boot_config.Config, s sto service.WithCacheManager(&cfg.Cache, cacheMgn), service.WithHealthCheckSvr(healthCheckServer), service.WithNamespaceSvr(namespaceSvr), - service.WithHiddenService(getSelfRegisterPolarsServiceKeySet(&cfg.Bootstrap.PolarisService)), + service.WithHiddenService(map[model.ServiceKey]struct{}{}), } // 初始化服务模块 @@ -350,7 +357,7 @@ func StopServers(servers []apiserver.Apiserver) { } } -// StartBootstrapOrder 开始进入启动加锁 +// StartBootstrapInOrder 开始进入启动加锁 // 原因:Server启动的时候会从数据库拉取大量数据,防止同时启动把DB压死 // 还有一种场景,server全部宕机批量重启,导致数据库被压死,导致雪崩 func StartBootstrapInOrder(s store.Store, c *boot_config.Config) (store.Transaction, error) { diff --git a/cache/cache.go b/cache/cache.go index 6599c5ef0..213a33339 100644 --- a/cache/cache.go +++ b/cache/cache.go @@ -460,6 +460,21 @@ func ComputeRevision(serviceRevision string, instances []*model.Instance) (strin return hex.EncodeToString(h.Sum(nil)), nil } +// CompositeComputeRevision 将多个 revision 合并计算为一个 +func CompositeComputeRevision(revisions []string) (string, error) { + h := sha1.New() + + sort.Strings(revisions) + + for i := range revisions { + if _, err := h.Write([]byte(revisions[i])); err != nil { + return "", err + } + } + + return hex.EncodeToString(h.Sum(nil)), nil +} + // RegisterCache 注册缓存资源 func RegisterCache(name string, index int) { if _, exist := cacheSet[name]; exist { diff --git a/cache/cache_test.go b/cache/cache_test.go index 25e0dc972..124827a5b 100644 --- a/cache/cache_test.go +++ b/cache/cache_test.go @@ -65,10 +65,8 @@ func TestCacheManager_Start(t *testing.T) { SetCacheConfig(conf) Convey("测试正常的更新缓存逻辑", t, func() { - err := TestCacheInitialize(context.Background(), &Config{Open: true}, storage) + c, err := TestCacheInitialize(context.Background(), &Config{Open: true}, storage) So(err, ShouldBeNil) - - c := cacheMgn So(c, ShouldNotBeNil) beg := time.Unix(0, 0).Add(DefaultTimeDiff) @@ -111,8 +109,7 @@ func TestRevisionWorker(t *testing.T) { defer ctl.Finish() Convey("revision计算,chan可以正常收发", t, func() { - err := TestCacheInitialize(context.TODO(), &Config{Open: true}, storage) - nc := cacheMgn + nc, err := TestCacheInitialize(context.TODO(), &Config{Open: true}, storage) defer func() { _ = nc.Clear() }() So(err, ShouldBeNil) diff --git a/cache/default.go b/cache/default.go index 8b10a5188..149283c98 100644 --- a/cache/default.go +++ b/cache/default.go @@ -48,63 +48,71 @@ func Initialize(ctx context.Context, cacheOpt *Config, storage store.Store) erro } // initialize cache 初始化 -func initialize(_ context.Context, cacheOpt *Config, storage store.Store) error { +func initialize(ctx context.Context, cacheOpt *Config, storage store.Store) error { if !cacheOpt.Open { return nil } + var err error + + cacheMgn, err = newCacheManager(ctx, cacheOpt, storage) + + return err +} + +func newCacheManager(_ context.Context, cacheOpt *Config, storage store.Store) (*CacheManager, error) { SetCacheConfig(cacheOpt) - cacheMgn = &CacheManager{ + mgr := &CacheManager{ storage: storage, caches: make([]Cache, CacheLast), comRevisionCh: make(chan *revisionNotify, RevisionChanCount), revisions: map[string]string{}, } - ic := newInstanceCache(storage, cacheMgn.comRevisionCh) - sc := newServiceCache(storage, cacheMgn.comRevisionCh, ic) - cacheMgn.caches[CacheService] = sc - cacheMgn.caches[CacheInstance] = ic - cacheMgn.caches[CacheRoutingConfig] = newRoutingConfigCache(storage) - cacheMgn.caches[CacheCL5] = &l5Cache{ + ic := newInstanceCache(storage, mgr.comRevisionCh) + sc := newServiceCache(storage, mgr.comRevisionCh, ic) + mgr.caches[CacheService] = sc + mgr.caches[CacheInstance] = ic + mgr.caches[CacheRoutingConfig] = newRoutingConfigCache(storage, sc) + mgr.caches[CacheCL5] = &l5Cache{ storage: storage, ic: ic, sc: sc, } - cacheMgn.caches[CacheRateLimit] = newRateLimitCache(storage) - cacheMgn.caches[CacheCircuitBreaker] = newCircuitBreakerCache(storage) + mgr.caches[CacheRateLimit] = newRateLimitCache(storage) + mgr.caches[CacheCircuitBreaker] = newCircuitBreakerCache(storage) notify := make(chan interface{}, 8) - cacheMgn.caches[CacheUser] = newUserCache(storage, notify) - cacheMgn.caches[CacheAuthStrategy] = newStrategyCache(storage, notify, cacheMgn.caches[CacheUser].(UserCache)) - cacheMgn.caches[CacheNamespace] = newNamespaceCache(storage) - cacheMgn.caches[CacheClient] = newClientCache(storage) + mgr.caches[CacheUser] = newUserCache(storage, notify) + mgr.caches[CacheAuthStrategy] = newStrategyCache(storage, notify, mgr.caches[CacheUser].(UserCache)) + mgr.caches[CacheNamespace] = newNamespaceCache(storage) + mgr.caches[CacheClient] = newClientCache(storage) - if len(cacheMgn.caches) != CacheLast { - return errors.New("some Cache implement not loaded into CacheManager") + if len(mgr.caches) != CacheLast { + return nil, errors.New("some Cache implement not loaded into CacheManager") } // call cache.addlistener here, need ensure that all of cache impl has been instantiated and loaded - cacheMgn.AddListener(CacheNameInstance, []Listener{ + mgr.AddListener(CacheNameInstance, []Listener{ &WatchInstanceReload{ Handler: func(val interface{}) { if svcIds, ok := val.(map[string]bool); ok { - cacheMgn.caches[CacheService].(*serviceCache).notifyServiceCountReload(svcIds) + mgr.caches[CacheService].(*serviceCache).notifyServiceCountReload(svcIds) } }, }, }) - if err := cacheMgn.initialize(); err != nil { - return err + if err := mgr.initialize(); err != nil { + return nil, err } - return nil + return mgr, nil } -func Run(ctx context.Context) error { - if startErr := cacheMgn.Start(ctx); startErr != nil { +func Run(cacheMgr *CacheManager, ctx context.Context) error { + if startErr := cacheMgr.Start(ctx); startErr != nil { log.CacheScope().Errorf("[Cache][Server] start cache err: %s", startErr.Error()) return startErr } diff --git a/cache/instance.go b/cache/instance.go index 163b4dec6..7e7e6f95f 100644 --- a/cache/instance.go +++ b/cache/instance.go @@ -25,6 +25,7 @@ import ( "go.uber.org/zap" "golang.org/x/sync/singleflight" + api "github.com/polarismesh/polaris-server/common/api/v1" "github.com/polarismesh/polaris-server/common/log" "github.com/polarismesh/polaris-server/common/model" "github.com/polarismesh/polaris-server/store" @@ -56,8 +57,10 @@ type InstanceCache interface { GetInstancesCount() int // GetInstancesCountByServiceID 根据服务ID获取实例数 GetInstancesCountByServiceID(serviceID string) model.InstanceCount - // GetServicePorts + // GetServicePorts 根据服务ID获取端口号 GetServicePorts(serviceID string) []string + // GetInstanceLabels Get the label of all instances under a service + GetInstanceLabels(serviceID string) *api.InstanceLabels } // instanceCache 实例缓存的类 @@ -264,7 +267,7 @@ func (ic *instanceCache) setInstances(ins map[string]*model.Instance) (int, int) item.Proto.Metadata = make(map[string]string) } - item = fillIntrnalLabels(item) + item = fillInternalLabels(item) ic.ids.Store(item.ID(), item) if !itemExist { @@ -299,7 +302,7 @@ func (ic *instanceCache) setInstances(ins map[string]*model.Instance) (int, int) return update, del } -func fillIntrnalLabels(item *model.Instance) *model.Instance { +func fillInternalLabels(item *model.Instance) *model.Instance { if len(item.Version()) > 0 { item.Proto.Metadata["version"] = item.Version() } @@ -427,6 +430,46 @@ func (ic *instanceCache) GetInstancesCount() int { return count } +// GetInstanceLabels 获取某个服务下实例的所有标签信息集合 +func (ic *instanceCache) GetInstanceLabels(serviceID string) *api.InstanceLabels { + if serviceID == "" { + return &api.InstanceLabels{} + } + + value, ok := ic.services.Load(serviceID) + if !ok { + return &api.InstanceLabels{} + } + + ret := &api.InstanceLabels{ + Labels: make(map[string]*api.StringList), + } + + tmp := make(map[string]map[string]struct{}) + iteratorInstancesProc(value.(*sync.Map), func(key string, value *model.Instance) (bool, error) { + metadata := value.Metadata() + for k, v := range metadata { + if _, ok := tmp[k]; !ok { + tmp[k] = make(map[string]struct{}) + } + tmp[k][v] = struct{}{} + } + return true, nil + }) + + for k, v := range tmp { + if _, ok := ret.Labels[k]; !ok { + ret.Labels[k] = &api.StringList{Values: make([]string, 0, 4)} + } + + for vv := range v { + ret.Labels[k].Values = append(ret.Labels[k].Values, vv) + } + } + + return ret +} + func (ic *instanceCache) GetServicePorts(serviceID string) []string { return ic.servicePortsBucket.listPort(serviceID) } diff --git a/cache/l5.go b/cache/l5.go index b011e070e..aa14dc8c0 100644 --- a/cache/l5.go +++ b/cache/l5.go @@ -22,9 +22,9 @@ import ( "sync" "time" + cl5common "github.com/polarismesh/polaris-server/common/cl5" "github.com/polarismesh/polaris-server/common/log" "github.com/polarismesh/polaris-server/common/model" - "github.com/polarismesh/polaris-server/common/utils" "github.com/polarismesh/polaris-server/store" ) @@ -148,7 +148,7 @@ func (lc *l5Cache) GetRouteByIP(ip uint32) []*model.Route { entry := value.(*sync.Map) entry.Range(func(key, value interface{}) bool { // sidStr -> setID - sid, err := utils.UnmarshalSid(key.(string)) + sid, err := cl5common.UnmarshalSid(key.(string)) if err != nil { return true } @@ -176,7 +176,7 @@ func (lc *l5Cache) CheckRouteExisted(ip uint32, modID uint32, cmdID uint32) bool entry := value.(*sync.Map) found := false entry.Range(func(key, value interface{}) bool { - sid, err := utils.UnmarshalSid(key.(string)) + sid, err := cl5common.UnmarshalSid(key.(string)) if err != nil { // continue range return true @@ -285,7 +285,7 @@ func (lc *l5Cache) setCL5Route(routes []*model.Route) error { lastRouteFlow = item.Flow } - sidStr := utils.MarshalModCmd(item.ModID, item.CmdID) + sidStr := cl5common.MarshalModCmd(item.ModID, item.CmdID) // 待删除的route if !item.Valid { diff --git a/cache/routing_config.go b/cache/routing_config.go index 7b4bb0e94..8578146dd 100644 --- a/cache/routing_config.go +++ b/cache/routing_config.go @@ -18,12 +18,19 @@ package cache import ( - "sync" + "sort" "time" + apiv1 "github.com/polarismesh/polaris-server/common/api/v1" + apiv2 "github.com/polarismesh/polaris-server/common/api/v2" "github.com/polarismesh/polaris-server/common/log" "github.com/polarismesh/polaris-server/common/model" + v2 "github.com/polarismesh/polaris-server/common/model/v2" + routingcommon "github.com/polarismesh/polaris-server/common/routing" + "github.com/polarismesh/polaris-server/common/utils" "github.com/polarismesh/polaris-server/store" + "go.uber.org/zap" + "golang.org/x/sync/singleflight" ) const ( @@ -31,26 +38,46 @@ const ( RoutingConfigName = "routingConfig" ) -// RoutingConfigCache routing配置的cache接口 -type RoutingConfigCache interface { - Cache +type ( + // RoutingIterProc 遍历路由规则的方法定义 + RoutingIterProc func(key string, value *v2.ExtendRoutingConfig) - // GetRoutingConfig 根据ServiceID获取路由配置 - GetRoutingConfig(id string) *model.RoutingConfig + // RoutingConfigCache routing配置的cache接口 + RoutingConfigCache interface { + Cache + // GetRoutingConfigV1 根据ServiceID获取路由配置 + GetRoutingConfigV1(id, service, namespace string) (*apiv1.Routing, error) + // GetRoutingConfig 根据ServiceID获取路由配置 + GetRoutingConfigV2(id, service, namespace string) ([]*apiv2.Routing, error) + // GetRoutingConfigCount 获取路由配置缓存的总个数 + GetRoutingConfigCount() int + // GetRoutingConfigsV2 查询路由配置列表 + GetRoutingConfigsV2(args *RoutingArgs) (uint32, []*v2.ExtendRoutingConfig, error) + // IsConvertFromV1 当前路由规则是否是从 v1 规则转换过来的 + IsConvertFromV1(id string) (string, bool) + } - // GetRoutingConfigCount 获取路由配置缓存的总个数 - GetRoutingConfigCount() int -} + // routingConfigCache 路由规则缓存 + routingConfigCache struct { + *baseCache -// routingCache的实现 -type routingConfigCache struct { - *baseCache + serviceCache ServiceCache + storage store.Store - storage store.Store - ids *sync.Map - lastMtime time.Time - firstUpdate bool -} + firstUpdate bool + + bucketV1 *routingBucketV1 + bucketV2 *routingBucketV2 + + lastMtimeV1 time.Time + lastMtimeV2 time.Time + + singleFlight singleflight.Group + + // pendingV1RuleIds 记录需要从 v1 转换到 v2 的路由规则id + pendingV1RuleIds map[string]struct{} + } +) // init 自注册到缓存列表 func init() { @@ -58,38 +85,78 @@ func init() { } // newRoutingConfigCache 返回一个操作RoutingConfigCache的对象 -func newRoutingConfigCache(s store.Store) *routingConfigCache { +func newRoutingConfigCache(s store.Store, serviceCache ServiceCache) *routingConfigCache { return &routingConfigCache{ - baseCache: newBaseCache(), - storage: s, + baseCache: newBaseCache(), + storage: s, + serviceCache: serviceCache, + pendingV1RuleIds: map[string]struct{}{}, } } // initialize 实现Cache接口的函数 func (rc *routingConfigCache) initialize(opt map[string]interface{}) error { - rc.ids = new(sync.Map) - rc.lastMtime = time.Unix(0, 0) rc.firstUpdate = true + + rc.initBuckets() + rc.lastMtimeV1 = time.Unix(0, 0) + rc.lastMtimeV2 = time.Unix(0, 0) + if opt == nil { return nil } return nil } +func (rc *routingConfigCache) initBuckets() { + rc.bucketV1 = newRoutingBucketV1() + rc.bucketV2 = newRoutingBucketV2() +} + // update 实现Cache接口的函数 func (rc *routingConfigCache) update(storeRollbackSec time.Duration) error { - out, err := rc.storage.GetRoutingConfigsForCache(rc.lastMtime.Add(storeRollbackSec), rc.firstUpdate) + // 多个线程竞争,只有一个线程进行更新 + _, err, _ := rc.singleFlight.Do("RoutingCache", func() (interface{}, error) { + return nil, rc.realUpdate(storeRollbackSec) + }) + return err +} + +// update 实现Cache接口的函数 +func (rc *routingConfigCache) realUpdate(storeRollbackSec time.Duration) error { + outV1, err := rc.storage.GetRoutingConfigsForCache(rc.lastMtimeV1.Add(storeRollbackSec), rc.firstUpdate) if err != nil { - log.CacheScope().Errorf("[Cache] routing config cache update err: %s", err.Error()) + log.CacheScope().Errorf("[Cache] routing config v1 cache get from store err: %s", err.Error()) + return err + } + + outV2, err := rc.storage.GetRoutingConfigsV2ForCache(rc.lastMtimeV2.Add(storeRollbackSec), rc.firstUpdate) + if err != nil { + log.CacheScope().Errorf("[Cache] routing config v2 cache get from store err: %s", err.Error()) return err } rc.firstUpdate = false - return rc.setRoutingConfig(out) + if err := rc.setRoutingConfigV1(outV1); err != nil { + log.CacheScope().Errorf("[Cache] routing config v1 cache update err: %s", err.Error()) + return err + } + if err := rc.setRoutingConfigV2(outV2); err != nil { + log.CacheScope().Errorf("[Cache] routing config v2 cache update err: %s", err.Error()) + return err + } + rc.setRoutingConfigV1ToV2() + return nil } // clear 实现Cache接口的函数 func (rc *routingConfigCache) clear() error { + rc.firstUpdate = true + + rc.initBuckets() + rc.lastMtimeV1 = time.Unix(0, 0) + rc.lastMtimeV2 = time.Unix(0, 0) + return nil } @@ -99,56 +166,261 @@ func (rc *routingConfigCache) name() string { } // GetRoutingConfig 根据ServiceID获取路由配置 -func (rc *routingConfigCache) GetRoutingConfig(id string) *model.RoutingConfig { - // TODO - if id == "" { +// case 1: 如果只存在 v2 的路由规则,使用 v2 +// case 2: 如果只存在 v1 的路由规则,使用 v1 +// case 3: 如果同时存在 v1 和 v2 的路由规则,进行合并 +func (rc *routingConfigCache) GetRoutingConfigV1(id, service, namespace string) (*apiv1.Routing, error) { + if id == "" && service == "" && namespace == "" { + return nil, nil } - value, ok := rc.ids.Load(id) - if !ok { - return nil + v2rules := rc.bucketV2.listByServiceWithPredicate(service, namespace, + // 只返回 enable 状态的路由规则进行下发 + func(item *v2.ExtendRoutingConfig) bool { + return item.Enable + }) + v1rules := rc.bucketV1.get(id) + if v2rules != nil && v1rules == nil { + return formatRoutingResponseV1(rc.convertRoutingV2toV1(v2rules, service, namespace)), nil + } + + if v2rules == nil && v1rules != nil { + ret, err := routingcommon.RoutingConfigV1ToAPI(v1rules, service, namespace) + if err != nil { + return nil, err + } + return formatRoutingResponseV1(ret), nil + } + + apiv1rule, err := routingcommon.RoutingConfigV1ToAPI(v1rules, service, namespace) + if err != nil { + return nil, err + } + compositeRule, revisions := routingcommon.CompositeRoutingV1AndV2(apiv1rule, + v2rules[level1RoutingV2], v2rules[level2RoutingV2], v2rules[level3RoutingV2]) + + revision, err := CompositeComputeRevision(revisions) + if err != nil { + log.CacheScope().Error("[Cache][Routing] v2=>v1 compute revisions", zap.Error(err)) + return nil, err + } + + compositeRule.Revision = utils.NewStringValue(revision) + return formatRoutingResponseV1(compositeRule), nil +} + +// formatRoutingResponseV1 给客户端的缓存,不需要暴露 ExtendInfo 信息数据 +func formatRoutingResponseV1(ret *apiv1.Routing) *apiv1.Routing { + inBounds := ret.Inbounds + outBounds := ret.Outbounds + + for i := range inBounds { + inBounds[i].ExtendInfo = nil + } + + for i := range outBounds { + outBounds[i].ExtendInfo = nil + } + return ret +} + +// GetRoutingConfigV2 根据服务信息获取该服务下的所有 v2 版本的规则路由 +func (rc *routingConfigCache) GetRoutingConfigV2(id, service, namespace string) ([]*apiv2.Routing, error) { + v2rules := rc.bucketV2.listByServiceWithPredicate(service, namespace, + func(item *v2.ExtendRoutingConfig) bool { + return item.Enable + }) + + ret := make([]*apiv2.Routing, 0, len(v2rules)) + for level := range v2rules { + items := v2rules[level] + for i := range items { + entry, err := items[i].ToApi() + if err != nil { + return nil, err + } + ret = append(ret, entry) + } } - return value.(*model.RoutingConfig) + return ret, nil +} + +// IteratorRoutings +func (rc *routingConfigCache) IteratorRoutings(iterProc RoutingIterProc) { + // 这里只需要遍历 v2 的 routing cache bucket 即可 + rc.bucketV2.foreach(iterProc) } // GetRoutingConfigCount 获取路由配置缓存的总个数 func (rc *routingConfigCache) GetRoutingConfigCount() int { - count := 0 - rc.ids.Range(func(key, value interface{}) bool { - count++ - return true - }) - - return count + return rc.bucketV2.size() } -// setRoutingConfig 更新store的数据到cache中 -func (rc *routingConfigCache) setRoutingConfig(cs []*model.RoutingConfig) error { +// setRoutingConfigV1 更新store的数据到cache中 +func (rc *routingConfigCache) setRoutingConfigV1(cs []*model.RoutingConfig) error { if len(cs) == 0 { return nil } - lastMtime := rc.lastMtime.Unix() + lastMtimeV1 := rc.lastMtimeV1.Unix() for _, entry := range cs { if entry.ID == "" { continue } - - if entry.ModifyTime.Unix() > lastMtime { - lastMtime = entry.ModifyTime.Unix() + if entry.ModifyTime.Unix() > lastMtimeV1 { + lastMtimeV1 = entry.ModifyTime.Unix() } - if !entry.Valid { - rc.ids.Delete(entry.ID) + // 删除老的 v1 缓存 + rc.bucketV1.delete(entry.ID) + // 删除转换为 v2 的缓存 + rc.bucketV2.deleteV1(entry.ID) + // 删除 v1 转换到 v2 的任务id + delete(rc.pendingV1RuleIds, entry.ID) continue } - rc.ids.Store(entry.ID, entry) + // 保存到老的 v1 缓存 + rc.bucketV1.save(entry) + rc.pendingV1RuleIds[entry.ID] = struct{}{} } - if rc.lastMtime.Unix() < lastMtime { - rc.lastMtime = time.Unix(lastMtime, 0) + if rc.lastMtimeV1.Unix() < lastMtimeV1 { + rc.lastMtimeV1 = time.Unix(lastMtimeV1, 0) } return nil } + +// setRoutingConfigV2 存储 v2 路由规则缓存 +func (rc *routingConfigCache) setRoutingConfigV2(cs []*v2.RoutingConfig) error { + if len(cs) == 0 { + return nil + } + + lastMtimeV2 := rc.lastMtimeV2.Unix() + for _, entry := range cs { + if entry.ID == "" { + continue + } + if entry.ModifyTime.Unix() > lastMtimeV2 { + lastMtimeV2 = entry.ModifyTime.Unix() + } + if !entry.Valid { + rc.bucketV2.deleteV2(entry.ID) + continue + } + extendEntry, err := entry.ToExpendRoutingConfig() + if err != nil { + log.CacheScope().Error("[Cache] routing config v2 convert to expend", zap.Error(err)) + continue + } + rc.bucketV2.saveV2(extendEntry) + } + if rc.lastMtimeV2.Unix() < lastMtimeV2 { + rc.lastMtimeV2 = time.Unix(lastMtimeV2, 0) + } + + return nil +} + +func (rc *routingConfigCache) setRoutingConfigV1ToV2() { + for id := range rc.pendingV1RuleIds { + + entry := rc.bucketV1.get(id) + + // 保存到新的 v2 缓存 + if v2rule, err := rc.convertRoutingV1toV2(entry); err != nil { + log.CacheScope().Error("[Cache] routing parse v1 => v2, will try again next", + zap.String("rule-id", entry.ID), zap.Error(err)) + } else { + rc.bucketV2.saveV1(entry, v2rule) + delete(rc.pendingV1RuleIds, id) + } + } + + log.CacheScope().Infof("[Cache] convert routing parse v1 => v2 count : %d", rc.bucketV2.convertV2Size()) +} + +func (rc *routingConfigCache) IsConvertFromV1(id string) (string, bool) { + val, ok := rc.bucketV2.v1rulesToOld[id] + return val, ok +} + +func (rc *routingConfigCache) convertRoutingV1toV2(rule *model.RoutingConfig) ([]*v2.ExtendRoutingConfig, error) { + svc := rc.serviceCache.GetServiceByID(rule.ID) + if svc == nil { + _svc, err := rc.storage.GetServiceByID(rule.ID) + if err != nil { + return nil, err + } + if _svc == nil { + return nil, nil + } + + svc = _svc + } + + in, out, err := routingcommon.ConvertRoutingV1ToExtendV2(svc.Name, svc.Namespace, rule) + if err != nil { + return nil, err + } + + ret := make([]*v2.ExtendRoutingConfig, 0, len(in)+len(out)) + ret = append(ret, in...) + ret = append(ret, out...) + + return ret, nil +} + +// convertRoutingV2toV1 v2 版本的路由规则转为 v1 版本进行返回给客户端,用于兼容 SDK 下发配置的场景 +func (rc *routingConfigCache) convertRoutingV2toV1(entries map[routingLevel][]*v2.ExtendRoutingConfig, + service, namespace string) *apiv1.Routing { + + level1 := entries[level1RoutingV2] + sort.Slice(level1, func(i, j int) bool { + return routingcommon.CompareRoutingV2(level1[i], level1[j]) + }) + + level2 := entries[level2RoutingV2] + sort.Slice(level2, func(i, j int) bool { + return routingcommon.CompareRoutingV2(level2[i], level2[j]) + }) + + level3 := entries[level3RoutingV2] + sort.Slice(level3, func(i, j int) bool { + return routingcommon.CompareRoutingV2(level3[i], level3[j]) + }) + + level1inRoutes, level1outRoutes, level1Revisions := routingcommon.BuildV1RoutesFromV2(service, namespace, level1) + level2inRoutes, level2outRoutes, level2Revisions := routingcommon.BuildV1RoutesFromV2(service, namespace, level2) + level3inRoutes, level3outRoutes, level3Revisions := routingcommon.BuildV1RoutesFromV2(service, namespace, level3) + + revisions := make([]string, 0, len(level1Revisions)+len(level2Revisions)+len(level3Revisions)) + revisions = append(revisions, level1Revisions...) + revisions = append(revisions, level2Revisions...) + revisions = append(revisions, level3Revisions...) + revision, err := CompositeComputeRevision(revisions) + if err != nil { + log.CacheScope().Error("[Cache][Routing] v2=>v1 compute revisions", zap.Error(err)) + return nil + } + + inRoutes := make([]*apiv1.Route, 0, len(level1inRoutes)+len(level2inRoutes)+len(level3inRoutes)) + inRoutes = append(inRoutes, level1inRoutes...) + inRoutes = append(inRoutes, level2inRoutes...) + inRoutes = append(inRoutes, level3inRoutes...) + + outRoutes := make([]*apiv1.Route, 0, len(level1outRoutes)+len(level2outRoutes)+len(level3outRoutes)) + outRoutes = append(outRoutes, level1outRoutes...) + outRoutes = append(outRoutes, level2outRoutes...) + outRoutes = append(outRoutes, level3outRoutes...) + + return &apiv1.Routing{ + Service: utils.NewStringValue(service), + Namespace: utils.NewStringValue(namespace), + Inbounds: inRoutes, + Outbounds: outRoutes, + Revision: utils.NewStringValue(revision), + } +} diff --git a/cache/routing_config_bucket.go b/cache/routing_config_bucket.go new file mode 100644 index 000000000..583276528 --- /dev/null +++ b/cache/routing_config_bucket.go @@ -0,0 +1,344 @@ +/** + * Tencent is pleased to support the open source community by making Polaris available. + * + * Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved. + * + * Licensed under the BSD 3-Clause License (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://opensource.org/licenses/BSD-3-Clause + * + * 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 cache + +import ( + "fmt" + "sync" + + apiv2 "github.com/polarismesh/polaris-server/common/api/v2" + "github.com/polarismesh/polaris-server/common/model" + v2 "github.com/polarismesh/polaris-server/common/model/v2" + routingcommon "github.com/polarismesh/polaris-server/common/routing" +) + +type ( + routingLevel int16 + boundType int16 + + serviceInfo interface { + GetNamespace() string + GetService() string + } +) + +const ( + _ routingLevel = iota + level1RoutingV2 + level2RoutingV2 + level3RoutingV2 + + _ boundType = iota + inBound + outBound +) + +func newRoutingBucketV1() *routingBucketV1 { + return &routingBucketV1{ + rules: make(map[string]*model.RoutingConfig), + } +} + +func newRoutingBucketV2() *routingBucketV2 { + return &routingBucketV2{ + rules: make(map[string]*v2.ExtendRoutingConfig), + level1Rules: map[string]map[string]struct{}{}, + level2Rules: map[boundType]map[string]map[string]struct{}{ + inBound: {}, + outBound: {}, + }, + level3Rules: map[boundType]map[string]struct{}{ + inBound: {}, + outBound: {}, + }, + v1rules: map[string][]*v2.ExtendRoutingConfig{}, + v1rulesToOld: map[string]string{}, + } +} + +// routingBucketV1 v1 路由规则缓存 bucket +type routingBucketV1 struct { + lock sync.RWMutex + rules map[string]*model.RoutingConfig +} + +func (b *routingBucketV1) get(id string) *model.RoutingConfig { + b.lock.RLock() + defer b.lock.RUnlock() + + return b.rules[id] +} + +func (b *routingBucketV1) save(conf *model.RoutingConfig) { + b.lock.Lock() + defer b.lock.Unlock() + + b.rules[conf.ID] = conf +} + +func (b *routingBucketV1) delete(id string) { + b.lock.Lock() + defer b.lock.Unlock() + + delete(b.rules, id) +} + +func (b *routingBucketV1) size() int { + b.lock.RLock() + defer b.lock.RUnlock() + + return len(b.rules) +} + +// routingBucketV2 v2 路由规则缓存 bucket +type routingBucketV2 struct { + lock sync.RWMutex + // rules id => routing rule + rules map[string]*v2.ExtendRoutingConfig + // level1Rules service(name)+namespace => 路由规则ID列表,只针对某个具体的服务有效 + level1Rules map[string]map[string]struct{} + // level2Rules service(*) + namesapce => 路由规则ID列表, 针对某个命名空间下所有服务都生效的路由规则 + level2Rules map[boundType]map[string]map[string]struct{} + // level3Rules service(*) + namesapce(*) => 路由规则ID列表, 针对所有命名空间下的所有服务都生效的规则 + level3Rules map[boundType]map[string]struct{} + // v1rules service-id => []*v2.ExtendRoutingConfig v1 版本的规则自动转为 v2 版本的规则,用于 v2 接口的数据查看 + v1rules map[string][]*v2.ExtendRoutingConfig + // v1rulesToOld 转为 v2 规则id 对应的原本的 v1 规则id 信息 + v1rulesToOld map[string]string +} + +func (b *routingBucketV2) getV2(id string) *v2.ExtendRoutingConfig { + b.lock.RLock() + defer b.lock.RUnlock() + + return b.rules[id] +} + +func (b *routingBucketV2) saveV2(conf *v2.ExtendRoutingConfig) { + b.lock.Lock() + defer b.lock.Unlock() + + b.rules[conf.ID] = conf + + handler := func(bt boundType, item serviceInfo) { + // level3 级别 cache 处理 + if item.GetService() == routingcommon.MatchAll && item.GetNamespace() == routingcommon.MatchAll { + b.level3Rules[bt][conf.ID] = struct{}{} + return + } + // level2 级别 cache 处理 + if item.GetService() == routingcommon.MatchAll && item.GetNamespace() != routingcommon.MatchAll { + if _, ok := b.level2Rules[bt][item.GetNamespace()]; !ok { + b.level2Rules[bt][item.GetNamespace()] = map[string]struct{}{} + } + b.level2Rules[bt][item.GetNamespace()][conf.ID] = struct{}{} + return + } + // level1 级别 cache 处理 + if item.GetService() != routingcommon.MatchAll && item.GetNamespace() != routingcommon.MatchAll { + key := buildServiceKey(item.GetNamespace(), item.GetService()) + if _, ok := b.level1Rules[key]; !ok { + b.level1Rules[key] = map[string]struct{}{} + } + + b.level1Rules[key][conf.ID] = struct{}{} + } + } + + if conf.GetRoutingPolicy() == apiv2.RoutingPolicy_RulePolicy { + sources := conf.RuleRouting.Sources + for i := range sources { + item := sources[i] + handler(outBound, item) + } + + destinations := conf.RuleRouting.Destinations + for i := range destinations { + item := destinations[i] + handler(inBound, item) + } + } +} + +// saveV1 保存 v1 级别的路由规则 +func (b *routingBucketV2) saveV1(v1rule *model.RoutingConfig, v2rules []*v2.ExtendRoutingConfig) { + b.lock.Lock() + defer b.lock.Unlock() + + b.v1rules[v1rule.ID] = v2rules + + for i := range v2rules { + item := v2rules[i] + b.v1rulesToOld[item.ID] = v1rule.ID + } +} + +func (b *routingBucketV2) convertV2Size() uint32 { + b.lock.RLock() + defer b.lock.RUnlock() + + return uint32(len(b.v1rulesToOld)) +} + +func (b *routingBucketV2) deleteV2(id string) { + b.lock.Lock() + defer b.lock.Unlock() + + rule := b.rules[id] + delete(b.rules, id) + + if rule == nil { + return + } + + if rule.GetRoutingPolicy() != apiv2.RoutingPolicy_RulePolicy { + return + } + for i := range rule.RuleRouting.GetSources() { + service := rule.RuleRouting.GetSources()[i].GetService() + namespace := rule.RuleRouting.GetSources()[i].GetNamespace() + + if service == routingcommon.MatchAll && namespace == routingcommon.MatchAll { + delete(b.level3Rules[outBound], id) + delete(b.level3Rules[inBound], id) + } + + if service == routingcommon.MatchAll && namespace != routingcommon.MatchAll { + delete(b.level2Rules[outBound][namespace], id) + delete(b.level2Rules[inBound][namespace], id) + } + + if service != routingcommon.MatchAll && namespace != routingcommon.MatchAll { + key := buildServiceKey(namespace, service) + delete(b.level1Rules[key], id) + } + + } +} + +// deleteV1 删除 v1 的路由规则 +func (b *routingBucketV2) deleteV1(serviceId string) { + b.lock.Lock() + defer b.lock.Unlock() + + items, ok := b.v1rules[serviceId] + if !ok { + delete(b.v1rules, serviceId) + return + } + + for i := range items { + delete(b.v1rulesToOld, items[i].ID) + } + delete(b.v1rules, serviceId) +} + +// size v2 路由缓存的规则数量 +func (b *routingBucketV2) size() int { + b.lock.RLock() + defer b.lock.RUnlock() + + cnt := len(b.rules) + + for k := range b.v1rules { + cnt += len(b.v1rules[k]) + } + + return cnt +} + +type predicate func(item *v2.ExtendRoutingConfig) bool + +// listByServiceWithPredicate 通过服务名称查询 v2 版本的路由规则,同时以及 predicate 进行一些过滤 +func (b *routingBucketV2) listByServiceWithPredicate(service, namespace string, + predicate predicate) map[routingLevel][]*v2.ExtendRoutingConfig { + + ret := make(map[routingLevel][]*v2.ExtendRoutingConfig) + tmpRecord := map[string]struct{}{} + + b.lock.RLock() + defer b.lock.RUnlock() + + // 查询 level1 级别的 v2 版本路由规则 + key := buildServiceKey(namespace, service) + ids := b.level1Rules[key] + level1 := make([]*v2.ExtendRoutingConfig, 0, 4) + for i := range ids { + if v, ok := b.rules[i]; ok && predicate(v) { + level1 = append(level1, v) + tmpRecord[v.ID] = struct{}{} + } + } + ret[level1RoutingV2] = level1 + + handler := func(ids map[string]struct{}, bt boundType) []*v2.ExtendRoutingConfig { + ret := make([]*v2.ExtendRoutingConfig, 0, 4) + + for k := range ids { + v := b.rules[k] + if v == nil { + continue + } + // 已经存在,不需要在重复加一次了 + if _, ok := tmpRecord[v.ID]; ok { + continue + } + if !predicate(v) { + continue + } + ret = append(ret, v) + tmpRecord[v.ID] = struct{}{} + } + + return ret + } + + // 查询 level2 级别的 v2 版本路由规则 + level2 := make([]*v2.ExtendRoutingConfig, 0, 4) + level2 = append(level2, handler(b.level2Rules[outBound][namespace], outBound)...) + level2 = append(level2, handler(b.level2Rules[inBound][namespace], inBound)...) + ret[level2RoutingV2] = level2 + + // 查询 level3 级别的 v2 版本路由规则 + level3 := make([]*v2.ExtendRoutingConfig, 0, 4) + level3 = append(level3, handler(b.level3Rules[outBound], outBound)...) + level3 = append(level3, handler(b.level3Rules[inBound], inBound)...) + ret[level3RoutingV2] = level3 + return ret + +} + +// foreach 遍历所有的路由规则 +func (b *routingBucketV2) foreach(proc RoutingIterProc) { + b.lock.RLock() + defer b.lock.RUnlock() + + for k, v := range b.rules { + proc(k, v) + } + + for _, rules := range b.v1rules { + for i := range rules { + proc(rules[i].ID, rules[i]) + } + } +} + +func buildServiceKey(namespace, service string) string { + return fmt.Sprintf("%s@@%s", namespace, service) +} diff --git a/cache/routing_config_query.go b/cache/routing_config_query.go new file mode 100644 index 000000000..98a2d576f --- /dev/null +++ b/cache/routing_config_query.go @@ -0,0 +1,169 @@ +/** + * Tencent is pleased to support the open source community by making Polaris available. + * + * Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved. + * + * Licensed under the BSD 3-Clause License (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://opensource.org/licenses/BSD-3-Clause + * + * 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 cache + +import ( + "sort" + "strings" + + apiv2 "github.com/polarismesh/polaris-server/common/api/v2" + v2 "github.com/polarismesh/polaris-server/common/model/v2" +) + +// RoutingArgs 路由规则查询参数 +type RoutingArgs struct { + // Filter + Filter map[string]string + // ID 路由规则 ID + ID string + // Name 条件中的服务名 + Name string + // FuzzyName + FuzzyName bool + // Namesapce 服务所在的 namespace + Namespace string + // Service 服务名称 + Service string + // Enable + Enable *bool + // Offset + Offset uint32 + // Limit + Limit uint32 + // OrderField 排序字段 + OrderField string + // OrderType 排序规则 + OrderType string +} + +// forceUpdate 更新配置 +func (rc *routingConfigCache) forceUpdate() error { + if err := rc.update(0); err != nil { + return err + } + return nil +} + +// GetRoutingConfigsV2 查询路由配置列表 +func (rc *routingConfigCache) GetRoutingConfigsV2(args *RoutingArgs) (uint32, []*v2.ExtendRoutingConfig, error) { + if err := rc.forceUpdate(); err != nil { + return 0, nil, err + } + + res := make([]*v2.ExtendRoutingConfig, 0, 8) + var process = func(_ string, svc *v2.ExtendRoutingConfig) { + if args.ID != "" && args.ID != svc.ID { + return + } + + if args.Namespace != "" && args.Service != "" && svc.GetRoutingPolicy() == apiv2.RoutingPolicy_RulePolicy { + var find bool + sources := svc.RuleRouting.GetSources() + for i := range sources { + item := sources[i] + if item.Service == args.Service && item.Namespace == args.Namespace { + find = true + break + } + } + + destinations := svc.RuleRouting.GetDestinations() + for i := range destinations { + item := destinations[i] + if item.Service == args.Service && item.Namespace == args.Namespace { + find = true + break + } + } + + if !find { + return + } + } + + if args.Name != "" { + queryName := args.Name + if args.FuzzyName { + queryName = args.Name[0 : len(args.Name)-1] + } + if !strings.Contains(svc.Name, queryName) { + return + } + } + + if args.Enable != nil && *args.Enable != svc.Enable { + return + } + + res = append(res, svc) + } + + rc.IteratorRoutings(func(key string, value *v2.ExtendRoutingConfig) { + process(key, value) + }) + + amount, routings := rc.sortBeforeTrim(res, args) + return amount, routings, nil +} + +func (rc *routingConfigCache) sortBeforeTrim(routings []*v2.ExtendRoutingConfig, + args *RoutingArgs) (uint32, []*v2.ExtendRoutingConfig) { + // 所有符合条件的路由规则数量 + amount := uint32(len(routings)) + // 判断 offset 和 limit 是否允许返回对应的服务 + if args.Offset >= amount || args.Limit == 0 { + return amount, nil + } + // 将路由规则按照修改时间和 id 进行排序 + sort.Slice(routings, func(i, j int) bool { + asc := strings.ToLower(args.OrderType) == "asc" || args.OrderType == "" + if strings.ToLower(args.OrderField) == "priority" { + return orderByRoutingPriority(routings[i], routings[j], asc) + } else { + return orderByRoutingModifyTime(routings[i], routings[j], asc) + } + }) + endIdx := args.Offset + args.Limit + if endIdx > amount { + endIdx = amount + } + return amount, routings[args.Offset:endIdx] +} + +func orderByRoutingModifyTime(a, b *v2.ExtendRoutingConfig, asc bool) bool { + ap := a.Priority + bp := b.Priority + + if ap < bp { + return true && asc + } + if ap > bp { + return false && asc + } + return strings.Compare(a.ID, b.ID) < 0 && asc +} + +func orderByRoutingPriority(a, b *v2.ExtendRoutingConfig, asc bool) bool { + if a.ModifyTime.After(b.ModifyTime) { + return true && asc + } else if a.ModifyTime.Before(b.ModifyTime) { + return false && asc + } else { + return strings.Compare(a.ID, b.ID) < 0 && asc + } +} diff --git a/cache/service.go b/cache/service.go index 488fa4f2e..ef62dea6f 100644 --- a/cache/service.go +++ b/cache/service.go @@ -77,9 +77,9 @@ type ServiceIterProc func(key string, value *model.Service) (bool, error) type ServiceCache interface { Cache - // GetNamesapceCntInfo Return to the service statistics according to the namespace, + // GetNamespaceCntInfo Return to the service statistics according to the namespace, // the count statistics and health instance statistics - GetNamesapceCntInfo(namespace string) model.NamespaceServiceCount + GetNamespaceCntInfo(namespace string) model.NamespaceServiceCount // GetAllNamespaces Return all namespaces GetAllNamespaces() []string @@ -284,9 +284,9 @@ func (sc *serviceCache) IteratorServices(iterProc ServiceIterProc) error { return err } -// GetNamesapceCntInfo Return to the service statistics according to the namespace, +// GetNamespaceCntInfo Return to the service statistics according to the namespace, // the count statistics and health instance statistics -func (sc *serviceCache) GetNamesapceCntInfo(namespace string) model.NamespaceServiceCount { +func (sc *serviceCache) GetNamespaceCntInfo(namespace string) model.NamespaceServiceCount { val, _ := sc.namespaceServiceCnt.Load(namespace) if val == nil { return model.NamespaceServiceCount{ diff --git a/cache/service_test.go b/cache/service_test.go index 82f242feb..faeed26ab 100644 --- a/cache/service_test.go +++ b/cache/service_test.go @@ -467,7 +467,7 @@ func TestServiceCache_NamespaceCount(t *testing.T) { // 这个时候拉取,数据不正常 for i := range nsList { ns := nsList[i] - acutalNsInsCount[ns] = int(sc.GetNamesapceCntInfo(ns).InstanceCnt.TotalInstanceCount) + acutalNsInsCount[ns] = int(sc.GetNamespaceCntInfo(ns).InstanceCnt.TotalInstanceCount) } fmt.Printf("expect ns-ins count : %#v\n", expectNsInsCount) @@ -512,7 +512,7 @@ func TestServiceCache_NamespaceCount(t *testing.T) { acutalNsInsCount = make(map[string]int) for i := range nsList { ns := nsList[i] - acutalNsInsCount[ns] = int(sc.GetNamesapceCntInfo(ns).InstanceCnt.TotalInstanceCount) + acutalNsInsCount[ns] = int(sc.GetNamespaceCntInfo(ns).InstanceCnt.TotalInstanceCount) } fmt.Printf("expect ns-ins count : %#v\n", expectNsInsCount) fmt.Printf("acutal ns-ins count : %#v\n", acutalNsInsCount) @@ -568,7 +568,7 @@ func TestServiceCache_NamespaceCount(t *testing.T) { acutalNsCount := make(map[string]int) for i := range nsList { ns := nsList[i] - acutalNsCount[ns] = int(sc.GetNamesapceCntInfo(ns).InstanceCnt.TotalInstanceCount) + acutalNsCount[ns] = int(sc.GetNamespaceCntInfo(ns).InstanceCnt.TotalInstanceCount) } fmt.Printf("expect ns count : %#v\n", expectNsCount) diff --git a/cache/store_time.go b/cache/store_time.go index 85dad818c..2e9b1fdfe 100644 --- a/cache/store_time.go +++ b/cache/store_time.go @@ -30,8 +30,7 @@ import ( // watchStoreTime The timestamp change of the storage layer, whether the clock is dialed in the detection func (nc *CacheManager) watchStoreTime(ctx context.Context) { - ticker := time.NewTicker(time.Duration(1 * time.Second)) - + ticker := time.NewTicker(1 * time.Second) defer ticker.Stop() preStoreTime, err := nc.storage.GetUnixSecond() @@ -48,14 +47,12 @@ func (nc *CacheManager) watchStoreTime(ctx context.Context) { log.CacheScope().Error("[Store][Time] watch store time", zap.Error(err)) continue } - + // 防止时间回退 if preStoreTime != 0 && preStoreTime > storeSec { - // 默认多查询 1 秒的数据 - atomic.StoreInt64(&nc.storeTimeDiffSec, int64(preStoreTime-storeSec)) + atomic.StoreInt64(&nc.storeTimeDiffSec, preStoreTime-storeSec) } else { preStoreTime = storeSec - // 默认多查询 1 秒的数据 - atomic.StoreInt64(&nc.storeTimeDiffSec, int64(0)) + atomic.StoreInt64(&nc.storeTimeDiffSec, 0) } case <-ctx.Done(): diff --git a/cache/test_export.go b/cache/test_export.go index f9726e1f2..b0cc747f5 100644 --- a/cache/test_export.go +++ b/cache/test_export.go @@ -26,12 +26,11 @@ import ( // TestCacheInitialize 由于某一些模块依赖Cache,但是由于Cache模块初始化采用sync.Once,会导致单元测试之间Cache存在脏数据问题,因此为了确保单 // 元测试能够正常执行,这里将 cache.initialize 方法导出并命名为 TestCacheInitialize,仅用于单元测试初始化一个完整的 CacheManager var ( - TestCacheInitialize = func(ctx context.Context, cacheOpt *Config, storage store.Store) error { - if err := initialize(ctx, cacheOpt, storage); err != nil { - finishInit = false - return err + TestCacheInitialize = func(ctx context.Context, cacheOpt *Config, storage store.Store) (*CacheManager, error) { + mgr, err := newCacheManager(ctx, cacheOpt, storage) + if err := Run(mgr, ctx); err != nil { + return nil, err } - finishInit = true - return Run(ctx) + return mgr, err } ) diff --git a/common/api/v1/codeinfo.go b/common/api/v1/codeinfo.go index 2962c1c45..7ca74425e 100644 --- a/common/api/v1/codeinfo.go +++ b/common/api/v1/codeinfo.go @@ -76,6 +76,10 @@ const ( InvalidCircuitBreakerBusiness uint32 = 400166 InvalidCircuitBreakerDepartment uint32 = 400167 InvalidCircuitBreakerComment uint32 = 400168 + InvalidRoutingID uint32 = 400700 + InvalidRoutingPolicy uint32 = 400701 + InvalidRoutingName uint32 = 400702 + InvalidRoutingPriority uint32 = 400703 // 网格相关错误码 ServicesExistedMesh uint32 = 400170 @@ -112,6 +116,7 @@ const ( NamespaceExistedCircuitBreakers uint32 = 400212 ServiceSubscribedByMeshes uint32 = 400213 ServiceExistedFluxRateLimits uint32 = 400214 + NamespaceExistedConfigGroups uint32 = 400219 NotFoundService uint32 = 400301 NotFoundRouting uint32 = 400302 @@ -182,6 +187,7 @@ const ( NotFoundUserGroup uint32 = 400314 NotFoundAuthStrategyRule uint32 = 400315 NotAllowModifyDefaultStrategyPrincipal uint32 = 400508 + NotAllowModifyOwnerDefaultStrategy uint32 = 400509 EmptyAutToken uint32 = 401002 TokenDisabled uint32 = 401003 @@ -342,6 +348,15 @@ var code2info = map[uint32]string{ SubAccountExisted: "some sub-account existed in owner", InvalidUserID: "invalid user-id", TokenNotExisted: "token not existed", + + NotAllowModifyDefaultStrategyPrincipal: "not allow modify default strategy principal", + NotAllowModifyOwnerDefaultStrategy: "not allow modify main account default strategy", + + InvalidRoutingID: "invalid routing id", + InvalidRoutingPolicy: "invalid routing policy, only support (RulePolicy,MetadataPolicy)", + InvalidRoutingName: "invalid routing name", + + NamespaceExistedConfigGroups: "some config group existed in namespace", } // code to info diff --git a/common/api/v1/config_file.pb.go b/common/api/v1/config_file.pb.go index 151fd8b9c..97c244a93 100644 --- a/common/api/v1/config_file.pb.go +++ b/common/api/v1/config_file.pb.go @@ -1,1440 +1,907 @@ -/* - * Tencent is pleased to support the open source community by making Polaris available. - * - * Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved. - * - * Licensed under the BSD 3-Clause License (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://opensource.org/licenses/BSD-3-Clause - * - * 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. - */ - // Code generated by protoc-gen-go. DO NOT EDIT. -// versions: -// protoc-gen-go v1.27.1 -// protoc v3.17.3 // source: config_file.proto package v1 -import ( - wrappers "github.com/golang/protobuf/ptypes/wrappers" - protoreflect "google.golang.org/protobuf/reflect/protoreflect" - protoimpl "google.golang.org/protobuf/runtime/protoimpl" - reflect "reflect" - sync "sync" -) - -const ( - // Verify that this generated code is sufficiently up-to-date. - _ = protoimpl.EnforceVersion(20 - protoimpl.MinVersion) - // Verify that runtime/protoimpl is sufficiently up-to-date. - _ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20) -) +import proto "github.com/golang/protobuf/proto" +import fmt "fmt" +import math "math" +import wrappers "github.com/golang/protobuf/ptypes/wrappers" -type ConfigFileGroup struct { - state protoimpl.MessageState - sizeCache protoimpl.SizeCache - unknownFields protoimpl.UnknownFields +// Reference imports to suppress errors if they are not otherwise used. +var _ = proto.Marshal +var _ = fmt.Errorf +var _ = math.Inf - Id *wrappers.UInt64Value `protobuf:"bytes,1,opt,name=id,proto3" json:"id,omitempty"` - Name *wrappers.StringValue `protobuf:"bytes,2,opt,name=name,proto3" json:"name,omitempty"` - Namespace *wrappers.StringValue `protobuf:"bytes,3,opt,name=namespace,proto3" json:"namespace,omitempty"` - Comment *wrappers.StringValue `protobuf:"bytes,4,opt,name=comment,proto3" json:"comment,omitempty"` - CreateTime *wrappers.StringValue `protobuf:"bytes,5,opt,name=create_time,json=createTime,proto3" json:"create_time,omitempty"` - CreateBy *wrappers.StringValue `protobuf:"bytes,6,opt,name=create_by,json=createBy,proto3" json:"create_by,omitempty"` - ModifyTime *wrappers.StringValue `protobuf:"bytes,7,opt,name=modify_time,json=modifyTime,proto3" json:"modify_time,omitempty"` - ModifyBy *wrappers.StringValue `protobuf:"bytes,8,opt,name=modify_by,json=modifyBy,proto3" json:"modify_by,omitempty"` - FileCount *wrappers.UInt64Value `protobuf:"bytes,9,opt,name=fileCount,proto3" json:"fileCount,omitempty"` -} +// This is a compile-time assertion to ensure that this generated file +// is compatible with the proto package it is being compiled against. +// A compilation error at this line likely means your copy of the +// proto package needs to be updated. +const _ = proto.ProtoPackageIsVersion2 // please upgrade the proto package -func (x *ConfigFileGroup) Reset() { - *x = ConfigFileGroup{} - if protoimpl.UnsafeEnabled { - mi := &file_config_file_proto_msgTypes[0] - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - ms.StoreMessageInfo(mi) - } +type ConfigFileGroup struct { + Id *wrappers.UInt64Value `protobuf:"bytes,1,opt,name=id,proto3" json:"id,omitempty"` + Name *wrappers.StringValue `protobuf:"bytes,2,opt,name=name,proto3" json:"name,omitempty"` + Namespace *wrappers.StringValue `protobuf:"bytes,3,opt,name=namespace,proto3" json:"namespace,omitempty"` + Comment *wrappers.StringValue `protobuf:"bytes,4,opt,name=comment,proto3" json:"comment,omitempty"` + CreateTime *wrappers.StringValue `protobuf:"bytes,5,opt,name=create_time,json=createTime,proto3" json:"create_time,omitempty"` + CreateBy *wrappers.StringValue `protobuf:"bytes,6,opt,name=create_by,json=createBy,proto3" json:"create_by,omitempty"` + ModifyTime *wrappers.StringValue `protobuf:"bytes,7,opt,name=modify_time,json=modifyTime,proto3" json:"modify_time,omitempty"` + ModifyBy *wrappers.StringValue `protobuf:"bytes,8,opt,name=modify_by,json=modifyBy,proto3" json:"modify_by,omitempty"` + FileCount *wrappers.UInt64Value `protobuf:"bytes,9,opt,name=fileCount,proto3" json:"fileCount,omitempty"` + XXX_NoUnkeyedLiteral struct{} `json:"-"` + XXX_unrecognized []byte `json:"-"` + XXX_sizecache int32 `json:"-"` +} + +func (m *ConfigFileGroup) Reset() { *m = ConfigFileGroup{} } +func (m *ConfigFileGroup) String() string { return proto.CompactTextString(m) } +func (*ConfigFileGroup) ProtoMessage() {} +func (*ConfigFileGroup) Descriptor() ([]byte, []int) { + return fileDescriptor_config_file_b643ace0171d7a6b, []int{0} } - -func (x *ConfigFileGroup) String() string { - return protoimpl.X.MessageStringOf(x) +func (m *ConfigFileGroup) XXX_Unmarshal(b []byte) error { + return xxx_messageInfo_ConfigFileGroup.Unmarshal(m, b) } - -func (*ConfigFileGroup) ProtoMessage() {} - -func (x *ConfigFileGroup) ProtoReflect() protoreflect.Message { - mi := &file_config_file_proto_msgTypes[0] - if protoimpl.UnsafeEnabled && x != nil { - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - if ms.LoadMessageInfo() == nil { - ms.StoreMessageInfo(mi) - } - return ms - } - return mi.MessageOf(x) +func (m *ConfigFileGroup) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + return xxx_messageInfo_ConfigFileGroup.Marshal(b, m, deterministic) } - -// Deprecated: Use ConfigFileGroup.ProtoReflect.Descriptor instead. -func (*ConfigFileGroup) Descriptor() ([]byte, []int) { - return file_config_file_proto_rawDescGZIP(), []int{0} +func (dst *ConfigFileGroup) XXX_Merge(src proto.Message) { + xxx_messageInfo_ConfigFileGroup.Merge(dst, src) +} +func (m *ConfigFileGroup) XXX_Size() int { + return xxx_messageInfo_ConfigFileGroup.Size(m) } +func (m *ConfigFileGroup) XXX_DiscardUnknown() { + xxx_messageInfo_ConfigFileGroup.DiscardUnknown(m) +} + +var xxx_messageInfo_ConfigFileGroup proto.InternalMessageInfo -func (x *ConfigFileGroup) GetId() *wrappers.UInt64Value { - if x != nil { - return x.Id +func (m *ConfigFileGroup) GetId() *wrappers.UInt64Value { + if m != nil { + return m.Id } return nil } -func (x *ConfigFileGroup) GetName() *wrappers.StringValue { - if x != nil { - return x.Name +func (m *ConfigFileGroup) GetName() *wrappers.StringValue { + if m != nil { + return m.Name } return nil } -func (x *ConfigFileGroup) GetNamespace() *wrappers.StringValue { - if x != nil { - return x.Namespace +func (m *ConfigFileGroup) GetNamespace() *wrappers.StringValue { + if m != nil { + return m.Namespace } return nil } -func (x *ConfigFileGroup) GetComment() *wrappers.StringValue { - if x != nil { - return x.Comment +func (m *ConfigFileGroup) GetComment() *wrappers.StringValue { + if m != nil { + return m.Comment } return nil } -func (x *ConfigFileGroup) GetCreateTime() *wrappers.StringValue { - if x != nil { - return x.CreateTime +func (m *ConfigFileGroup) GetCreateTime() *wrappers.StringValue { + if m != nil { + return m.CreateTime } return nil } -func (x *ConfigFileGroup) GetCreateBy() *wrappers.StringValue { - if x != nil { - return x.CreateBy +func (m *ConfigFileGroup) GetCreateBy() *wrappers.StringValue { + if m != nil { + return m.CreateBy } return nil } -func (x *ConfigFileGroup) GetModifyTime() *wrappers.StringValue { - if x != nil { - return x.ModifyTime +func (m *ConfigFileGroup) GetModifyTime() *wrappers.StringValue { + if m != nil { + return m.ModifyTime } return nil } -func (x *ConfigFileGroup) GetModifyBy() *wrappers.StringValue { - if x != nil { - return x.ModifyBy +func (m *ConfigFileGroup) GetModifyBy() *wrappers.StringValue { + if m != nil { + return m.ModifyBy } return nil } -func (x *ConfigFileGroup) GetFileCount() *wrappers.UInt64Value { - if x != nil { - return x.FileCount +func (m *ConfigFileGroup) GetFileCount() *wrappers.UInt64Value { + if m != nil { + return m.FileCount } return nil } type ConfigFile struct { - state protoimpl.MessageState - sizeCache protoimpl.SizeCache - unknownFields protoimpl.UnknownFields - - Id *wrappers.UInt64Value `protobuf:"bytes,1,opt,name=id,proto3" json:"id,omitempty"` - Name *wrappers.StringValue `protobuf:"bytes,2,opt,name=name,proto3" json:"name,omitempty"` - Namespace *wrappers.StringValue `protobuf:"bytes,3,opt,name=namespace,proto3" json:"namespace,omitempty"` - Group *wrappers.StringValue `protobuf:"bytes,4,opt,name=group,proto3" json:"group,omitempty"` - Content *wrappers.StringValue `protobuf:"bytes,5,opt,name=content,proto3" json:"content,omitempty"` - Format *wrappers.StringValue `protobuf:"bytes,6,opt,name=format,proto3" json:"format,omitempty"` - Comment *wrappers.StringValue `protobuf:"bytes,7,opt,name=comment,proto3" json:"comment,omitempty"` - Status *wrappers.StringValue `protobuf:"bytes,8,opt,name=status,proto3" json:"status,omitempty"` - Tags []*ConfigFileTag `protobuf:"bytes,9,rep,name=tags,proto3" json:"tags,omitempty"` - CreateTime *wrappers.StringValue `protobuf:"bytes,10,opt,name=create_time,json=createTime,proto3" json:"create_time,omitempty"` - CreateBy *wrappers.StringValue `protobuf:"bytes,11,opt,name=create_by,json=createBy,proto3" json:"create_by,omitempty"` - ModifyTime *wrappers.StringValue `protobuf:"bytes,12,opt,name=modify_time,json=modifyTime,proto3" json:"modify_time,omitempty"` - ModifyBy *wrappers.StringValue `protobuf:"bytes,13,opt,name=modify_by,json=modifyBy,proto3" json:"modify_by,omitempty"` - ReleaseTime *wrappers.StringValue `protobuf:"bytes,14,opt,name=release_time,json=releaseTime,proto3" json:"release_time,omitempty"` - ReleaseBy *wrappers.StringValue `protobuf:"bytes,15,opt,name=release_by,json=releaseBy,proto3" json:"release_by,omitempty"` + Id *wrappers.UInt64Value `protobuf:"bytes,1,opt,name=id,proto3" json:"id,omitempty"` + Name *wrappers.StringValue `protobuf:"bytes,2,opt,name=name,proto3" json:"name,omitempty"` + Namespace *wrappers.StringValue `protobuf:"bytes,3,opt,name=namespace,proto3" json:"namespace,omitempty"` + Group *wrappers.StringValue `protobuf:"bytes,4,opt,name=group,proto3" json:"group,omitempty"` + Content *wrappers.StringValue `protobuf:"bytes,5,opt,name=content,proto3" json:"content,omitempty"` + Format *wrappers.StringValue `protobuf:"bytes,6,opt,name=format,proto3" json:"format,omitempty"` + Comment *wrappers.StringValue `protobuf:"bytes,7,opt,name=comment,proto3" json:"comment,omitempty"` + Status *wrappers.StringValue `protobuf:"bytes,8,opt,name=status,proto3" json:"status,omitempty"` + Tags []*ConfigFileTag `protobuf:"bytes,9,rep,name=tags,proto3" json:"tags,omitempty"` + CreateTime *wrappers.StringValue `protobuf:"bytes,10,opt,name=create_time,json=createTime,proto3" json:"create_time,omitempty"` + CreateBy *wrappers.StringValue `protobuf:"bytes,11,opt,name=create_by,json=createBy,proto3" json:"create_by,omitempty"` + ModifyTime *wrappers.StringValue `protobuf:"bytes,12,opt,name=modify_time,json=modifyTime,proto3" json:"modify_time,omitempty"` + ModifyBy *wrappers.StringValue `protobuf:"bytes,13,opt,name=modify_by,json=modifyBy,proto3" json:"modify_by,omitempty"` + ReleaseTime *wrappers.StringValue `protobuf:"bytes,14,opt,name=release_time,json=releaseTime,proto3" json:"release_time,omitempty"` + ReleaseBy *wrappers.StringValue `protobuf:"bytes,15,opt,name=release_by,json=releaseBy,proto3" json:"release_by,omitempty"` + XXX_NoUnkeyedLiteral struct{} `json:"-"` + XXX_unrecognized []byte `json:"-"` + XXX_sizecache int32 `json:"-"` +} + +func (m *ConfigFile) Reset() { *m = ConfigFile{} } +func (m *ConfigFile) String() string { return proto.CompactTextString(m) } +func (*ConfigFile) ProtoMessage() {} +func (*ConfigFile) Descriptor() ([]byte, []int) { + return fileDescriptor_config_file_b643ace0171d7a6b, []int{1} } - -func (x *ConfigFile) Reset() { - *x = ConfigFile{} - if protoimpl.UnsafeEnabled { - mi := &file_config_file_proto_msgTypes[1] - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - ms.StoreMessageInfo(mi) - } +func (m *ConfigFile) XXX_Unmarshal(b []byte) error { + return xxx_messageInfo_ConfigFile.Unmarshal(m, b) } - -func (x *ConfigFile) String() string { - return protoimpl.X.MessageStringOf(x) +func (m *ConfigFile) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + return xxx_messageInfo_ConfigFile.Marshal(b, m, deterministic) } - -func (*ConfigFile) ProtoMessage() {} - -func (x *ConfigFile) ProtoReflect() protoreflect.Message { - mi := &file_config_file_proto_msgTypes[1] - if protoimpl.UnsafeEnabled && x != nil { - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - if ms.LoadMessageInfo() == nil { - ms.StoreMessageInfo(mi) - } - return ms - } - return mi.MessageOf(x) +func (dst *ConfigFile) XXX_Merge(src proto.Message) { + xxx_messageInfo_ConfigFile.Merge(dst, src) } - -// Deprecated: Use ConfigFile.ProtoReflect.Descriptor instead. -func (*ConfigFile) Descriptor() ([]byte, []int) { - return file_config_file_proto_rawDescGZIP(), []int{1} +func (m *ConfigFile) XXX_Size() int { + return xxx_messageInfo_ConfigFile.Size(m) } +func (m *ConfigFile) XXX_DiscardUnknown() { + xxx_messageInfo_ConfigFile.DiscardUnknown(m) +} + +var xxx_messageInfo_ConfigFile proto.InternalMessageInfo -func (x *ConfigFile) GetId() *wrappers.UInt64Value { - if x != nil { - return x.Id +func (m *ConfigFile) GetId() *wrappers.UInt64Value { + if m != nil { + return m.Id } return nil } -func (x *ConfigFile) GetName() *wrappers.StringValue { - if x != nil { - return x.Name +func (m *ConfigFile) GetName() *wrappers.StringValue { + if m != nil { + return m.Name } return nil } -func (x *ConfigFile) GetNamespace() *wrappers.StringValue { - if x != nil { - return x.Namespace +func (m *ConfigFile) GetNamespace() *wrappers.StringValue { + if m != nil { + return m.Namespace } return nil } -func (x *ConfigFile) GetGroup() *wrappers.StringValue { - if x != nil { - return x.Group +func (m *ConfigFile) GetGroup() *wrappers.StringValue { + if m != nil { + return m.Group } return nil } -func (x *ConfigFile) GetContent() *wrappers.StringValue { - if x != nil { - return x.Content +func (m *ConfigFile) GetContent() *wrappers.StringValue { + if m != nil { + return m.Content } return nil } -func (x *ConfigFile) GetFormat() *wrappers.StringValue { - if x != nil { - return x.Format +func (m *ConfigFile) GetFormat() *wrappers.StringValue { + if m != nil { + return m.Format } return nil } -func (x *ConfigFile) GetComment() *wrappers.StringValue { - if x != nil { - return x.Comment +func (m *ConfigFile) GetComment() *wrappers.StringValue { + if m != nil { + return m.Comment } return nil } -func (x *ConfigFile) GetStatus() *wrappers.StringValue { - if x != nil { - return x.Status +func (m *ConfigFile) GetStatus() *wrappers.StringValue { + if m != nil { + return m.Status } return nil } -func (x *ConfigFile) GetTags() []*ConfigFileTag { - if x != nil { - return x.Tags +func (m *ConfigFile) GetTags() []*ConfigFileTag { + if m != nil { + return m.Tags } return nil } -func (x *ConfigFile) GetCreateTime() *wrappers.StringValue { - if x != nil { - return x.CreateTime +func (m *ConfigFile) GetCreateTime() *wrappers.StringValue { + if m != nil { + return m.CreateTime } return nil } -func (x *ConfigFile) GetCreateBy() *wrappers.StringValue { - if x != nil { - return x.CreateBy +func (m *ConfigFile) GetCreateBy() *wrappers.StringValue { + if m != nil { + return m.CreateBy } return nil } -func (x *ConfigFile) GetModifyTime() *wrappers.StringValue { - if x != nil { - return x.ModifyTime +func (m *ConfigFile) GetModifyTime() *wrappers.StringValue { + if m != nil { + return m.ModifyTime } return nil } -func (x *ConfigFile) GetModifyBy() *wrappers.StringValue { - if x != nil { - return x.ModifyBy +func (m *ConfigFile) GetModifyBy() *wrappers.StringValue { + if m != nil { + return m.ModifyBy } return nil } -func (x *ConfigFile) GetReleaseTime() *wrappers.StringValue { - if x != nil { - return x.ReleaseTime +func (m *ConfigFile) GetReleaseTime() *wrappers.StringValue { + if m != nil { + return m.ReleaseTime } return nil } -func (x *ConfigFile) GetReleaseBy() *wrappers.StringValue { - if x != nil { - return x.ReleaseBy +func (m *ConfigFile) GetReleaseBy() *wrappers.StringValue { + if m != nil { + return m.ReleaseBy } return nil } type ConfigFileTag struct { - state protoimpl.MessageState - sizeCache protoimpl.SizeCache - unknownFields protoimpl.UnknownFields - - Key *wrappers.StringValue `protobuf:"bytes,1,opt,name=key,proto3" json:"key,omitempty"` - Value *wrappers.StringValue `protobuf:"bytes,2,opt,name=value,proto3" json:"value,omitempty"` + Key *wrappers.StringValue `protobuf:"bytes,1,opt,name=key,proto3" json:"key,omitempty"` + Value *wrappers.StringValue `protobuf:"bytes,2,opt,name=value,proto3" json:"value,omitempty"` + XXX_NoUnkeyedLiteral struct{} `json:"-"` + XXX_unrecognized []byte `json:"-"` + XXX_sizecache int32 `json:"-"` } -func (x *ConfigFileTag) Reset() { - *x = ConfigFileTag{} - if protoimpl.UnsafeEnabled { - mi := &file_config_file_proto_msgTypes[2] - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - ms.StoreMessageInfo(mi) - } +func (m *ConfigFileTag) Reset() { *m = ConfigFileTag{} } +func (m *ConfigFileTag) String() string { return proto.CompactTextString(m) } +func (*ConfigFileTag) ProtoMessage() {} +func (*ConfigFileTag) Descriptor() ([]byte, []int) { + return fileDescriptor_config_file_b643ace0171d7a6b, []int{2} } - -func (x *ConfigFileTag) String() string { - return protoimpl.X.MessageStringOf(x) +func (m *ConfigFileTag) XXX_Unmarshal(b []byte) error { + return xxx_messageInfo_ConfigFileTag.Unmarshal(m, b) } - -func (*ConfigFileTag) ProtoMessage() {} - -func (x *ConfigFileTag) ProtoReflect() protoreflect.Message { - mi := &file_config_file_proto_msgTypes[2] - if protoimpl.UnsafeEnabled && x != nil { - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - if ms.LoadMessageInfo() == nil { - ms.StoreMessageInfo(mi) - } - return ms - } - return mi.MessageOf(x) +func (m *ConfigFileTag) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + return xxx_messageInfo_ConfigFileTag.Marshal(b, m, deterministic) } - -// Deprecated: Use ConfigFileTag.ProtoReflect.Descriptor instead. -func (*ConfigFileTag) Descriptor() ([]byte, []int) { - return file_config_file_proto_rawDescGZIP(), []int{2} +func (dst *ConfigFileTag) XXX_Merge(src proto.Message) { + xxx_messageInfo_ConfigFileTag.Merge(dst, src) +} +func (m *ConfigFileTag) XXX_Size() int { + return xxx_messageInfo_ConfigFileTag.Size(m) } +func (m *ConfigFileTag) XXX_DiscardUnknown() { + xxx_messageInfo_ConfigFileTag.DiscardUnknown(m) +} + +var xxx_messageInfo_ConfigFileTag proto.InternalMessageInfo -func (x *ConfigFileTag) GetKey() *wrappers.StringValue { - if x != nil { - return x.Key +func (m *ConfigFileTag) GetKey() *wrappers.StringValue { + if m != nil { + return m.Key } return nil } -func (x *ConfigFileTag) GetValue() *wrappers.StringValue { - if x != nil { - return x.Value +func (m *ConfigFileTag) GetValue() *wrappers.StringValue { + if m != nil { + return m.Value } return nil } type ConfigFileRelease struct { - state protoimpl.MessageState - sizeCache protoimpl.SizeCache - unknownFields protoimpl.UnknownFields - - Id *wrappers.UInt64Value `protobuf:"bytes,1,opt,name=id,proto3" json:"id,omitempty"` - Name *wrappers.StringValue `protobuf:"bytes,2,opt,name=name,proto3" json:"name,omitempty"` - Namespace *wrappers.StringValue `protobuf:"bytes,3,opt,name=namespace,proto3" json:"namespace,omitempty"` - Group *wrappers.StringValue `protobuf:"bytes,4,opt,name=group,proto3" json:"group,omitempty"` - FileName *wrappers.StringValue `protobuf:"bytes,5,opt,name=file_name,json=fileName,proto3" json:"file_name,omitempty"` - Content *wrappers.StringValue `protobuf:"bytes,6,opt,name=content,proto3" json:"content,omitempty"` - Comment *wrappers.StringValue `protobuf:"bytes,7,opt,name=comment,proto3" json:"comment,omitempty"` - Md5 *wrappers.StringValue `protobuf:"bytes,8,opt,name=md5,proto3" json:"md5,omitempty"` - Version *wrappers.UInt64Value `protobuf:"bytes,9,opt,name=version,proto3" json:"version,omitempty"` - CreateTime *wrappers.StringValue `protobuf:"bytes,10,opt,name=create_time,json=createTime,proto3" json:"create_time,omitempty"` - CreateBy *wrappers.StringValue `protobuf:"bytes,11,opt,name=create_by,json=createBy,proto3" json:"create_by,omitempty"` - ModifyTime *wrappers.StringValue `protobuf:"bytes,12,opt,name=modify_time,json=modifyTime,proto3" json:"modify_time,omitempty"` - ModifyBy *wrappers.StringValue `protobuf:"bytes,13,opt,name=modify_by,json=modifyBy,proto3" json:"modify_by,omitempty"` + Id *wrappers.UInt64Value `protobuf:"bytes,1,opt,name=id,proto3" json:"id,omitempty"` + Name *wrappers.StringValue `protobuf:"bytes,2,opt,name=name,proto3" json:"name,omitempty"` + Namespace *wrappers.StringValue `protobuf:"bytes,3,opt,name=namespace,proto3" json:"namespace,omitempty"` + Group *wrappers.StringValue `protobuf:"bytes,4,opt,name=group,proto3" json:"group,omitempty"` + FileName *wrappers.StringValue `protobuf:"bytes,5,opt,name=file_name,json=fileName,proto3" json:"file_name,omitempty"` + Content *wrappers.StringValue `protobuf:"bytes,6,opt,name=content,proto3" json:"content,omitempty"` + Comment *wrappers.StringValue `protobuf:"bytes,7,opt,name=comment,proto3" json:"comment,omitempty"` + Md5 *wrappers.StringValue `protobuf:"bytes,8,opt,name=md5,proto3" json:"md5,omitempty"` + Version *wrappers.UInt64Value `protobuf:"bytes,9,opt,name=version,proto3" json:"version,omitempty"` + CreateTime *wrappers.StringValue `protobuf:"bytes,10,opt,name=create_time,json=createTime,proto3" json:"create_time,omitempty"` + CreateBy *wrappers.StringValue `protobuf:"bytes,11,opt,name=create_by,json=createBy,proto3" json:"create_by,omitempty"` + ModifyTime *wrappers.StringValue `protobuf:"bytes,12,opt,name=modify_time,json=modifyTime,proto3" json:"modify_time,omitempty"` + ModifyBy *wrappers.StringValue `protobuf:"bytes,13,opt,name=modify_by,json=modifyBy,proto3" json:"modify_by,omitempty"` + XXX_NoUnkeyedLiteral struct{} `json:"-"` + XXX_unrecognized []byte `json:"-"` + XXX_sizecache int32 `json:"-"` +} + +func (m *ConfigFileRelease) Reset() { *m = ConfigFileRelease{} } +func (m *ConfigFileRelease) String() string { return proto.CompactTextString(m) } +func (*ConfigFileRelease) ProtoMessage() {} +func (*ConfigFileRelease) Descriptor() ([]byte, []int) { + return fileDescriptor_config_file_b643ace0171d7a6b, []int{3} } - -func (x *ConfigFileRelease) Reset() { - *x = ConfigFileRelease{} - if protoimpl.UnsafeEnabled { - mi := &file_config_file_proto_msgTypes[3] - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - ms.StoreMessageInfo(mi) - } +func (m *ConfigFileRelease) XXX_Unmarshal(b []byte) error { + return xxx_messageInfo_ConfigFileRelease.Unmarshal(m, b) } - -func (x *ConfigFileRelease) String() string { - return protoimpl.X.MessageStringOf(x) +func (m *ConfigFileRelease) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + return xxx_messageInfo_ConfigFileRelease.Marshal(b, m, deterministic) } - -func (*ConfigFileRelease) ProtoMessage() {} - -func (x *ConfigFileRelease) ProtoReflect() protoreflect.Message { - mi := &file_config_file_proto_msgTypes[3] - if protoimpl.UnsafeEnabled && x != nil { - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - if ms.LoadMessageInfo() == nil { - ms.StoreMessageInfo(mi) - } - return ms - } - return mi.MessageOf(x) +func (dst *ConfigFileRelease) XXX_Merge(src proto.Message) { + xxx_messageInfo_ConfigFileRelease.Merge(dst, src) } - -// Deprecated: Use ConfigFileRelease.ProtoReflect.Descriptor instead. -func (*ConfigFileRelease) Descriptor() ([]byte, []int) { - return file_config_file_proto_rawDescGZIP(), []int{3} +func (m *ConfigFileRelease) XXX_Size() int { + return xxx_messageInfo_ConfigFileRelease.Size(m) } +func (m *ConfigFileRelease) XXX_DiscardUnknown() { + xxx_messageInfo_ConfigFileRelease.DiscardUnknown(m) +} + +var xxx_messageInfo_ConfigFileRelease proto.InternalMessageInfo -func (x *ConfigFileRelease) GetId() *wrappers.UInt64Value { - if x != nil { - return x.Id +func (m *ConfigFileRelease) GetId() *wrappers.UInt64Value { + if m != nil { + return m.Id } return nil } -func (x *ConfigFileRelease) GetName() *wrappers.StringValue { - if x != nil { - return x.Name +func (m *ConfigFileRelease) GetName() *wrappers.StringValue { + if m != nil { + return m.Name } return nil } -func (x *ConfigFileRelease) GetNamespace() *wrappers.StringValue { - if x != nil { - return x.Namespace +func (m *ConfigFileRelease) GetNamespace() *wrappers.StringValue { + if m != nil { + return m.Namespace } return nil } -func (x *ConfigFileRelease) GetGroup() *wrappers.StringValue { - if x != nil { - return x.Group +func (m *ConfigFileRelease) GetGroup() *wrappers.StringValue { + if m != nil { + return m.Group } return nil } -func (x *ConfigFileRelease) GetFileName() *wrappers.StringValue { - if x != nil { - return x.FileName +func (m *ConfigFileRelease) GetFileName() *wrappers.StringValue { + if m != nil { + return m.FileName } return nil } -func (x *ConfigFileRelease) GetContent() *wrappers.StringValue { - if x != nil { - return x.Content +func (m *ConfigFileRelease) GetContent() *wrappers.StringValue { + if m != nil { + return m.Content } return nil } -func (x *ConfigFileRelease) GetComment() *wrappers.StringValue { - if x != nil { - return x.Comment +func (m *ConfigFileRelease) GetComment() *wrappers.StringValue { + if m != nil { + return m.Comment } return nil } -func (x *ConfigFileRelease) GetMd5() *wrappers.StringValue { - if x != nil { - return x.Md5 +func (m *ConfigFileRelease) GetMd5() *wrappers.StringValue { + if m != nil { + return m.Md5 } return nil } -func (x *ConfigFileRelease) GetVersion() *wrappers.UInt64Value { - if x != nil { - return x.Version +func (m *ConfigFileRelease) GetVersion() *wrappers.UInt64Value { + if m != nil { + return m.Version } return nil } -func (x *ConfigFileRelease) GetCreateTime() *wrappers.StringValue { - if x != nil { - return x.CreateTime +func (m *ConfigFileRelease) GetCreateTime() *wrappers.StringValue { + if m != nil { + return m.CreateTime } return nil } -func (x *ConfigFileRelease) GetCreateBy() *wrappers.StringValue { - if x != nil { - return x.CreateBy +func (m *ConfigFileRelease) GetCreateBy() *wrappers.StringValue { + if m != nil { + return m.CreateBy } return nil } -func (x *ConfigFileRelease) GetModifyTime() *wrappers.StringValue { - if x != nil { - return x.ModifyTime +func (m *ConfigFileRelease) GetModifyTime() *wrappers.StringValue { + if m != nil { + return m.ModifyTime } return nil } -func (x *ConfigFileRelease) GetModifyBy() *wrappers.StringValue { - if x != nil { - return x.ModifyBy +func (m *ConfigFileRelease) GetModifyBy() *wrappers.StringValue { + if m != nil { + return m.ModifyBy } return nil } type ConfigFileReleaseHistory struct { - state protoimpl.MessageState - sizeCache protoimpl.SizeCache - unknownFields protoimpl.UnknownFields - - Id *wrappers.UInt64Value `protobuf:"bytes,1,opt,name=id,proto3" json:"id,omitempty"` - Name *wrappers.StringValue `protobuf:"bytes,2,opt,name=name,proto3" json:"name,omitempty"` - Namespace *wrappers.StringValue `protobuf:"bytes,3,opt,name=namespace,proto3" json:"namespace,omitempty"` - Group *wrappers.StringValue `protobuf:"bytes,4,opt,name=group,proto3" json:"group,omitempty"` - FileName *wrappers.StringValue `protobuf:"bytes,5,opt,name=file_name,json=fileName,proto3" json:"file_name,omitempty"` - Content *wrappers.StringValue `protobuf:"bytes,6,opt,name=content,proto3" json:"content,omitempty"` - Format *wrappers.StringValue `protobuf:"bytes,7,opt,name=format,proto3" json:"format,omitempty"` - Comment *wrappers.StringValue `protobuf:"bytes,8,opt,name=comment,proto3" json:"comment,omitempty"` - Md5 *wrappers.StringValue `protobuf:"bytes,9,opt,name=md5,proto3" json:"md5,omitempty"` - Type *wrappers.StringValue `protobuf:"bytes,10,opt,name=type,proto3" json:"type,omitempty"` - Status *wrappers.StringValue `protobuf:"bytes,11,opt,name=status,proto3" json:"status,omitempty"` - Tags []*ConfigFileTag `protobuf:"bytes,12,rep,name=tags,proto3" json:"tags,omitempty"` - CreateTime *wrappers.StringValue `protobuf:"bytes,13,opt,name=create_time,json=createTime,proto3" json:"create_time,omitempty"` - CreateBy *wrappers.StringValue `protobuf:"bytes,14,opt,name=create_by,json=createBy,proto3" json:"create_by,omitempty"` - ModifyTime *wrappers.StringValue `protobuf:"bytes,15,opt,name=modify_time,json=modifyTime,proto3" json:"modify_time,omitempty"` - ModifyBy *wrappers.StringValue `protobuf:"bytes,16,opt,name=modify_by,json=modifyBy,proto3" json:"modify_by,omitempty"` + Id *wrappers.UInt64Value `protobuf:"bytes,1,opt,name=id,proto3" json:"id,omitempty"` + Name *wrappers.StringValue `protobuf:"bytes,2,opt,name=name,proto3" json:"name,omitempty"` + Namespace *wrappers.StringValue `protobuf:"bytes,3,opt,name=namespace,proto3" json:"namespace,omitempty"` + Group *wrappers.StringValue `protobuf:"bytes,4,opt,name=group,proto3" json:"group,omitempty"` + FileName *wrappers.StringValue `protobuf:"bytes,5,opt,name=file_name,json=fileName,proto3" json:"file_name,omitempty"` + Content *wrappers.StringValue `protobuf:"bytes,6,opt,name=content,proto3" json:"content,omitempty"` + Format *wrappers.StringValue `protobuf:"bytes,7,opt,name=format,proto3" json:"format,omitempty"` + Comment *wrappers.StringValue `protobuf:"bytes,8,opt,name=comment,proto3" json:"comment,omitempty"` + Md5 *wrappers.StringValue `protobuf:"bytes,9,opt,name=md5,proto3" json:"md5,omitempty"` + Type *wrappers.StringValue `protobuf:"bytes,10,opt,name=type,proto3" json:"type,omitempty"` + Status *wrappers.StringValue `protobuf:"bytes,11,opt,name=status,proto3" json:"status,omitempty"` + Tags []*ConfigFileTag `protobuf:"bytes,12,rep,name=tags,proto3" json:"tags,omitempty"` + CreateTime *wrappers.StringValue `protobuf:"bytes,13,opt,name=create_time,json=createTime,proto3" json:"create_time,omitempty"` + CreateBy *wrappers.StringValue `protobuf:"bytes,14,opt,name=create_by,json=createBy,proto3" json:"create_by,omitempty"` + ModifyTime *wrappers.StringValue `protobuf:"bytes,15,opt,name=modify_time,json=modifyTime,proto3" json:"modify_time,omitempty"` + ModifyBy *wrappers.StringValue `protobuf:"bytes,16,opt,name=modify_by,json=modifyBy,proto3" json:"modify_by,omitempty"` + XXX_NoUnkeyedLiteral struct{} `json:"-"` + XXX_unrecognized []byte `json:"-"` + XXX_sizecache int32 `json:"-"` +} + +func (m *ConfigFileReleaseHistory) Reset() { *m = ConfigFileReleaseHistory{} } +func (m *ConfigFileReleaseHistory) String() string { return proto.CompactTextString(m) } +func (*ConfigFileReleaseHistory) ProtoMessage() {} +func (*ConfigFileReleaseHistory) Descriptor() ([]byte, []int) { + return fileDescriptor_config_file_b643ace0171d7a6b, []int{4} } - -func (x *ConfigFileReleaseHistory) Reset() { - *x = ConfigFileReleaseHistory{} - if protoimpl.UnsafeEnabled { - mi := &file_config_file_proto_msgTypes[4] - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - ms.StoreMessageInfo(mi) - } +func (m *ConfigFileReleaseHistory) XXX_Unmarshal(b []byte) error { + return xxx_messageInfo_ConfigFileReleaseHistory.Unmarshal(m, b) } - -func (x *ConfigFileReleaseHistory) String() string { - return protoimpl.X.MessageStringOf(x) +func (m *ConfigFileReleaseHistory) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + return xxx_messageInfo_ConfigFileReleaseHistory.Marshal(b, m, deterministic) } - -func (*ConfigFileReleaseHistory) ProtoMessage() {} - -func (x *ConfigFileReleaseHistory) ProtoReflect() protoreflect.Message { - mi := &file_config_file_proto_msgTypes[4] - if protoimpl.UnsafeEnabled && x != nil { - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - if ms.LoadMessageInfo() == nil { - ms.StoreMessageInfo(mi) - } - return ms - } - return mi.MessageOf(x) +func (dst *ConfigFileReleaseHistory) XXX_Merge(src proto.Message) { + xxx_messageInfo_ConfigFileReleaseHistory.Merge(dst, src) } - -// Deprecated: Use ConfigFileReleaseHistory.ProtoReflect.Descriptor instead. -func (*ConfigFileReleaseHistory) Descriptor() ([]byte, []int) { - return file_config_file_proto_rawDescGZIP(), []int{4} +func (m *ConfigFileReleaseHistory) XXX_Size() int { + return xxx_messageInfo_ConfigFileReleaseHistory.Size(m) } +func (m *ConfigFileReleaseHistory) XXX_DiscardUnknown() { + xxx_messageInfo_ConfigFileReleaseHistory.DiscardUnknown(m) +} + +var xxx_messageInfo_ConfigFileReleaseHistory proto.InternalMessageInfo -func (x *ConfigFileReleaseHistory) GetId() *wrappers.UInt64Value { - if x != nil { - return x.Id +func (m *ConfigFileReleaseHistory) GetId() *wrappers.UInt64Value { + if m != nil { + return m.Id } return nil } -func (x *ConfigFileReleaseHistory) GetName() *wrappers.StringValue { - if x != nil { - return x.Name +func (m *ConfigFileReleaseHistory) GetName() *wrappers.StringValue { + if m != nil { + return m.Name } return nil } -func (x *ConfigFileReleaseHistory) GetNamespace() *wrappers.StringValue { - if x != nil { - return x.Namespace +func (m *ConfigFileReleaseHistory) GetNamespace() *wrappers.StringValue { + if m != nil { + return m.Namespace } return nil } -func (x *ConfigFileReleaseHistory) GetGroup() *wrappers.StringValue { - if x != nil { - return x.Group +func (m *ConfigFileReleaseHistory) GetGroup() *wrappers.StringValue { + if m != nil { + return m.Group } return nil } -func (x *ConfigFileReleaseHistory) GetFileName() *wrappers.StringValue { - if x != nil { - return x.FileName +func (m *ConfigFileReleaseHistory) GetFileName() *wrappers.StringValue { + if m != nil { + return m.FileName } return nil } -func (x *ConfigFileReleaseHistory) GetContent() *wrappers.StringValue { - if x != nil { - return x.Content +func (m *ConfigFileReleaseHistory) GetContent() *wrappers.StringValue { + if m != nil { + return m.Content } return nil } -func (x *ConfigFileReleaseHistory) GetFormat() *wrappers.StringValue { - if x != nil { - return x.Format +func (m *ConfigFileReleaseHistory) GetFormat() *wrappers.StringValue { + if m != nil { + return m.Format } return nil } -func (x *ConfigFileReleaseHistory) GetComment() *wrappers.StringValue { - if x != nil { - return x.Comment +func (m *ConfigFileReleaseHistory) GetComment() *wrappers.StringValue { + if m != nil { + return m.Comment } return nil } -func (x *ConfigFileReleaseHistory) GetMd5() *wrappers.StringValue { - if x != nil { - return x.Md5 +func (m *ConfigFileReleaseHistory) GetMd5() *wrappers.StringValue { + if m != nil { + return m.Md5 } return nil } -func (x *ConfigFileReleaseHistory) GetType() *wrappers.StringValue { - if x != nil { - return x.Type +func (m *ConfigFileReleaseHistory) GetType() *wrappers.StringValue { + if m != nil { + return m.Type } return nil } -func (x *ConfigFileReleaseHistory) GetStatus() *wrappers.StringValue { - if x != nil { - return x.Status +func (m *ConfigFileReleaseHistory) GetStatus() *wrappers.StringValue { + if m != nil { + return m.Status } return nil } -func (x *ConfigFileReleaseHistory) GetTags() []*ConfigFileTag { - if x != nil { - return x.Tags +func (m *ConfigFileReleaseHistory) GetTags() []*ConfigFileTag { + if m != nil { + return m.Tags } return nil } -func (x *ConfigFileReleaseHistory) GetCreateTime() *wrappers.StringValue { - if x != nil { - return x.CreateTime +func (m *ConfigFileReleaseHistory) GetCreateTime() *wrappers.StringValue { + if m != nil { + return m.CreateTime } return nil } -func (x *ConfigFileReleaseHistory) GetCreateBy() *wrappers.StringValue { - if x != nil { - return x.CreateBy +func (m *ConfigFileReleaseHistory) GetCreateBy() *wrappers.StringValue { + if m != nil { + return m.CreateBy } return nil } -func (x *ConfigFileReleaseHistory) GetModifyTime() *wrappers.StringValue { - if x != nil { - return x.ModifyTime +func (m *ConfigFileReleaseHistory) GetModifyTime() *wrappers.StringValue { + if m != nil { + return m.ModifyTime } return nil } -func (x *ConfigFileReleaseHistory) GetModifyBy() *wrappers.StringValue { - if x != nil { - return x.ModifyBy +func (m *ConfigFileReleaseHistory) GetModifyBy() *wrappers.StringValue { + if m != nil { + return m.ModifyBy } return nil } type ConfigFileTemplate struct { - state protoimpl.MessageState - sizeCache protoimpl.SizeCache - unknownFields protoimpl.UnknownFields - - Id *wrappers.UInt64Value `protobuf:"bytes,1,opt,name=id,proto3" json:"id,omitempty"` - Name *wrappers.StringValue `protobuf:"bytes,2,opt,name=name,proto3" json:"name,omitempty"` - Content *wrappers.StringValue `protobuf:"bytes,3,opt,name=content,proto3" json:"content,omitempty"` - Format *wrappers.StringValue `protobuf:"bytes,4,opt,name=format,proto3" json:"format,omitempty"` - Comment *wrappers.StringValue `protobuf:"bytes,5,opt,name=comment,proto3" json:"comment,omitempty"` - CreateTime *wrappers.StringValue `protobuf:"bytes,6,opt,name=create_time,json=createTime,proto3" json:"create_time,omitempty"` - CreateBy *wrappers.StringValue `protobuf:"bytes,7,opt,name=create_by,json=createBy,proto3" json:"create_by,omitempty"` - ModifyTime *wrappers.StringValue `protobuf:"bytes,8,opt,name=modify_time,json=modifyTime,proto3" json:"modify_time,omitempty"` - ModifyBy *wrappers.StringValue `protobuf:"bytes,9,opt,name=modify_by,json=modifyBy,proto3" json:"modify_by,omitempty"` + Id *wrappers.UInt64Value `protobuf:"bytes,1,opt,name=id,proto3" json:"id,omitempty"` + Name *wrappers.StringValue `protobuf:"bytes,2,opt,name=name,proto3" json:"name,omitempty"` + Content *wrappers.StringValue `protobuf:"bytes,3,opt,name=content,proto3" json:"content,omitempty"` + Format *wrappers.StringValue `protobuf:"bytes,4,opt,name=format,proto3" json:"format,omitempty"` + Comment *wrappers.StringValue `protobuf:"bytes,5,opt,name=comment,proto3" json:"comment,omitempty"` + CreateTime *wrappers.StringValue `protobuf:"bytes,6,opt,name=create_time,json=createTime,proto3" json:"create_time,omitempty"` + CreateBy *wrappers.StringValue `protobuf:"bytes,7,opt,name=create_by,json=createBy,proto3" json:"create_by,omitempty"` + ModifyTime *wrappers.StringValue `protobuf:"bytes,8,opt,name=modify_time,json=modifyTime,proto3" json:"modify_time,omitempty"` + ModifyBy *wrappers.StringValue `protobuf:"bytes,9,opt,name=modify_by,json=modifyBy,proto3" json:"modify_by,omitempty"` + XXX_NoUnkeyedLiteral struct{} `json:"-"` + XXX_unrecognized []byte `json:"-"` + XXX_sizecache int32 `json:"-"` +} + +func (m *ConfigFileTemplate) Reset() { *m = ConfigFileTemplate{} } +func (m *ConfigFileTemplate) String() string { return proto.CompactTextString(m) } +func (*ConfigFileTemplate) ProtoMessage() {} +func (*ConfigFileTemplate) Descriptor() ([]byte, []int) { + return fileDescriptor_config_file_b643ace0171d7a6b, []int{5} } - -func (x *ConfigFileTemplate) Reset() { - *x = ConfigFileTemplate{} - if protoimpl.UnsafeEnabled { - mi := &file_config_file_proto_msgTypes[5] - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - ms.StoreMessageInfo(mi) - } +func (m *ConfigFileTemplate) XXX_Unmarshal(b []byte) error { + return xxx_messageInfo_ConfigFileTemplate.Unmarshal(m, b) } - -func (x *ConfigFileTemplate) String() string { - return protoimpl.X.MessageStringOf(x) +func (m *ConfigFileTemplate) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + return xxx_messageInfo_ConfigFileTemplate.Marshal(b, m, deterministic) } - -func (*ConfigFileTemplate) ProtoMessage() {} - -func (x *ConfigFileTemplate) ProtoReflect() protoreflect.Message { - mi := &file_config_file_proto_msgTypes[5] - if protoimpl.UnsafeEnabled && x != nil { - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - if ms.LoadMessageInfo() == nil { - ms.StoreMessageInfo(mi) - } - return ms - } - return mi.MessageOf(x) +func (dst *ConfigFileTemplate) XXX_Merge(src proto.Message) { + xxx_messageInfo_ConfigFileTemplate.Merge(dst, src) } - -// Deprecated: Use ConfigFileTemplate.ProtoReflect.Descriptor instead. -func (*ConfigFileTemplate) Descriptor() ([]byte, []int) { - return file_config_file_proto_rawDescGZIP(), []int{5} +func (m *ConfigFileTemplate) XXX_Size() int { + return xxx_messageInfo_ConfigFileTemplate.Size(m) } +func (m *ConfigFileTemplate) XXX_DiscardUnknown() { + xxx_messageInfo_ConfigFileTemplate.DiscardUnknown(m) +} + +var xxx_messageInfo_ConfigFileTemplate proto.InternalMessageInfo -func (x *ConfigFileTemplate) GetId() *wrappers.UInt64Value { - if x != nil { - return x.Id +func (m *ConfigFileTemplate) GetId() *wrappers.UInt64Value { + if m != nil { + return m.Id } return nil } -func (x *ConfigFileTemplate) GetName() *wrappers.StringValue { - if x != nil { - return x.Name +func (m *ConfigFileTemplate) GetName() *wrappers.StringValue { + if m != nil { + return m.Name } return nil } -func (x *ConfigFileTemplate) GetContent() *wrappers.StringValue { - if x != nil { - return x.Content +func (m *ConfigFileTemplate) GetContent() *wrappers.StringValue { + if m != nil { + return m.Content } return nil } -func (x *ConfigFileTemplate) GetFormat() *wrappers.StringValue { - if x != nil { - return x.Format +func (m *ConfigFileTemplate) GetFormat() *wrappers.StringValue { + if m != nil { + return m.Format } return nil } -func (x *ConfigFileTemplate) GetComment() *wrappers.StringValue { - if x != nil { - return x.Comment +func (m *ConfigFileTemplate) GetComment() *wrappers.StringValue { + if m != nil { + return m.Comment } return nil } -func (x *ConfigFileTemplate) GetCreateTime() *wrappers.StringValue { - if x != nil { - return x.CreateTime +func (m *ConfigFileTemplate) GetCreateTime() *wrappers.StringValue { + if m != nil { + return m.CreateTime } return nil } -func (x *ConfigFileTemplate) GetCreateBy() *wrappers.StringValue { - if x != nil { - return x.CreateBy +func (m *ConfigFileTemplate) GetCreateBy() *wrappers.StringValue { + if m != nil { + return m.CreateBy } return nil } -func (x *ConfigFileTemplate) GetModifyTime() *wrappers.StringValue { - if x != nil { - return x.ModifyTime +func (m *ConfigFileTemplate) GetModifyTime() *wrappers.StringValue { + if m != nil { + return m.ModifyTime } return nil } -func (x *ConfigFileTemplate) GetModifyBy() *wrappers.StringValue { - if x != nil { - return x.ModifyBy +func (m *ConfigFileTemplate) GetModifyBy() *wrappers.StringValue { + if m != nil { + return m.ModifyBy } return nil } type ClientConfigFileInfo struct { - state protoimpl.MessageState - sizeCache protoimpl.SizeCache - unknownFields protoimpl.UnknownFields - - Namespace *wrappers.StringValue `protobuf:"bytes,1,opt,name=namespace,proto3" json:"namespace,omitempty"` - Group *wrappers.StringValue `protobuf:"bytes,2,opt,name=group,proto3" json:"group,omitempty"` - FileName *wrappers.StringValue `protobuf:"bytes,3,opt,name=file_name,json=fileName,proto3" json:"file_name,omitempty"` - Content *wrappers.StringValue `protobuf:"bytes,4,opt,name=content,proto3" json:"content,omitempty"` - Version *wrappers.UInt64Value `protobuf:"bytes,5,opt,name=version,proto3" json:"version,omitempty"` - Md5 *wrappers.StringValue `protobuf:"bytes,6,opt,name=md5,proto3" json:"md5,omitempty"` + Namespace *wrappers.StringValue `protobuf:"bytes,1,opt,name=namespace,proto3" json:"namespace,omitempty"` + Group *wrappers.StringValue `protobuf:"bytes,2,opt,name=group,proto3" json:"group,omitempty"` + FileName *wrappers.StringValue `protobuf:"bytes,3,opt,name=file_name,json=fileName,proto3" json:"file_name,omitempty"` + Content *wrappers.StringValue `protobuf:"bytes,4,opt,name=content,proto3" json:"content,omitempty"` + Version *wrappers.UInt64Value `protobuf:"bytes,5,opt,name=version,proto3" json:"version,omitempty"` + Md5 *wrappers.StringValue `protobuf:"bytes,6,opt,name=md5,proto3" json:"md5,omitempty"` + XXX_NoUnkeyedLiteral struct{} `json:"-"` + XXX_unrecognized []byte `json:"-"` + XXX_sizecache int32 `json:"-"` +} + +func (m *ClientConfigFileInfo) Reset() { *m = ClientConfigFileInfo{} } +func (m *ClientConfigFileInfo) String() string { return proto.CompactTextString(m) } +func (*ClientConfigFileInfo) ProtoMessage() {} +func (*ClientConfigFileInfo) Descriptor() ([]byte, []int) { + return fileDescriptor_config_file_b643ace0171d7a6b, []int{6} } - -func (x *ClientConfigFileInfo) Reset() { - *x = ClientConfigFileInfo{} - if protoimpl.UnsafeEnabled { - mi := &file_config_file_proto_msgTypes[6] - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - ms.StoreMessageInfo(mi) - } +func (m *ClientConfigFileInfo) XXX_Unmarshal(b []byte) error { + return xxx_messageInfo_ClientConfigFileInfo.Unmarshal(m, b) } - -func (x *ClientConfigFileInfo) String() string { - return protoimpl.X.MessageStringOf(x) +func (m *ClientConfigFileInfo) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + return xxx_messageInfo_ClientConfigFileInfo.Marshal(b, m, deterministic) } - -func (*ClientConfigFileInfo) ProtoMessage() {} - -func (x *ClientConfigFileInfo) ProtoReflect() protoreflect.Message { - mi := &file_config_file_proto_msgTypes[6] - if protoimpl.UnsafeEnabled && x != nil { - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - if ms.LoadMessageInfo() == nil { - ms.StoreMessageInfo(mi) - } - return ms - } - return mi.MessageOf(x) +func (dst *ClientConfigFileInfo) XXX_Merge(src proto.Message) { + xxx_messageInfo_ClientConfigFileInfo.Merge(dst, src) } - -// Deprecated: Use ClientConfigFileInfo.ProtoReflect.Descriptor instead. -func (*ClientConfigFileInfo) Descriptor() ([]byte, []int) { - return file_config_file_proto_rawDescGZIP(), []int{6} +func (m *ClientConfigFileInfo) XXX_Size() int { + return xxx_messageInfo_ClientConfigFileInfo.Size(m) } +func (m *ClientConfigFileInfo) XXX_DiscardUnknown() { + xxx_messageInfo_ClientConfigFileInfo.DiscardUnknown(m) +} + +var xxx_messageInfo_ClientConfigFileInfo proto.InternalMessageInfo -func (x *ClientConfigFileInfo) GetNamespace() *wrappers.StringValue { - if x != nil { - return x.Namespace +func (m *ClientConfigFileInfo) GetNamespace() *wrappers.StringValue { + if m != nil { + return m.Namespace } return nil } -func (x *ClientConfigFileInfo) GetGroup() *wrappers.StringValue { - if x != nil { - return x.Group +func (m *ClientConfigFileInfo) GetGroup() *wrappers.StringValue { + if m != nil { + return m.Group } return nil } -func (x *ClientConfigFileInfo) GetFileName() *wrappers.StringValue { - if x != nil { - return x.FileName +func (m *ClientConfigFileInfo) GetFileName() *wrappers.StringValue { + if m != nil { + return m.FileName } return nil } -func (x *ClientConfigFileInfo) GetContent() *wrappers.StringValue { - if x != nil { - return x.Content +func (m *ClientConfigFileInfo) GetContent() *wrappers.StringValue { + if m != nil { + return m.Content } return nil } -func (x *ClientConfigFileInfo) GetVersion() *wrappers.UInt64Value { - if x != nil { - return x.Version +func (m *ClientConfigFileInfo) GetVersion() *wrappers.UInt64Value { + if m != nil { + return m.Version } return nil } -func (x *ClientConfigFileInfo) GetMd5() *wrappers.StringValue { - if x != nil { - return x.Md5 +func (m *ClientConfigFileInfo) GetMd5() *wrappers.StringValue { + if m != nil { + return m.Md5 } return nil } type ClientWatchConfigFileRequest struct { - state protoimpl.MessageState - sizeCache protoimpl.SizeCache - unknownFields protoimpl.UnknownFields - - ClientIp *wrappers.StringValue `protobuf:"bytes,1,opt,name=client_ip,json=clientIp,proto3" json:"client_ip,omitempty"` - ServiceName *wrappers.StringValue `protobuf:"bytes,2,opt,name=service_name,json=serviceName,proto3" json:"service_name,omitempty"` - WatchFiles []*ClientConfigFileInfo `protobuf:"bytes,3,rep,name=watch_files,json=watchFiles,proto3" json:"watch_files,omitempty"` -} - -func (x *ClientWatchConfigFileRequest) Reset() { - *x = ClientWatchConfigFileRequest{} - if protoimpl.UnsafeEnabled { - mi := &file_config_file_proto_msgTypes[7] - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - ms.StoreMessageInfo(mi) - } -} - -func (x *ClientWatchConfigFileRequest) String() string { - return protoimpl.X.MessageStringOf(x) -} - -func (*ClientWatchConfigFileRequest) ProtoMessage() {} - -func (x *ClientWatchConfigFileRequest) ProtoReflect() protoreflect.Message { - mi := &file_config_file_proto_msgTypes[7] - if protoimpl.UnsafeEnabled && x != nil { - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - if ms.LoadMessageInfo() == nil { - ms.StoreMessageInfo(mi) - } - return ms - } - return mi.MessageOf(x) + ClientIp *wrappers.StringValue `protobuf:"bytes,1,opt,name=client_ip,json=clientIp,proto3" json:"client_ip,omitempty"` + ServiceName *wrappers.StringValue `protobuf:"bytes,2,opt,name=service_name,json=serviceName,proto3" json:"service_name,omitempty"` + WatchFiles []*ClientConfigFileInfo `protobuf:"bytes,3,rep,name=watch_files,json=watchFiles,proto3" json:"watch_files,omitempty"` + XXX_NoUnkeyedLiteral struct{} `json:"-"` + XXX_unrecognized []byte `json:"-"` + XXX_sizecache int32 `json:"-"` } -// Deprecated: Use ClientWatchConfigFileRequest.ProtoReflect.Descriptor instead. +func (m *ClientWatchConfigFileRequest) Reset() { *m = ClientWatchConfigFileRequest{} } +func (m *ClientWatchConfigFileRequest) String() string { return proto.CompactTextString(m) } +func (*ClientWatchConfigFileRequest) ProtoMessage() {} func (*ClientWatchConfigFileRequest) Descriptor() ([]byte, []int) { - return file_config_file_proto_rawDescGZIP(), []int{7} -} - -func (x *ClientWatchConfigFileRequest) GetClientIp() *wrappers.StringValue { - if x != nil { - return x.ClientIp - } - return nil -} - -func (x *ClientWatchConfigFileRequest) GetServiceName() *wrappers.StringValue { - if x != nil { - return x.ServiceName - } - return nil -} - -func (x *ClientWatchConfigFileRequest) GetWatchFiles() []*ClientConfigFileInfo { - if x != nil { - return x.WatchFiles - } - return nil -} - -var File_config_file_proto protoreflect.FileDescriptor - -var file_config_file_proto_rawDesc = []byte{ - 0x0a, 0x11, 0x63, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x5f, 0x66, 0x69, 0x6c, 0x65, 0x2e, 0x70, 0x72, - 0x6f, 0x74, 0x6f, 0x12, 0x02, 0x76, 0x31, 0x1a, 0x1e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2f, - 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2f, 0x77, 0x72, 0x61, 0x70, 0x70, 0x65, 0x72, - 0x73, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x22, 0x95, 0x04, 0x0a, 0x0f, 0x43, 0x6f, 0x6e, 0x66, - 0x69, 0x67, 0x46, 0x69, 0x6c, 0x65, 0x47, 0x72, 0x6f, 0x75, 0x70, 0x12, 0x2c, 0x0a, 0x02, 0x69, - 0x64, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x1c, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, - 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x55, 0x49, 0x6e, 0x74, 0x36, 0x34, - 0x56, 0x61, 0x6c, 0x75, 0x65, 0x52, 0x02, 0x69, 0x64, 0x12, 0x30, 0x0a, 0x04, 0x6e, 0x61, 0x6d, - 0x65, 0x18, 0x02, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x1c, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, - 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x53, 0x74, 0x72, 0x69, 0x6e, 0x67, - 0x56, 0x61, 0x6c, 0x75, 0x65, 0x52, 0x04, 0x6e, 0x61, 0x6d, 0x65, 0x12, 0x3a, 0x0a, 0x09, 0x6e, - 0x61, 0x6d, 0x65, 0x73, 0x70, 0x61, 0x63, 0x65, 0x18, 0x03, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x1c, - 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, - 0x2e, 0x53, 0x74, 0x72, 0x69, 0x6e, 0x67, 0x56, 0x61, 0x6c, 0x75, 0x65, 0x52, 0x09, 0x6e, 0x61, - 0x6d, 0x65, 0x73, 0x70, 0x61, 0x63, 0x65, 0x12, 0x36, 0x0a, 0x07, 0x63, 0x6f, 0x6d, 0x6d, 0x65, - 0x6e, 0x74, 0x18, 0x04, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x1c, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, - 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x53, 0x74, 0x72, 0x69, 0x6e, - 0x67, 0x56, 0x61, 0x6c, 0x75, 0x65, 0x52, 0x07, 0x63, 0x6f, 0x6d, 0x6d, 0x65, 0x6e, 0x74, 0x12, - 0x3d, 0x0a, 0x0b, 0x63, 0x72, 0x65, 0x61, 0x74, 0x65, 0x5f, 0x74, 0x69, 0x6d, 0x65, 0x18, 0x05, - 0x20, 0x01, 0x28, 0x0b, 0x32, 0x1c, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, - 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x53, 0x74, 0x72, 0x69, 0x6e, 0x67, 0x56, 0x61, 0x6c, - 0x75, 0x65, 0x52, 0x0a, 0x63, 0x72, 0x65, 0x61, 0x74, 0x65, 0x54, 0x69, 0x6d, 0x65, 0x12, 0x39, - 0x0a, 0x09, 0x63, 0x72, 0x65, 0x61, 0x74, 0x65, 0x5f, 0x62, 0x79, 0x18, 0x06, 0x20, 0x01, 0x28, - 0x0b, 0x32, 0x1c, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, - 0x62, 0x75, 0x66, 0x2e, 0x53, 0x74, 0x72, 0x69, 0x6e, 0x67, 0x56, 0x61, 0x6c, 0x75, 0x65, 0x52, - 0x08, 0x63, 0x72, 0x65, 0x61, 0x74, 0x65, 0x42, 0x79, 0x12, 0x3d, 0x0a, 0x0b, 0x6d, 0x6f, 0x64, - 0x69, 0x66, 0x79, 0x5f, 0x74, 0x69, 0x6d, 0x65, 0x18, 0x07, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x1c, - 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, - 0x2e, 0x53, 0x74, 0x72, 0x69, 0x6e, 0x67, 0x56, 0x61, 0x6c, 0x75, 0x65, 0x52, 0x0a, 0x6d, 0x6f, - 0x64, 0x69, 0x66, 0x79, 0x54, 0x69, 0x6d, 0x65, 0x12, 0x39, 0x0a, 0x09, 0x6d, 0x6f, 0x64, 0x69, - 0x66, 0x79, 0x5f, 0x62, 0x79, 0x18, 0x08, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x1c, 0x2e, 0x67, 0x6f, - 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x53, 0x74, - 0x72, 0x69, 0x6e, 0x67, 0x56, 0x61, 0x6c, 0x75, 0x65, 0x52, 0x08, 0x6d, 0x6f, 0x64, 0x69, 0x66, - 0x79, 0x42, 0x79, 0x12, 0x3a, 0x0a, 0x09, 0x66, 0x69, 0x6c, 0x65, 0x43, 0x6f, 0x75, 0x6e, 0x74, - 0x18, 0x09, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x1c, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, - 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x55, 0x49, 0x6e, 0x74, 0x36, 0x34, 0x56, - 0x61, 0x6c, 0x75, 0x65, 0x52, 0x09, 0x66, 0x69, 0x6c, 0x65, 0x43, 0x6f, 0x75, 0x6e, 0x74, 0x22, - 0xd1, 0x06, 0x0a, 0x0a, 0x43, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x46, 0x69, 0x6c, 0x65, 0x12, 0x2c, - 0x0a, 0x02, 0x69, 0x64, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x1c, 0x2e, 0x67, 0x6f, 0x6f, - 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x55, 0x49, 0x6e, - 0x74, 0x36, 0x34, 0x56, 0x61, 0x6c, 0x75, 0x65, 0x52, 0x02, 0x69, 0x64, 0x12, 0x30, 0x0a, 0x04, - 0x6e, 0x61, 0x6d, 0x65, 0x18, 0x02, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x1c, 0x2e, 0x67, 0x6f, 0x6f, - 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x53, 0x74, 0x72, - 0x69, 0x6e, 0x67, 0x56, 0x61, 0x6c, 0x75, 0x65, 0x52, 0x04, 0x6e, 0x61, 0x6d, 0x65, 0x12, 0x3a, - 0x0a, 0x09, 0x6e, 0x61, 0x6d, 0x65, 0x73, 0x70, 0x61, 0x63, 0x65, 0x18, 0x03, 0x20, 0x01, 0x28, - 0x0b, 0x32, 0x1c, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, - 0x62, 0x75, 0x66, 0x2e, 0x53, 0x74, 0x72, 0x69, 0x6e, 0x67, 0x56, 0x61, 0x6c, 0x75, 0x65, 0x52, - 0x09, 0x6e, 0x61, 0x6d, 0x65, 0x73, 0x70, 0x61, 0x63, 0x65, 0x12, 0x32, 0x0a, 0x05, 0x67, 0x72, - 0x6f, 0x75, 0x70, 0x18, 0x04, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x1c, 0x2e, 0x67, 0x6f, 0x6f, 0x67, - 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x53, 0x74, 0x72, 0x69, - 0x6e, 0x67, 0x56, 0x61, 0x6c, 0x75, 0x65, 0x52, 0x05, 0x67, 0x72, 0x6f, 0x75, 0x70, 0x12, 0x36, - 0x0a, 0x07, 0x63, 0x6f, 0x6e, 0x74, 0x65, 0x6e, 0x74, 0x18, 0x05, 0x20, 0x01, 0x28, 0x0b, 0x32, - 0x1c, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, - 0x66, 0x2e, 0x53, 0x74, 0x72, 0x69, 0x6e, 0x67, 0x56, 0x61, 0x6c, 0x75, 0x65, 0x52, 0x07, 0x63, - 0x6f, 0x6e, 0x74, 0x65, 0x6e, 0x74, 0x12, 0x34, 0x0a, 0x06, 0x66, 0x6f, 0x72, 0x6d, 0x61, 0x74, - 0x18, 0x06, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x1c, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, - 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x53, 0x74, 0x72, 0x69, 0x6e, 0x67, 0x56, - 0x61, 0x6c, 0x75, 0x65, 0x52, 0x06, 0x66, 0x6f, 0x72, 0x6d, 0x61, 0x74, 0x12, 0x36, 0x0a, 0x07, - 0x63, 0x6f, 0x6d, 0x6d, 0x65, 0x6e, 0x74, 0x18, 0x07, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x1c, 0x2e, - 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, - 0x53, 0x74, 0x72, 0x69, 0x6e, 0x67, 0x56, 0x61, 0x6c, 0x75, 0x65, 0x52, 0x07, 0x63, 0x6f, 0x6d, - 0x6d, 0x65, 0x6e, 0x74, 0x12, 0x34, 0x0a, 0x06, 0x73, 0x74, 0x61, 0x74, 0x75, 0x73, 0x18, 0x08, - 0x20, 0x01, 0x28, 0x0b, 0x32, 0x1c, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, - 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x53, 0x74, 0x72, 0x69, 0x6e, 0x67, 0x56, 0x61, 0x6c, - 0x75, 0x65, 0x52, 0x06, 0x73, 0x74, 0x61, 0x74, 0x75, 0x73, 0x12, 0x25, 0x0a, 0x04, 0x74, 0x61, - 0x67, 0x73, 0x18, 0x09, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x11, 0x2e, 0x76, 0x31, 0x2e, 0x43, 0x6f, - 0x6e, 0x66, 0x69, 0x67, 0x46, 0x69, 0x6c, 0x65, 0x54, 0x61, 0x67, 0x52, 0x04, 0x74, 0x61, 0x67, - 0x73, 0x12, 0x3d, 0x0a, 0x0b, 0x63, 0x72, 0x65, 0x61, 0x74, 0x65, 0x5f, 0x74, 0x69, 0x6d, 0x65, - 0x18, 0x0a, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x1c, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, - 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x53, 0x74, 0x72, 0x69, 0x6e, 0x67, 0x56, - 0x61, 0x6c, 0x75, 0x65, 0x52, 0x0a, 0x63, 0x72, 0x65, 0x61, 0x74, 0x65, 0x54, 0x69, 0x6d, 0x65, - 0x12, 0x39, 0x0a, 0x09, 0x63, 0x72, 0x65, 0x61, 0x74, 0x65, 0x5f, 0x62, 0x79, 0x18, 0x0b, 0x20, - 0x01, 0x28, 0x0b, 0x32, 0x1c, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, - 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x53, 0x74, 0x72, 0x69, 0x6e, 0x67, 0x56, 0x61, 0x6c, 0x75, - 0x65, 0x52, 0x08, 0x63, 0x72, 0x65, 0x61, 0x74, 0x65, 0x42, 0x79, 0x12, 0x3d, 0x0a, 0x0b, 0x6d, - 0x6f, 0x64, 0x69, 0x66, 0x79, 0x5f, 0x74, 0x69, 0x6d, 0x65, 0x18, 0x0c, 0x20, 0x01, 0x28, 0x0b, - 0x32, 0x1c, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, - 0x75, 0x66, 0x2e, 0x53, 0x74, 0x72, 0x69, 0x6e, 0x67, 0x56, 0x61, 0x6c, 0x75, 0x65, 0x52, 0x0a, - 0x6d, 0x6f, 0x64, 0x69, 0x66, 0x79, 0x54, 0x69, 0x6d, 0x65, 0x12, 0x39, 0x0a, 0x09, 0x6d, 0x6f, - 0x64, 0x69, 0x66, 0x79, 0x5f, 0x62, 0x79, 0x18, 0x0d, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x1c, 0x2e, - 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, - 0x53, 0x74, 0x72, 0x69, 0x6e, 0x67, 0x56, 0x61, 0x6c, 0x75, 0x65, 0x52, 0x08, 0x6d, 0x6f, 0x64, - 0x69, 0x66, 0x79, 0x42, 0x79, 0x12, 0x3f, 0x0a, 0x0c, 0x72, 0x65, 0x6c, 0x65, 0x61, 0x73, 0x65, - 0x5f, 0x74, 0x69, 0x6d, 0x65, 0x18, 0x0e, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x1c, 0x2e, 0x67, 0x6f, - 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x53, 0x74, - 0x72, 0x69, 0x6e, 0x67, 0x56, 0x61, 0x6c, 0x75, 0x65, 0x52, 0x0b, 0x72, 0x65, 0x6c, 0x65, 0x61, - 0x73, 0x65, 0x54, 0x69, 0x6d, 0x65, 0x12, 0x3b, 0x0a, 0x0a, 0x72, 0x65, 0x6c, 0x65, 0x61, 0x73, - 0x65, 0x5f, 0x62, 0x79, 0x18, 0x0f, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x1c, 0x2e, 0x67, 0x6f, 0x6f, - 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x53, 0x74, 0x72, - 0x69, 0x6e, 0x67, 0x56, 0x61, 0x6c, 0x75, 0x65, 0x52, 0x09, 0x72, 0x65, 0x6c, 0x65, 0x61, 0x73, - 0x65, 0x42, 0x79, 0x22, 0x73, 0x0a, 0x0d, 0x43, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x46, 0x69, 0x6c, - 0x65, 0x54, 0x61, 0x67, 0x12, 0x2e, 0x0a, 0x03, 0x6b, 0x65, 0x79, 0x18, 0x01, 0x20, 0x01, 0x28, - 0x0b, 0x32, 0x1c, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, - 0x62, 0x75, 0x66, 0x2e, 0x53, 0x74, 0x72, 0x69, 0x6e, 0x67, 0x56, 0x61, 0x6c, 0x75, 0x65, 0x52, - 0x03, 0x6b, 0x65, 0x79, 0x12, 0x32, 0x0a, 0x05, 0x76, 0x61, 0x6c, 0x75, 0x65, 0x18, 0x02, 0x20, - 0x01, 0x28, 0x0b, 0x32, 0x1c, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, - 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x53, 0x74, 0x72, 0x69, 0x6e, 0x67, 0x56, 0x61, 0x6c, 0x75, - 0x65, 0x52, 0x05, 0x76, 0x61, 0x6c, 0x75, 0x65, 0x22, 0xea, 0x05, 0x0a, 0x11, 0x43, 0x6f, 0x6e, - 0x66, 0x69, 0x67, 0x46, 0x69, 0x6c, 0x65, 0x52, 0x65, 0x6c, 0x65, 0x61, 0x73, 0x65, 0x12, 0x2c, - 0x0a, 0x02, 0x69, 0x64, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x1c, 0x2e, 0x67, 0x6f, 0x6f, - 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x55, 0x49, 0x6e, - 0x74, 0x36, 0x34, 0x56, 0x61, 0x6c, 0x75, 0x65, 0x52, 0x02, 0x69, 0x64, 0x12, 0x30, 0x0a, 0x04, - 0x6e, 0x61, 0x6d, 0x65, 0x18, 0x02, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x1c, 0x2e, 0x67, 0x6f, 0x6f, - 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x53, 0x74, 0x72, - 0x69, 0x6e, 0x67, 0x56, 0x61, 0x6c, 0x75, 0x65, 0x52, 0x04, 0x6e, 0x61, 0x6d, 0x65, 0x12, 0x3a, - 0x0a, 0x09, 0x6e, 0x61, 0x6d, 0x65, 0x73, 0x70, 0x61, 0x63, 0x65, 0x18, 0x03, 0x20, 0x01, 0x28, - 0x0b, 0x32, 0x1c, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, - 0x62, 0x75, 0x66, 0x2e, 0x53, 0x74, 0x72, 0x69, 0x6e, 0x67, 0x56, 0x61, 0x6c, 0x75, 0x65, 0x52, - 0x09, 0x6e, 0x61, 0x6d, 0x65, 0x73, 0x70, 0x61, 0x63, 0x65, 0x12, 0x32, 0x0a, 0x05, 0x67, 0x72, - 0x6f, 0x75, 0x70, 0x18, 0x04, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x1c, 0x2e, 0x67, 0x6f, 0x6f, 0x67, - 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x53, 0x74, 0x72, 0x69, - 0x6e, 0x67, 0x56, 0x61, 0x6c, 0x75, 0x65, 0x52, 0x05, 0x67, 0x72, 0x6f, 0x75, 0x70, 0x12, 0x39, - 0x0a, 0x09, 0x66, 0x69, 0x6c, 0x65, 0x5f, 0x6e, 0x61, 0x6d, 0x65, 0x18, 0x05, 0x20, 0x01, 0x28, - 0x0b, 0x32, 0x1c, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, - 0x62, 0x75, 0x66, 0x2e, 0x53, 0x74, 0x72, 0x69, 0x6e, 0x67, 0x56, 0x61, 0x6c, 0x75, 0x65, 0x52, - 0x08, 0x66, 0x69, 0x6c, 0x65, 0x4e, 0x61, 0x6d, 0x65, 0x12, 0x36, 0x0a, 0x07, 0x63, 0x6f, 0x6e, - 0x74, 0x65, 0x6e, 0x74, 0x18, 0x06, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x1c, 0x2e, 0x67, 0x6f, 0x6f, - 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x53, 0x74, 0x72, - 0x69, 0x6e, 0x67, 0x56, 0x61, 0x6c, 0x75, 0x65, 0x52, 0x07, 0x63, 0x6f, 0x6e, 0x74, 0x65, 0x6e, - 0x74, 0x12, 0x36, 0x0a, 0x07, 0x63, 0x6f, 0x6d, 0x6d, 0x65, 0x6e, 0x74, 0x18, 0x07, 0x20, 0x01, - 0x28, 0x0b, 0x32, 0x1c, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, - 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x53, 0x74, 0x72, 0x69, 0x6e, 0x67, 0x56, 0x61, 0x6c, 0x75, 0x65, - 0x52, 0x07, 0x63, 0x6f, 0x6d, 0x6d, 0x65, 0x6e, 0x74, 0x12, 0x2e, 0x0a, 0x03, 0x6d, 0x64, 0x35, - 0x18, 0x08, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x1c, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, - 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x53, 0x74, 0x72, 0x69, 0x6e, 0x67, 0x56, - 0x61, 0x6c, 0x75, 0x65, 0x52, 0x03, 0x6d, 0x64, 0x35, 0x12, 0x36, 0x0a, 0x07, 0x76, 0x65, 0x72, - 0x73, 0x69, 0x6f, 0x6e, 0x18, 0x09, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x1c, 0x2e, 0x67, 0x6f, 0x6f, - 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x55, 0x49, 0x6e, - 0x74, 0x36, 0x34, 0x56, 0x61, 0x6c, 0x75, 0x65, 0x52, 0x07, 0x76, 0x65, 0x72, 0x73, 0x69, 0x6f, - 0x6e, 0x12, 0x3d, 0x0a, 0x0b, 0x63, 0x72, 0x65, 0x61, 0x74, 0x65, 0x5f, 0x74, 0x69, 0x6d, 0x65, - 0x18, 0x0a, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x1c, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, - 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x53, 0x74, 0x72, 0x69, 0x6e, 0x67, 0x56, - 0x61, 0x6c, 0x75, 0x65, 0x52, 0x0a, 0x63, 0x72, 0x65, 0x61, 0x74, 0x65, 0x54, 0x69, 0x6d, 0x65, - 0x12, 0x39, 0x0a, 0x09, 0x63, 0x72, 0x65, 0x61, 0x74, 0x65, 0x5f, 0x62, 0x79, 0x18, 0x0b, 0x20, - 0x01, 0x28, 0x0b, 0x32, 0x1c, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, - 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x53, 0x74, 0x72, 0x69, 0x6e, 0x67, 0x56, 0x61, 0x6c, 0x75, - 0x65, 0x52, 0x08, 0x63, 0x72, 0x65, 0x61, 0x74, 0x65, 0x42, 0x79, 0x12, 0x3d, 0x0a, 0x0b, 0x6d, - 0x6f, 0x64, 0x69, 0x66, 0x79, 0x5f, 0x74, 0x69, 0x6d, 0x65, 0x18, 0x0c, 0x20, 0x01, 0x28, 0x0b, - 0x32, 0x1c, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, - 0x75, 0x66, 0x2e, 0x53, 0x74, 0x72, 0x69, 0x6e, 0x67, 0x56, 0x61, 0x6c, 0x75, 0x65, 0x52, 0x0a, - 0x6d, 0x6f, 0x64, 0x69, 0x66, 0x79, 0x54, 0x69, 0x6d, 0x65, 0x12, 0x39, 0x0a, 0x09, 0x6d, 0x6f, - 0x64, 0x69, 0x66, 0x79, 0x5f, 0x62, 0x79, 0x18, 0x0d, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x1c, 0x2e, - 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, - 0x53, 0x74, 0x72, 0x69, 0x6e, 0x67, 0x56, 0x61, 0x6c, 0x75, 0x65, 0x52, 0x08, 0x6d, 0x6f, 0x64, - 0x69, 0x66, 0x79, 0x42, 0x79, 0x22, 0xfe, 0x06, 0x0a, 0x18, 0x43, 0x6f, 0x6e, 0x66, 0x69, 0x67, - 0x46, 0x69, 0x6c, 0x65, 0x52, 0x65, 0x6c, 0x65, 0x61, 0x73, 0x65, 0x48, 0x69, 0x73, 0x74, 0x6f, - 0x72, 0x79, 0x12, 0x2c, 0x0a, 0x02, 0x69, 0x64, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x1c, - 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, - 0x2e, 0x55, 0x49, 0x6e, 0x74, 0x36, 0x34, 0x56, 0x61, 0x6c, 0x75, 0x65, 0x52, 0x02, 0x69, 0x64, - 0x12, 0x30, 0x0a, 0x04, 0x6e, 0x61, 0x6d, 0x65, 0x18, 0x02, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x1c, - 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, - 0x2e, 0x53, 0x74, 0x72, 0x69, 0x6e, 0x67, 0x56, 0x61, 0x6c, 0x75, 0x65, 0x52, 0x04, 0x6e, 0x61, - 0x6d, 0x65, 0x12, 0x3a, 0x0a, 0x09, 0x6e, 0x61, 0x6d, 0x65, 0x73, 0x70, 0x61, 0x63, 0x65, 0x18, - 0x03, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x1c, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, - 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x53, 0x74, 0x72, 0x69, 0x6e, 0x67, 0x56, 0x61, - 0x6c, 0x75, 0x65, 0x52, 0x09, 0x6e, 0x61, 0x6d, 0x65, 0x73, 0x70, 0x61, 0x63, 0x65, 0x12, 0x32, - 0x0a, 0x05, 0x67, 0x72, 0x6f, 0x75, 0x70, 0x18, 0x04, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x1c, 0x2e, - 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, - 0x53, 0x74, 0x72, 0x69, 0x6e, 0x67, 0x56, 0x61, 0x6c, 0x75, 0x65, 0x52, 0x05, 0x67, 0x72, 0x6f, - 0x75, 0x70, 0x12, 0x39, 0x0a, 0x09, 0x66, 0x69, 0x6c, 0x65, 0x5f, 0x6e, 0x61, 0x6d, 0x65, 0x18, - 0x05, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x1c, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, - 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x53, 0x74, 0x72, 0x69, 0x6e, 0x67, 0x56, 0x61, - 0x6c, 0x75, 0x65, 0x52, 0x08, 0x66, 0x69, 0x6c, 0x65, 0x4e, 0x61, 0x6d, 0x65, 0x12, 0x36, 0x0a, - 0x07, 0x63, 0x6f, 0x6e, 0x74, 0x65, 0x6e, 0x74, 0x18, 0x06, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x1c, - 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, - 0x2e, 0x53, 0x74, 0x72, 0x69, 0x6e, 0x67, 0x56, 0x61, 0x6c, 0x75, 0x65, 0x52, 0x07, 0x63, 0x6f, - 0x6e, 0x74, 0x65, 0x6e, 0x74, 0x12, 0x34, 0x0a, 0x06, 0x66, 0x6f, 0x72, 0x6d, 0x61, 0x74, 0x18, - 0x07, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x1c, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, - 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x53, 0x74, 0x72, 0x69, 0x6e, 0x67, 0x56, 0x61, - 0x6c, 0x75, 0x65, 0x52, 0x06, 0x66, 0x6f, 0x72, 0x6d, 0x61, 0x74, 0x12, 0x36, 0x0a, 0x07, 0x63, - 0x6f, 0x6d, 0x6d, 0x65, 0x6e, 0x74, 0x18, 0x08, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x1c, 0x2e, 0x67, - 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x53, - 0x74, 0x72, 0x69, 0x6e, 0x67, 0x56, 0x61, 0x6c, 0x75, 0x65, 0x52, 0x07, 0x63, 0x6f, 0x6d, 0x6d, - 0x65, 0x6e, 0x74, 0x12, 0x2e, 0x0a, 0x03, 0x6d, 0x64, 0x35, 0x18, 0x09, 0x20, 0x01, 0x28, 0x0b, - 0x32, 0x1c, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, - 0x75, 0x66, 0x2e, 0x53, 0x74, 0x72, 0x69, 0x6e, 0x67, 0x56, 0x61, 0x6c, 0x75, 0x65, 0x52, 0x03, - 0x6d, 0x64, 0x35, 0x12, 0x30, 0x0a, 0x04, 0x74, 0x79, 0x70, 0x65, 0x18, 0x0a, 0x20, 0x01, 0x28, - 0x0b, 0x32, 0x1c, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, - 0x62, 0x75, 0x66, 0x2e, 0x53, 0x74, 0x72, 0x69, 0x6e, 0x67, 0x56, 0x61, 0x6c, 0x75, 0x65, 0x52, - 0x04, 0x74, 0x79, 0x70, 0x65, 0x12, 0x34, 0x0a, 0x06, 0x73, 0x74, 0x61, 0x74, 0x75, 0x73, 0x18, - 0x0b, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x1c, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, - 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x53, 0x74, 0x72, 0x69, 0x6e, 0x67, 0x56, 0x61, - 0x6c, 0x75, 0x65, 0x52, 0x06, 0x73, 0x74, 0x61, 0x74, 0x75, 0x73, 0x12, 0x25, 0x0a, 0x04, 0x74, - 0x61, 0x67, 0x73, 0x18, 0x0c, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x11, 0x2e, 0x76, 0x31, 0x2e, 0x43, - 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x46, 0x69, 0x6c, 0x65, 0x54, 0x61, 0x67, 0x52, 0x04, 0x74, 0x61, - 0x67, 0x73, 0x12, 0x3d, 0x0a, 0x0b, 0x63, 0x72, 0x65, 0x61, 0x74, 0x65, 0x5f, 0x74, 0x69, 0x6d, - 0x65, 0x18, 0x0d, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x1c, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, - 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x53, 0x74, 0x72, 0x69, 0x6e, 0x67, - 0x56, 0x61, 0x6c, 0x75, 0x65, 0x52, 0x0a, 0x63, 0x72, 0x65, 0x61, 0x74, 0x65, 0x54, 0x69, 0x6d, - 0x65, 0x12, 0x39, 0x0a, 0x09, 0x63, 0x72, 0x65, 0x61, 0x74, 0x65, 0x5f, 0x62, 0x79, 0x18, 0x0e, - 0x20, 0x01, 0x28, 0x0b, 0x32, 0x1c, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, - 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x53, 0x74, 0x72, 0x69, 0x6e, 0x67, 0x56, 0x61, 0x6c, - 0x75, 0x65, 0x52, 0x08, 0x63, 0x72, 0x65, 0x61, 0x74, 0x65, 0x42, 0x79, 0x12, 0x3d, 0x0a, 0x0b, - 0x6d, 0x6f, 0x64, 0x69, 0x66, 0x79, 0x5f, 0x74, 0x69, 0x6d, 0x65, 0x18, 0x0f, 0x20, 0x01, 0x28, - 0x0b, 0x32, 0x1c, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, - 0x62, 0x75, 0x66, 0x2e, 0x53, 0x74, 0x72, 0x69, 0x6e, 0x67, 0x56, 0x61, 0x6c, 0x75, 0x65, 0x52, - 0x0a, 0x6d, 0x6f, 0x64, 0x69, 0x66, 0x79, 0x54, 0x69, 0x6d, 0x65, 0x12, 0x39, 0x0a, 0x09, 0x6d, - 0x6f, 0x64, 0x69, 0x66, 0x79, 0x5f, 0x62, 0x79, 0x18, 0x10, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x1c, - 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, - 0x2e, 0x53, 0x74, 0x72, 0x69, 0x6e, 0x67, 0x56, 0x61, 0x6c, 0x75, 0x65, 0x52, 0x08, 0x6d, 0x6f, - 0x64, 0x69, 0x66, 0x79, 0x42, 0x79, 0x22, 0x8e, 0x04, 0x0a, 0x12, 0x43, 0x6f, 0x6e, 0x66, 0x69, - 0x67, 0x46, 0x69, 0x6c, 0x65, 0x54, 0x65, 0x6d, 0x70, 0x6c, 0x61, 0x74, 0x65, 0x12, 0x2c, 0x0a, - 0x02, 0x69, 0x64, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x1c, 0x2e, 0x67, 0x6f, 0x6f, 0x67, - 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x55, 0x49, 0x6e, 0x74, - 0x36, 0x34, 0x56, 0x61, 0x6c, 0x75, 0x65, 0x52, 0x02, 0x69, 0x64, 0x12, 0x30, 0x0a, 0x04, 0x6e, - 0x61, 0x6d, 0x65, 0x18, 0x02, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x1c, 0x2e, 0x67, 0x6f, 0x6f, 0x67, - 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x53, 0x74, 0x72, 0x69, - 0x6e, 0x67, 0x56, 0x61, 0x6c, 0x75, 0x65, 0x52, 0x04, 0x6e, 0x61, 0x6d, 0x65, 0x12, 0x36, 0x0a, - 0x07, 0x63, 0x6f, 0x6e, 0x74, 0x65, 0x6e, 0x74, 0x18, 0x03, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x1c, - 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, - 0x2e, 0x53, 0x74, 0x72, 0x69, 0x6e, 0x67, 0x56, 0x61, 0x6c, 0x75, 0x65, 0x52, 0x07, 0x63, 0x6f, - 0x6e, 0x74, 0x65, 0x6e, 0x74, 0x12, 0x34, 0x0a, 0x06, 0x66, 0x6f, 0x72, 0x6d, 0x61, 0x74, 0x18, - 0x04, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x1c, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, - 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x53, 0x74, 0x72, 0x69, 0x6e, 0x67, 0x56, 0x61, - 0x6c, 0x75, 0x65, 0x52, 0x06, 0x66, 0x6f, 0x72, 0x6d, 0x61, 0x74, 0x12, 0x36, 0x0a, 0x07, 0x63, - 0x6f, 0x6d, 0x6d, 0x65, 0x6e, 0x74, 0x18, 0x05, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x1c, 0x2e, 0x67, - 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x53, - 0x74, 0x72, 0x69, 0x6e, 0x67, 0x56, 0x61, 0x6c, 0x75, 0x65, 0x52, 0x07, 0x63, 0x6f, 0x6d, 0x6d, - 0x65, 0x6e, 0x74, 0x12, 0x3d, 0x0a, 0x0b, 0x63, 0x72, 0x65, 0x61, 0x74, 0x65, 0x5f, 0x74, 0x69, - 0x6d, 0x65, 0x18, 0x06, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x1c, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, - 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x53, 0x74, 0x72, 0x69, 0x6e, - 0x67, 0x56, 0x61, 0x6c, 0x75, 0x65, 0x52, 0x0a, 0x63, 0x72, 0x65, 0x61, 0x74, 0x65, 0x54, 0x69, - 0x6d, 0x65, 0x12, 0x39, 0x0a, 0x09, 0x63, 0x72, 0x65, 0x61, 0x74, 0x65, 0x5f, 0x62, 0x79, 0x18, - 0x07, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x1c, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, - 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x53, 0x74, 0x72, 0x69, 0x6e, 0x67, 0x56, 0x61, - 0x6c, 0x75, 0x65, 0x52, 0x08, 0x63, 0x72, 0x65, 0x61, 0x74, 0x65, 0x42, 0x79, 0x12, 0x3d, 0x0a, - 0x0b, 0x6d, 0x6f, 0x64, 0x69, 0x66, 0x79, 0x5f, 0x74, 0x69, 0x6d, 0x65, 0x18, 0x08, 0x20, 0x01, - 0x28, 0x0b, 0x32, 0x1c, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, - 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x53, 0x74, 0x72, 0x69, 0x6e, 0x67, 0x56, 0x61, 0x6c, 0x75, 0x65, - 0x52, 0x0a, 0x6d, 0x6f, 0x64, 0x69, 0x66, 0x79, 0x54, 0x69, 0x6d, 0x65, 0x12, 0x39, 0x0a, 0x09, - 0x6d, 0x6f, 0x64, 0x69, 0x66, 0x79, 0x5f, 0x62, 0x79, 0x18, 0x09, 0x20, 0x01, 0x28, 0x0b, 0x32, - 0x1c, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, - 0x66, 0x2e, 0x53, 0x74, 0x72, 0x69, 0x6e, 0x67, 0x56, 0x61, 0x6c, 0x75, 0x65, 0x52, 0x08, 0x6d, - 0x6f, 0x64, 0x69, 0x66, 0x79, 0x42, 0x79, 0x22, 0xe1, 0x02, 0x0a, 0x14, 0x43, 0x6c, 0x69, 0x65, - 0x6e, 0x74, 0x43, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x46, 0x69, 0x6c, 0x65, 0x49, 0x6e, 0x66, 0x6f, - 0x12, 0x3a, 0x0a, 0x09, 0x6e, 0x61, 0x6d, 0x65, 0x73, 0x70, 0x61, 0x63, 0x65, 0x18, 0x01, 0x20, - 0x01, 0x28, 0x0b, 0x32, 0x1c, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, - 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x53, 0x74, 0x72, 0x69, 0x6e, 0x67, 0x56, 0x61, 0x6c, 0x75, - 0x65, 0x52, 0x09, 0x6e, 0x61, 0x6d, 0x65, 0x73, 0x70, 0x61, 0x63, 0x65, 0x12, 0x32, 0x0a, 0x05, - 0x67, 0x72, 0x6f, 0x75, 0x70, 0x18, 0x02, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x1c, 0x2e, 0x67, 0x6f, - 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x53, 0x74, - 0x72, 0x69, 0x6e, 0x67, 0x56, 0x61, 0x6c, 0x75, 0x65, 0x52, 0x05, 0x67, 0x72, 0x6f, 0x75, 0x70, - 0x12, 0x39, 0x0a, 0x09, 0x66, 0x69, 0x6c, 0x65, 0x5f, 0x6e, 0x61, 0x6d, 0x65, 0x18, 0x03, 0x20, - 0x01, 0x28, 0x0b, 0x32, 0x1c, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, - 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x53, 0x74, 0x72, 0x69, 0x6e, 0x67, 0x56, 0x61, 0x6c, 0x75, - 0x65, 0x52, 0x08, 0x66, 0x69, 0x6c, 0x65, 0x4e, 0x61, 0x6d, 0x65, 0x12, 0x36, 0x0a, 0x07, 0x63, - 0x6f, 0x6e, 0x74, 0x65, 0x6e, 0x74, 0x18, 0x04, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x1c, 0x2e, 0x67, - 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x53, - 0x74, 0x72, 0x69, 0x6e, 0x67, 0x56, 0x61, 0x6c, 0x75, 0x65, 0x52, 0x07, 0x63, 0x6f, 0x6e, 0x74, - 0x65, 0x6e, 0x74, 0x12, 0x36, 0x0a, 0x07, 0x76, 0x65, 0x72, 0x73, 0x69, 0x6f, 0x6e, 0x18, 0x05, - 0x20, 0x01, 0x28, 0x0b, 0x32, 0x1c, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, - 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x55, 0x49, 0x6e, 0x74, 0x36, 0x34, 0x56, 0x61, 0x6c, - 0x75, 0x65, 0x52, 0x07, 0x76, 0x65, 0x72, 0x73, 0x69, 0x6f, 0x6e, 0x12, 0x2e, 0x0a, 0x03, 0x6d, - 0x64, 0x35, 0x18, 0x06, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x1c, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, - 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x53, 0x74, 0x72, 0x69, 0x6e, - 0x67, 0x56, 0x61, 0x6c, 0x75, 0x65, 0x52, 0x03, 0x6d, 0x64, 0x35, 0x22, 0xd5, 0x01, 0x0a, 0x1c, - 0x43, 0x6c, 0x69, 0x65, 0x6e, 0x74, 0x57, 0x61, 0x74, 0x63, 0x68, 0x43, 0x6f, 0x6e, 0x66, 0x69, - 0x67, 0x46, 0x69, 0x6c, 0x65, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x12, 0x39, 0x0a, 0x09, - 0x63, 0x6c, 0x69, 0x65, 0x6e, 0x74, 0x5f, 0x69, 0x70, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0b, 0x32, - 0x1c, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, - 0x66, 0x2e, 0x53, 0x74, 0x72, 0x69, 0x6e, 0x67, 0x56, 0x61, 0x6c, 0x75, 0x65, 0x52, 0x08, 0x63, - 0x6c, 0x69, 0x65, 0x6e, 0x74, 0x49, 0x70, 0x12, 0x3f, 0x0a, 0x0c, 0x73, 0x65, 0x72, 0x76, 0x69, - 0x63, 0x65, 0x5f, 0x6e, 0x61, 0x6d, 0x65, 0x18, 0x02, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x1c, 0x2e, - 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, - 0x53, 0x74, 0x72, 0x69, 0x6e, 0x67, 0x56, 0x61, 0x6c, 0x75, 0x65, 0x52, 0x0b, 0x73, 0x65, 0x72, - 0x76, 0x69, 0x63, 0x65, 0x4e, 0x61, 0x6d, 0x65, 0x12, 0x39, 0x0a, 0x0b, 0x77, 0x61, 0x74, 0x63, - 0x68, 0x5f, 0x66, 0x69, 0x6c, 0x65, 0x73, 0x18, 0x03, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x18, 0x2e, - 0x76, 0x31, 0x2e, 0x43, 0x6c, 0x69, 0x65, 0x6e, 0x74, 0x43, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x46, - 0x69, 0x6c, 0x65, 0x49, 0x6e, 0x66, 0x6f, 0x52, 0x0a, 0x77, 0x61, 0x74, 0x63, 0x68, 0x46, 0x69, - 0x6c, 0x65, 0x73, 0x42, 0x05, 0x5a, 0x03, 0x2f, 0x76, 0x31, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, - 0x6f, 0x33, -} - -var ( - file_config_file_proto_rawDescOnce sync.Once - file_config_file_proto_rawDescData = file_config_file_proto_rawDesc -) - -func file_config_file_proto_rawDescGZIP() []byte { - file_config_file_proto_rawDescOnce.Do(func() { - file_config_file_proto_rawDescData = protoimpl.X.CompressGZIP(file_config_file_proto_rawDescData) - }) - return file_config_file_proto_rawDescData -} - -var file_config_file_proto_msgTypes = make([]protoimpl.MessageInfo, 8) -var file_config_file_proto_goTypes = []interface{}{ - (*ConfigFileGroup)(nil), // 0: v1.ConfigFileGroup - (*ConfigFile)(nil), // 1: v1.ConfigFile - (*ConfigFileTag)(nil), // 2: v1.ConfigFileTag - (*ConfigFileRelease)(nil), // 3: v1.ConfigFileRelease - (*ConfigFileReleaseHistory)(nil), // 4: v1.ConfigFileReleaseHistory - (*ConfigFileTemplate)(nil), // 5: v1.ConfigFileTemplate - (*ClientConfigFileInfo)(nil), // 6: v1.ClientConfigFileInfo - (*ClientWatchConfigFileRequest)(nil), // 7: v1.ClientWatchConfigFileRequest - (*wrappers.UInt64Value)(nil), // 8: google.protobuf.UInt64Value - (*wrappers.StringValue)(nil), // 9: google.protobuf.StringValue -} -var file_config_file_proto_depIdxs = []int32{ - 8, // 0: v1.ConfigFileGroup.id:type_name -> google.protobuf.UInt64Value - 9, // 1: v1.ConfigFileGroup.name:type_name -> google.protobuf.StringValue - 9, // 2: v1.ConfigFileGroup.namespace:type_name -> google.protobuf.StringValue - 9, // 3: v1.ConfigFileGroup.comment:type_name -> google.protobuf.StringValue - 9, // 4: v1.ConfigFileGroup.create_time:type_name -> google.protobuf.StringValue - 9, // 5: v1.ConfigFileGroup.create_by:type_name -> google.protobuf.StringValue - 9, // 6: v1.ConfigFileGroup.modify_time:type_name -> google.protobuf.StringValue - 9, // 7: v1.ConfigFileGroup.modify_by:type_name -> google.protobuf.StringValue - 8, // 8: v1.ConfigFileGroup.fileCount:type_name -> google.protobuf.UInt64Value - 8, // 9: v1.ConfigFile.id:type_name -> google.protobuf.UInt64Value - 9, // 10: v1.ConfigFile.name:type_name -> google.protobuf.StringValue - 9, // 11: v1.ConfigFile.namespace:type_name -> google.protobuf.StringValue - 9, // 12: v1.ConfigFile.group:type_name -> google.protobuf.StringValue - 9, // 13: v1.ConfigFile.content:type_name -> google.protobuf.StringValue - 9, // 14: v1.ConfigFile.format:type_name -> google.protobuf.StringValue - 9, // 15: v1.ConfigFile.comment:type_name -> google.protobuf.StringValue - 9, // 16: v1.ConfigFile.status:type_name -> google.protobuf.StringValue - 2, // 17: v1.ConfigFile.tags:type_name -> v1.ConfigFileTag - 9, // 18: v1.ConfigFile.create_time:type_name -> google.protobuf.StringValue - 9, // 19: v1.ConfigFile.create_by:type_name -> google.protobuf.StringValue - 9, // 20: v1.ConfigFile.modify_time:type_name -> google.protobuf.StringValue - 9, // 21: v1.ConfigFile.modify_by:type_name -> google.protobuf.StringValue - 9, // 22: v1.ConfigFile.release_time:type_name -> google.protobuf.StringValue - 9, // 23: v1.ConfigFile.release_by:type_name -> google.protobuf.StringValue - 9, // 24: v1.ConfigFileTag.key:type_name -> google.protobuf.StringValue - 9, // 25: v1.ConfigFileTag.value:type_name -> google.protobuf.StringValue - 8, // 26: v1.ConfigFileRelease.id:type_name -> google.protobuf.UInt64Value - 9, // 27: v1.ConfigFileRelease.name:type_name -> google.protobuf.StringValue - 9, // 28: v1.ConfigFileRelease.namespace:type_name -> google.protobuf.StringValue - 9, // 29: v1.ConfigFileRelease.group:type_name -> google.protobuf.StringValue - 9, // 30: v1.ConfigFileRelease.file_name:type_name -> google.protobuf.StringValue - 9, // 31: v1.ConfigFileRelease.content:type_name -> google.protobuf.StringValue - 9, // 32: v1.ConfigFileRelease.comment:type_name -> google.protobuf.StringValue - 9, // 33: v1.ConfigFileRelease.md5:type_name -> google.protobuf.StringValue - 8, // 34: v1.ConfigFileRelease.version:type_name -> google.protobuf.UInt64Value - 9, // 35: v1.ConfigFileRelease.create_time:type_name -> google.protobuf.StringValue - 9, // 36: v1.ConfigFileRelease.create_by:type_name -> google.protobuf.StringValue - 9, // 37: v1.ConfigFileRelease.modify_time:type_name -> google.protobuf.StringValue - 9, // 38: v1.ConfigFileRelease.modify_by:type_name -> google.protobuf.StringValue - 8, // 39: v1.ConfigFileReleaseHistory.id:type_name -> google.protobuf.UInt64Value - 9, // 40: v1.ConfigFileReleaseHistory.name:type_name -> google.protobuf.StringValue - 9, // 41: v1.ConfigFileReleaseHistory.namespace:type_name -> google.protobuf.StringValue - 9, // 42: v1.ConfigFileReleaseHistory.group:type_name -> google.protobuf.StringValue - 9, // 43: v1.ConfigFileReleaseHistory.file_name:type_name -> google.protobuf.StringValue - 9, // 44: v1.ConfigFileReleaseHistory.content:type_name -> google.protobuf.StringValue - 9, // 45: v1.ConfigFileReleaseHistory.format:type_name -> google.protobuf.StringValue - 9, // 46: v1.ConfigFileReleaseHistory.comment:type_name -> google.protobuf.StringValue - 9, // 47: v1.ConfigFileReleaseHistory.md5:type_name -> google.protobuf.StringValue - 9, // 48: v1.ConfigFileReleaseHistory.type:type_name -> google.protobuf.StringValue - 9, // 49: v1.ConfigFileReleaseHistory.status:type_name -> google.protobuf.StringValue - 2, // 50: v1.ConfigFileReleaseHistory.tags:type_name -> v1.ConfigFileTag - 9, // 51: v1.ConfigFileReleaseHistory.create_time:type_name -> google.protobuf.StringValue - 9, // 52: v1.ConfigFileReleaseHistory.create_by:type_name -> google.protobuf.StringValue - 9, // 53: v1.ConfigFileReleaseHistory.modify_time:type_name -> google.protobuf.StringValue - 9, // 54: v1.ConfigFileReleaseHistory.modify_by:type_name -> google.protobuf.StringValue - 8, // 55: v1.ConfigFileTemplate.id:type_name -> google.protobuf.UInt64Value - 9, // 56: v1.ConfigFileTemplate.name:type_name -> google.protobuf.StringValue - 9, // 57: v1.ConfigFileTemplate.content:type_name -> google.protobuf.StringValue - 9, // 58: v1.ConfigFileTemplate.format:type_name -> google.protobuf.StringValue - 9, // 59: v1.ConfigFileTemplate.comment:type_name -> google.protobuf.StringValue - 9, // 60: v1.ConfigFileTemplate.create_time:type_name -> google.protobuf.StringValue - 9, // 61: v1.ConfigFileTemplate.create_by:type_name -> google.protobuf.StringValue - 9, // 62: v1.ConfigFileTemplate.modify_time:type_name -> google.protobuf.StringValue - 9, // 63: v1.ConfigFileTemplate.modify_by:type_name -> google.protobuf.StringValue - 9, // 64: v1.ClientConfigFileInfo.namespace:type_name -> google.protobuf.StringValue - 9, // 65: v1.ClientConfigFileInfo.group:type_name -> google.protobuf.StringValue - 9, // 66: v1.ClientConfigFileInfo.file_name:type_name -> google.protobuf.StringValue - 9, // 67: v1.ClientConfigFileInfo.content:type_name -> google.protobuf.StringValue - 8, // 68: v1.ClientConfigFileInfo.version:type_name -> google.protobuf.UInt64Value - 9, // 69: v1.ClientConfigFileInfo.md5:type_name -> google.protobuf.StringValue - 9, // 70: v1.ClientWatchConfigFileRequest.client_ip:type_name -> google.protobuf.StringValue - 9, // 71: v1.ClientWatchConfigFileRequest.service_name:type_name -> google.protobuf.StringValue - 6, // 72: v1.ClientWatchConfigFileRequest.watch_files:type_name -> v1.ClientConfigFileInfo - 73, // [73:73] is the sub-list for method output_type - 73, // [73:73] is the sub-list for method input_type - 73, // [73:73] is the sub-list for extension type_name - 73, // [73:73] is the sub-list for extension extendee - 0, // [0:73] is the sub-list for field type_name -} - -func init() { file_config_file_proto_init() } -func file_config_file_proto_init() { - if File_config_file_proto != nil { - return - } - if !protoimpl.UnsafeEnabled { - file_config_file_proto_msgTypes[0].Exporter = func(v interface{}, i int) interface{} { - switch v := v.(*ConfigFileGroup); i { - case 0: - return &v.state - case 1: - return &v.sizeCache - case 2: - return &v.unknownFields - default: - return nil - } - } - file_config_file_proto_msgTypes[1].Exporter = func(v interface{}, i int) interface{} { - switch v := v.(*ConfigFile); i { - case 0: - return &v.state - case 1: - return &v.sizeCache - case 2: - return &v.unknownFields - default: - return nil - } - } - file_config_file_proto_msgTypes[2].Exporter = func(v interface{}, i int) interface{} { - switch v := v.(*ConfigFileTag); i { - case 0: - return &v.state - case 1: - return &v.sizeCache - case 2: - return &v.unknownFields - default: - return nil - } - } - file_config_file_proto_msgTypes[3].Exporter = func(v interface{}, i int) interface{} { - switch v := v.(*ConfigFileRelease); i { - case 0: - return &v.state - case 1: - return &v.sizeCache - case 2: - return &v.unknownFields - default: - return nil - } - } - file_config_file_proto_msgTypes[4].Exporter = func(v interface{}, i int) interface{} { - switch v := v.(*ConfigFileReleaseHistory); i { - case 0: - return &v.state - case 1: - return &v.sizeCache - case 2: - return &v.unknownFields - default: - return nil - } - } - file_config_file_proto_msgTypes[5].Exporter = func(v interface{}, i int) interface{} { - switch v := v.(*ConfigFileTemplate); i { - case 0: - return &v.state - case 1: - return &v.sizeCache - case 2: - return &v.unknownFields - default: - return nil - } - } - file_config_file_proto_msgTypes[6].Exporter = func(v interface{}, i int) interface{} { - switch v := v.(*ClientConfigFileInfo); i { - case 0: - return &v.state - case 1: - return &v.sizeCache - case 2: - return &v.unknownFields - default: - return nil - } - } - file_config_file_proto_msgTypes[7].Exporter = func(v interface{}, i int) interface{} { - switch v := v.(*ClientWatchConfigFileRequest); i { - case 0: - return &v.state - case 1: - return &v.sizeCache - case 2: - return &v.unknownFields - default: - return nil - } - } - } - type x struct{} - out := protoimpl.TypeBuilder{ - File: protoimpl.DescBuilder{ - GoPackagePath: reflect.TypeOf(x{}).PkgPath(), - RawDescriptor: file_config_file_proto_rawDesc, - NumEnums: 0, - NumMessages: 8, - NumExtensions: 0, - NumServices: 0, - }, - GoTypes: file_config_file_proto_goTypes, - DependencyIndexes: file_config_file_proto_depIdxs, - MessageInfos: file_config_file_proto_msgTypes, - }.Build() - File_config_file_proto = out.File - file_config_file_proto_rawDesc = nil - file_config_file_proto_goTypes = nil - file_config_file_proto_depIdxs = nil + return fileDescriptor_config_file_b643ace0171d7a6b, []int{7} +} +func (m *ClientWatchConfigFileRequest) XXX_Unmarshal(b []byte) error { + return xxx_messageInfo_ClientWatchConfigFileRequest.Unmarshal(m, b) +} +func (m *ClientWatchConfigFileRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + return xxx_messageInfo_ClientWatchConfigFileRequest.Marshal(b, m, deterministic) +} +func (dst *ClientWatchConfigFileRequest) XXX_Merge(src proto.Message) { + xxx_messageInfo_ClientWatchConfigFileRequest.Merge(dst, src) +} +func (m *ClientWatchConfigFileRequest) XXX_Size() int { + return xxx_messageInfo_ClientWatchConfigFileRequest.Size(m) +} +func (m *ClientWatchConfigFileRequest) XXX_DiscardUnknown() { + xxx_messageInfo_ClientWatchConfigFileRequest.DiscardUnknown(m) +} + +var xxx_messageInfo_ClientWatchConfigFileRequest proto.InternalMessageInfo + +func (m *ClientWatchConfigFileRequest) GetClientIp() *wrappers.StringValue { + if m != nil { + return m.ClientIp + } + return nil +} + +func (m *ClientWatchConfigFileRequest) GetServiceName() *wrappers.StringValue { + if m != nil { + return m.ServiceName + } + return nil +} + +func (m *ClientWatchConfigFileRequest) GetWatchFiles() []*ClientConfigFileInfo { + if m != nil { + return m.WatchFiles + } + return nil +} + +func init() { + proto.RegisterType((*ConfigFileGroup)(nil), "v1.ConfigFileGroup") + proto.RegisterType((*ConfigFile)(nil), "v1.ConfigFile") + proto.RegisterType((*ConfigFileTag)(nil), "v1.ConfigFileTag") + proto.RegisterType((*ConfigFileRelease)(nil), "v1.ConfigFileRelease") + proto.RegisterType((*ConfigFileReleaseHistory)(nil), "v1.ConfigFileReleaseHistory") + proto.RegisterType((*ConfigFileTemplate)(nil), "v1.ConfigFileTemplate") + proto.RegisterType((*ClientConfigFileInfo)(nil), "v1.ClientConfigFileInfo") + proto.RegisterType((*ClientWatchConfigFileRequest)(nil), "v1.ClientWatchConfigFileRequest") +} + +func init() { proto.RegisterFile("config_file.proto", fileDescriptor_config_file_b643ace0171d7a6b) } + +var fileDescriptor_config_file_b643ace0171d7a6b = []byte{ + // 727 bytes of a gzipped FileDescriptorProto + 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xec, 0x98, 0xdd, 0x8a, 0xd3, 0x40, + 0x14, 0xc7, 0x69, 0x92, 0xa6, 0xed, 0xc9, 0x7e, 0xb8, 0xc1, 0x8b, 0x41, 0x16, 0x59, 0x0a, 0xc2, + 0x5e, 0x48, 0xf6, 0xc3, 0x75, 0x61, 0x15, 0x11, 0xba, 0xa0, 0xf6, 0xc6, 0x8b, 0xba, 0x2a, 0x78, + 0x53, 0xd2, 0x76, 0x1a, 0x07, 0x93, 0x4c, 0xcc, 0x4c, 0xbb, 0xe4, 0x25, 0xbc, 0xf3, 0xc1, 0xbc, + 0xf0, 0x01, 0xbc, 0xf5, 0x21, 0x44, 0x66, 0x26, 0x21, 0x59, 0x75, 0x61, 0x92, 0x20, 0x88, 0x7a, + 0x55, 0xd2, 0xfc, 0xcf, 0x9c, 0xe9, 0x99, 0xdf, 0xff, 0x9c, 0x34, 0xb0, 0x33, 0xa7, 0xf1, 0x92, + 0x04, 0xd3, 0x25, 0x09, 0xb1, 0x97, 0xa4, 0x94, 0x53, 0xd7, 0x58, 0x1f, 0xdd, 0xba, 0x1d, 0x50, + 0x1a, 0x84, 0xf8, 0x40, 0x7e, 0x33, 0x5b, 0x2d, 0x0f, 0x2e, 0x53, 0x3f, 0x49, 0x70, 0xca, 0x94, + 0x66, 0xf8, 0xd1, 0x82, 0xed, 0x73, 0x19, 0xf9, 0x84, 0x84, 0xf8, 0x69, 0x4a, 0x57, 0x89, 0x7b, + 0x17, 0x0c, 0xb2, 0x40, 0x9d, 0xbd, 0xce, 0xbe, 0x73, 0xbc, 0xeb, 0xa9, 0x05, 0xbc, 0x62, 0x01, + 0xef, 0xe5, 0x38, 0xe6, 0xa7, 0x27, 0xaf, 0xfc, 0x70, 0x85, 0x27, 0x06, 0x59, 0xb8, 0x87, 0x60, + 0xc5, 0x7e, 0x84, 0x91, 0x71, 0x8d, 0xfe, 0x05, 0x4f, 0x49, 0x1c, 0x28, 0xbd, 0x54, 0xba, 0x0f, + 0x60, 0x20, 0x3e, 0x59, 0xe2, 0xcf, 0x31, 0x32, 0x35, 0xc2, 0x4a, 0xb9, 0x7b, 0x0a, 0xbd, 0x39, + 0x8d, 0x22, 0x1c, 0x73, 0x64, 0x69, 0x44, 0x16, 0x62, 0xf7, 0x11, 0x38, 0xf3, 0x14, 0xfb, 0x1c, + 0x4f, 0x39, 0x89, 0x30, 0xea, 0x6a, 0xc4, 0x82, 0x0a, 0xb8, 0x20, 0x11, 0x76, 0xcf, 0x60, 0x90, + 0x87, 0xcf, 0x32, 0x64, 0x6b, 0x04, 0xf7, 0x95, 0x7c, 0x94, 0x89, 0xcc, 0x11, 0x5d, 0x90, 0x65, + 0xa6, 0x32, 0xf7, 0x74, 0x32, 0xab, 0x80, 0x22, 0x73, 0x1e, 0x3e, 0xcb, 0x50, 0x5f, 0x27, 0xb3, + 0x92, 0x8f, 0x32, 0x51, 0x67, 0x41, 0xc3, 0x39, 0x5d, 0xc5, 0x1c, 0x0d, 0x34, 0x8e, 0xb3, 0x94, + 0x0f, 0x3f, 0xd9, 0x00, 0x25, 0x17, 0x7f, 0x34, 0x12, 0xc7, 0xd0, 0x0d, 0x04, 0xb7, 0x5a, 0x40, + 0x28, 0xa9, 0xc2, 0x28, 0xe6, 0x02, 0xa3, 0xae, 0x1e, 0x46, 0x52, 0xec, 0x9e, 0x80, 0xbd, 0xa4, + 0x69, 0xe4, 0x73, 0x2d, 0x08, 0x72, 0x6d, 0x15, 0xda, 0x5e, 0x1d, 0x68, 0x4f, 0xc0, 0x66, 0xdc, + 0xe7, 0x2b, 0xa6, 0x75, 0xf0, 0xb9, 0xd6, 0xbd, 0x03, 0x16, 0xf7, 0x03, 0x86, 0x06, 0x7b, 0xe6, + 0xbe, 0x73, 0xbc, 0xe3, 0xad, 0x8f, 0xbc, 0xf2, 0x24, 0x2f, 0xfc, 0x60, 0x22, 0x6f, 0xff, 0xe8, + 0x08, 0x68, 0xe3, 0x08, 0xa7, 0x8d, 0x23, 0x36, 0xda, 0x38, 0x62, 0xb3, 0x96, 0x23, 0x1e, 0xc3, + 0x46, 0x8a, 0x43, 0xec, 0xb3, 0xfc, 0x47, 0x6f, 0x69, 0x44, 0x3b, 0x79, 0x84, 0xcc, 0xfd, 0x10, + 0xa0, 0x58, 0x60, 0x96, 0xa1, 0x6d, 0x1d, 0x50, 0x73, 0xfd, 0x28, 0x1b, 0x32, 0xd8, 0xbc, 0x72, + 0x10, 0xae, 0x07, 0xe6, 0x3b, 0x9c, 0x5d, 0x6b, 0xab, 0xea, 0x32, 0x42, 0x28, 0x48, 0x5f, 0x8b, + 0x2b, 0x2d, 0x63, 0x29, 0xe9, 0xf0, 0x6b, 0x17, 0x76, 0xca, 0xac, 0x13, 0xb5, 0x99, 0xbf, 0xce, + 0xcf, 0x67, 0xaa, 0xd5, 0x4d, 0xe5, 0x36, 0x75, 0x1c, 0xdd, 0x17, 0xf2, 0xe7, 0x62, 0xab, 0x95, + 0x56, 0x60, 0xd7, 0x69, 0x05, 0x4d, 0x4d, 0xed, 0x81, 0x19, 0x2d, 0xee, 0x6b, 0x39, 0x5a, 0x08, + 0x45, 0x9e, 0x35, 0x4e, 0x19, 0xa1, 0xb1, 0x56, 0x0f, 0x2f, 0xc4, 0xff, 0xa2, 0xbf, 0x87, 0xdf, + 0x6c, 0x40, 0x3f, 0xc1, 0xfe, 0x8c, 0x30, 0x4e, 0xd3, 0xec, 0x3f, 0xf3, 0xed, 0x99, 0x2f, 0xc7, + 0x5f, 0xaf, 0xd9, 0xf8, 0xeb, 0x37, 0x70, 0xca, 0x40, 0xd7, 0x29, 0x87, 0x60, 0xf1, 0x2c, 0xd1, + 0x43, 0x5d, 0x2a, 0x2b, 0x03, 0xd6, 0x69, 0x30, 0x60, 0x37, 0x6a, 0x0d, 0xd8, 0xcd, 0x36, 0x06, + 0xdc, 0x6a, 0x63, 0xc0, 0xed, 0x36, 0x06, 0xbc, 0x51, 0xcb, 0x80, 0x1f, 0x2c, 0x70, 0x2b, 0xb5, + 0xc0, 0x51, 0x12, 0xfa, 0xfc, 0xf7, 0x8f, 0x9b, 0x0a, 0xcf, 0x66, 0x33, 0x9e, 0xad, 0x66, 0x3c, + 0x77, 0x5b, 0xfc, 0x07, 0xb1, 0xdb, 0x00, 0xd1, 0x6b, 0x03, 0x44, 0xbf, 0x0d, 0x10, 0x83, 0x5a, + 0x40, 0x7c, 0x31, 0xe0, 0xe6, 0x79, 0x48, 0x70, 0xcc, 0x4b, 0x2c, 0xc6, 0xf1, 0x92, 0x5e, 0xed, + 0x96, 0x9d, 0x86, 0xdd, 0xd2, 0x68, 0xd8, 0x2d, 0xcd, 0xa6, 0xdd, 0xd2, 0xaa, 0xf9, 0x84, 0x50, + 0x4c, 0xee, 0x6e, 0x9d, 0xc9, 0x9d, 0xf7, 0x3d, 0x5b, 0xb3, 0xef, 0x0d, 0x3f, 0x77, 0x60, 0x57, + 0xd5, 0xf8, 0xb5, 0xcf, 0xe7, 0x6f, 0xab, 0x03, 0xf0, 0xfd, 0x0a, 0x33, 0x2e, 0xc9, 0x91, 0xf7, + 0xa7, 0x24, 0xd1, 0xaa, 0x75, 0x5f, 0xc9, 0xc7, 0x89, 0x78, 0x62, 0x66, 0x38, 0x5d, 0x93, 0x79, + 0x5e, 0x39, 0x9d, 0x8a, 0x3b, 0x79, 0x84, 0x2c, 0xde, 0x19, 0x38, 0x97, 0x62, 0x57, 0xf2, 0xc5, + 0x04, 0x43, 0xa6, 0xec, 0x99, 0x48, 0xf6, 0xcc, 0x5f, 0x60, 0x31, 0x01, 0x29, 0x16, 0x97, 0x6c, + 0x64, 0xbd, 0x31, 0xd6, 0x47, 0x33, 0x5b, 0xe6, 0xb8, 0xf7, 0x3d, 0x00, 0x00, 0xff, 0xff, 0x28, + 0x36, 0x72, 0xf3, 0xe1, 0x10, 0x00, 0x00, } diff --git a/common/api/v1/config_file_response.pb.go b/common/api/v1/config_file_response.pb.go index b5dafd98e..f04abc9b6 100644 --- a/common/api/v1/config_file_response.pb.go +++ b/common/api/v1/config_file_response.pb.go @@ -1,103 +1,71 @@ -/* - * Tencent is pleased to support the open source community by making Polaris available. - * - * Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved. - * - * Licensed under the BSD 3-Clause License (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://opensource.org/licenses/BSD-3-Clause - * - * 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. - */ - // Code generated by protoc-gen-go. DO NOT EDIT. -// versions: -// protoc-gen-go v1.27.1 -// protoc v3.17.3 // source: config_file_response.proto package v1 -import ( - wrappers "github.com/golang/protobuf/ptypes/wrappers" - protoreflect "google.golang.org/protobuf/reflect/protoreflect" - protoimpl "google.golang.org/protobuf/runtime/protoimpl" - reflect "reflect" - sync "sync" -) - -const ( - // Verify that this generated code is sufficiently up-to-date. - _ = protoimpl.EnforceVersion(20 - protoimpl.MinVersion) - // Verify that runtime/protoimpl is sufficiently up-to-date. - _ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20) -) +import proto "github.com/golang/protobuf/proto" +import fmt "fmt" +import math "math" +import wrappers "github.com/golang/protobuf/ptypes/wrappers" -type ConfigSimpleResponse struct { - state protoimpl.MessageState - sizeCache protoimpl.SizeCache - unknownFields protoimpl.UnknownFields +// Reference imports to suppress errors if they are not otherwise used. +var _ = proto.Marshal +var _ = fmt.Errorf +var _ = math.Inf - Code *wrappers.UInt32Value `protobuf:"bytes,1,opt,name=code,proto3" json:"code,omitempty"` - Info *wrappers.StringValue `protobuf:"bytes,2,opt,name=info,proto3" json:"info,omitempty"` -} +// This is a compile-time assertion to ensure that this generated file +// is compatible with the proto package it is being compiled against. +// A compilation error at this line likely means your copy of the +// proto package needs to be updated. +const _ = proto.ProtoPackageIsVersion2 // please upgrade the proto package -func (x *ConfigSimpleResponse) Reset() { - *x = ConfigSimpleResponse{} - if protoimpl.UnsafeEnabled { - mi := &file_config_file_response_proto_msgTypes[0] - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - ms.StoreMessageInfo(mi) - } +type ConfigSimpleResponse struct { + Code *wrappers.UInt32Value `protobuf:"bytes,1,opt,name=code,proto3" json:"code,omitempty"` + Info *wrappers.StringValue `protobuf:"bytes,2,opt,name=info,proto3" json:"info,omitempty"` + XXX_NoUnkeyedLiteral struct{} `json:"-"` + XXX_unrecognized []byte `json:"-"` + XXX_sizecache int32 `json:"-"` } -func (x *ConfigSimpleResponse) String() string { - return protoimpl.X.MessageStringOf(x) +func (m *ConfigSimpleResponse) Reset() { *m = ConfigSimpleResponse{} } +func (m *ConfigSimpleResponse) String() string { return proto.CompactTextString(m) } +func (*ConfigSimpleResponse) ProtoMessage() {} +func (*ConfigSimpleResponse) Descriptor() ([]byte, []int) { + return fileDescriptor_config_file_response_1d88ce8660f9af44, []int{0} } - -func (*ConfigSimpleResponse) ProtoMessage() {} - -func (x *ConfigSimpleResponse) ProtoReflect() protoreflect.Message { - mi := &file_config_file_response_proto_msgTypes[0] - if protoimpl.UnsafeEnabled && x != nil { - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - if ms.LoadMessageInfo() == nil { - ms.StoreMessageInfo(mi) - } - return ms - } - return mi.MessageOf(x) +func (m *ConfigSimpleResponse) XXX_Unmarshal(b []byte) error { + return xxx_messageInfo_ConfigSimpleResponse.Unmarshal(m, b) } - -// Deprecated: Use ConfigSimpleResponse.ProtoReflect.Descriptor instead. -func (*ConfigSimpleResponse) Descriptor() ([]byte, []int) { - return file_config_file_response_proto_rawDescGZIP(), []int{0} +func (m *ConfigSimpleResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + return xxx_messageInfo_ConfigSimpleResponse.Marshal(b, m, deterministic) +} +func (dst *ConfigSimpleResponse) XXX_Merge(src proto.Message) { + xxx_messageInfo_ConfigSimpleResponse.Merge(dst, src) +} +func (m *ConfigSimpleResponse) XXX_Size() int { + return xxx_messageInfo_ConfigSimpleResponse.Size(m) +} +func (m *ConfigSimpleResponse) XXX_DiscardUnknown() { + xxx_messageInfo_ConfigSimpleResponse.DiscardUnknown(m) } -func (x *ConfigSimpleResponse) GetCode() *wrappers.UInt32Value { - if x != nil { - return x.Code +var xxx_messageInfo_ConfigSimpleResponse proto.InternalMessageInfo + +func (m *ConfigSimpleResponse) GetCode() *wrappers.UInt32Value { + if m != nil { + return m.Code } return nil } -func (x *ConfigSimpleResponse) GetInfo() *wrappers.StringValue { - if x != nil { - return x.Info +func (m *ConfigSimpleResponse) GetInfo() *wrappers.StringValue { + if m != nil { + return m.Info } return nil } type ConfigResponse struct { - state protoimpl.MessageState - sizeCache protoimpl.SizeCache - unknownFields protoimpl.UnknownFields - Code *wrappers.UInt32Value `protobuf:"bytes,1,opt,name=code,proto3" json:"code,omitempty"` Info *wrappers.StringValue `protobuf:"bytes,2,opt,name=info,proto3" json:"info,omitempty"` ConfigFileGroup *ConfigFileGroup `protobuf:"bytes,3,opt,name=configFileGroup,proto3" json:"configFileGroup,omitempty"` @@ -105,165 +73,147 @@ type ConfigResponse struct { ConfigFileRelease *ConfigFileRelease `protobuf:"bytes,5,opt,name=configFileRelease,proto3" json:"configFileRelease,omitempty"` ConfigFileReleaseHistory *ConfigFileReleaseHistory `protobuf:"bytes,6,opt,name=configFileReleaseHistory,proto3" json:"configFileReleaseHistory,omitempty"` ConfigFileTemplate *ConfigFileTemplate `protobuf:"bytes,7,opt,name=configFileTemplate,proto3" json:"configFileTemplate,omitempty"` + XXX_NoUnkeyedLiteral struct{} `json:"-"` + XXX_unrecognized []byte `json:"-"` + XXX_sizecache int32 `json:"-"` } -func (x *ConfigResponse) Reset() { - *x = ConfigResponse{} - if protoimpl.UnsafeEnabled { - mi := &file_config_file_response_proto_msgTypes[1] - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - ms.StoreMessageInfo(mi) - } +func (m *ConfigResponse) Reset() { *m = ConfigResponse{} } +func (m *ConfigResponse) String() string { return proto.CompactTextString(m) } +func (*ConfigResponse) ProtoMessage() {} +func (*ConfigResponse) Descriptor() ([]byte, []int) { + return fileDescriptor_config_file_response_1d88ce8660f9af44, []int{1} } - -func (x *ConfigResponse) String() string { - return protoimpl.X.MessageStringOf(x) +func (m *ConfigResponse) XXX_Unmarshal(b []byte) error { + return xxx_messageInfo_ConfigResponse.Unmarshal(m, b) } - -func (*ConfigResponse) ProtoMessage() {} - -func (x *ConfigResponse) ProtoReflect() protoreflect.Message { - mi := &file_config_file_response_proto_msgTypes[1] - if protoimpl.UnsafeEnabled && x != nil { - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - if ms.LoadMessageInfo() == nil { - ms.StoreMessageInfo(mi) - } - return ms - } - return mi.MessageOf(x) +func (m *ConfigResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + return xxx_messageInfo_ConfigResponse.Marshal(b, m, deterministic) } - -// Deprecated: Use ConfigResponse.ProtoReflect.Descriptor instead. -func (*ConfigResponse) Descriptor() ([]byte, []int) { - return file_config_file_response_proto_rawDescGZIP(), []int{1} +func (dst *ConfigResponse) XXX_Merge(src proto.Message) { + xxx_messageInfo_ConfigResponse.Merge(dst, src) +} +func (m *ConfigResponse) XXX_Size() int { + return xxx_messageInfo_ConfigResponse.Size(m) +} +func (m *ConfigResponse) XXX_DiscardUnknown() { + xxx_messageInfo_ConfigResponse.DiscardUnknown(m) } -func (x *ConfigResponse) GetCode() *wrappers.UInt32Value { - if x != nil { - return x.Code +var xxx_messageInfo_ConfigResponse proto.InternalMessageInfo + +func (m *ConfigResponse) GetCode() *wrappers.UInt32Value { + if m != nil { + return m.Code } return nil } -func (x *ConfigResponse) GetInfo() *wrappers.StringValue { - if x != nil { - return x.Info +func (m *ConfigResponse) GetInfo() *wrappers.StringValue { + if m != nil { + return m.Info } return nil } -func (x *ConfigResponse) GetConfigFileGroup() *ConfigFileGroup { - if x != nil { - return x.ConfigFileGroup +func (m *ConfigResponse) GetConfigFileGroup() *ConfigFileGroup { + if m != nil { + return m.ConfigFileGroup } return nil } -func (x *ConfigResponse) GetConfigFile() *ConfigFile { - if x != nil { - return x.ConfigFile +func (m *ConfigResponse) GetConfigFile() *ConfigFile { + if m != nil { + return m.ConfigFile } return nil } -func (x *ConfigResponse) GetConfigFileRelease() *ConfigFileRelease { - if x != nil { - return x.ConfigFileRelease +func (m *ConfigResponse) GetConfigFileRelease() *ConfigFileRelease { + if m != nil { + return m.ConfigFileRelease } return nil } -func (x *ConfigResponse) GetConfigFileReleaseHistory() *ConfigFileReleaseHistory { - if x != nil { - return x.ConfigFileReleaseHistory +func (m *ConfigResponse) GetConfigFileReleaseHistory() *ConfigFileReleaseHistory { + if m != nil { + return m.ConfigFileReleaseHistory } return nil } -func (x *ConfigResponse) GetConfigFileTemplate() *ConfigFileTemplate { - if x != nil { - return x.ConfigFileTemplate +func (m *ConfigResponse) GetConfigFileTemplate() *ConfigFileTemplate { + if m != nil { + return m.ConfigFileTemplate } return nil } type ConfigBatchWriteResponse struct { - state protoimpl.MessageState - sizeCache protoimpl.SizeCache - unknownFields protoimpl.UnknownFields - - Code *wrappers.UInt32Value `protobuf:"bytes,1,opt,name=code,proto3" json:"code,omitempty"` - Info *wrappers.StringValue `protobuf:"bytes,2,opt,name=info,proto3" json:"info,omitempty"` - Total *wrappers.UInt32Value `protobuf:"bytes,3,opt,name=total,proto3" json:"total,omitempty"` - Responses []*ConfigResponse `protobuf:"bytes,4,rep,name=responses,proto3" json:"responses,omitempty"` -} - -func (x *ConfigBatchWriteResponse) Reset() { - *x = ConfigBatchWriteResponse{} - if protoimpl.UnsafeEnabled { - mi := &file_config_file_response_proto_msgTypes[2] - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - ms.StoreMessageInfo(mi) - } + Code *wrappers.UInt32Value `protobuf:"bytes,1,opt,name=code,proto3" json:"code,omitempty"` + Info *wrappers.StringValue `protobuf:"bytes,2,opt,name=info,proto3" json:"info,omitempty"` + Total *wrappers.UInt32Value `protobuf:"bytes,3,opt,name=total,proto3" json:"total,omitempty"` + Responses []*ConfigResponse `protobuf:"bytes,4,rep,name=responses,proto3" json:"responses,omitempty"` + XXX_NoUnkeyedLiteral struct{} `json:"-"` + XXX_unrecognized []byte `json:"-"` + XXX_sizecache int32 `json:"-"` +} + +func (m *ConfigBatchWriteResponse) Reset() { *m = ConfigBatchWriteResponse{} } +func (m *ConfigBatchWriteResponse) String() string { return proto.CompactTextString(m) } +func (*ConfigBatchWriteResponse) ProtoMessage() {} +func (*ConfigBatchWriteResponse) Descriptor() ([]byte, []int) { + return fileDescriptor_config_file_response_1d88ce8660f9af44, []int{2} } - -func (x *ConfigBatchWriteResponse) String() string { - return protoimpl.X.MessageStringOf(x) +func (m *ConfigBatchWriteResponse) XXX_Unmarshal(b []byte) error { + return xxx_messageInfo_ConfigBatchWriteResponse.Unmarshal(m, b) } - -func (*ConfigBatchWriteResponse) ProtoMessage() {} - -func (x *ConfigBatchWriteResponse) ProtoReflect() protoreflect.Message { - mi := &file_config_file_response_proto_msgTypes[2] - if protoimpl.UnsafeEnabled && x != nil { - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - if ms.LoadMessageInfo() == nil { - ms.StoreMessageInfo(mi) - } - return ms - } - return mi.MessageOf(x) +func (m *ConfigBatchWriteResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + return xxx_messageInfo_ConfigBatchWriteResponse.Marshal(b, m, deterministic) } - -// Deprecated: Use ConfigBatchWriteResponse.ProtoReflect.Descriptor instead. -func (*ConfigBatchWriteResponse) Descriptor() ([]byte, []int) { - return file_config_file_response_proto_rawDescGZIP(), []int{2} +func (dst *ConfigBatchWriteResponse) XXX_Merge(src proto.Message) { + xxx_messageInfo_ConfigBatchWriteResponse.Merge(dst, src) +} +func (m *ConfigBatchWriteResponse) XXX_Size() int { + return xxx_messageInfo_ConfigBatchWriteResponse.Size(m) } +func (m *ConfigBatchWriteResponse) XXX_DiscardUnknown() { + xxx_messageInfo_ConfigBatchWriteResponse.DiscardUnknown(m) +} + +var xxx_messageInfo_ConfigBatchWriteResponse proto.InternalMessageInfo -func (x *ConfigBatchWriteResponse) GetCode() *wrappers.UInt32Value { - if x != nil { - return x.Code +func (m *ConfigBatchWriteResponse) GetCode() *wrappers.UInt32Value { + if m != nil { + return m.Code } return nil } -func (x *ConfigBatchWriteResponse) GetInfo() *wrappers.StringValue { - if x != nil { - return x.Info +func (m *ConfigBatchWriteResponse) GetInfo() *wrappers.StringValue { + if m != nil { + return m.Info } return nil } -func (x *ConfigBatchWriteResponse) GetTotal() *wrappers.UInt32Value { - if x != nil { - return x.Total +func (m *ConfigBatchWriteResponse) GetTotal() *wrappers.UInt32Value { + if m != nil { + return m.Total } return nil } -func (x *ConfigBatchWriteResponse) GetResponses() []*ConfigResponse { - if x != nil { - return x.Responses +func (m *ConfigBatchWriteResponse) GetResponses() []*ConfigResponse { + if m != nil { + return m.Responses } return nil } type ConfigBatchQueryResponse struct { - state protoimpl.MessageState - sizeCache protoimpl.SizeCache - unknownFields protoimpl.UnknownFields - Code *wrappers.UInt32Value `protobuf:"bytes,1,opt,name=code,proto3" json:"code,omitempty"` Info *wrappers.StringValue `protobuf:"bytes,2,opt,name=info,proto3" json:"info,omitempty"` Total *wrappers.UInt32Value `protobuf:"bytes,3,opt,name=total,proto3" json:"total,omitempty"` @@ -272,410 +222,187 @@ type ConfigBatchQueryResponse struct { ConfigFileReleases []*ConfigFileRelease `protobuf:"bytes,6,rep,name=configFileReleases,proto3" json:"configFileReleases,omitempty"` ConfigFileReleaseHistories []*ConfigFileReleaseHistory `protobuf:"bytes,7,rep,name=configFileReleaseHistories,proto3" json:"configFileReleaseHistories,omitempty"` ConfigFileTemplates []*ConfigFileTemplate `protobuf:"bytes,8,rep,name=configFileTemplates,proto3" json:"configFileTemplates,omitempty"` + XXX_NoUnkeyedLiteral struct{} `json:"-"` + XXX_unrecognized []byte `json:"-"` + XXX_sizecache int32 `json:"-"` } -func (x *ConfigBatchQueryResponse) Reset() { - *x = ConfigBatchQueryResponse{} - if protoimpl.UnsafeEnabled { - mi := &file_config_file_response_proto_msgTypes[3] - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - ms.StoreMessageInfo(mi) - } +func (m *ConfigBatchQueryResponse) Reset() { *m = ConfigBatchQueryResponse{} } +func (m *ConfigBatchQueryResponse) String() string { return proto.CompactTextString(m) } +func (*ConfigBatchQueryResponse) ProtoMessage() {} +func (*ConfigBatchQueryResponse) Descriptor() ([]byte, []int) { + return fileDescriptor_config_file_response_1d88ce8660f9af44, []int{3} } - -func (x *ConfigBatchQueryResponse) String() string { - return protoimpl.X.MessageStringOf(x) +func (m *ConfigBatchQueryResponse) XXX_Unmarshal(b []byte) error { + return xxx_messageInfo_ConfigBatchQueryResponse.Unmarshal(m, b) } - -func (*ConfigBatchQueryResponse) ProtoMessage() {} - -func (x *ConfigBatchQueryResponse) ProtoReflect() protoreflect.Message { - mi := &file_config_file_response_proto_msgTypes[3] - if protoimpl.UnsafeEnabled && x != nil { - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - if ms.LoadMessageInfo() == nil { - ms.StoreMessageInfo(mi) - } - return ms - } - return mi.MessageOf(x) +func (m *ConfigBatchQueryResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + return xxx_messageInfo_ConfigBatchQueryResponse.Marshal(b, m, deterministic) } - -// Deprecated: Use ConfigBatchQueryResponse.ProtoReflect.Descriptor instead. -func (*ConfigBatchQueryResponse) Descriptor() ([]byte, []int) { - return file_config_file_response_proto_rawDescGZIP(), []int{3} +func (dst *ConfigBatchQueryResponse) XXX_Merge(src proto.Message) { + xxx_messageInfo_ConfigBatchQueryResponse.Merge(dst, src) +} +func (m *ConfigBatchQueryResponse) XXX_Size() int { + return xxx_messageInfo_ConfigBatchQueryResponse.Size(m) } +func (m *ConfigBatchQueryResponse) XXX_DiscardUnknown() { + xxx_messageInfo_ConfigBatchQueryResponse.DiscardUnknown(m) +} + +var xxx_messageInfo_ConfigBatchQueryResponse proto.InternalMessageInfo -func (x *ConfigBatchQueryResponse) GetCode() *wrappers.UInt32Value { - if x != nil { - return x.Code +func (m *ConfigBatchQueryResponse) GetCode() *wrappers.UInt32Value { + if m != nil { + return m.Code } return nil } -func (x *ConfigBatchQueryResponse) GetInfo() *wrappers.StringValue { - if x != nil { - return x.Info +func (m *ConfigBatchQueryResponse) GetInfo() *wrappers.StringValue { + if m != nil { + return m.Info } return nil } -func (x *ConfigBatchQueryResponse) GetTotal() *wrappers.UInt32Value { - if x != nil { - return x.Total +func (m *ConfigBatchQueryResponse) GetTotal() *wrappers.UInt32Value { + if m != nil { + return m.Total } return nil } -func (x *ConfigBatchQueryResponse) GetConfigFileGroups() []*ConfigFileGroup { - if x != nil { - return x.ConfigFileGroups +func (m *ConfigBatchQueryResponse) GetConfigFileGroups() []*ConfigFileGroup { + if m != nil { + return m.ConfigFileGroups } return nil } -func (x *ConfigBatchQueryResponse) GetConfigFiles() []*ConfigFile { - if x != nil { - return x.ConfigFiles +func (m *ConfigBatchQueryResponse) GetConfigFiles() []*ConfigFile { + if m != nil { + return m.ConfigFiles } return nil } -func (x *ConfigBatchQueryResponse) GetConfigFileReleases() []*ConfigFileRelease { - if x != nil { - return x.ConfigFileReleases +func (m *ConfigBatchQueryResponse) GetConfigFileReleases() []*ConfigFileRelease { + if m != nil { + return m.ConfigFileReleases } return nil } -func (x *ConfigBatchQueryResponse) GetConfigFileReleaseHistories() []*ConfigFileReleaseHistory { - if x != nil { - return x.ConfigFileReleaseHistories +func (m *ConfigBatchQueryResponse) GetConfigFileReleaseHistories() []*ConfigFileReleaseHistory { + if m != nil { + return m.ConfigFileReleaseHistories } return nil } -func (x *ConfigBatchQueryResponse) GetConfigFileTemplates() []*ConfigFileTemplate { - if x != nil { - return x.ConfigFileTemplates +func (m *ConfigBatchQueryResponse) GetConfigFileTemplates() []*ConfigFileTemplate { + if m != nil { + return m.ConfigFileTemplates } return nil } type ConfigClientResponse struct { - state protoimpl.MessageState - sizeCache protoimpl.SizeCache - unknownFields protoimpl.UnknownFields - - Code *wrappers.UInt32Value `protobuf:"bytes,1,opt,name=code,proto3" json:"code,omitempty"` - Info *wrappers.StringValue `protobuf:"bytes,2,opt,name=info,proto3" json:"info,omitempty"` - ConfigFile *ClientConfigFileInfo `protobuf:"bytes,3,opt,name=configFile,proto3" json:"configFile,omitempty"` + Code *wrappers.UInt32Value `protobuf:"bytes,1,opt,name=code,proto3" json:"code,omitempty"` + Info *wrappers.StringValue `protobuf:"bytes,2,opt,name=info,proto3" json:"info,omitempty"` + ConfigFile *ClientConfigFileInfo `protobuf:"bytes,3,opt,name=configFile,proto3" json:"configFile,omitempty"` + XXX_NoUnkeyedLiteral struct{} `json:"-"` + XXX_unrecognized []byte `json:"-"` + XXX_sizecache int32 `json:"-"` } -func (x *ConfigClientResponse) Reset() { - *x = ConfigClientResponse{} - if protoimpl.UnsafeEnabled { - mi := &file_config_file_response_proto_msgTypes[4] - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - ms.StoreMessageInfo(mi) - } +func (m *ConfigClientResponse) Reset() { *m = ConfigClientResponse{} } +func (m *ConfigClientResponse) String() string { return proto.CompactTextString(m) } +func (*ConfigClientResponse) ProtoMessage() {} +func (*ConfigClientResponse) Descriptor() ([]byte, []int) { + return fileDescriptor_config_file_response_1d88ce8660f9af44, []int{4} } - -func (x *ConfigClientResponse) String() string { - return protoimpl.X.MessageStringOf(x) +func (m *ConfigClientResponse) XXX_Unmarshal(b []byte) error { + return xxx_messageInfo_ConfigClientResponse.Unmarshal(m, b) } - -func (*ConfigClientResponse) ProtoMessage() {} - -func (x *ConfigClientResponse) ProtoReflect() protoreflect.Message { - mi := &file_config_file_response_proto_msgTypes[4] - if protoimpl.UnsafeEnabled && x != nil { - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - if ms.LoadMessageInfo() == nil { - ms.StoreMessageInfo(mi) - } - return ms - } - return mi.MessageOf(x) +func (m *ConfigClientResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + return xxx_messageInfo_ConfigClientResponse.Marshal(b, m, deterministic) } - -// Deprecated: Use ConfigClientResponse.ProtoReflect.Descriptor instead. -func (*ConfigClientResponse) Descriptor() ([]byte, []int) { - return file_config_file_response_proto_rawDescGZIP(), []int{4} +func (dst *ConfigClientResponse) XXX_Merge(src proto.Message) { + xxx_messageInfo_ConfigClientResponse.Merge(dst, src) +} +func (m *ConfigClientResponse) XXX_Size() int { + return xxx_messageInfo_ConfigClientResponse.Size(m) } +func (m *ConfigClientResponse) XXX_DiscardUnknown() { + xxx_messageInfo_ConfigClientResponse.DiscardUnknown(m) +} + +var xxx_messageInfo_ConfigClientResponse proto.InternalMessageInfo -func (x *ConfigClientResponse) GetCode() *wrappers.UInt32Value { - if x != nil { - return x.Code +func (m *ConfigClientResponse) GetCode() *wrappers.UInt32Value { + if m != nil { + return m.Code } return nil } -func (x *ConfigClientResponse) GetInfo() *wrappers.StringValue { - if x != nil { - return x.Info +func (m *ConfigClientResponse) GetInfo() *wrappers.StringValue { + if m != nil { + return m.Info } return nil } -func (x *ConfigClientResponse) GetConfigFile() *ClientConfigFileInfo { - if x != nil { - return x.ConfigFile +func (m *ConfigClientResponse) GetConfigFile() *ClientConfigFileInfo { + if m != nil { + return m.ConfigFile } return nil } -var File_config_file_response_proto protoreflect.FileDescriptor - -var file_config_file_response_proto_rawDesc = []byte{ - 0x0a, 0x1a, 0x63, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x5f, 0x66, 0x69, 0x6c, 0x65, 0x5f, 0x72, 0x65, - 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x12, 0x02, 0x76, 0x31, - 0x1a, 0x1e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2f, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, - 0x66, 0x2f, 0x77, 0x72, 0x61, 0x70, 0x70, 0x65, 0x72, 0x73, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, - 0x1a, 0x11, 0x63, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x5f, 0x66, 0x69, 0x6c, 0x65, 0x2e, 0x70, 0x72, - 0x6f, 0x74, 0x6f, 0x22, 0x7a, 0x0a, 0x14, 0x43, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x53, 0x69, 0x6d, - 0x70, 0x6c, 0x65, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x30, 0x0a, 0x04, 0x63, - 0x6f, 0x64, 0x65, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x1c, 0x2e, 0x67, 0x6f, 0x6f, 0x67, - 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x55, 0x49, 0x6e, 0x74, - 0x33, 0x32, 0x56, 0x61, 0x6c, 0x75, 0x65, 0x52, 0x04, 0x63, 0x6f, 0x64, 0x65, 0x12, 0x30, 0x0a, - 0x04, 0x69, 0x6e, 0x66, 0x6f, 0x18, 0x02, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x1c, 0x2e, 0x67, 0x6f, - 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x53, 0x74, - 0x72, 0x69, 0x6e, 0x67, 0x56, 0x61, 0x6c, 0x75, 0x65, 0x52, 0x04, 0x69, 0x6e, 0x66, 0x6f, 0x22, - 0xca, 0x03, 0x0a, 0x0e, 0x43, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, - 0x73, 0x65, 0x12, 0x30, 0x0a, 0x04, 0x63, 0x6f, 0x64, 0x65, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0b, - 0x32, 0x1c, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, - 0x75, 0x66, 0x2e, 0x55, 0x49, 0x6e, 0x74, 0x33, 0x32, 0x56, 0x61, 0x6c, 0x75, 0x65, 0x52, 0x04, - 0x63, 0x6f, 0x64, 0x65, 0x12, 0x30, 0x0a, 0x04, 0x69, 0x6e, 0x66, 0x6f, 0x18, 0x02, 0x20, 0x01, - 0x28, 0x0b, 0x32, 0x1c, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, - 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x53, 0x74, 0x72, 0x69, 0x6e, 0x67, 0x56, 0x61, 0x6c, 0x75, 0x65, - 0x52, 0x04, 0x69, 0x6e, 0x66, 0x6f, 0x12, 0x3d, 0x0a, 0x0f, 0x63, 0x6f, 0x6e, 0x66, 0x69, 0x67, - 0x46, 0x69, 0x6c, 0x65, 0x47, 0x72, 0x6f, 0x75, 0x70, 0x18, 0x03, 0x20, 0x01, 0x28, 0x0b, 0x32, - 0x13, 0x2e, 0x76, 0x31, 0x2e, 0x43, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x46, 0x69, 0x6c, 0x65, 0x47, - 0x72, 0x6f, 0x75, 0x70, 0x52, 0x0f, 0x63, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x46, 0x69, 0x6c, 0x65, - 0x47, 0x72, 0x6f, 0x75, 0x70, 0x12, 0x2e, 0x0a, 0x0a, 0x63, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x46, - 0x69, 0x6c, 0x65, 0x18, 0x04, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x0e, 0x2e, 0x76, 0x31, 0x2e, 0x43, - 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x46, 0x69, 0x6c, 0x65, 0x52, 0x0a, 0x63, 0x6f, 0x6e, 0x66, 0x69, - 0x67, 0x46, 0x69, 0x6c, 0x65, 0x12, 0x43, 0x0a, 0x11, 0x63, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x46, - 0x69, 0x6c, 0x65, 0x52, 0x65, 0x6c, 0x65, 0x61, 0x73, 0x65, 0x18, 0x05, 0x20, 0x01, 0x28, 0x0b, - 0x32, 0x15, 0x2e, 0x76, 0x31, 0x2e, 0x43, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x46, 0x69, 0x6c, 0x65, - 0x52, 0x65, 0x6c, 0x65, 0x61, 0x73, 0x65, 0x52, 0x11, 0x63, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x46, - 0x69, 0x6c, 0x65, 0x52, 0x65, 0x6c, 0x65, 0x61, 0x73, 0x65, 0x12, 0x58, 0x0a, 0x18, 0x63, 0x6f, - 0x6e, 0x66, 0x69, 0x67, 0x46, 0x69, 0x6c, 0x65, 0x52, 0x65, 0x6c, 0x65, 0x61, 0x73, 0x65, 0x48, - 0x69, 0x73, 0x74, 0x6f, 0x72, 0x79, 0x18, 0x06, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x1c, 0x2e, 0x76, - 0x31, 0x2e, 0x43, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x46, 0x69, 0x6c, 0x65, 0x52, 0x65, 0x6c, 0x65, - 0x61, 0x73, 0x65, 0x48, 0x69, 0x73, 0x74, 0x6f, 0x72, 0x79, 0x52, 0x18, 0x63, 0x6f, 0x6e, 0x66, - 0x69, 0x67, 0x46, 0x69, 0x6c, 0x65, 0x52, 0x65, 0x6c, 0x65, 0x61, 0x73, 0x65, 0x48, 0x69, 0x73, - 0x74, 0x6f, 0x72, 0x79, 0x12, 0x46, 0x0a, 0x12, 0x63, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x46, 0x69, - 0x6c, 0x65, 0x54, 0x65, 0x6d, 0x70, 0x6c, 0x61, 0x74, 0x65, 0x18, 0x07, 0x20, 0x01, 0x28, 0x0b, - 0x32, 0x16, 0x2e, 0x76, 0x31, 0x2e, 0x43, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x46, 0x69, 0x6c, 0x65, - 0x54, 0x65, 0x6d, 0x70, 0x6c, 0x61, 0x74, 0x65, 0x52, 0x12, 0x63, 0x6f, 0x6e, 0x66, 0x69, 0x67, - 0x46, 0x69, 0x6c, 0x65, 0x54, 0x65, 0x6d, 0x70, 0x6c, 0x61, 0x74, 0x65, 0x22, 0xe4, 0x01, 0x0a, - 0x18, 0x43, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x42, 0x61, 0x74, 0x63, 0x68, 0x57, 0x72, 0x69, 0x74, - 0x65, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x30, 0x0a, 0x04, 0x63, 0x6f, 0x64, - 0x65, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x1c, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, - 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x55, 0x49, 0x6e, 0x74, 0x33, 0x32, - 0x56, 0x61, 0x6c, 0x75, 0x65, 0x52, 0x04, 0x63, 0x6f, 0x64, 0x65, 0x12, 0x30, 0x0a, 0x04, 0x69, - 0x6e, 0x66, 0x6f, 0x18, 0x02, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x1c, 0x2e, 0x67, 0x6f, 0x6f, 0x67, - 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x53, 0x74, 0x72, 0x69, - 0x6e, 0x67, 0x56, 0x61, 0x6c, 0x75, 0x65, 0x52, 0x04, 0x69, 0x6e, 0x66, 0x6f, 0x12, 0x32, 0x0a, - 0x05, 0x74, 0x6f, 0x74, 0x61, 0x6c, 0x18, 0x03, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x1c, 0x2e, 0x67, - 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x55, - 0x49, 0x6e, 0x74, 0x33, 0x32, 0x56, 0x61, 0x6c, 0x75, 0x65, 0x52, 0x05, 0x74, 0x6f, 0x74, 0x61, - 0x6c, 0x12, 0x30, 0x0a, 0x09, 0x72, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x73, 0x18, 0x04, - 0x20, 0x03, 0x28, 0x0b, 0x32, 0x12, 0x2e, 0x76, 0x31, 0x2e, 0x43, 0x6f, 0x6e, 0x66, 0x69, 0x67, - 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x52, 0x09, 0x72, 0x65, 0x73, 0x70, 0x6f, 0x6e, - 0x73, 0x65, 0x73, 0x22, 0x94, 0x04, 0x0a, 0x18, 0x43, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x42, 0x61, - 0x74, 0x63, 0x68, 0x51, 0x75, 0x65, 0x72, 0x79, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, - 0x12, 0x30, 0x0a, 0x04, 0x63, 0x6f, 0x64, 0x65, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x1c, - 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, - 0x2e, 0x55, 0x49, 0x6e, 0x74, 0x33, 0x32, 0x56, 0x61, 0x6c, 0x75, 0x65, 0x52, 0x04, 0x63, 0x6f, - 0x64, 0x65, 0x12, 0x30, 0x0a, 0x04, 0x69, 0x6e, 0x66, 0x6f, 0x18, 0x02, 0x20, 0x01, 0x28, 0x0b, - 0x32, 0x1c, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, - 0x75, 0x66, 0x2e, 0x53, 0x74, 0x72, 0x69, 0x6e, 0x67, 0x56, 0x61, 0x6c, 0x75, 0x65, 0x52, 0x04, - 0x69, 0x6e, 0x66, 0x6f, 0x12, 0x32, 0x0a, 0x05, 0x74, 0x6f, 0x74, 0x61, 0x6c, 0x18, 0x03, 0x20, - 0x01, 0x28, 0x0b, 0x32, 0x1c, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, - 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x55, 0x49, 0x6e, 0x74, 0x33, 0x32, 0x56, 0x61, 0x6c, 0x75, - 0x65, 0x52, 0x05, 0x74, 0x6f, 0x74, 0x61, 0x6c, 0x12, 0x3f, 0x0a, 0x10, 0x63, 0x6f, 0x6e, 0x66, - 0x69, 0x67, 0x46, 0x69, 0x6c, 0x65, 0x47, 0x72, 0x6f, 0x75, 0x70, 0x73, 0x18, 0x04, 0x20, 0x03, - 0x28, 0x0b, 0x32, 0x13, 0x2e, 0x76, 0x31, 0x2e, 0x43, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x46, 0x69, - 0x6c, 0x65, 0x47, 0x72, 0x6f, 0x75, 0x70, 0x52, 0x10, 0x63, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x46, - 0x69, 0x6c, 0x65, 0x47, 0x72, 0x6f, 0x75, 0x70, 0x73, 0x12, 0x30, 0x0a, 0x0b, 0x63, 0x6f, 0x6e, - 0x66, 0x69, 0x67, 0x46, 0x69, 0x6c, 0x65, 0x73, 0x18, 0x05, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x0e, - 0x2e, 0x76, 0x31, 0x2e, 0x43, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x46, 0x69, 0x6c, 0x65, 0x52, 0x0b, - 0x63, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x46, 0x69, 0x6c, 0x65, 0x73, 0x12, 0x45, 0x0a, 0x12, 0x63, - 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x46, 0x69, 0x6c, 0x65, 0x52, 0x65, 0x6c, 0x65, 0x61, 0x73, 0x65, - 0x73, 0x18, 0x06, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x15, 0x2e, 0x76, 0x31, 0x2e, 0x43, 0x6f, 0x6e, - 0x66, 0x69, 0x67, 0x46, 0x69, 0x6c, 0x65, 0x52, 0x65, 0x6c, 0x65, 0x61, 0x73, 0x65, 0x52, 0x12, - 0x63, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x46, 0x69, 0x6c, 0x65, 0x52, 0x65, 0x6c, 0x65, 0x61, 0x73, - 0x65, 0x73, 0x12, 0x5c, 0x0a, 0x1a, 0x63, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x46, 0x69, 0x6c, 0x65, - 0x52, 0x65, 0x6c, 0x65, 0x61, 0x73, 0x65, 0x48, 0x69, 0x73, 0x74, 0x6f, 0x72, 0x69, 0x65, 0x73, - 0x18, 0x07, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x1c, 0x2e, 0x76, 0x31, 0x2e, 0x43, 0x6f, 0x6e, 0x66, - 0x69, 0x67, 0x46, 0x69, 0x6c, 0x65, 0x52, 0x65, 0x6c, 0x65, 0x61, 0x73, 0x65, 0x48, 0x69, 0x73, - 0x74, 0x6f, 0x72, 0x79, 0x52, 0x1a, 0x63, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x46, 0x69, 0x6c, 0x65, - 0x52, 0x65, 0x6c, 0x65, 0x61, 0x73, 0x65, 0x48, 0x69, 0x73, 0x74, 0x6f, 0x72, 0x69, 0x65, 0x73, - 0x12, 0x48, 0x0a, 0x13, 0x63, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x46, 0x69, 0x6c, 0x65, 0x54, 0x65, - 0x6d, 0x70, 0x6c, 0x61, 0x74, 0x65, 0x73, 0x18, 0x08, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x16, 0x2e, - 0x76, 0x31, 0x2e, 0x43, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x46, 0x69, 0x6c, 0x65, 0x54, 0x65, 0x6d, - 0x70, 0x6c, 0x61, 0x74, 0x65, 0x52, 0x13, 0x63, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x46, 0x69, 0x6c, - 0x65, 0x54, 0x65, 0x6d, 0x70, 0x6c, 0x61, 0x74, 0x65, 0x73, 0x22, 0xb4, 0x01, 0x0a, 0x14, 0x43, - 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x43, 0x6c, 0x69, 0x65, 0x6e, 0x74, 0x52, 0x65, 0x73, 0x70, 0x6f, - 0x6e, 0x73, 0x65, 0x12, 0x30, 0x0a, 0x04, 0x63, 0x6f, 0x64, 0x65, 0x18, 0x01, 0x20, 0x01, 0x28, - 0x0b, 0x32, 0x1c, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, - 0x62, 0x75, 0x66, 0x2e, 0x55, 0x49, 0x6e, 0x74, 0x33, 0x32, 0x56, 0x61, 0x6c, 0x75, 0x65, 0x52, - 0x04, 0x63, 0x6f, 0x64, 0x65, 0x12, 0x30, 0x0a, 0x04, 0x69, 0x6e, 0x66, 0x6f, 0x18, 0x02, 0x20, - 0x01, 0x28, 0x0b, 0x32, 0x1c, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, - 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x53, 0x74, 0x72, 0x69, 0x6e, 0x67, 0x56, 0x61, 0x6c, 0x75, - 0x65, 0x52, 0x04, 0x69, 0x6e, 0x66, 0x6f, 0x12, 0x38, 0x0a, 0x0a, 0x63, 0x6f, 0x6e, 0x66, 0x69, - 0x67, 0x46, 0x69, 0x6c, 0x65, 0x18, 0x03, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x18, 0x2e, 0x76, 0x31, - 0x2e, 0x43, 0x6c, 0x69, 0x65, 0x6e, 0x74, 0x43, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x46, 0x69, 0x6c, - 0x65, 0x49, 0x6e, 0x66, 0x6f, 0x52, 0x0a, 0x63, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x46, 0x69, 0x6c, - 0x65, 0x42, 0x05, 0x5a, 0x03, 0x2f, 0x76, 0x31, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33, -} - -var ( - file_config_file_response_proto_rawDescOnce sync.Once - file_config_file_response_proto_rawDescData = file_config_file_response_proto_rawDesc -) - -func file_config_file_response_proto_rawDescGZIP() []byte { - file_config_file_response_proto_rawDescOnce.Do(func() { - file_config_file_response_proto_rawDescData = protoimpl.X.CompressGZIP(file_config_file_response_proto_rawDescData) - }) - return file_config_file_response_proto_rawDescData -} - -var file_config_file_response_proto_msgTypes = make([]protoimpl.MessageInfo, 5) -var file_config_file_response_proto_goTypes = []interface{}{ - (*ConfigSimpleResponse)(nil), // 0: v1.ConfigSimpleResponse - (*ConfigResponse)(nil), // 1: v1.ConfigResponse - (*ConfigBatchWriteResponse)(nil), // 2: v1.ConfigBatchWriteResponse - (*ConfigBatchQueryResponse)(nil), // 3: v1.ConfigBatchQueryResponse - (*ConfigClientResponse)(nil), // 4: v1.ConfigClientResponse - (*wrappers.UInt32Value)(nil), // 5: google.protobuf.UInt32Value - (*wrappers.StringValue)(nil), // 6: google.protobuf.StringValue - (*ConfigFileGroup)(nil), // 7: v1.ConfigFileGroup - (*ConfigFile)(nil), // 8: v1.ConfigFile - (*ConfigFileRelease)(nil), // 9: v1.ConfigFileRelease - (*ConfigFileReleaseHistory)(nil), // 10: v1.ConfigFileReleaseHistory - (*ConfigFileTemplate)(nil), // 11: v1.ConfigFileTemplate - (*ClientConfigFileInfo)(nil), // 12: v1.ClientConfigFileInfo -} -var file_config_file_response_proto_depIdxs = []int32{ - 5, // 0: v1.ConfigSimpleResponse.code:type_name -> google.protobuf.UInt32Value - 6, // 1: v1.ConfigSimpleResponse.info:type_name -> google.protobuf.StringValue - 5, // 2: v1.ConfigResponse.code:type_name -> google.protobuf.UInt32Value - 6, // 3: v1.ConfigResponse.info:type_name -> google.protobuf.StringValue - 7, // 4: v1.ConfigResponse.configFileGroup:type_name -> v1.ConfigFileGroup - 8, // 5: v1.ConfigResponse.configFile:type_name -> v1.ConfigFile - 9, // 6: v1.ConfigResponse.configFileRelease:type_name -> v1.ConfigFileRelease - 10, // 7: v1.ConfigResponse.configFileReleaseHistory:type_name -> v1.ConfigFileReleaseHistory - 11, // 8: v1.ConfigResponse.configFileTemplate:type_name -> v1.ConfigFileTemplate - 5, // 9: v1.ConfigBatchWriteResponse.code:type_name -> google.protobuf.UInt32Value - 6, // 10: v1.ConfigBatchWriteResponse.info:type_name -> google.protobuf.StringValue - 5, // 11: v1.ConfigBatchWriteResponse.total:type_name -> google.protobuf.UInt32Value - 1, // 12: v1.ConfigBatchWriteResponse.responses:type_name -> v1.ConfigResponse - 5, // 13: v1.ConfigBatchQueryResponse.code:type_name -> google.protobuf.UInt32Value - 6, // 14: v1.ConfigBatchQueryResponse.info:type_name -> google.protobuf.StringValue - 5, // 15: v1.ConfigBatchQueryResponse.total:type_name -> google.protobuf.UInt32Value - 7, // 16: v1.ConfigBatchQueryResponse.configFileGroups:type_name -> v1.ConfigFileGroup - 8, // 17: v1.ConfigBatchQueryResponse.configFiles:type_name -> v1.ConfigFile - 9, // 18: v1.ConfigBatchQueryResponse.configFileReleases:type_name -> v1.ConfigFileRelease - 10, // 19: v1.ConfigBatchQueryResponse.configFileReleaseHistories:type_name -> v1.ConfigFileReleaseHistory - 11, // 20: v1.ConfigBatchQueryResponse.configFileTemplates:type_name -> v1.ConfigFileTemplate - 5, // 21: v1.ConfigClientResponse.code:type_name -> google.protobuf.UInt32Value - 6, // 22: v1.ConfigClientResponse.info:type_name -> google.protobuf.StringValue - 12, // 23: v1.ConfigClientResponse.configFile:type_name -> v1.ClientConfigFileInfo - 24, // [24:24] is the sub-list for method output_type - 24, // [24:24] is the sub-list for method input_type - 24, // [24:24] is the sub-list for extension type_name - 24, // [24:24] is the sub-list for extension extendee - 0, // [0:24] is the sub-list for field type_name -} - -func init() { file_config_file_response_proto_init() } -func file_config_file_response_proto_init() { - if File_config_file_response_proto != nil { - return - } - file_config_file_proto_init() - if !protoimpl.UnsafeEnabled { - file_config_file_response_proto_msgTypes[0].Exporter = func(v interface{}, i int) interface{} { - switch v := v.(*ConfigSimpleResponse); i { - case 0: - return &v.state - case 1: - return &v.sizeCache - case 2: - return &v.unknownFields - default: - return nil - } - } - file_config_file_response_proto_msgTypes[1].Exporter = func(v interface{}, i int) interface{} { - switch v := v.(*ConfigResponse); i { - case 0: - return &v.state - case 1: - return &v.sizeCache - case 2: - return &v.unknownFields - default: - return nil - } - } - file_config_file_response_proto_msgTypes[2].Exporter = func(v interface{}, i int) interface{} { - switch v := v.(*ConfigBatchWriteResponse); i { - case 0: - return &v.state - case 1: - return &v.sizeCache - case 2: - return &v.unknownFields - default: - return nil - } - } - file_config_file_response_proto_msgTypes[3].Exporter = func(v interface{}, i int) interface{} { - switch v := v.(*ConfigBatchQueryResponse); i { - case 0: - return &v.state - case 1: - return &v.sizeCache - case 2: - return &v.unknownFields - default: - return nil - } - } - file_config_file_response_proto_msgTypes[4].Exporter = func(v interface{}, i int) interface{} { - switch v := v.(*ConfigClientResponse); i { - case 0: - return &v.state - case 1: - return &v.sizeCache - case 2: - return &v.unknownFields - default: - return nil - } - } - } - type x struct{} - out := protoimpl.TypeBuilder{ - File: protoimpl.DescBuilder{ - GoPackagePath: reflect.TypeOf(x{}).PkgPath(), - RawDescriptor: file_config_file_response_proto_rawDesc, - NumEnums: 0, - NumMessages: 5, - NumExtensions: 0, - NumServices: 0, - }, - GoTypes: file_config_file_response_proto_goTypes, - DependencyIndexes: file_config_file_response_proto_depIdxs, - MessageInfos: file_config_file_response_proto_msgTypes, - }.Build() - File_config_file_response_proto = out.File - file_config_file_response_proto_rawDesc = nil - file_config_file_response_proto_goTypes = nil - file_config_file_response_proto_depIdxs = nil +func init() { + proto.RegisterType((*ConfigSimpleResponse)(nil), "v1.ConfigSimpleResponse") + proto.RegisterType((*ConfigResponse)(nil), "v1.ConfigResponse") + proto.RegisterType((*ConfigBatchWriteResponse)(nil), "v1.ConfigBatchWriteResponse") + proto.RegisterType((*ConfigBatchQueryResponse)(nil), "v1.ConfigBatchQueryResponse") + proto.RegisterType((*ConfigClientResponse)(nil), "v1.ConfigClientResponse") +} + +func init() { + proto.RegisterFile("config_file_response.proto", fileDescriptor_config_file_response_1d88ce8660f9af44) +} + +var fileDescriptor_config_file_response_1d88ce8660f9af44 = []byte{ + // 468 bytes of a gzipped FileDescriptorProto + 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xcc, 0x94, 0xdf, 0x6e, 0xd3, 0x30, + 0x14, 0xc6, 0xd5, 0x36, 0xed, 0xe0, 0x54, 0x1a, 0xcc, 0x03, 0x64, 0x55, 0x08, 0x4d, 0xb9, 0xda, + 0x55, 0xd6, 0x76, 0x37, 0xdc, 0x20, 0xa4, 0x55, 0x8c, 0xed, 0x12, 0x8f, 0x7f, 0x42, 0x48, 0x53, + 0x56, 0x4e, 0x82, 0x25, 0x2f, 0x8e, 0x6c, 0xa7, 0x68, 0x3c, 0x07, 0x8f, 0xc2, 0x53, 0xf0, 0x1c, + 0x3c, 0x08, 0x9a, 0x9d, 0x28, 0xff, 0x7b, 0x59, 0x71, 0x99, 0x73, 0xbe, 0xdf, 0x67, 0x9f, 0xe4, + 0xcb, 0x81, 0xd9, 0x5a, 0x26, 0x11, 0x8f, 0xaf, 0x23, 0x2e, 0xf0, 0x5a, 0xa1, 0x4e, 0x65, 0xa2, + 0x31, 0x48, 0x95, 0x34, 0x92, 0x0c, 0x37, 0x8b, 0xd9, 0x8b, 0x58, 0xca, 0x58, 0xe0, 0x89, 0xad, + 0xdc, 0x64, 0xd1, 0xc9, 0x0f, 0x15, 0xa6, 0x29, 0x2a, 0xed, 0x34, 0xb3, 0x83, 0x0a, 0xef, 0x4a, + 0xfe, 0x4f, 0x78, 0xb2, 0xb2, 0xc5, 0x2b, 0x7e, 0x9b, 0x0a, 0x64, 0xb9, 0x29, 0x99, 0x83, 0xb7, + 0x96, 0xdf, 0x90, 0x0e, 0x8e, 0x06, 0xc7, 0xd3, 0xe5, 0xf3, 0xc0, 0x39, 0x07, 0x85, 0x73, 0xf0, + 0xe1, 0x32, 0x31, 0xa7, 0xcb, 0x8f, 0xa1, 0xc8, 0x90, 0x59, 0xe5, 0x3d, 0xc1, 0x93, 0x48, 0xd2, + 0x61, 0x0f, 0x71, 0x65, 0x14, 0x4f, 0xe2, 0x9c, 0xb8, 0x57, 0xfa, 0x7f, 0x46, 0xb0, 0xef, 0x0e, + 0xdf, 0xe5, 0xb1, 0xe4, 0x15, 0x3c, 0x72, 0xef, 0xe1, 0x9c, 0x0b, 0x7c, 0xab, 0x64, 0x96, 0xd2, + 0x91, 0x85, 0x0f, 0x83, 0xcd, 0x22, 0x58, 0xd5, 0x5b, 0xac, 0xa9, 0x25, 0x01, 0x40, 0x59, 0xa2, + 0x9e, 0x25, 0xf7, 0xeb, 0x24, 0xab, 0x28, 0xc8, 0x0a, 0x0e, 0xca, 0x27, 0x86, 0x02, 0x43, 0x8d, + 0x74, 0x6c, 0xb1, 0xa7, 0x0d, 0xcc, 0x35, 0x59, 0x5b, 0x4f, 0x3e, 0x03, 0x6d, 0x15, 0x2f, 0xb8, + 0x36, 0x52, 0xdd, 0xd1, 0x49, 0x3e, 0x79, 0x97, 0x57, 0xae, 0x61, 0xbd, 0x34, 0x39, 0x07, 0x52, + 0xf6, 0xde, 0xe3, 0x6d, 0x2a, 0x42, 0x83, 0x74, 0xcf, 0x7a, 0x3e, 0xab, 0x7b, 0x16, 0x5d, 0xd6, + 0x41, 0xf8, 0x7f, 0x07, 0x40, 0x9d, 0xf4, 0x2c, 0x34, 0xeb, 0xef, 0x9f, 0x14, 0x37, 0x3b, 0x4d, + 0x13, 0x59, 0xc2, 0xd8, 0x48, 0x13, 0x8a, 0xfc, 0x63, 0x6e, 0x3f, 0xc4, 0x49, 0xc9, 0x1c, 0x1e, + 0x16, 0xbf, 0x91, 0xa6, 0xde, 0xd1, 0xe8, 0x78, 0xba, 0x24, 0xe5, 0xcc, 0xc5, 0xf5, 0x59, 0x29, + 0xf2, 0x7f, 0x79, 0xb5, 0x31, 0xdf, 0x65, 0xa8, 0xee, 0xfe, 0xfb, 0x31, 0x5f, 0xc3, 0xe3, 0x46, + 0x8a, 0x8b, 0x69, 0x3b, 0x23, 0xdf, 0x12, 0x93, 0x39, 0x4c, 0xcb, 0x9a, 0xa6, 0x63, 0xcb, 0x36, + 0x43, 0x5f, 0x95, 0x90, 0x37, 0xd5, 0x58, 0xe5, 0x91, 0xd3, 0x74, 0x62, 0xc1, 0x9e, 0xd8, 0x77, + 0x00, 0xe4, 0x6b, 0xb1, 0xf3, 0x5a, 0xc9, 0xe5, 0xa8, 0xe9, 0x9e, 0xb5, 0xdb, 0x9e, 0xfc, 0x2d, + 0x3c, 0xb9, 0x80, 0xc3, 0x76, 0x92, 0x35, 0x7d, 0x60, 0x6d, 0xfb, 0xc2, 0xdf, 0x85, 0xf8, 0xbf, + 0x07, 0xc5, 0x1e, 0x5d, 0x09, 0x8e, 0x89, 0xd9, 0x69, 0x24, 0x5e, 0xd6, 0x36, 0x92, 0xcb, 0x05, + 0xb5, 0xb7, 0xb7, 0x77, 0x29, 0x67, 0xb8, 0x4c, 0x22, 0x59, 0xdd, 0x4d, 0x67, 0xde, 0x97, 0xe1, + 0x66, 0x71, 0x33, 0xb1, 0xde, 0xa7, 0xff, 0x02, 0x00, 0x00, 0xff, 0xff, 0x8c, 0x1f, 0x83, 0x12, + 0x5f, 0x06, 0x00, 0x00, } diff --git a/common/api/v1/model.pb.go b/common/api/v1/model.pb.go index f1e6d2a6e..e49e7a379 100644 --- a/common/api/v1/model.pb.go +++ b/common/api/v1/model.pb.go @@ -53,7 +53,7 @@ func (x MatchString_MatchStringType) String() string { return proto.EnumName(MatchString_MatchStringType_name, int32(x)) } func (MatchString_MatchStringType) EnumDescriptor() ([]byte, []int) { - return fileDescriptor_model_99674f3804a5acf0, []int{1, 0} + return fileDescriptor_model_5147fed3aedd1f0a, []int{1, 0} } type MatchString_ValueType int32 @@ -79,7 +79,7 @@ func (x MatchString_ValueType) String() string { return proto.EnumName(MatchString_ValueType_name, int32(x)) } func (MatchString_ValueType) EnumDescriptor() ([]byte, []int) { - return fileDescriptor_model_99674f3804a5acf0, []int{1, 1} + return fileDescriptor_model_5147fed3aedd1f0a, []int{1, 1} } type Location struct { @@ -95,7 +95,7 @@ func (m *Location) Reset() { *m = Location{} } func (m *Location) String() string { return proto.CompactTextString(m) } func (*Location) ProtoMessage() {} func (*Location) Descriptor() ([]byte, []int) { - return fileDescriptor_model_99674f3804a5acf0, []int{0} + return fileDescriptor_model_5147fed3aedd1f0a, []int{0} } func (m *Location) XXX_Unmarshal(b []byte) error { return xxx_messageInfo_Location.Unmarshal(m, b) @@ -149,7 +149,7 @@ func (m *MatchString) Reset() { *m = MatchString{} } func (m *MatchString) String() string { return proto.CompactTextString(m) } func (*MatchString) ProtoMessage() {} func (*MatchString) Descriptor() ([]byte, []int) { - return fileDescriptor_model_99674f3804a5acf0, []int{1} + return fileDescriptor_model_5147fed3aedd1f0a, []int{1} } func (m *MatchString) XXX_Unmarshal(b []byte) error { return xxx_messageInfo_MatchString.Unmarshal(m, b) @@ -190,40 +190,40 @@ func (m *MatchString) GetValueType() MatchString_ValueType { return MatchString_TEXT } -type OptionSwitch struct { - Options map[string]string `protobuf:"bytes,1,rep,name=options,proto3" json:"options,omitempty" protobuf_key:"bytes,1,opt,name=key,proto3" protobuf_val:"bytes,2,opt,name=value,proto3"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` +type StringList struct { + Values []string `protobuf:"bytes,1,rep,name=values,proto3" json:"values,omitempty"` + XXX_NoUnkeyedLiteral struct{} `json:"-"` + XXX_unrecognized []byte `json:"-"` + XXX_sizecache int32 `json:"-"` } -func (m *OptionSwitch) Reset() { *m = OptionSwitch{} } -func (m *OptionSwitch) String() string { return proto.CompactTextString(m) } -func (*OptionSwitch) ProtoMessage() {} -func (*OptionSwitch) Descriptor() ([]byte, []int) { - return fileDescriptor_model_99674f3804a5acf0, []int{2} +func (m *StringList) Reset() { *m = StringList{} } +func (m *StringList) String() string { return proto.CompactTextString(m) } +func (*StringList) ProtoMessage() {} +func (*StringList) Descriptor() ([]byte, []int) { + return fileDescriptor_model_5147fed3aedd1f0a, []int{2} } -func (m *OptionSwitch) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_OptionSwitch.Unmarshal(m, b) +func (m *StringList) XXX_Unmarshal(b []byte) error { + return xxx_messageInfo_StringList.Unmarshal(m, b) } -func (m *OptionSwitch) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_OptionSwitch.Marshal(b, m, deterministic) +func (m *StringList) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + return xxx_messageInfo_StringList.Marshal(b, m, deterministic) } -func (dst *OptionSwitch) XXX_Merge(src proto.Message) { - xxx_messageInfo_OptionSwitch.Merge(dst, src) +func (dst *StringList) XXX_Merge(src proto.Message) { + xxx_messageInfo_StringList.Merge(dst, src) } -func (m *OptionSwitch) XXX_Size() int { - return xxx_messageInfo_OptionSwitch.Size(m) +func (m *StringList) XXX_Size() int { + return xxx_messageInfo_StringList.Size(m) } -func (m *OptionSwitch) XXX_DiscardUnknown() { - xxx_messageInfo_OptionSwitch.DiscardUnknown(m) +func (m *StringList) XXX_DiscardUnknown() { + xxx_messageInfo_StringList.DiscardUnknown(m) } -var xxx_messageInfo_OptionSwitch proto.InternalMessageInfo +var xxx_messageInfo_StringList proto.InternalMessageInfo -func (m *OptionSwitch) GetOptions() map[string]string { +func (m *StringList) GetValues() []string { if m != nil { - return m.Options + return m.Values } return nil } @@ -231,39 +231,35 @@ func (m *OptionSwitch) GetOptions() map[string]string { func init() { proto.RegisterType((*Location)(nil), "v1.Location") proto.RegisterType((*MatchString)(nil), "v1.MatchString") - proto.RegisterType((*OptionSwitch)(nil), "v1.OptionSwitch") - proto.RegisterMapType((map[string]string)(nil), "v1.OptionSwitch.OptionsEntry") + proto.RegisterType((*StringList)(nil), "v1.StringList") proto.RegisterEnum("v1.MatchString_MatchStringType", MatchString_MatchStringType_name, MatchString_MatchStringType_value) proto.RegisterEnum("v1.MatchString_ValueType", MatchString_ValueType_name, MatchString_ValueType_value) } -func init() { proto.RegisterFile("model.proto", fileDescriptor_model_99674f3804a5acf0) } +func init() { proto.RegisterFile("model.proto", fileDescriptor_model_5147fed3aedd1f0a) } -var fileDescriptor_model_99674f3804a5acf0 = []byte{ - // 392 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x8c, 0x91, 0x4f, 0x6f, 0x9b, 0x40, - 0x10, 0xc5, 0xbb, 0x40, 0xa8, 0x19, 0xd2, 0x74, 0xb5, 0xea, 0x81, 0x46, 0xfd, 0x13, 0x71, 0xca, - 0x89, 0x34, 0xa4, 0x52, 0xa3, 0xdc, 0x68, 0xb5, 0xaa, 0xac, 0xfa, 0x4f, 0xbb, 0xa6, 0x96, 0x6f, - 0x16, 0xa6, 0x5b, 0x8c, 0x6a, 0xb3, 0x08, 0x30, 0x16, 0xbd, 0xf6, 0xcb, 0xf4, 0xda, 0x6f, 0x58, - 0xed, 0x62, 0x22, 0xe4, 0x93, 0x6f, 0x6f, 0x67, 0x7e, 0x33, 0x6f, 0x78, 0x80, 0xbd, 0x15, 0x3f, - 0xf8, 0xc6, 0xcb, 0x0b, 0x51, 0x09, 0xa2, 0xd5, 0xb7, 0x97, 0x6f, 0x12, 0x21, 0x92, 0x0d, 0xbf, - 0x51, 0x95, 0xd5, 0xee, 0xe7, 0xcd, 0xbe, 0x88, 0xf2, 0x9c, 0x17, 0x65, 0xcb, 0xb8, 0x7f, 0x11, - 0x0c, 0x46, 0x22, 0x8e, 0xaa, 0x54, 0x64, 0xe4, 0x3d, 0x98, 0x05, 0x4f, 0x52, 0x91, 0x39, 0xe8, - 0x0a, 0x5d, 0xdb, 0xfe, 0x2b, 0xaf, 0x9d, 0xf6, 0xba, 0x69, 0x6f, 0x56, 0x15, 0x69, 0x96, 0xcc, - 0xa3, 0xcd, 0x8e, 0xb3, 0x03, 0x4b, 0xde, 0x81, 0xf1, 0x5b, 0x64, 0xdc, 0xd1, 0x4e, 0x98, 0x51, - 0xa4, 0xf4, 0x89, 0xa3, 0x6d, 0xbe, 0x2b, 0x1d, 0xfd, 0x14, 0x9f, 0x96, 0x75, 0xff, 0x69, 0x60, - 0x8f, 0xa3, 0x2a, 0x5e, 0xb7, 0x4d, 0x72, 0x07, 0x46, 0xd5, 0xe4, 0x5c, 0xdd, 0x7a, 0xe1, 0xbf, - 0xf5, 0xea, 0x5b, 0xaf, 0xd7, 0xee, 0xeb, 0xb0, 0xc9, 0x39, 0x53, 0x30, 0xf1, 0xe1, 0xac, 0x96, - 0x5b, 0x4f, 0xba, 0xb6, 0x45, 0xc9, 0x3d, 0x80, 0x12, 0x4b, 0x65, 0xa7, 0x2b, 0xbb, 0x97, 0xc7, - 0x76, 0x6a, 0x42, 0x19, 0x59, 0x75, 0x27, 0xdd, 0x2f, 0xf0, 0xfc, 0xe8, 0x0c, 0x62, 0xc1, 0x19, - 0x5d, 0x04, 0x9f, 0x42, 0xfc, 0x44, 0x4a, 0x46, 0x3f, 0xd3, 0x05, 0x46, 0xe4, 0x02, 0x60, 0x32, - 0x0d, 0x97, 0xf4, 0xdb, 0xf7, 0x60, 0x34, 0xc3, 0x1a, 0x31, 0x41, 0x1b, 0x4e, 0xb0, 0x4e, 0x00, - 0x4c, 0x59, 0x1f, 0x4e, 0xb0, 0xe1, 0xfa, 0x60, 0x3d, 0x9a, 0x90, 0x01, 0x18, 0x21, 0x5d, 0xc8, - 0x2d, 0xcf, 0xc0, 0xfa, 0x1a, 0xb0, 0x60, 0x4c, 0x43, 0xca, 0x30, 0x22, 0xe7, 0x30, 0x98, 0x07, - 0x6c, 0x18, 0x7c, 0x1c, 0x51, 0xac, 0xb9, 0x7f, 0x10, 0x9c, 0x4f, 0x73, 0xf9, 0x73, 0x67, 0xfb, - 0xb4, 0x8a, 0xd7, 0xe4, 0x03, 0x3c, 0x15, 0xea, 0x5d, 0x3a, 0xe8, 0x4a, 0xbf, 0xb6, 0xfd, 0xd7, - 0xf2, 0x43, 0xfa, 0xc8, 0xe1, 0x51, 0xd2, 0xac, 0x2a, 0x1a, 0xd6, 0xd1, 0x97, 0x0f, 0xdd, 0xa2, - 0xb6, 0x41, 0x30, 0xe8, 0xbf, 0x78, 0xa3, 0xc2, 0xb7, 0x98, 0x94, 0xe4, 0x45, 0x3f, 0x5a, 0xeb, - 0x10, 0xde, 0x83, 0x76, 0x8f, 0x56, 0xa6, 0x4a, 0xf7, 0xee, 0x7f, 0x00, 0x00, 0x00, 0xff, 0xff, - 0xc4, 0xee, 0xf2, 0x16, 0x9e, 0x02, 0x00, 0x00, +var fileDescriptor_model_5147fed3aedd1f0a = []byte{ + // 341 bytes of a gzipped FileDescriptorProto + 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x8c, 0x8f, 0xcf, 0x4e, 0xf2, 0x40, + 0x14, 0xc5, 0xbf, 0xfe, 0xa1, 0xa1, 0x97, 0x4f, 0x6c, 0xee, 0xc2, 0x54, 0x63, 0x94, 0x34, 0x2e, + 0x58, 0x15, 0x29, 0x2e, 0xdc, 0x56, 0x33, 0x31, 0xc4, 0x82, 0x3a, 0x54, 0xc2, 0x8e, 0x14, 0x1c, + 0x6b, 0x13, 0xe8, 0x34, 0x6d, 0xa9, 0xc1, 0x27, 0x72, 0xeb, 0x1b, 0x9a, 0x4e, 0xc1, 0x10, 0x56, + 0xec, 0xce, 0xdc, 0x7b, 0xce, 0xfd, 0x9d, 0x81, 0xc6, 0x92, 0xbf, 0xb1, 0x85, 0x9d, 0xa4, 0x3c, + 0xe7, 0x28, 0x17, 0xdd, 0xb3, 0x8b, 0x90, 0xf3, 0x70, 0xc1, 0x3a, 0x62, 0x32, 0x5b, 0xbd, 0x77, + 0x3e, 0xd3, 0x20, 0x49, 0x58, 0x9a, 0x55, 0x1e, 0xeb, 0x5b, 0x82, 0xba, 0xc7, 0xe7, 0x41, 0x1e, + 0xf1, 0x18, 0x6f, 0x40, 0x4b, 0x59, 0x18, 0xf1, 0xd8, 0x94, 0x5a, 0x52, 0xbb, 0xe1, 0x9c, 0xdb, + 0x55, 0xda, 0xde, 0xa6, 0xed, 0x51, 0x9e, 0x46, 0x71, 0x38, 0x0e, 0x16, 0x2b, 0x46, 0x37, 0x5e, + 0xbc, 0x06, 0xf5, 0x8b, 0xc7, 0xcc, 0x94, 0x0f, 0xc8, 0x08, 0x67, 0xc9, 0x99, 0x07, 0xcb, 0x64, + 0x95, 0x99, 0xca, 0x21, 0x9c, 0xca, 0x6b, 0xfd, 0xc8, 0xd0, 0x18, 0x04, 0xf9, 0xfc, 0xa3, 0x5a, + 0x62, 0x0f, 0xd4, 0x7c, 0x9d, 0x30, 0xd1, 0xb5, 0xe9, 0x5c, 0xda, 0x45, 0xd7, 0xde, 0x59, 0xef, + 0x6a, 0x7f, 0x9d, 0x30, 0x2a, 0xcc, 0xe8, 0x40, 0xad, 0x28, 0xaf, 0x1e, 0xd4, 0xb6, 0xb2, 0xe2, + 0x2d, 0x80, 0x10, 0x53, 0x81, 0x53, 0x04, 0xee, 0x74, 0x1f, 0x27, 0x12, 0x02, 0xa4, 0x17, 0x5b, + 0x69, 0x3d, 0xc2, 0xf1, 0x5e, 0x0d, 0xd4, 0xa1, 0x46, 0x26, 0xee, 0xbd, 0x6f, 0xfc, 0x2b, 0x25, + 0x25, 0x0f, 0x64, 0x62, 0x48, 0xd8, 0x04, 0x18, 0x3e, 0xf9, 0x53, 0xf2, 0xf2, 0xea, 0x7a, 0x23, + 0x43, 0x46, 0x0d, 0xe4, 0xfe, 0xd0, 0x50, 0x10, 0x40, 0x2b, 0xe7, 0xfd, 0xa1, 0xa1, 0x5a, 0x0e, + 0xe8, 0x7f, 0x10, 0xac, 0x83, 0xea, 0x93, 0x49, 0x79, 0xe5, 0x08, 0xf4, 0x67, 0x97, 0xba, 0x03, + 0xe2, 0x13, 0x6a, 0x48, 0xf8, 0x1f, 0xea, 0x63, 0x97, 0xf6, 0xdd, 0x3b, 0x8f, 0x18, 0xb2, 0x75, + 0x05, 0x50, 0xb1, 0xbd, 0x28, 0xcb, 0xf1, 0x04, 0x34, 0xd1, 0x2d, 0x33, 0xa5, 0x96, 0xd2, 0xd6, + 0xe9, 0xe6, 0x35, 0xd3, 0xc4, 0xef, 0x7b, 0xbf, 0x01, 0x00, 0x00, 0xff, 0xff, 0xd1, 0x6f, 0xe9, + 0x65, 0x3e, 0x02, 0x00, 0x00, } diff --git a/common/api/v1/model.proto b/common/api/v1/model.proto index 22dc86d19..2ce1e14b0 100644 --- a/common/api/v1/model.proto +++ b/common/api/v1/model.proto @@ -36,6 +36,6 @@ message MatchString { } -message OptionSwitch { - map options = 1; +message StringList { + repeated string values = 1; } diff --git a/common/api/v1/request.proto b/common/api/v1/request.proto index dfc122bf7..18afe7227 100644 --- a/common/api/v1/request.proto +++ b/common/api/v1/request.proto @@ -21,3 +21,4 @@ message DiscoverRequest { Service service = 2; reserved 3 to 4; } + diff --git a/common/api/v1/response.go b/common/api/v1/response.go index 0cf8100d9..fea513975 100644 --- a/common/api/v1/response.go +++ b/common/api/v1/response.go @@ -45,8 +45,10 @@ func CalcCode(rm ResponseMessage) int { func (b *BatchWriteResponse) Collect(response *Response) { // 非200的code,都归为异常 if CalcCode(response) != 200 { - b.Code.Value = ExecuteException - b.Info.Value = code2info[ExecuteException] + if response.GetCode().GetValue() >= b.GetCode().GetValue() { + b.Code.Value = response.GetCode().GetValue() + b.Info.Value = code2info[b.GetCode().GetValue()] + } } b.Size.Value++ diff --git a/common/api/v1/response.pb.go b/common/api/v1/response.pb.go index 7c3f69fbb..b2c21a216 100644 --- a/common/api/v1/response.pb.go +++ b/common/api/v1/response.pb.go @@ -57,7 +57,7 @@ func (x DiscoverResponse_DiscoverResponseType) String() string { return proto.EnumName(DiscoverResponse_DiscoverResponseType_name, int32(x)) } func (DiscoverResponse_DiscoverResponseType) EnumDescriptor() ([]byte, []int) { - return fileDescriptor_response_fa138b2a9919ddc6, []int{4, 0} + return fileDescriptor_response_0e23fdabc0351e9e, []int{4, 0} } type SimpleResponse struct { @@ -72,7 +72,7 @@ func (m *SimpleResponse) Reset() { *m = SimpleResponse{} } func (m *SimpleResponse) String() string { return proto.CompactTextString(m) } func (*SimpleResponse) ProtoMessage() {} func (*SimpleResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_response_fa138b2a9919ddc6, []int{0} + return fileDescriptor_response_0e23fdabc0351e9e, []int{0} } func (m *SimpleResponse) XXX_Unmarshal(b []byte) error { return xxx_messageInfo_SimpleResponse.Unmarshal(m, b) @@ -128,6 +128,7 @@ type Response struct { ModifyUserGroup *ModifyUserGroup `protobuf:"bytes,25,opt,name=modifyUserGroup,proto3" json:"modifyUserGroup,omitempty"` Resources *StrategyResources `protobuf:"bytes,26,opt,name=resources,proto3" json:"resources,omitempty"` OptionSwitch *OptionSwitch `protobuf:"bytes,27,opt,name=optionSwitch,proto3" json:"optionSwitch,omitempty"` + InstanceLabels *InstanceLabels `protobuf:"bytes,28,opt,name=instanceLabels,proto3" json:"instanceLabels,omitempty"` XXX_NoUnkeyedLiteral struct{} `json:"-"` XXX_unrecognized []byte `json:"-"` XXX_sizecache int32 `json:"-"` @@ -137,7 +138,7 @@ func (m *Response) Reset() { *m = Response{} } func (m *Response) String() string { return proto.CompactTextString(m) } func (*Response) ProtoMessage() {} func (*Response) Descriptor() ([]byte, []int) { - return fileDescriptor_response_fa138b2a9919ddc6, []int{1} + return fileDescriptor_response_0e23fdabc0351e9e, []int{1} } func (m *Response) XXX_Unmarshal(b []byte) error { return xxx_messageInfo_Response.Unmarshal(m, b) @@ -304,6 +305,13 @@ func (m *Response) GetOptionSwitch() *OptionSwitch { return nil } +func (m *Response) GetInstanceLabels() *InstanceLabels { + if m != nil { + return m.InstanceLabels + } + return nil +} + type BatchWriteResponse struct { Code *wrappers.UInt32Value `protobuf:"bytes,1,opt,name=code,proto3" json:"code,omitempty"` Info *wrappers.StringValue `protobuf:"bytes,2,opt,name=info,proto3" json:"info,omitempty"` @@ -318,7 +326,7 @@ func (m *BatchWriteResponse) Reset() { *m = BatchWriteResponse{} } func (m *BatchWriteResponse) String() string { return proto.CompactTextString(m) } func (*BatchWriteResponse) ProtoMessage() {} func (*BatchWriteResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_response_fa138b2a9919ddc6, []int{2} + return fileDescriptor_response_0e23fdabc0351e9e, []int{2} } func (m *BatchWriteResponse) XXX_Unmarshal(b []byte) error { return xxx_messageInfo_BatchWriteResponse.Unmarshal(m, b) @@ -392,7 +400,7 @@ func (m *BatchQueryResponse) Reset() { *m = BatchQueryResponse{} } func (m *BatchQueryResponse) String() string { return proto.CompactTextString(m) } func (*BatchQueryResponse) ProtoMessage() {} func (*BatchQueryResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_response_fa138b2a9919ddc6, []int{3} + return fileDescriptor_response_0e23fdabc0351e9e, []int{3} } func (m *BatchQueryResponse) XXX_Unmarshal(b []byte) error { return xxx_messageInfo_BatchQueryResponse.Unmarshal(m, b) @@ -544,7 +552,7 @@ func (m *DiscoverResponse) Reset() { *m = DiscoverResponse{} } func (m *DiscoverResponse) String() string { return proto.CompactTextString(m) } func (*DiscoverResponse) ProtoMessage() {} func (*DiscoverResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_response_fa138b2a9919ddc6, []int{4} + return fileDescriptor_response_0e23fdabc0351e9e, []int{4} } func (m *DiscoverResponse) XXX_Unmarshal(b []byte) error { return xxx_messageInfo_DiscoverResponse.Unmarshal(m, b) @@ -634,86 +642,174 @@ func (m *DiscoverResponse) GetNamespaces() []*Namespace { return nil } +type OptionSwitch struct { + Options map[string]string `protobuf:"bytes,1,rep,name=options,proto3" json:"options,omitempty" protobuf_key:"bytes,1,opt,name=key,proto3" protobuf_val:"bytes,2,opt,name=value,proto3"` + XXX_NoUnkeyedLiteral struct{} `json:"-"` + XXX_unrecognized []byte `json:"-"` + XXX_sizecache int32 `json:"-"` +} + +func (m *OptionSwitch) Reset() { *m = OptionSwitch{} } +func (m *OptionSwitch) String() string { return proto.CompactTextString(m) } +func (*OptionSwitch) ProtoMessage() {} +func (*OptionSwitch) Descriptor() ([]byte, []int) { + return fileDescriptor_response_0e23fdabc0351e9e, []int{5} +} +func (m *OptionSwitch) XXX_Unmarshal(b []byte) error { + return xxx_messageInfo_OptionSwitch.Unmarshal(m, b) +} +func (m *OptionSwitch) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + return xxx_messageInfo_OptionSwitch.Marshal(b, m, deterministic) +} +func (dst *OptionSwitch) XXX_Merge(src proto.Message) { + xxx_messageInfo_OptionSwitch.Merge(dst, src) +} +func (m *OptionSwitch) XXX_Size() int { + return xxx_messageInfo_OptionSwitch.Size(m) +} +func (m *OptionSwitch) XXX_DiscardUnknown() { + xxx_messageInfo_OptionSwitch.DiscardUnknown(m) +} + +var xxx_messageInfo_OptionSwitch proto.InternalMessageInfo + +func (m *OptionSwitch) GetOptions() map[string]string { + if m != nil { + return m.Options + } + return nil +} + +type InstanceLabels struct { + Labels map[string]*StringList `protobuf:"bytes,1,rep,name=labels,proto3" json:"labels,omitempty" protobuf_key:"bytes,1,opt,name=key,proto3" protobuf_val:"bytes,2,opt,name=value,proto3"` + XXX_NoUnkeyedLiteral struct{} `json:"-"` + XXX_unrecognized []byte `json:"-"` + XXX_sizecache int32 `json:"-"` +} + +func (m *InstanceLabels) Reset() { *m = InstanceLabels{} } +func (m *InstanceLabels) String() string { return proto.CompactTextString(m) } +func (*InstanceLabels) ProtoMessage() {} +func (*InstanceLabels) Descriptor() ([]byte, []int) { + return fileDescriptor_response_0e23fdabc0351e9e, []int{6} +} +func (m *InstanceLabels) XXX_Unmarshal(b []byte) error { + return xxx_messageInfo_InstanceLabels.Unmarshal(m, b) +} +func (m *InstanceLabels) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + return xxx_messageInfo_InstanceLabels.Marshal(b, m, deterministic) +} +func (dst *InstanceLabels) XXX_Merge(src proto.Message) { + xxx_messageInfo_InstanceLabels.Merge(dst, src) +} +func (m *InstanceLabels) XXX_Size() int { + return xxx_messageInfo_InstanceLabels.Size(m) +} +func (m *InstanceLabels) XXX_DiscardUnknown() { + xxx_messageInfo_InstanceLabels.DiscardUnknown(m) +} + +var xxx_messageInfo_InstanceLabels proto.InternalMessageInfo + +func (m *InstanceLabels) GetLabels() map[string]*StringList { + if m != nil { + return m.Labels + } + return nil +} + func init() { proto.RegisterType((*SimpleResponse)(nil), "v1.SimpleResponse") proto.RegisterType((*Response)(nil), "v1.Response") proto.RegisterType((*BatchWriteResponse)(nil), "v1.BatchWriteResponse") proto.RegisterType((*BatchQueryResponse)(nil), "v1.BatchQueryResponse") proto.RegisterType((*DiscoverResponse)(nil), "v1.DiscoverResponse") + proto.RegisterType((*OptionSwitch)(nil), "v1.OptionSwitch") + proto.RegisterMapType((map[string]string)(nil), "v1.OptionSwitch.OptionsEntry") + proto.RegisterType((*InstanceLabels)(nil), "v1.InstanceLabels") + proto.RegisterMapType((map[string]*StringList)(nil), "v1.InstanceLabels.LabelsEntry") proto.RegisterEnum("v1.DiscoverResponse_DiscoverResponseType", DiscoverResponse_DiscoverResponseType_name, DiscoverResponse_DiscoverResponseType_value) } -func init() { proto.RegisterFile("response.proto", fileDescriptor_response_fa138b2a9919ddc6) } - -var fileDescriptor_response_fa138b2a9919ddc6 = []byte{ - // 1091 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xbc, 0x55, 0x5d, 0x6f, 0xdb, 0x36, - 0x17, 0x7e, 0xd3, 0xc8, 0xb6, 0x7c, 0xec, 0xda, 0x2a, 0x9d, 0xf4, 0xe5, 0xb2, 0xa2, 0x28, 0x8c, - 0xad, 0xcb, 0x5c, 0xcc, 0x5d, 0x92, 0x02, 0x1b, 0x06, 0xf4, 0xc2, 0x71, 0x94, 0xcc, 0xf9, 0x70, - 0x3a, 0xca, 0x4e, 0x76, 0x17, 0x28, 0x0a, 0xe3, 0x10, 0x93, 0x25, 0x83, 0x94, 0x52, 0x64, 0xff, - 0xa2, 0xbf, 0x6a, 0x77, 0xbb, 0xdc, 0xef, 0x19, 0x48, 0x7d, 0x50, 0x76, 0x32, 0xb7, 0x57, 0xb9, - 0xb1, 0xc5, 0xf3, 0x3c, 0x87, 0xe4, 0x39, 0x3c, 0xe7, 0x39, 0xd0, 0xe0, 0x54, 0xcc, 0xc2, 0x40, - 0xd0, 0xee, 0x8c, 0x87, 0x51, 0x88, 0x9e, 0xdc, 0x6e, 0x6d, 0xbc, 0x9c, 0x84, 0xe1, 0xc4, 0xa7, - 0x6f, 0x95, 0xe5, 0x32, 0xbe, 0x7e, 0xfb, 0x91, 0xbb, 0xb3, 0x19, 0xe5, 0x22, 0xe1, 0x6c, 0x3c, - 0x15, 0x94, 0xdf, 0x32, 0x8f, 0x66, 0x4b, 0x1e, 0xc6, 0x11, 0x0b, 0x26, 0xe9, 0xb2, 0xee, 0xf9, - 0x8c, 0x06, 0x51, 0xba, 0x6a, 0x72, 0x37, 0xa2, 0x3e, 0x9b, 0xb2, 0xcc, 0xb0, 0xe6, 0x31, 0xee, - 0xc5, 0x2c, 0xba, 0xe4, 0xd4, 0xfd, 0x83, 0xf2, 0xd4, 0xda, 0xf2, 0xc2, 0xe0, 0x9a, 0x4d, 0x38, - 0xf5, 0xa9, 0x9b, 0xdd, 0x65, 0xa3, 0x31, 0xf3, 0xdd, 0xe8, 0x3a, 0xe4, 0xd3, 0x74, 0x0d, 0x6e, - 0x1c, 0xdd, 0xa4, 0xdf, 0xb5, 0x69, 0x78, 0x45, 0xfd, 0x64, 0xd1, 0x8e, 0xa0, 0xe1, 0xb0, 0xe9, - 0xcc, 0xa7, 0x24, 0x0d, 0x06, 0xfd, 0x08, 0x86, 0x17, 0x5e, 0x51, 0xbc, 0xf2, 0x6a, 0x65, 0xb3, - 0xb6, 0xfd, 0xa2, 0x9b, 0x44, 0xd4, 0xcd, 0x22, 0xea, 0x8e, 0x07, 0x41, 0xb4, 0xb3, 0x7d, 0xe6, - 0xfa, 0x31, 0x25, 0x8a, 0x29, 0x3d, 0x58, 0x70, 0x1d, 0xe2, 0x27, 0xff, 0xe1, 0xe1, 0x44, 0x9c, - 0x05, 0x93, 0xd4, 0x43, 0x32, 0xdb, 0x9f, 0x4c, 0x30, 0x1f, 0xf3, 0x40, 0xd4, 0x86, 0x72, 0x92, - 0x5b, 0xbc, 0xaa, 0x7c, 0xa0, 0x7b, 0xbb, 0xd5, 0xed, 0x2b, 0x0b, 0x49, 0x11, 0xf4, 0x06, 0xaa, - 0x81, 0x3b, 0xa5, 0x62, 0xe6, 0x7a, 0x14, 0x1b, 0x8a, 0xf6, 0x54, 0xd2, 0x86, 0x99, 0x91, 0x68, - 0x1c, 0x7d, 0x0b, 0x95, 0xf4, 0x29, 0x71, 0x49, 0x51, 0x6b, 0x92, 0xea, 0x24, 0x26, 0x92, 0x61, - 0x68, 0x13, 0x4c, 0x16, 0x88, 0xc8, 0x0d, 0x3c, 0x8a, 0xcb, 0x8a, 0x57, 0x97, 0xbc, 0x41, 0x6a, - 0x23, 0x39, 0x2a, 0x37, 0x4c, 0x8b, 0x01, 0x57, 0xf4, 0x86, 0x24, 0x31, 0x91, 0x0c, 0x43, 0xaf, - 0xa1, 0xe4, 0xfa, 0xcc, 0x15, 0xd8, 0x54, 0x24, 0xab, 0x70, 0x6a, 0x4f, 0xda, 0x49, 0x02, 0xa3, - 0xd7, 0x50, 0x95, 0xe5, 0x73, 0x2c, 0xcb, 0x07, 0x57, 0x15, 0xd7, 0x54, 0x1b, 0xc6, 0x3e, 0x25, - 0x1a, 0x42, 0xbf, 0x40, 0x23, 0xad, 0xaa, 0xdd, 0xa4, 0xaa, 0x30, 0x28, 0x32, 0x52, 0x09, 0x9a, - 0x43, 0xc8, 0x02, 0x13, 0xfd, 0x04, 0x4f, 0x93, 0xda, 0x23, 0x49, 0xed, 0xe1, 0x9a, 0x72, 0x7d, - 0xa6, 0x5c, 0x8b, 0x00, 0x99, 0xe7, 0xc9, 0xac, 0x64, 0xf5, 0x89, 0x9b, 0x3a, 0x2b, 0x1f, 0x52, - 0x1b, 0xc9, 0x51, 0xf4, 0x02, 0x8c, 0x58, 0x50, 0x8e, 0x5b, 0x3a, 0x82, 0xb1, 0xa0, 0x9c, 0x28, - 0xab, 0x7c, 0x31, 0xf9, 0x7f, 0xc0, 0xc3, 0x78, 0x86, 0xd7, 0xf4, 0x8b, 0x8d, 0x33, 0x23, 0xd1, - 0x38, 0x7a, 0x07, 0x75, 0xd9, 0x04, 0x4e, 0x24, 0x83, 0x9f, 0xdc, 0xe1, 0x75, 0x9d, 0xc0, 0x5e, - 0xc1, 0x4e, 0xe6, 0x58, 0x68, 0x0b, 0x4c, 0x4e, 0x7d, 0x37, 0x62, 0x61, 0x80, 0x9f, 0x2b, 0x8f, - 0xf5, 0xf9, 0x13, 0x52, 0x90, 0xe4, 0x34, 0x99, 0x16, 0x3f, 0x9c, 0xb0, 0x20, 0x2b, 0x70, 0xfc, - 0x7f, 0x9d, 0x96, 0xe3, 0x22, 0x40, 0xe6, 0x79, 0x68, 0x1f, 0xd0, 0x34, 0xbc, 0x62, 0xd7, 0x77, - 0xc5, 0xfb, 0x60, 0xac, 0xbc, 0x9f, 0x4b, 0xef, 0x93, 0x7b, 0x28, 0x79, 0xc0, 0x03, 0xbd, 0x87, - 0x66, 0x62, 0xcd, 0x6f, 0x89, 0xbf, 0x52, 0x9b, 0xb4, 0xf4, 0x26, 0x3a, 0x80, 0x45, 0x2e, 0xda, - 0x81, 0x2a, 0xa7, 0x22, 0x8c, 0xb9, 0x47, 0x05, 0xde, 0xd0, 0x31, 0xe7, 0x67, 0x66, 0x20, 0xd1, - 0x3c, 0x99, 0xdd, 0x70, 0x26, 0xc3, 0x77, 0x3e, 0xb2, 0xc8, 0xbb, 0xc1, 0x5f, 0xeb, 0xec, 0x9e, - 0x16, 0xec, 0x64, 0x8e, 0x75, 0x68, 0x98, 0x75, 0xab, 0x79, 0x68, 0x98, 0x96, 0xd5, 0x6a, 0xff, - 0xb3, 0x02, 0x68, 0xd7, 0x8d, 0xbc, 0x9b, 0x73, 0xce, 0xa2, 0x47, 0x95, 0x23, 0xe9, 0x21, 0xd8, - 0x9f, 0x34, 0xd5, 0x86, 0xcf, 0x9c, 0x21, 0x99, 0xa8, 0xa3, 0x72, 0xa4, 0x6e, 0x28, 0xb0, 0xf1, - 0x6a, 0x35, 0x2b, 0xe1, 0xfc, 0x69, 0x35, 0xdc, 0xfe, 0x54, 0x4e, 0x03, 0xfb, 0x2d, 0xa6, 0xfc, - 0xee, 0x51, 0x03, 0x7b, 0x07, 0x65, 0x77, 0x1a, 0xc6, 0xb9, 0xec, 0x2d, 0x3f, 0x25, 0xe5, 0xe6, - 0xe9, 0x30, 0xbe, 0x38, 0x1d, 0x3f, 0x00, 0xe4, 0xd2, 0x28, 0x70, 0x49, 0xe5, 0x63, 0x41, 0x3b, - 0x0b, 0x04, 0xf4, 0x1d, 0x98, 0xa9, 0x40, 0x0a, 0x5c, 0x56, 0xe4, 0x39, 0xf5, 0xcc, 0x41, 0x99, - 0xe6, 0x4c, 0x20, 0x05, 0xae, 0xe8, 0x34, 0xe7, 0xfa, 0xa9, 0x61, 0xb9, 0x69, 0x2a, 0x92, 0x52, - 0x1c, 0x57, 0x17, 0x15, 0x34, 0x07, 0x51, 0x07, 0x2a, 0x4a, 0x23, 0xa9, 0xc0, 0x55, 0xc5, 0xbb, - 0x2f, 0xa2, 0x19, 0x01, 0x6d, 0x02, 0xe4, 0x5a, 0x29, 0x30, 0x28, 0xba, 0xd6, 0xd1, 0x02, 0x86, - 0x6c, 0x40, 0x89, 0xc8, 0x9d, 0xb3, 0xe8, 0xc6, 0xc9, 0xa2, 0xab, 0x29, 0x8f, 0x75, 0xad, 0x88, - 0x05, 0x94, 0x3c, 0xe0, 0x20, 0x23, 0xce, 0xc4, 0x4f, 0xe0, 0xa6, 0x8e, 0x38, 0xd7, 0x46, 0x0d, - 0xa3, 0x97, 0x50, 0x92, 0xf2, 0x26, 0x30, 0xd2, 0xf7, 0x52, 0xea, 0x98, 0x98, 0xe5, 0xab, 0xe4, - 0xf2, 0x27, 0x70, 0x4b, 0xbf, 0x8a, 0x6e, 0xfe, 0x02, 0x01, 0xfd, 0x0c, 0x8d, 0x82, 0xf4, 0x31, - 0x2a, 0xf0, 0x9a, 0x4e, 0xcf, 0x9c, 0xe8, 0x2c, 0xf0, 0xd0, 0x37, 0x50, 0x49, 0x66, 0xa8, 0xc0, - 0xeb, 0xca, 0xa5, 0x38, 0x5e, 0x33, 0xa8, 0xd0, 0xec, 0xcf, 0xda, 0x7f, 0x95, 0xc0, 0xda, 0x63, - 0xc2, 0x0b, 0x6f, 0x29, 0x7f, 0xd4, 0x8e, 0x78, 0x0f, 0x46, 0x74, 0x37, 0x4b, 0x5a, 0xbd, 0xb1, - 0xfd, 0xbd, 0xbc, 0xe7, 0xe2, 0x3d, 0xee, 0x19, 0x46, 0x77, 0x33, 0x4a, 0x94, 0x5b, 0x71, 0xec, - 0x1b, 0x4b, 0xc6, 0xfe, 0x5c, 0xdd, 0x96, 0x96, 0xd7, 0x6d, 0x61, 0xf0, 0x97, 0x97, 0x0c, 0xfe, - 0x37, 0xc5, 0x81, 0x5e, 0xd1, 0xb3, 0x8e, 0x64, 0xc6, 0xe5, 0x53, 0xdd, 0xfc, 0xe2, 0xa9, 0x5e, - 0x6c, 0xce, 0xea, 0xb2, 0xe6, 0x9c, 0x6f, 0x7a, 0xf8, 0x4c, 0xd3, 0xb7, 0xff, 0x5e, 0x81, 0xb5, - 0x87, 0x32, 0x8b, 0x6a, 0x50, 0x19, 0x0f, 0x8f, 0x86, 0xa7, 0xe7, 0x43, 0xeb, 0x7f, 0xa8, 0x0e, - 0xe6, 0x60, 0xe8, 0x8c, 0x7a, 0xc3, 0xbe, 0x6d, 0xad, 0x48, 0xa8, 0x7f, 0x3c, 0x76, 0x46, 0x36, - 0xb1, 0x9e, 0xc8, 0x05, 0x39, 0x1d, 0x8f, 0x06, 0xc3, 0x03, 0x6b, 0x15, 0x35, 0x00, 0x48, 0x6f, - 0x64, 0x5f, 0x1c, 0x0f, 0x4e, 0x06, 0x23, 0xcb, 0x40, 0x2d, 0x68, 0xf6, 0x07, 0xa4, 0x3f, 0x1e, - 0x8c, 0x2e, 0x76, 0x89, 0xdd, 0x3b, 0xb2, 0x89, 0x55, 0x92, 0x9b, 0x39, 0x36, 0x39, 0x1b, 0xf4, - 0x6d, 0xc7, 0x2a, 0x4b, 0x97, 0x61, 0xef, 0xc4, 0x76, 0x3e, 0xf4, 0xe4, 0xba, 0xde, 0x36, 0xcc, - 0x8a, 0x55, 0xeb, 0x18, 0x27, 0xb6, 0xf3, 0x6b, 0xa7, 0x26, 0x7f, 0x2f, 0xfa, 0xa7, 0xc3, 0xfd, - 0xc1, 0x41, 0xa7, 0xb1, 0x7f, 0x3c, 0xfe, 0xfd, 0x62, 0x6f, 0x97, 0xd8, 0xfb, 0x44, 0x82, 0xa6, - 0x5a, 0x3b, 0x7b, 0x47, 0x9d, 0x5a, 0xf2, 0x65, 0x93, 0x33, 0x9b, 0x1c, 0x1a, 0x66, 0xcd, 0x6a, - 0x5c, 0x96, 0x55, 0xb1, 0xed, 0xfc, 0x1b, 0x00, 0x00, 0xff, 0xff, 0x8e, 0x40, 0xf0, 0x06, 0x0e, - 0x0c, 0x00, 0x00, +func init() { proto.RegisterFile("response.proto", fileDescriptor_response_0e23fdabc0351e9e) } + +var fileDescriptor_response_0e23fdabc0351e9e = []byte{ + // 1225 bytes of a gzipped FileDescriptorProto + 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xbc, 0x56, 0x5f, 0x73, 0xd3, 0x46, + 0x10, 0xaf, 0x13, 0xd9, 0x96, 0x57, 0xc6, 0x11, 0x97, 0x84, 0x5e, 0x5d, 0xca, 0x30, 0x1e, 0x4a, + 0xa9, 0x99, 0x9a, 0x12, 0x98, 0xc2, 0x30, 0xc3, 0x83, 0x63, 0x14, 0x2a, 0x70, 0x1c, 0x7a, 0xb2, + 0xa1, 0x6f, 0x19, 0x45, 0x5c, 0x9c, 0x1b, 0x64, 0xc9, 0xa3, 0x93, 0xc3, 0xb8, 0xaf, 0xfd, 0x04, + 0x9d, 0x7e, 0xa8, 0x3e, 0xb5, 0x8f, 0xfd, 0x3c, 0x9d, 0x3b, 0xfd, 0x39, 0xc9, 0x49, 0x0d, 0x4f, + 0x79, 0x49, 0x7c, 0xfb, 0xfb, 0xed, 0xdd, 0xee, 0x6a, 0xf7, 0x77, 0x07, 0xad, 0x88, 0xf2, 0x79, + 0x18, 0x70, 0xda, 0x9b, 0x47, 0x61, 0x1c, 0xa2, 0x8d, 0xf3, 0x87, 0xed, 0x5b, 0xd3, 0x30, 0x9c, + 0xfa, 0xf4, 0x81, 0xb4, 0x9c, 0x2c, 0x4e, 0x1f, 0x7c, 0x8c, 0xdc, 0xf9, 0x9c, 0x46, 0x3c, 0xe1, + 0xb4, 0xaf, 0x71, 0x1a, 0x9d, 0x33, 0x8f, 0x66, 0xcb, 0x28, 0x5c, 0xc4, 0x2c, 0x98, 0xa6, 0xcb, + 0xa6, 0xe7, 0x33, 0x1a, 0xc4, 0xe9, 0x6a, 0x2b, 0x72, 0x63, 0xea, 0xb3, 0x19, 0xcb, 0x0c, 0x3b, + 0x1e, 0x8b, 0xbc, 0x05, 0x8b, 0x4f, 0x22, 0xea, 0x7e, 0xa0, 0x51, 0x6a, 0xdd, 0xf6, 0xc2, 0xe0, + 0x94, 0x4d, 0x23, 0xea, 0x53, 0x37, 0x8b, 0xa5, 0xdd, 0x9a, 0xfb, 0x6e, 0x7c, 0x1a, 0x46, 0xb3, + 0x74, 0x0d, 0xee, 0x22, 0x3e, 0x4b, 0x7f, 0x1b, 0xb3, 0xf0, 0x3d, 0xf5, 0x93, 0x45, 0x27, 0x86, + 0x96, 0xc3, 0x66, 0x73, 0x9f, 0x92, 0x34, 0x19, 0xf4, 0x23, 0x68, 0x5e, 0xf8, 0x9e, 0xe2, 0xca, + 0xed, 0xca, 0x3d, 0x63, 0xef, 0x66, 0x2f, 0xc9, 0xa8, 0x97, 0x65, 0xd4, 0x9b, 0xd8, 0x41, 0xfc, + 0x68, 0xef, 0xad, 0xeb, 0x2f, 0x28, 0x91, 0x4c, 0xe1, 0xc1, 0x82, 0xd3, 0x10, 0x6f, 0xfc, 0x8f, + 0x87, 0x13, 0x47, 0x2c, 0x98, 0xa6, 0x1e, 0x82, 0xd9, 0xf9, 0x5b, 0x07, 0xfd, 0x2a, 0x0f, 0x44, + 0x1d, 0xa8, 0x25, 0xb5, 0xc5, 0x9b, 0xd2, 0x07, 0x7a, 0xe7, 0x0f, 0x7b, 0x03, 0x69, 0x21, 0x29, + 0x82, 0xee, 0x43, 0x23, 0x70, 0x67, 0x94, 0xcf, 0x5d, 0x8f, 0x62, 0x4d, 0xd2, 0xae, 0x09, 0xda, + 0x28, 0x33, 0x12, 0x85, 0xa3, 0x6f, 0xa1, 0x9e, 0x7e, 0x4a, 0x5c, 0x95, 0x54, 0x43, 0x50, 0x9d, + 0xc4, 0x44, 0x32, 0x0c, 0xdd, 0x03, 0x9d, 0x05, 0x3c, 0x76, 0x03, 0x8f, 0xe2, 0x9a, 0xe4, 0x35, + 0x05, 0xcf, 0x4e, 0x6d, 0x24, 0x47, 0xc5, 0x86, 0x69, 0x33, 0xe0, 0xba, 0xda, 0x90, 0x24, 0x26, + 0x92, 0x61, 0xe8, 0x2e, 0x54, 0x5d, 0x9f, 0xb9, 0x1c, 0xeb, 0x92, 0x64, 0x16, 0x4e, 0xed, 0x0b, + 0x3b, 0x49, 0x60, 0x74, 0x17, 0x1a, 0xa2, 0x7d, 0x86, 0xa2, 0x7d, 0x70, 0x43, 0x72, 0x75, 0xb9, + 0xe1, 0xc2, 0xa7, 0x44, 0x41, 0xe8, 0x19, 0xb4, 0xd2, 0xae, 0xda, 0x4f, 0xba, 0x0a, 0x83, 0x24, + 0x23, 0x59, 0xa0, 0x12, 0x42, 0x56, 0x98, 0xe8, 0x09, 0x5c, 0x4b, 0x7a, 0x8f, 0x24, 0xbd, 0x87, + 0x0d, 0xe9, 0x7a, 0x5d, 0xba, 0x16, 0x01, 0x52, 0xe6, 0x89, 0xaa, 0x64, 0xfd, 0x89, 0xb7, 0x54, + 0x55, 0xde, 0xa4, 0x36, 0x92, 0xa3, 0xe8, 0x26, 0x68, 0x0b, 0x4e, 0x23, 0xbc, 0xad, 0x32, 0x98, + 0x70, 0x1a, 0x11, 0x69, 0x15, 0x5f, 0x4c, 0xfc, 0x7f, 0x19, 0x85, 0x8b, 0x39, 0xde, 0x51, 0x5f, + 0x6c, 0x92, 0x19, 0x89, 0xc2, 0xd1, 0x63, 0x68, 0x8a, 0x21, 0x70, 0x62, 0x91, 0xfc, 0x74, 0x89, + 0x77, 0x55, 0x01, 0xfb, 0x05, 0x3b, 0x29, 0xb1, 0xd0, 0x43, 0xd0, 0x23, 0xea, 0xbb, 0x31, 0x0b, + 0x03, 0x7c, 0x43, 0x7a, 0xec, 0x96, 0x4f, 0x48, 0x41, 0x92, 0xd3, 0x44, 0x59, 0xfc, 0x70, 0xca, + 0x82, 0xac, 0xc1, 0xf1, 0x97, 0xaa, 0x2c, 0xc3, 0x22, 0x40, 0xca, 0x3c, 0x74, 0x00, 0x68, 0x16, + 0xbe, 0x67, 0xa7, 0xcb, 0x62, 0x3c, 0x18, 0x4b, 0xef, 0x1b, 0xc2, 0xfb, 0xf0, 0x02, 0x4a, 0x2e, + 0xf1, 0x40, 0xcf, 0x61, 0x2b, 0xb1, 0xe6, 0x51, 0xe2, 0xaf, 0xe4, 0x26, 0xdb, 0x6a, 0x13, 0x95, + 0xc0, 0x2a, 0x17, 0x3d, 0x82, 0x46, 0x44, 0x79, 0xb8, 0x88, 0x3c, 0xca, 0x71, 0x5b, 0xe5, 0x9c, + 0x9f, 0x99, 0x81, 0x44, 0xf1, 0x44, 0x75, 0xc3, 0xb9, 0x48, 0xdf, 0xf9, 0xc8, 0x62, 0xef, 0x0c, + 0x7f, 0xad, 0xaa, 0x7b, 0x54, 0xb0, 0x93, 0x12, 0x4b, 0x74, 0x5f, 0x36, 0x00, 0x43, 0xf7, 0x84, + 0xfa, 0x1c, 0xdf, 0x54, 0xdd, 0x67, 0x97, 0x10, 0xb2, 0xc2, 0x7c, 0xa5, 0xe9, 0x4d, 0x73, 0xeb, + 0x95, 0xa6, 0x9b, 0xe6, 0x76, 0xe7, 0xdf, 0x0a, 0xa0, 0x7d, 0x37, 0xf6, 0xce, 0xde, 0x45, 0x2c, + 0xbe, 0x52, 0x29, 0x13, 0x1e, 0x9c, 0xfd, 0x46, 0x53, 0x5d, 0xf9, 0xc4, 0x19, 0x82, 0x89, 0xba, + 0xb2, 0xbe, 0x32, 0x42, 0x8e, 0xb5, 0xdb, 0x9b, 0x59, 0xfb, 0xe7, 0x6d, 0xa1, 0xe0, 0xce, 0x1f, + 0xb5, 0x34, 0xb1, 0x5f, 0x16, 0x34, 0x5a, 0x5e, 0x69, 0x62, 0x8f, 0xa1, 0xe6, 0xce, 0xc2, 0x45, + 0x2e, 0x99, 0xeb, 0x4f, 0x49, 0xb9, 0x79, 0x39, 0xb4, 0xcf, 0x2e, 0xc7, 0x0f, 0x00, 0xb9, 0xac, + 0x72, 0x5c, 0x95, 0xf5, 0x58, 0xd1, 0xdd, 0x02, 0x01, 0x7d, 0x07, 0x7a, 0x2a, 0xae, 0x1c, 0xd7, + 0x24, 0xb9, 0xa4, 0xbc, 0x39, 0x28, 0xca, 0x9c, 0x75, 0x0c, 0xc7, 0x75, 0x55, 0xe6, 0x5c, 0x7b, + 0x15, 0x2c, 0x36, 0x4d, 0x05, 0x56, 0x08, 0xeb, 0xe6, 0xaa, 0xfa, 0xe6, 0x20, 0xea, 0x42, 0x5d, + 0xea, 0x2b, 0xe5, 0xb8, 0x21, 0x79, 0x17, 0x05, 0x38, 0x23, 0xa0, 0x7b, 0x00, 0xb9, 0xce, 0x72, + 0x0c, 0x92, 0xae, 0x34, 0xb8, 0x80, 0x21, 0x0b, 0x50, 0x22, 0x90, 0xef, 0x58, 0x7c, 0xe6, 0x64, + 0xd9, 0x19, 0xd2, 0x63, 0x57, 0xa9, 0x69, 0x01, 0x25, 0x97, 0x38, 0x88, 0x8c, 0x33, 0xe1, 0xe4, + 0x78, 0x4b, 0x65, 0x9c, 0xeb, 0xaa, 0x82, 0xd1, 0x2d, 0xa8, 0x0a, 0x69, 0xe4, 0x18, 0xa9, 0xb8, + 0xa4, 0xb2, 0x26, 0x66, 0xf1, 0x55, 0x72, 0xe9, 0xe4, 0x78, 0x5b, 0x7d, 0x15, 0x25, 0x1c, 0x05, + 0x02, 0x7a, 0x0a, 0xad, 0x82, 0x6c, 0x32, 0xca, 0xf1, 0x8e, 0x2a, 0x4f, 0x49, 0xb0, 0x56, 0x78, + 0xe8, 0x0e, 0xd4, 0x93, 0xfb, 0x97, 0xe3, 0x5d, 0xe9, 0x52, 0xbc, 0x9a, 0x33, 0xa8, 0x30, 0xec, + 0xd7, 0x3b, 0x7f, 0x55, 0xc1, 0x7c, 0xc1, 0xb8, 0x17, 0x9e, 0xd3, 0xe8, 0x4a, 0x27, 0xe2, 0x39, + 0x68, 0xf1, 0x72, 0x9e, 0x8c, 0x7a, 0x6b, 0xef, 0x7b, 0x11, 0xe7, 0x6a, 0x1c, 0x17, 0x0c, 0xe3, + 0xe5, 0x9c, 0x12, 0xe9, 0x56, 0x7c, 0x32, 0x68, 0x6b, 0x9e, 0x0c, 0xa5, 0xbe, 0xad, 0xae, 0xef, + 0xdb, 0xc2, 0xa3, 0xa1, 0xb6, 0xe6, 0xd1, 0x70, 0xbf, 0xf8, 0x18, 0xa8, 0xab, 0x7b, 0x92, 0x64, + 0xc6, 0xf5, 0x2f, 0x02, 0xfd, 0xb3, 0x5f, 0x04, 0xc5, 0xe1, 0x6c, 0xac, 0x1b, 0xce, 0xf2, 0xd0, + 0xc3, 0x27, 0x86, 0xbe, 0xf3, 0x4f, 0x05, 0x76, 0x2e, 0xab, 0x2c, 0x32, 0xa0, 0x3e, 0x19, 0xbd, + 0x1e, 0x1d, 0xbd, 0x1b, 0x99, 0x5f, 0xa0, 0x26, 0xe8, 0xf6, 0xc8, 0x19, 0xf7, 0x47, 0x03, 0xcb, + 0xac, 0x08, 0x68, 0x30, 0x9c, 0x38, 0x63, 0x8b, 0x98, 0x1b, 0x62, 0x41, 0x8e, 0x26, 0x63, 0x7b, + 0xf4, 0xd2, 0xdc, 0x44, 0x2d, 0x00, 0xd2, 0x1f, 0x5b, 0xc7, 0x43, 0xfb, 0xd0, 0x1e, 0x9b, 0x1a, + 0xda, 0x86, 0xad, 0x81, 0x4d, 0x06, 0x13, 0x7b, 0x7c, 0xbc, 0x4f, 0xac, 0xfe, 0x6b, 0x8b, 0x98, + 0x55, 0xb1, 0x99, 0x63, 0x91, 0xb7, 0xf6, 0xc0, 0x72, 0xcc, 0x9a, 0x70, 0x19, 0xf5, 0x0f, 0x2d, + 0xe7, 0x4d, 0x5f, 0xac, 0x9b, 0x1d, 0x4d, 0xaf, 0x9b, 0x46, 0x57, 0x3b, 0xb4, 0x9c, 0x9f, 0xbb, + 0x86, 0xf8, 0x7b, 0x3c, 0x38, 0x1a, 0x1d, 0xd8, 0x2f, 0xbb, 0xad, 0x83, 0xe1, 0xe4, 0xd7, 0xe3, + 0x17, 0xfb, 0xc4, 0x3a, 0x20, 0x02, 0xd4, 0xe5, 0xda, 0x79, 0xf1, 0xba, 0x6b, 0x24, 0xbf, 0x2c, + 0xf2, 0xd6, 0x22, 0xaf, 0x34, 0xdd, 0x30, 0x5b, 0x9d, 0xdf, 0x2b, 0xd0, 0x2c, 0xde, 0x8e, 0xe8, + 0x09, 0xd4, 0x93, 0xfb, 0x91, 0xe3, 0x8a, 0xac, 0xc9, 0x37, 0xab, 0x17, 0x68, 0xba, 0xe0, 0x56, + 0x10, 0x47, 0x4b, 0x92, 0xb1, 0xdb, 0xcf, 0xb2, 0x8d, 0x12, 0x00, 0x99, 0xb0, 0xf9, 0x81, 0x2e, + 0xe5, 0x34, 0x34, 0x88, 0xf8, 0x89, 0x76, 0xa0, 0x7a, 0x2e, 0x7a, 0x59, 0xf6, 0x7b, 0x83, 0x24, + 0x8b, 0x67, 0x1b, 0x4f, 0x2b, 0x9d, 0x3f, 0x2b, 0xd0, 0x2a, 0xdf, 0xb5, 0xe8, 0x27, 0xa8, 0xf9, + 0xc9, 0x7d, 0x9c, 0x84, 0x71, 0xeb, 0xe2, 0x7d, 0xdc, 0x4b, 0xfe, 0x25, 0x71, 0xa4, 0xec, 0xb6, + 0x0d, 0x46, 0xc1, 0x7c, 0x49, 0x14, 0x77, 0x8a, 0x51, 0x18, 0x7b, 0xad, 0xf4, 0x5d, 0xc1, 0x82, + 0xe9, 0x90, 0xf1, 0xb8, 0x10, 0xd5, 0x49, 0x4d, 0x0e, 0xe2, 0xa3, 0xff, 0x02, 0x00, 0x00, 0xff, + 0xff, 0x51, 0x04, 0xda, 0xdc, 0x66, 0x0d, 0x00, 0x00, } diff --git a/common/api/v1/response.proto b/common/api/v1/response.proto index e12fe1975..36ef15884 100644 --- a/common/api/v1/response.proto +++ b/common/api/v1/response.proto @@ -40,6 +40,7 @@ message Response { ModifyUserGroup modifyUserGroup = 25; StrategyResources resources = 26; OptionSwitch optionSwitch = 27; + InstanceLabels instanceLabels = 28; reserved 12 to 14, 16 to 18; } @@ -97,3 +98,13 @@ message DiscoverResponse { repeated Namespace namespaces = 10; reserved 11 to 13; } + + +message OptionSwitch { + map options = 1; +} + +message InstanceLabels { + map labels = 1; +} + diff --git a/common/api/v1/routing.pb.go b/common/api/v1/routing.pb.go index a9064c3ee..44f5cf230 100644 --- a/common/api/v1/routing.pb.go +++ b/common/api/v1/routing.pb.go @@ -40,7 +40,7 @@ func (m *Routing) Reset() { *m = Routing{} } func (m *Routing) String() string { return proto.CompactTextString(m) } func (*Routing) ProtoMessage() {} func (*Routing) Descriptor() ([]byte, []int) { - return fileDescriptor_routing_fd42ba95ca14a6d0, []int{0} + return fileDescriptor_routing_06b2863d308e147a, []int{0} } func (m *Routing) XXX_Unmarshal(b []byte) error { return xxx_messageInfo_Routing.Unmarshal(m, b) @@ -119,18 +119,21 @@ func (m *Routing) GetServiceToken() *wrappers.StringValue { type Route struct { // 如果匹配Source规则,按照Destination路由 // 多个Source之间的关系为或 - Sources []*Source `protobuf:"bytes,1,rep,name=sources,proto3" json:"sources,omitempty"` - Destinations []*Destination `protobuf:"bytes,2,rep,name=destinations,proto3" json:"destinations,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` + Sources []*Source `protobuf:"bytes,1,rep,name=sources,proto3" json:"sources,omitempty"` + Destinations []*Destination `protobuf:"bytes,2,rep,name=destinations,proto3" json:"destinations,omitempty"` + // extendInfo 用于承载一些额外信息 + // case 1: 升级到 v2 版本时,记录对应到 v2 版本的 id 信息 + ExtendInfo map[string]string `protobuf:"bytes,3,rep,name=extendInfo,proto3" json:"extendInfo,omitempty" protobuf_key:"bytes,1,opt,name=key,proto3" protobuf_val:"bytes,2,opt,name=value,proto3"` + XXX_NoUnkeyedLiteral struct{} `json:"-"` + XXX_unrecognized []byte `json:"-"` + XXX_sizecache int32 `json:"-"` } func (m *Route) Reset() { *m = Route{} } func (m *Route) String() string { return proto.CompactTextString(m) } func (*Route) ProtoMessage() {} func (*Route) Descriptor() ([]byte, []int) { - return fileDescriptor_routing_fd42ba95ca14a6d0, []int{1} + return fileDescriptor_routing_06b2863d308e147a, []int{1} } func (m *Route) XXX_Unmarshal(b []byte) error { return xxx_messageInfo_Route.Unmarshal(m, b) @@ -164,6 +167,13 @@ func (m *Route) GetDestinations() []*Destination { return nil } +func (m *Route) GetExtendInfo() map[string]string { + if m != nil { + return m.ExtendInfo + } + return nil +} + type Source struct { // 主调方服务以及命名空间 Service *wrappers.StringValue `protobuf:"bytes,1,opt,name=service,proto3" json:"service,omitempty"` @@ -180,7 +190,7 @@ func (m *Source) Reset() { *m = Source{} } func (m *Source) String() string { return proto.CompactTextString(m) } func (*Source) ProtoMessage() {} func (*Source) Descriptor() ([]byte, []int) { - return fileDescriptor_routing_fd42ba95ca14a6d0, []int{2} + return fileDescriptor_routing_06b2863d308e147a, []int{2} } func (m *Source) XXX_Unmarshal(b []byte) error { return xxx_messageInfo_Source.Unmarshal(m, b) @@ -253,7 +263,7 @@ func (m *Destination) Reset() { *m = Destination{} } func (m *Destination) String() string { return proto.CompactTextString(m) } func (*Destination) ProtoMessage() {} func (*Destination) Descriptor() ([]byte, []int) { - return fileDescriptor_routing_fd42ba95ca14a6d0, []int{3} + return fileDescriptor_routing_06b2863d308e147a, []int{3} } func (m *Destination) XXX_Unmarshal(b []byte) error { return xxx_messageInfo_Destination.Unmarshal(m, b) @@ -325,44 +335,47 @@ func (m *Destination) GetIsolate() *wrappers.BoolValue { func init() { proto.RegisterType((*Routing)(nil), "v1.Routing") proto.RegisterType((*Route)(nil), "v1.Route") + proto.RegisterMapType((map[string]string)(nil), "v1.Route.ExtendInfoEntry") proto.RegisterType((*Source)(nil), "v1.Source") proto.RegisterMapType((map[string]*MatchString)(nil), "v1.Source.MetadataEntry") proto.RegisterType((*Destination)(nil), "v1.Destination") proto.RegisterMapType((map[string]*MatchString)(nil), "v1.Destination.MetadataEntry") } -func init() { proto.RegisterFile("routing.proto", fileDescriptor_routing_fd42ba95ca14a6d0) } - -var fileDescriptor_routing_fd42ba95ca14a6d0 = []byte{ - // 468 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xc4, 0x93, 0xc1, 0x6a, 0xdb, 0x40, - 0x10, 0x86, 0xb1, 0x15, 0x5b, 0xf6, 0xb8, 0xa6, 0x65, 0x4f, 0x8b, 0x69, 0x4b, 0x30, 0x0d, 0xcd, - 0x49, 0x21, 0xb6, 0x29, 0x69, 0x8e, 0xa1, 0x3d, 0x14, 0x9a, 0x8b, 0x42, 0x7b, 0x2d, 0x6b, 0x79, - 0xa2, 0x2c, 0x91, 0x76, 0xc5, 0xee, 0x48, 0xc1, 0xb7, 0xbe, 0x53, 0xdf, 0xaa, 0x4f, 0x51, 0xb4, - 0x5a, 0xdb, 0x71, 0x82, 0x41, 0x87, 0x42, 0x6e, 0xd2, 0xce, 0xf7, 0xcf, 0xcc, 0xfe, 0x3b, 0x03, - 0x63, 0xa3, 0x4b, 0x92, 0x2a, 0x8d, 0x0a, 0xa3, 0x49, 0xb3, 0x6e, 0x75, 0x3e, 0x79, 0x9f, 0x6a, - 0x9d, 0x66, 0x78, 0xe6, 0x4e, 0x96, 0xe5, 0xed, 0xd9, 0x83, 0x11, 0x45, 0x81, 0xc6, 0x36, 0xcc, - 0x64, 0x94, 0xeb, 0x15, 0x66, 0xcd, 0xcf, 0xf4, 0x4f, 0x00, 0x61, 0xdc, 0xa4, 0x60, 0x9f, 0x20, - 0xb4, 0x68, 0x2a, 0x99, 0x20, 0xef, 0x1c, 0x77, 0x4e, 0x47, 0xb3, 0xb7, 0x51, 0x93, 0x2a, 0xda, - 0xa4, 0x8a, 0x6e, 0xc8, 0x48, 0x95, 0xfe, 0x14, 0x59, 0x89, 0xf1, 0x06, 0x66, 0x97, 0x30, 0x54, - 0x22, 0x47, 0x5b, 0x88, 0x04, 0x79, 0xb7, 0x85, 0x72, 0x87, 0xb3, 0x13, 0x18, 0x48, 0xb5, 0xd4, - 0xa5, 0x5a, 0x59, 0x1e, 0x1c, 0x07, 0xa7, 0xa3, 0xd9, 0x30, 0xaa, 0xce, 0xa3, 0xba, 0x25, 0x8c, - 0xb7, 0x21, 0xf6, 0x11, 0x86, 0xba, 0x24, 0xcf, 0x1d, 0x3d, 0xe5, 0x76, 0x31, 0x36, 0x83, 0x5e, - 0x42, 0x32, 0x47, 0xde, 0x6b, 0xd1, 0x47, 0x83, 0xd6, 0x9a, 0xdc, 0x69, 0xfa, 0x6d, 0x34, 0x0e, - 0x65, 0x17, 0x30, 0x30, 0x58, 0x49, 0x2b, 0xb5, 0xe2, 0x61, 0x0b, 0xd9, 0x96, 0x66, 0x57, 0x30, - 0xf6, 0xc6, 0xfd, 0x22, 0x7d, 0x8f, 0x8a, 0x0f, 0x5a, 0xc8, 0xf7, 0x25, 0xd3, 0x25, 0xf4, 0xdc, - 0xcd, 0xd9, 0x07, 0x08, 0xad, 0x2e, 0x4d, 0x82, 0x96, 0x77, 0x9c, 0x2b, 0x50, 0xbb, 0x72, 0xe3, - 0x8e, 0xe2, 0x4d, 0x88, 0xcd, 0xe1, 0xd5, 0x0a, 0x2d, 0x49, 0x25, 0x48, 0x6a, 0x65, 0x79, 0xd7, - 0xa1, 0xaf, 0x6b, 0xf4, 0xcb, 0xee, 0x3c, 0xde, 0x83, 0xa6, 0xbf, 0xbb, 0xd0, 0x6f, 0x12, 0xbd, - 0xc8, 0x60, 0x2c, 0x60, 0x90, 0x23, 0x89, 0x95, 0x20, 0xe1, 0x07, 0x83, 0xef, 0xae, 0x16, 0x5d, - 0xfb, 0xd0, 0x57, 0x45, 0x66, 0x1d, 0x6f, 0xc9, 0xc9, 0x77, 0x18, 0xef, 0x85, 0xd8, 0x1b, 0x08, - 0xee, 0x71, 0xed, 0xda, 0x1e, 0xc6, 0xf5, 0x27, 0x3b, 0x81, 0x5e, 0x55, 0x17, 0xf3, 0x0d, 0x39, - 0x17, 0xae, 0x05, 0x25, 0x77, 0x4d, 0x23, 0x71, 0x13, 0xbd, 0xec, 0x5e, 0x74, 0xa6, 0x7f, 0x03, - 0x18, 0x3d, 0x32, 0xe8, 0x45, 0x7c, 0xf8, 0xfc, 0xcc, 0x87, 0x77, 0x4f, 0xde, 0xed, 0x90, 0x19, - 0xf5, 0x8c, 0x16, 0x46, 0x6a, 0x23, 0x69, 0xcd, 0x8f, 0x0e, 0x54, 0xfd, 0xf1, 0x4d, 0xd1, 0x7c, - 0xe6, 0x67, 0x74, 0x43, 0xb3, 0x05, 0xf4, 0x1f, 0x50, 0xa6, 0x77, 0x74, 0x70, 0x8d, 0x1e, 0xeb, - 0x3c, 0x5b, 0xd7, 0x23, 0x23, 0x94, 0xbd, 0x45, 0xd3, 0x6a, 0x95, 0xb6, 0x34, 0x5b, 0x40, 0x28, - 0xad, 0xce, 0x04, 0xa1, 0x5f, 0xa6, 0xc9, 0x33, 0xe1, 0x95, 0xd6, 0x99, 0xb7, 0xd5, 0xa3, 0xff, - 0xf7, 0xb1, 0x97, 0x7d, 0x57, 0x6a, 0xfe, 0x2f, 0x00, 0x00, 0xff, 0xff, 0xb3, 0x0a, 0x3d, 0x7c, - 0x52, 0x05, 0x00, 0x00, +func init() { proto.RegisterFile("routing.proto", fileDescriptor_routing_06b2863d308e147a) } + +var fileDescriptor_routing_06b2863d308e147a = []byte{ + // 511 bytes of a gzipped FileDescriptorProto + 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xc4, 0x93, 0x4f, 0x6b, 0xdb, 0x30, + 0x18, 0xc6, 0x49, 0xd2, 0xfc, 0x7b, 0xb3, 0xd0, 0x21, 0x76, 0xd0, 0xc2, 0x36, 0x4a, 0x58, 0x59, + 0x4f, 0x2e, 0x4d, 0xc2, 0x68, 0x0b, 0xbb, 0x94, 0xf5, 0x50, 0x58, 0x2f, 0x2e, 0xdb, 0x75, 0x28, + 0xf1, 0x1b, 0x57, 0xd4, 0x96, 0x8c, 0x24, 0xbb, 0xcb, 0x6d, 0xdf, 0x69, 0x5f, 0x67, 0x9f, 0x60, + 0x9f, 0x62, 0x58, 0x56, 0x1c, 0x27, 0x5d, 0xc0, 0x87, 0x41, 0x6f, 0xb6, 0xde, 0xdf, 0x23, 0xe9, + 0x79, 0xf4, 0xbe, 0x30, 0x54, 0x32, 0x35, 0x5c, 0x84, 0x5e, 0xa2, 0xa4, 0x91, 0xa4, 0x99, 0x9d, + 0x8d, 0xde, 0x85, 0x52, 0x86, 0x11, 0x9e, 0xda, 0x95, 0x79, 0xba, 0x3c, 0x7d, 0x54, 0x2c, 0x49, + 0x50, 0xe9, 0x82, 0x19, 0x0d, 0x62, 0x19, 0x60, 0x54, 0xfc, 0x8c, 0x7f, 0xb5, 0xa0, 0xeb, 0x17, + 0x5b, 0x90, 0x8f, 0xd0, 0xd5, 0xa8, 0x32, 0xbe, 0x40, 0xda, 0x38, 0x6a, 0x9c, 0x0c, 0x26, 0x6f, + 0xbc, 0x62, 0x2b, 0x6f, 0xbd, 0x95, 0x77, 0x67, 0x14, 0x17, 0xe1, 0x37, 0x16, 0xa5, 0xe8, 0xaf, + 0x61, 0x72, 0x09, 0x7d, 0xc1, 0x62, 0xd4, 0x09, 0x5b, 0x20, 0x6d, 0xd6, 0x50, 0x6e, 0x70, 0x72, + 0x0c, 0x3d, 0x2e, 0xe6, 0x32, 0x15, 0x81, 0xa6, 0xad, 0xa3, 0xd6, 0xc9, 0x60, 0xd2, 0xf7, 0xb2, + 0x33, 0x2f, 0xbf, 0x12, 0xfa, 0x65, 0x89, 0x7c, 0x80, 0xbe, 0x4c, 0x8d, 0xe3, 0x0e, 0x76, 0xb9, + 0x4d, 0x8d, 0x4c, 0xa0, 0xbd, 0x30, 0x3c, 0x46, 0xda, 0xae, 0x71, 0x8f, 0x02, 0xcd, 0x35, 0xb1, + 0xd5, 0x74, 0xea, 0x68, 0x2c, 0x4a, 0xce, 0xa1, 0xa7, 0x30, 0xe3, 0x9a, 0x4b, 0x41, 0xbb, 0x35, + 0x64, 0x25, 0x4d, 0xae, 0x60, 0xe8, 0x82, 0xfb, 0x6e, 0xe4, 0x03, 0x0a, 0xda, 0xab, 0x21, 0xdf, + 0x96, 0x8c, 0x7f, 0x37, 0xa0, 0x6d, 0xad, 0x93, 0xf7, 0xd0, 0xd5, 0x32, 0x55, 0x0b, 0xd4, 0xb4, + 0x61, 0x63, 0x81, 0x3c, 0x96, 0x3b, 0xbb, 0xe4, 0xaf, 0x4b, 0x64, 0x0a, 0x2f, 0x02, 0xd4, 0x86, + 0x0b, 0x66, 0xb8, 0x14, 0x9a, 0x36, 0x2d, 0x7a, 0x98, 0xa3, 0x9f, 0x37, 0xeb, 0xfe, 0x16, 0x44, + 0x2e, 0x00, 0xf0, 0x87, 0x41, 0x11, 0xdc, 0x88, 0xa5, 0x74, 0x8f, 0xf3, 0xba, 0x0c, 0xdd, 0xbb, + 0x2e, 0x6b, 0xd7, 0xc2, 0xa8, 0x95, 0x5f, 0x81, 0x47, 0x9f, 0xe0, 0x70, 0xa7, 0x4c, 0x5e, 0x42, + 0xeb, 0x01, 0x57, 0xb6, 0xb1, 0xfa, 0x7e, 0xfe, 0x49, 0x5e, 0x41, 0x3b, 0xcb, 0xcd, 0xd9, 0x96, + 0xe9, 0xfb, 0xc5, 0xcf, 0x65, 0xf3, 0xbc, 0x31, 0xfe, 0xd9, 0x84, 0x4e, 0x61, 0xe1, 0x59, 0x7a, + 0x72, 0x06, 0xbd, 0x18, 0x0d, 0x0b, 0x98, 0x61, 0xce, 0x36, 0xdd, 0x84, 0xea, 0xdd, 0xba, 0x52, + 0xe1, 0xba, 0x24, 0x47, 0x5f, 0x60, 0xb8, 0x55, 0xfa, 0x87, 0xe3, 0xe3, 0xaa, 0x63, 0x97, 0xff, + 0x2d, 0x33, 0x8b, 0xfb, 0xe2, 0x22, 0xd5, 0x08, 0xfe, 0xb4, 0x60, 0x50, 0x79, 0x9a, 0x67, 0xc9, + 0xe1, 0xe2, 0x49, 0x0e, 0x6f, 0x77, 0x3a, 0x66, 0x5f, 0x18, 0xf9, 0x78, 0x24, 0x8a, 0x4b, 0xc5, + 0xcd, 0x8a, 0x1e, 0xec, 0x39, 0xf5, 0xeb, 0x8d, 0x30, 0xd3, 0x89, 0x1b, 0x8f, 0x35, 0x4d, 0x66, + 0xd0, 0x79, 0x44, 0x1e, 0xde, 0x9b, 0xbd, 0x13, 0x5c, 0xd5, 0x39, 0x36, 0x3f, 0xcf, 0x28, 0x26, + 0xf4, 0x12, 0x55, 0xad, 0x29, 0x2e, 0x69, 0x32, 0x83, 0x2e, 0xd7, 0x32, 0x62, 0x06, 0xdd, 0x1c, + 0x8f, 0x9e, 0x08, 0xaf, 0xa4, 0x8c, 0x5c, 0xac, 0x0e, 0xfd, 0xbf, 0x8f, 0x3d, 0xef, 0xd8, 0xa3, + 0xa6, 0x7f, 0x03, 0x00, 0x00, 0xff, 0xff, 0xe2, 0x31, 0x18, 0xc2, 0xcd, 0x05, 0x00, 0x00, } diff --git a/common/api/v1/routing.proto b/common/api/v1/routing.proto index b913246a1..9e6d0661f 100644 --- a/common/api/v1/routing.proto +++ b/common/api/v1/routing.proto @@ -19,7 +19,7 @@ message Routing { google.protobuf.StringValue mtime = 6; google.protobuf.StringValue revision = 7; - google.protobuf.StringValue service_token = 8 [json_name = "service_token"]; + google.protobuf.StringValue service_token = 8 [ json_name = "service_token" ]; } message Route { @@ -27,6 +27,10 @@ message Route { // 多个Source之间的关系为或 repeated Source sources = 1; repeated Destination destinations = 2; + + // extendInfo 用于承载一些额外信息 + // case 1: 升级到 v2 版本时,记录对应到 v2 版本的 id 信息 + map extendInfo = 3; } message Source { diff --git a/common/api/v2/build.sh b/common/api/v2/build.sh new file mode 100644 index 000000000..6c130f01d --- /dev/null +++ b/common/api/v2/build.sh @@ -0,0 +1,22 @@ +#!/bin/bash + +# 安装protoc和protoc-gen-go插件 +# +# 注意: +# grpc包引入github.com/golang/protobuf/proto v1.2.0 +# protoc-gen-go插件和引入proto包的版本必须保持一致 +# +# github.com/golang/protobuf/ +# protoc-gen-go:在pb.go文件中插入proto.ProtoPackageIsVersionX +# proto:在lib.go中定义ProtoPackageIsVersionX +# +# ProtoPackageIsVersion并非表示proto2/proto3 + +PROTOC=../protoc + +${PROTOC}/bin/protoc \ + --plugin=protoc-gen-go=${PROTOC}/bin/protoc-gen-go \ + --go_out=plugins=grpc:. \ + --proto_path=${PROTOC}/include \ + --proto_path=. \ + model_v2.proto routing_v2.proto request_v2.proto response_v2.proto grpcapi_v2.proto diff --git a/common/api/v2/grpcapi_v2.pb.go b/common/api/v2/grpcapi_v2.pb.go new file mode 100644 index 000000000..ae48dfa43 --- /dev/null +++ b/common/api/v2/grpcapi_v2.pb.go @@ -0,0 +1,144 @@ +// Code generated by protoc-gen-go. DO NOT EDIT. +// source: grpcapi_v2.proto + +package v2 + +import proto "github.com/golang/protobuf/proto" +import fmt "fmt" +import math "math" + +import ( + context "golang.org/x/net/context" + grpc "google.golang.org/grpc" +) + +// Reference imports to suppress errors if they are not otherwise used. +var _ = proto.Marshal +var _ = fmt.Errorf +var _ = math.Inf + +// This is a compile-time assertion to ensure that this generated file +// is compatible with the proto package it is being compiled against. +// A compilation error at this line likely means your copy of the +// proto package needs to be updated. +const _ = proto.ProtoPackageIsVersion2 // please upgrade the proto package + +// Reference imports to suppress errors if they are not otherwise used. +var _ context.Context +var _ grpc.ClientConn + +// This is a compile-time assertion to ensure that this generated file +// is compatible with the grpc package it is being compiled against. +const _ = grpc.SupportPackageIsVersion4 + +// PolarisGRPCClient is the client API for PolarisGRPC service. +// +// For semantics around ctx use and closing/ending streaming RPCs, please refer to https://godoc.org/google.golang.org/grpc#ClientConn.NewStream. +type PolarisGRPCClient interface { + // 统一发现接口 + Discover(ctx context.Context, opts ...grpc.CallOption) (PolarisGRPC_DiscoverClient, error) +} + +type polarisGRPCClient struct { + cc *grpc.ClientConn +} + +func NewPolarisGRPCClient(cc *grpc.ClientConn) PolarisGRPCClient { + return &polarisGRPCClient{cc} +} + +func (c *polarisGRPCClient) Discover(ctx context.Context, opts ...grpc.CallOption) (PolarisGRPC_DiscoverClient, error) { + stream, err := c.cc.NewStream(ctx, &_PolarisGRPC_serviceDesc.Streams[0], "/v2.PolarisGRPC/Discover", opts...) + if err != nil { + return nil, err + } + x := &polarisGRPCDiscoverClient{stream} + return x, nil +} + +type PolarisGRPC_DiscoverClient interface { + Send(*DiscoverRequest) error + Recv() (*DiscoverResponse, error) + grpc.ClientStream +} + +type polarisGRPCDiscoverClient struct { + grpc.ClientStream +} + +func (x *polarisGRPCDiscoverClient) Send(m *DiscoverRequest) error { + return x.ClientStream.SendMsg(m) +} + +func (x *polarisGRPCDiscoverClient) Recv() (*DiscoverResponse, error) { + m := new(DiscoverResponse) + if err := x.ClientStream.RecvMsg(m); err != nil { + return nil, err + } + return m, nil +} + +// PolarisGRPCServer is the server API for PolarisGRPC service. +type PolarisGRPCServer interface { + // 统一发现接口 + Discover(PolarisGRPC_DiscoverServer) error +} + +func RegisterPolarisGRPCServer(s *grpc.Server, srv PolarisGRPCServer) { + s.RegisterService(&_PolarisGRPC_serviceDesc, srv) +} + +func _PolarisGRPC_Discover_Handler(srv interface{}, stream grpc.ServerStream) error { + return srv.(PolarisGRPCServer).Discover(&polarisGRPCDiscoverServer{stream}) +} + +type PolarisGRPC_DiscoverServer interface { + Send(*DiscoverResponse) error + Recv() (*DiscoverRequest, error) + grpc.ServerStream +} + +type polarisGRPCDiscoverServer struct { + grpc.ServerStream +} + +func (x *polarisGRPCDiscoverServer) Send(m *DiscoverResponse) error { + return x.ServerStream.SendMsg(m) +} + +func (x *polarisGRPCDiscoverServer) Recv() (*DiscoverRequest, error) { + m := new(DiscoverRequest) + if err := x.ServerStream.RecvMsg(m); err != nil { + return nil, err + } + return m, nil +} + +var _PolarisGRPC_serviceDesc = grpc.ServiceDesc{ + ServiceName: "v2.PolarisGRPC", + HandlerType: (*PolarisGRPCServer)(nil), + Methods: []grpc.MethodDesc{}, + Streams: []grpc.StreamDesc{ + { + StreamName: "Discover", + Handler: _PolarisGRPC_Discover_Handler, + ServerStreams: true, + ClientStreams: true, + }, + }, + Metadata: "grpcapi_v2.proto", +} + +func init() { proto.RegisterFile("grpcapi_v2.proto", fileDescriptor_grpcapi_v2_99138fa445bc3382) } + +var fileDescriptor_grpcapi_v2_99138fa445bc3382 = []byte{ + // 124 bytes of a gzipped FileDescriptorProto + 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0x12, 0x48, 0x2f, 0x2a, 0x48, + 0x4e, 0x2c, 0xc8, 0x8c, 0x2f, 0x33, 0xd2, 0x2b, 0x28, 0xca, 0x2f, 0xc9, 0x17, 0x62, 0x2a, 0x33, + 0x92, 0x12, 0x28, 0x4a, 0x2d, 0x2c, 0x4d, 0x2d, 0x2e, 0x81, 0x8b, 0x4a, 0x09, 0x16, 0xa5, 0x16, + 0x17, 0xe4, 0xe7, 0x15, 0xa7, 0xc2, 0x85, 0x8c, 0xbc, 0xb8, 0xb8, 0x03, 0xf2, 0x73, 0x12, 0x8b, + 0x32, 0x8b, 0xdd, 0x83, 0x02, 0x9c, 0x85, 0xac, 0xb9, 0x38, 0x5c, 0x32, 0x8b, 0x93, 0xf3, 0xcb, + 0x52, 0x8b, 0x84, 0x84, 0xf5, 0xca, 0x8c, 0xf4, 0x60, 0xbc, 0x20, 0x88, 0x59, 0x52, 0x22, 0xa8, + 0x82, 0x10, 0xe3, 0x94, 0x18, 0x34, 0x18, 0x0d, 0x18, 0x93, 0xd8, 0xc0, 0x46, 0x1a, 0x03, 0x02, + 0x00, 0x00, 0xff, 0xff, 0xe0, 0x0c, 0xae, 0x02, 0x8f, 0x00, 0x00, 0x00, +} diff --git a/common/api/v2/grpcapi_v2.proto b/common/api/v2/grpcapi_v2.proto new file mode 100644 index 000000000..9079889e8 --- /dev/null +++ b/common/api/v2/grpcapi_v2.proto @@ -0,0 +1,11 @@ +syntax = "proto3"; + +package v2; + +import "request_v2.proto"; +import "response_v2.proto"; + +service PolarisGRPC { + // 统一发现接口 + rpc Discover(stream DiscoverRequest) returns (stream DiscoverResponse) {} +} diff --git a/common/api/v2/model_v2.pb.go b/common/api/v2/model_v2.pb.go new file mode 100644 index 000000000..89c778fce --- /dev/null +++ b/common/api/v2/model_v2.pb.go @@ -0,0 +1,167 @@ +// Code generated by protoc-gen-go. DO NOT EDIT. +// source: model_v2.proto + +package v2 + +import proto "github.com/golang/protobuf/proto" +import fmt "fmt" +import math "math" +import wrappers "github.com/golang/protobuf/ptypes/wrappers" + +// Reference imports to suppress errors if they are not otherwise used. +var _ = proto.Marshal +var _ = fmt.Errorf +var _ = math.Inf + +// This is a compile-time assertion to ensure that this generated file +// is compatible with the proto package it is being compiled against. +// A compilation error at this line likely means your copy of the +// proto package needs to be updated. +const _ = proto.ProtoPackageIsVersion2 // please upgrade the proto package + +type MatchString_MatchStringType int32 + +const ( + // Equivalent match + MatchString_EXACT MatchString_MatchStringType = 0 + // Regular match + MatchString_REGEX MatchString_MatchStringType = 1 + // Not equals match + MatchString_NOT_EQUALS MatchString_MatchStringType = 2 + // Include match + MatchString_IN MatchString_MatchStringType = 3 + // Not include match + MatchString_NOT_IN MatchString_MatchStringType = 4 +) + +var MatchString_MatchStringType_name = map[int32]string{ + 0: "EXACT", + 1: "REGEX", + 2: "NOT_EQUALS", + 3: "IN", + 4: "NOT_IN", +} +var MatchString_MatchStringType_value = map[string]int32{ + "EXACT": 0, + "REGEX": 1, + "NOT_EQUALS": 2, + "IN": 3, + "NOT_IN": 4, +} + +func (x MatchString_MatchStringType) String() string { + return proto.EnumName(MatchString_MatchStringType_name, int32(x)) +} +func (MatchString_MatchStringType) EnumDescriptor() ([]byte, []int) { + return fileDescriptor_model_v2_63fbe5e126956d10, []int{0, 0} +} + +type MatchString_ValueType int32 + +const ( + MatchString_TEXT MatchString_ValueType = 0 + MatchString_PARAMETER MatchString_ValueType = 1 + MatchString_VARIABLE MatchString_ValueType = 2 +) + +var MatchString_ValueType_name = map[int32]string{ + 0: "TEXT", + 1: "PARAMETER", + 2: "VARIABLE", +} +var MatchString_ValueType_value = map[string]int32{ + "TEXT": 0, + "PARAMETER": 1, + "VARIABLE": 2, +} + +func (x MatchString_ValueType) String() string { + return proto.EnumName(MatchString_ValueType_name, int32(x)) +} +func (MatchString_ValueType) EnumDescriptor() ([]byte, []int) { + return fileDescriptor_model_v2_63fbe5e126956d10, []int{0, 1} +} + +// MatchString 这里的序号需要保证和 v1.MatchSrting 保持一致 +type MatchString struct { + Type MatchString_MatchStringType `protobuf:"varint,1,opt,name=type,proto3,enum=v2.MatchString_MatchStringType" json:"type,omitempty"` + Value *wrappers.StringValue `protobuf:"bytes,2,opt,name=value,proto3" json:"value,omitempty"` + ValueType MatchString_ValueType `protobuf:"varint,3,opt,name=value_type,json=valueType,proto3,enum=v2.MatchString_ValueType" json:"value_type,omitempty"` + XXX_NoUnkeyedLiteral struct{} `json:"-"` + XXX_unrecognized []byte `json:"-"` + XXX_sizecache int32 `json:"-"` +} + +func (m *MatchString) Reset() { *m = MatchString{} } +func (m *MatchString) String() string { return proto.CompactTextString(m) } +func (*MatchString) ProtoMessage() {} +func (*MatchString) Descriptor() ([]byte, []int) { + return fileDescriptor_model_v2_63fbe5e126956d10, []int{0} +} +func (m *MatchString) XXX_Unmarshal(b []byte) error { + return xxx_messageInfo_MatchString.Unmarshal(m, b) +} +func (m *MatchString) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + return xxx_messageInfo_MatchString.Marshal(b, m, deterministic) +} +func (dst *MatchString) XXX_Merge(src proto.Message) { + xxx_messageInfo_MatchString.Merge(dst, src) +} +func (m *MatchString) XXX_Size() int { + return xxx_messageInfo_MatchString.Size(m) +} +func (m *MatchString) XXX_DiscardUnknown() { + xxx_messageInfo_MatchString.DiscardUnknown(m) +} + +var xxx_messageInfo_MatchString proto.InternalMessageInfo + +func (m *MatchString) GetType() MatchString_MatchStringType { + if m != nil { + return m.Type + } + return MatchString_EXACT +} + +func (m *MatchString) GetValue() *wrappers.StringValue { + if m != nil { + return m.Value + } + return nil +} + +func (m *MatchString) GetValueType() MatchString_ValueType { + if m != nil { + return m.ValueType + } + return MatchString_TEXT +} + +func init() { + proto.RegisterType((*MatchString)(nil), "v2.MatchString") + proto.RegisterEnum("v2.MatchString_MatchStringType", MatchString_MatchStringType_name, MatchString_MatchStringType_value) + proto.RegisterEnum("v2.MatchString_ValueType", MatchString_ValueType_name, MatchString_ValueType_value) +} + +func init() { proto.RegisterFile("model_v2.proto", fileDescriptor_model_v2_63fbe5e126956d10) } + +var fileDescriptor_model_v2_63fbe5e126956d10 = []byte{ + // 271 bytes of a gzipped FileDescriptorProto + 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x5c, 0x8f, 0x41, 0x4b, 0xc3, 0x30, + 0x14, 0x80, 0x6d, 0xd6, 0x95, 0xf5, 0x4d, 0x6b, 0x78, 0xa7, 0x29, 0xa2, 0xa3, 0xa7, 0x9d, 0x32, + 0xc8, 0x2e, 0x5e, 0xa3, 0x04, 0x29, 0x6e, 0x55, 0xb3, 0x3a, 0x7a, 0x2b, 0x9d, 0xc6, 0x2a, 0x54, + 0x5b, 0x6a, 0x57, 0xd9, 0xcf, 0xf2, 0x1f, 0x4a, 0x53, 0x26, 0x63, 0xb7, 0x8f, 0x97, 0xef, 0xe5, + 0x4b, 0xc0, 0xfb, 0x2c, 0x5e, 0x75, 0x9e, 0x34, 0x9c, 0x95, 0x55, 0x51, 0x17, 0x48, 0x1a, 0x7e, + 0x7e, 0x99, 0x15, 0x45, 0x96, 0xeb, 0xa9, 0x99, 0xac, 0x37, 0x6f, 0xd3, 0x9f, 0x2a, 0x2d, 0x4b, + 0x5d, 0x7d, 0x77, 0x8e, 0xff, 0x4b, 0x60, 0xb8, 0x48, 0xeb, 0x97, 0xf7, 0x65, 0x5d, 0x7d, 0x7c, + 0x65, 0x38, 0x03, 0xbb, 0xde, 0x96, 0x7a, 0x64, 0x8d, 0xad, 0x89, 0xc7, 0xaf, 0x58, 0xc3, 0xd9, + 0xde, 0xf1, 0x3e, 0x47, 0xdb, 0x52, 0x2b, 0x23, 0x23, 0x87, 0x7e, 0x93, 0xe6, 0x1b, 0x3d, 0x22, + 0x63, 0x6b, 0x32, 0xe4, 0x17, 0xac, 0x8b, 0xb2, 0x5d, 0x94, 0x75, 0x1b, 0xab, 0xd6, 0x51, 0x9d, + 0x8a, 0xd7, 0x00, 0x06, 0x12, 0x93, 0xeb, 0x99, 0xdc, 0xd9, 0x61, 0xce, 0x6c, 0x98, 0x90, 0xdb, + 0xec, 0xd0, 0xbf, 0x87, 0xd3, 0x83, 0x67, 0xa0, 0x0b, 0x7d, 0x19, 0x8b, 0xdb, 0x88, 0x1e, 0xb5, + 0xa8, 0xe4, 0x9d, 0x8c, 0xa9, 0x85, 0x1e, 0x40, 0xf8, 0x10, 0x25, 0xf2, 0xe9, 0x59, 0xcc, 0x97, + 0x94, 0xa0, 0x03, 0x24, 0x08, 0x69, 0x0f, 0x01, 0x9c, 0x76, 0x1e, 0x84, 0xd4, 0xf6, 0x39, 0xb8, + 0xff, 0x11, 0x1c, 0x80, 0x1d, 0xc9, 0xb8, 0xbd, 0xe5, 0x04, 0xdc, 0x47, 0xa1, 0xc4, 0x42, 0x46, + 0x52, 0x51, 0x0b, 0x8f, 0x61, 0xb0, 0x12, 0x2a, 0x10, 0x37, 0x73, 0x49, 0xc9, 0xda, 0x31, 0xff, + 0x9a, 0xfd, 0x05, 0x00, 0x00, 0xff, 0xff, 0x46, 0x96, 0xcc, 0xae, 0x70, 0x01, 0x00, 0x00, +} diff --git a/common/api/v2/model_v2.proto b/common/api/v2/model_v2.proto new file mode 100644 index 000000000..12ac0d3f7 --- /dev/null +++ b/common/api/v2/model_v2.proto @@ -0,0 +1,31 @@ +syntax = "proto3"; + +package v2; + +import "google/protobuf/wrappers.proto"; + +// MatchString 这里的序号需要保证和 v1.MatchSrting 保持一致 +message MatchString { + enum MatchStringType { + // Equivalent match + EXACT = 0; + // Regular match + REGEX = 1; + // Not equals match + NOT_EQUALS = 2; + // Include match + IN = 3; + // Not include match + NOT_IN = 4; + } + + enum ValueType { + TEXT = 0; + PARAMETER = 1; + VARIABLE = 2; + } + + MatchStringType type = 1; + google.protobuf.StringValue value = 2; + ValueType value_type = 3; +} diff --git a/common/api/v2/request_v2.pb.go b/common/api/v2/request_v2.pb.go new file mode 100644 index 000000000..1d8751aff --- /dev/null +++ b/common/api/v2/request_v2.pb.go @@ -0,0 +1,173 @@ +// Code generated by protoc-gen-go. DO NOT EDIT. +// source: request_v2.proto + +package v2 + +import proto "github.com/golang/protobuf/proto" +import fmt "fmt" +import math "math" + +// Reference imports to suppress errors if they are not otherwise used. +var _ = proto.Marshal +var _ = fmt.Errorf +var _ = math.Inf + +// This is a compile-time assertion to ensure that this generated file +// is compatible with the proto package it is being compiled against. +// A compilation error at this line likely means your copy of the +// proto package needs to be updated. +const _ = proto.ProtoPackageIsVersion2 // please upgrade the proto package + +type DiscoverRequest_DiscoverRequestType int32 + +const ( + DiscoverRequest_UNKNOWN DiscoverRequest_DiscoverRequestType = 0 + DiscoverRequest_ROUTING DiscoverRequest_DiscoverRequestType = 1 + DiscoverRequest_CIRCUIT_BREAKER DiscoverRequest_DiscoverRequestType = 2 +) + +var DiscoverRequest_DiscoverRequestType_name = map[int32]string{ + 0: "UNKNOWN", + 1: "ROUTING", + 2: "CIRCUIT_BREAKER", +} +var DiscoverRequest_DiscoverRequestType_value = map[string]int32{ + "UNKNOWN": 0, + "ROUTING": 1, + "CIRCUIT_BREAKER": 2, +} + +func (x DiscoverRequest_DiscoverRequestType) String() string { + return proto.EnumName(DiscoverRequest_DiscoverRequestType_name, int32(x)) +} +func (DiscoverRequest_DiscoverRequestType) EnumDescriptor() ([]byte, []int) { + return fileDescriptor_request_v2_da411c9ba009335d, []int{1, 0} +} + +type Service struct { + Name string `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"` + Namespace string `protobuf:"bytes,2,opt,name=namespace,proto3" json:"namespace,omitempty"` + Revision string `protobuf:"bytes,3,opt,name=revision,proto3" json:"revision,omitempty"` + XXX_NoUnkeyedLiteral struct{} `json:"-"` + XXX_unrecognized []byte `json:"-"` + XXX_sizecache int32 `json:"-"` +} + +func (m *Service) Reset() { *m = Service{} } +func (m *Service) String() string { return proto.CompactTextString(m) } +func (*Service) ProtoMessage() {} +func (*Service) Descriptor() ([]byte, []int) { + return fileDescriptor_request_v2_da411c9ba009335d, []int{0} +} +func (m *Service) XXX_Unmarshal(b []byte) error { + return xxx_messageInfo_Service.Unmarshal(m, b) +} +func (m *Service) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + return xxx_messageInfo_Service.Marshal(b, m, deterministic) +} +func (dst *Service) XXX_Merge(src proto.Message) { + xxx_messageInfo_Service.Merge(dst, src) +} +func (m *Service) XXX_Size() int { + return xxx_messageInfo_Service.Size(m) +} +func (m *Service) XXX_DiscardUnknown() { + xxx_messageInfo_Service.DiscardUnknown(m) +} + +var xxx_messageInfo_Service proto.InternalMessageInfo + +func (m *Service) GetName() string { + if m != nil { + return m.Name + } + return "" +} + +func (m *Service) GetNamespace() string { + if m != nil { + return m.Namespace + } + return "" +} + +func (m *Service) GetRevision() string { + if m != nil { + return m.Revision + } + return "" +} + +type DiscoverRequest struct { + Type DiscoverRequest_DiscoverRequestType `protobuf:"varint,1,opt,name=type,proto3,enum=v2.DiscoverRequest_DiscoverRequestType" json:"type,omitempty"` + Serivce *Service `protobuf:"bytes,2,opt,name=serivce,proto3" json:"serivce,omitempty"` + XXX_NoUnkeyedLiteral struct{} `json:"-"` + XXX_unrecognized []byte `json:"-"` + XXX_sizecache int32 `json:"-"` +} + +func (m *DiscoverRequest) Reset() { *m = DiscoverRequest{} } +func (m *DiscoverRequest) String() string { return proto.CompactTextString(m) } +func (*DiscoverRequest) ProtoMessage() {} +func (*DiscoverRequest) Descriptor() ([]byte, []int) { + return fileDescriptor_request_v2_da411c9ba009335d, []int{1} +} +func (m *DiscoverRequest) XXX_Unmarshal(b []byte) error { + return xxx_messageInfo_DiscoverRequest.Unmarshal(m, b) +} +func (m *DiscoverRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + return xxx_messageInfo_DiscoverRequest.Marshal(b, m, deterministic) +} +func (dst *DiscoverRequest) XXX_Merge(src proto.Message) { + xxx_messageInfo_DiscoverRequest.Merge(dst, src) +} +func (m *DiscoverRequest) XXX_Size() int { + return xxx_messageInfo_DiscoverRequest.Size(m) +} +func (m *DiscoverRequest) XXX_DiscardUnknown() { + xxx_messageInfo_DiscoverRequest.DiscardUnknown(m) +} + +var xxx_messageInfo_DiscoverRequest proto.InternalMessageInfo + +func (m *DiscoverRequest) GetType() DiscoverRequest_DiscoverRequestType { + if m != nil { + return m.Type + } + return DiscoverRequest_UNKNOWN +} + +func (m *DiscoverRequest) GetSerivce() *Service { + if m != nil { + return m.Serivce + } + return nil +} + +func init() { + proto.RegisterType((*Service)(nil), "v2.Service") + proto.RegisterType((*DiscoverRequest)(nil), "v2.DiscoverRequest") + proto.RegisterEnum("v2.DiscoverRequest_DiscoverRequestType", DiscoverRequest_DiscoverRequestType_name, DiscoverRequest_DiscoverRequestType_value) +} + +func init() { proto.RegisterFile("request_v2.proto", fileDescriptor_request_v2_da411c9ba009335d) } + +var fileDescriptor_request_v2_da411c9ba009335d = []byte{ + // 241 bytes of a gzipped FileDescriptorProto + 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0x12, 0x28, 0x4a, 0x2d, 0x2c, + 0x4d, 0x2d, 0x2e, 0x89, 0x2f, 0x33, 0xd2, 0x2b, 0x28, 0xca, 0x2f, 0xc9, 0x17, 0x62, 0x2a, 0x33, + 0x52, 0x0a, 0xe7, 0x62, 0x0f, 0x4e, 0x2d, 0x2a, 0xcb, 0x4c, 0x4e, 0x15, 0x12, 0xe2, 0x62, 0xc9, + 0x4b, 0xcc, 0x4d, 0x95, 0x60, 0x54, 0x60, 0xd4, 0xe0, 0x0c, 0x02, 0xb3, 0x85, 0x64, 0xb8, 0x38, + 0x41, 0x74, 0x71, 0x41, 0x62, 0x72, 0xaa, 0x04, 0x13, 0x58, 0x02, 0x21, 0x20, 0x24, 0xc5, 0xc5, + 0x51, 0x94, 0x5a, 0x96, 0x59, 0x9c, 0x99, 0x9f, 0x27, 0xc1, 0x0c, 0x96, 0x84, 0xf3, 0x95, 0x8e, + 0x33, 0x72, 0xf1, 0xbb, 0x64, 0x16, 0x27, 0xe7, 0x97, 0xa5, 0x16, 0x05, 0x41, 0x6c, 0x16, 0xb2, + 0xe6, 0x62, 0x29, 0xa9, 0x2c, 0x80, 0xd8, 0xc0, 0x67, 0xa4, 0xae, 0x57, 0x66, 0xa4, 0x87, 0xa6, + 0x04, 0x9d, 0x1f, 0x52, 0x59, 0x90, 0x1a, 0x04, 0xd6, 0x24, 0xa4, 0xca, 0xc5, 0x5e, 0x9c, 0x5a, + 0x94, 0x59, 0x06, 0x75, 0x08, 0xb7, 0x11, 0x37, 0x48, 0x3f, 0xd4, 0xf1, 0x41, 0x30, 0x39, 0x25, + 0x2f, 0x2e, 0x61, 0x2c, 0x66, 0x08, 0x71, 0x73, 0xb1, 0x87, 0xfa, 0x79, 0xfb, 0xf9, 0x87, 0xfb, + 0x09, 0x30, 0x80, 0x38, 0x41, 0xfe, 0xa1, 0x21, 0x9e, 0x7e, 0xee, 0x02, 0x8c, 0x42, 0xc2, 0x5c, + 0xfc, 0xce, 0x9e, 0x41, 0xce, 0xa1, 0x9e, 0x21, 0xf1, 0x4e, 0x41, 0xae, 0x8e, 0xde, 0xae, 0x41, + 0x02, 0x4c, 0x4a, 0x2c, 0x1c, 0xec, 0x02, 0xdc, 0x5e, 0x2c, 0x1c, 0xcc, 0x02, 0xac, 0x49, 0x6c, + 0xe0, 0xd0, 0x32, 0x06, 0x04, 0x00, 0x00, 0xff, 0xff, 0x23, 0xae, 0x3a, 0x13, 0x41, 0x01, 0x00, + 0x00, +} diff --git a/common/api/v2/request_v2.proto b/common/api/v2/request_v2.proto new file mode 100644 index 000000000..19f7fc501 --- /dev/null +++ b/common/api/v2/request_v2.proto @@ -0,0 +1,22 @@ +syntax = "proto3"; + +package v2; + +message Service { + string name = 1; + string namespace = 2; + string revision = 3; +} + +message DiscoverRequest { + enum DiscoverRequestType { + UNKNOWN = 0; + ROUTING = 1; + CIRCUIT_BREAKER = 2; + reserved 7 to 11; + } + + DiscoverRequestType type = 1; + Service serivce = 2; + reserved 3 to 4; +} diff --git a/common/api/v2/response.go b/common/api/v2/response.go new file mode 100644 index 000000000..73afccac5 --- /dev/null +++ b/common/api/v2/response.go @@ -0,0 +1,221 @@ +/** + * Tencent is pleased to support the open source community by making Polaris available. + * + * Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved. + * + * Licensed under the BSD 3-Clause License (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://opensource.org/licenses/BSD-3-Clause + * + * 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 v2 + +import ( + "github.com/golang/protobuf/proto" + "github.com/golang/protobuf/ptypes" + v1 "github.com/polarismesh/polaris-server/common/api/v1" +) + +/** + * @brief 回复消息接口 + */ +type ResponseMessage interface { + proto.Message + GetCode() uint32 + GetInfo() string +} + +/** + * @brief 获取返回码前三位 + * @note 返回码前三位和HTTP返回码定义一致 + */ +func CalcCode(rm ResponseMessage) int { + return int(rm.GetCode() / 1000) +} + +/** + * @brief BatchWriteResponse添加Response + */ +func (b *BatchWriteResponse) Collect(response *Response) { + // 非200的code,都归为异常 + if CalcCode(response) != 200 { + if response.GetCode() >= b.GetCode() { + b.Code = response.GetCode() + b.Info = v1.Code2Info(b.GetCode()) + } + } + + b.Size++ + b.Responses = append(b.Responses, response) +} + +/** + * @brief BatchWriteResponse添加Response + */ +func (b *BatchWriteResponse) CollectBatch(response []*Response) { + for _, resp := range response { + b.Collect(resp) + } +} + +/** + * @brief 创建简单回复 + */ +func NewSimpleResponse(code uint32) *SimpleResponse { + return &SimpleResponse{ + Code: code, + Info: v1.Code2Info(code), + } +} + +/** + * @brief 创建回复 + */ +func NewResponse(code uint32) *Response { + return &Response{ + Code: code, + Info: v1.Code2Info(code), + } +} + +// 带上具体的错误信息 +func NewResponseWithMsg(code uint32, msg string) *Response { + resp := NewResponse(code) + resp.Info += ": " + msg + return resp +} + +/** + * @brief 创建回复带服务路由信息 + */ +func NewRoutingResponse(code uint32, routing *Routing) *Response { + ret, err := ptypes.MarshalAny(routing) + if err != nil { + return &Response{ + Code: code, + Info: v1.Code2Info(code), + } + } + + return &Response{ + Code: code, + Info: v1.Code2Info(code), + Data: ret, + } +} + +/** + * @brief 创建批量回复 + */ +func NewBatchWriteResponse(code uint32) *BatchWriteResponse { + return &BatchWriteResponse{ + Code: code, + Info: v1.Code2Info(code), + Size: 0, + } +} + +/** + * @brief 创建带详细信息的批量回复 + */ +func NewBatchWriteResponseWithMsg(code uint32, msg string) *BatchWriteResponse { + resp := NewBatchWriteResponse(code) + resp.Info += ": " + msg + return resp +} + +/** + * @brief 创建批量查询回复 + */ +func NewBatchQueryResponse(code uint32) *BatchQueryResponse { + return &BatchQueryResponse{ + Code: code, + Info: v1.Code2Info(code), + Amount: 0, + Size: 0, + } +} + +/** + * @brief 创建带详细信息的批量查询回复 + */ +func NewBatchQueryResponseWithMsg(code uint32, msg string) *BatchQueryResponse { + resp := NewBatchQueryResponse(code) + resp.Info += ": " + msg + return resp +} + +// 格式化responses +// batch操作 +// 如果所有子错误码一致,那么使用子错误码 +// 如果包含任意一个5xx,那么返回500 +func FormatBatchWriteResponse(response *BatchWriteResponse) *BatchWriteResponse { + var code uint32 + for _, resp := range response.Responses { + if code == 0 { + code = resp.GetCode() + continue + } + if code == resp.GetCode() { + continue + } + // 发现不一样 + code = 0 + break + } + // code不等于0,意味着所有的resp都是一样的错误码,则合并为同一个错误码 + if code != 0 { + response.Code = code + response.Info = v1.Code2Info(code) + return response + } + + // 错误都不一致 + // 存在5XX,则返回500 + // 不存在5XX,但是存在4XX,则返回4XX + // 除去以上两个情况,不修改返回值 + hasBadRequest := false + for _, resp := range response.Responses { + httpStatus := CalcCode(resp) + if httpStatus >= 500 { + response.Code = v1.ExecuteException + response.Info = v1.Code2Info(response.Code) + return response + } else if httpStatus >= 400 { + hasBadRequest = true + } + } + + if hasBadRequest { + response.Code = v1.BadRequest + response.Info = v1.Code2Info(response.Code) + } + return response +} + +/** + * @brief 创建查询服务路由回复 + */ +func NewDiscoverRoutingResponse(code uint32, service *Service) *DiscoverResponse { + return &DiscoverResponse{ + Code: code, + Info: v1.Code2Info(code), + Type: DiscoverResponse_ROUTING, + Service: service, + } +} + +// 创建一个空白的discoverResponse +func NewDiscoverResponse(code uint32) *DiscoverResponse { + return &DiscoverResponse{ + Code: code, + Info: v1.Code2Info(code), + } +} diff --git a/common/api/v2/response_v2.pb.go b/common/api/v2/response_v2.pb.go new file mode 100644 index 000000000..c20640aab --- /dev/null +++ b/common/api/v2/response_v2.pb.go @@ -0,0 +1,410 @@ +// Code generated by protoc-gen-go. DO NOT EDIT. +// source: response_v2.proto + +package v2 + +import proto "github.com/golang/protobuf/proto" +import fmt "fmt" +import math "math" +import any "github.com/golang/protobuf/ptypes/any" + +// Reference imports to suppress errors if they are not otherwise used. +var _ = proto.Marshal +var _ = fmt.Errorf +var _ = math.Inf + +// This is a compile-time assertion to ensure that this generated file +// is compatible with the proto package it is being compiled against. +// A compilation error at this line likely means your copy of the +// proto package needs to be updated. +const _ = proto.ProtoPackageIsVersion2 // please upgrade the proto package + +type DiscoverResponse_DiscoverResponseType int32 + +const ( + DiscoverResponse_UNKNOWN DiscoverResponse_DiscoverResponseType = 0 + DiscoverResponse_INSTANCE DiscoverResponse_DiscoverResponseType = 1 + DiscoverResponse_CLUSTER DiscoverResponse_DiscoverResponseType = 2 + DiscoverResponse_ROUTING DiscoverResponse_DiscoverResponseType = 3 + DiscoverResponse_RATE_LIMIT DiscoverResponse_DiscoverResponseType = 4 + DiscoverResponse_CIRCUIT_BREAKER DiscoverResponse_DiscoverResponseType = 5 + DiscoverResponse_SERVICES DiscoverResponse_DiscoverResponseType = 6 + DiscoverResponse_NAMESPACES DiscoverResponse_DiscoverResponseType = 12 +) + +var DiscoverResponse_DiscoverResponseType_name = map[int32]string{ + 0: "UNKNOWN", + 1: "INSTANCE", + 2: "CLUSTER", + 3: "ROUTING", + 4: "RATE_LIMIT", + 5: "CIRCUIT_BREAKER", + 6: "SERVICES", + 12: "NAMESPACES", +} +var DiscoverResponse_DiscoverResponseType_value = map[string]int32{ + "UNKNOWN": 0, + "INSTANCE": 1, + "CLUSTER": 2, + "ROUTING": 3, + "RATE_LIMIT": 4, + "CIRCUIT_BREAKER": 5, + "SERVICES": 6, + "NAMESPACES": 12, +} + +func (x DiscoverResponse_DiscoverResponseType) String() string { + return proto.EnumName(DiscoverResponse_DiscoverResponseType_name, int32(x)) +} +func (DiscoverResponse_DiscoverResponseType) EnumDescriptor() ([]byte, []int) { + return fileDescriptor_response_v2_32a9e06b08c12914, []int{4, 0} +} + +type SimpleResponse struct { + Code uint32 `protobuf:"varint,1,opt,name=code,proto3" json:"code,omitempty"` + Info string `protobuf:"bytes,2,opt,name=info,proto3" json:"info,omitempty"` + XXX_NoUnkeyedLiteral struct{} `json:"-"` + XXX_unrecognized []byte `json:"-"` + XXX_sizecache int32 `json:"-"` +} + +func (m *SimpleResponse) Reset() { *m = SimpleResponse{} } +func (m *SimpleResponse) String() string { return proto.CompactTextString(m) } +func (*SimpleResponse) ProtoMessage() {} +func (*SimpleResponse) Descriptor() ([]byte, []int) { + return fileDescriptor_response_v2_32a9e06b08c12914, []int{0} +} +func (m *SimpleResponse) XXX_Unmarshal(b []byte) error { + return xxx_messageInfo_SimpleResponse.Unmarshal(m, b) +} +func (m *SimpleResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + return xxx_messageInfo_SimpleResponse.Marshal(b, m, deterministic) +} +func (dst *SimpleResponse) XXX_Merge(src proto.Message) { + xxx_messageInfo_SimpleResponse.Merge(dst, src) +} +func (m *SimpleResponse) XXX_Size() int { + return xxx_messageInfo_SimpleResponse.Size(m) +} +func (m *SimpleResponse) XXX_DiscardUnknown() { + xxx_messageInfo_SimpleResponse.DiscardUnknown(m) +} + +var xxx_messageInfo_SimpleResponse proto.InternalMessageInfo + +func (m *SimpleResponse) GetCode() uint32 { + if m != nil { + return m.Code + } + return 0 +} + +func (m *SimpleResponse) GetInfo() string { + if m != nil { + return m.Info + } + return "" +} + +type Response struct { + Code uint32 `protobuf:"varint,1,opt,name=code,proto3" json:"code,omitempty"` + Info string `protobuf:"bytes,2,opt,name=info,proto3" json:"info,omitempty"` + Data *any.Any `protobuf:"bytes,3,opt,name=data,proto3" json:"data,omitempty"` + XXX_NoUnkeyedLiteral struct{} `json:"-"` + XXX_unrecognized []byte `json:"-"` + XXX_sizecache int32 `json:"-"` +} + +func (m *Response) Reset() { *m = Response{} } +func (m *Response) String() string { return proto.CompactTextString(m) } +func (*Response) ProtoMessage() {} +func (*Response) Descriptor() ([]byte, []int) { + return fileDescriptor_response_v2_32a9e06b08c12914, []int{1} +} +func (m *Response) XXX_Unmarshal(b []byte) error { + return xxx_messageInfo_Response.Unmarshal(m, b) +} +func (m *Response) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + return xxx_messageInfo_Response.Marshal(b, m, deterministic) +} +func (dst *Response) XXX_Merge(src proto.Message) { + xxx_messageInfo_Response.Merge(dst, src) +} +func (m *Response) XXX_Size() int { + return xxx_messageInfo_Response.Size(m) +} +func (m *Response) XXX_DiscardUnknown() { + xxx_messageInfo_Response.DiscardUnknown(m) +} + +var xxx_messageInfo_Response proto.InternalMessageInfo + +func (m *Response) GetCode() uint32 { + if m != nil { + return m.Code + } + return 0 +} + +func (m *Response) GetInfo() string { + if m != nil { + return m.Info + } + return "" +} + +func (m *Response) GetData() *any.Any { + if m != nil { + return m.Data + } + return nil +} + +type BatchWriteResponse struct { + Code uint32 `protobuf:"varint,1,opt,name=code,proto3" json:"code,omitempty"` + Info string `protobuf:"bytes,2,opt,name=info,proto3" json:"info,omitempty"` + Size uint32 `protobuf:"varint,3,opt,name=size,proto3" json:"size,omitempty"` + Responses []*Response `protobuf:"bytes,4,rep,name=responses,proto3" json:"responses,omitempty"` + XXX_NoUnkeyedLiteral struct{} `json:"-"` + XXX_unrecognized []byte `json:"-"` + XXX_sizecache int32 `json:"-"` +} + +func (m *BatchWriteResponse) Reset() { *m = BatchWriteResponse{} } +func (m *BatchWriteResponse) String() string { return proto.CompactTextString(m) } +func (*BatchWriteResponse) ProtoMessage() {} +func (*BatchWriteResponse) Descriptor() ([]byte, []int) { + return fileDescriptor_response_v2_32a9e06b08c12914, []int{2} +} +func (m *BatchWriteResponse) XXX_Unmarshal(b []byte) error { + return xxx_messageInfo_BatchWriteResponse.Unmarshal(m, b) +} +func (m *BatchWriteResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + return xxx_messageInfo_BatchWriteResponse.Marshal(b, m, deterministic) +} +func (dst *BatchWriteResponse) XXX_Merge(src proto.Message) { + xxx_messageInfo_BatchWriteResponse.Merge(dst, src) +} +func (m *BatchWriteResponse) XXX_Size() int { + return xxx_messageInfo_BatchWriteResponse.Size(m) +} +func (m *BatchWriteResponse) XXX_DiscardUnknown() { + xxx_messageInfo_BatchWriteResponse.DiscardUnknown(m) +} + +var xxx_messageInfo_BatchWriteResponse proto.InternalMessageInfo + +func (m *BatchWriteResponse) GetCode() uint32 { + if m != nil { + return m.Code + } + return 0 +} + +func (m *BatchWriteResponse) GetInfo() string { + if m != nil { + return m.Info + } + return "" +} + +func (m *BatchWriteResponse) GetSize() uint32 { + if m != nil { + return m.Size + } + return 0 +} + +func (m *BatchWriteResponse) GetResponses() []*Response { + if m != nil { + return m.Responses + } + return nil +} + +type BatchQueryResponse struct { + Code uint32 `protobuf:"varint,1,opt,name=code,proto3" json:"code,omitempty"` + Info string `protobuf:"bytes,2,opt,name=info,proto3" json:"info,omitempty"` + Amount uint32 `protobuf:"varint,3,opt,name=amount,proto3" json:"amount,omitempty"` + Size uint32 `protobuf:"varint,4,opt,name=size,proto3" json:"size,omitempty"` + Data []*any.Any `protobuf:"bytes,5,rep,name=data,proto3" json:"data,omitempty"` + XXX_NoUnkeyedLiteral struct{} `json:"-"` + XXX_unrecognized []byte `json:"-"` + XXX_sizecache int32 `json:"-"` +} + +func (m *BatchQueryResponse) Reset() { *m = BatchQueryResponse{} } +func (m *BatchQueryResponse) String() string { return proto.CompactTextString(m) } +func (*BatchQueryResponse) ProtoMessage() {} +func (*BatchQueryResponse) Descriptor() ([]byte, []int) { + return fileDescriptor_response_v2_32a9e06b08c12914, []int{3} +} +func (m *BatchQueryResponse) XXX_Unmarshal(b []byte) error { + return xxx_messageInfo_BatchQueryResponse.Unmarshal(m, b) +} +func (m *BatchQueryResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + return xxx_messageInfo_BatchQueryResponse.Marshal(b, m, deterministic) +} +func (dst *BatchQueryResponse) XXX_Merge(src proto.Message) { + xxx_messageInfo_BatchQueryResponse.Merge(dst, src) +} +func (m *BatchQueryResponse) XXX_Size() int { + return xxx_messageInfo_BatchQueryResponse.Size(m) +} +func (m *BatchQueryResponse) XXX_DiscardUnknown() { + xxx_messageInfo_BatchQueryResponse.DiscardUnknown(m) +} + +var xxx_messageInfo_BatchQueryResponse proto.InternalMessageInfo + +func (m *BatchQueryResponse) GetCode() uint32 { + if m != nil { + return m.Code + } + return 0 +} + +func (m *BatchQueryResponse) GetInfo() string { + if m != nil { + return m.Info + } + return "" +} + +func (m *BatchQueryResponse) GetAmount() uint32 { + if m != nil { + return m.Amount + } + return 0 +} + +func (m *BatchQueryResponse) GetSize() uint32 { + if m != nil { + return m.Size + } + return 0 +} + +func (m *BatchQueryResponse) GetData() []*any.Any { + if m != nil { + return m.Data + } + return nil +} + +type DiscoverResponse struct { + Code uint32 `protobuf:"varint,1,opt,name=code,proto3" json:"code,omitempty"` + Info string `protobuf:"bytes,2,opt,name=info,proto3" json:"info,omitempty"` + Type DiscoverResponse_DiscoverResponseType `protobuf:"varint,3,opt,name=type,proto3,enum=v2.DiscoverResponse_DiscoverResponseType" json:"type,omitempty"` + Service *Service `protobuf:"bytes,4,opt,name=service,proto3" json:"service,omitempty"` + Routings []*Routing `protobuf:"bytes,6,rep,name=routings,proto3" json:"routings,omitempty"` + XXX_NoUnkeyedLiteral struct{} `json:"-"` + XXX_unrecognized []byte `json:"-"` + XXX_sizecache int32 `json:"-"` +} + +func (m *DiscoverResponse) Reset() { *m = DiscoverResponse{} } +func (m *DiscoverResponse) String() string { return proto.CompactTextString(m) } +func (*DiscoverResponse) ProtoMessage() {} +func (*DiscoverResponse) Descriptor() ([]byte, []int) { + return fileDescriptor_response_v2_32a9e06b08c12914, []int{4} +} +func (m *DiscoverResponse) XXX_Unmarshal(b []byte) error { + return xxx_messageInfo_DiscoverResponse.Unmarshal(m, b) +} +func (m *DiscoverResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + return xxx_messageInfo_DiscoverResponse.Marshal(b, m, deterministic) +} +func (dst *DiscoverResponse) XXX_Merge(src proto.Message) { + xxx_messageInfo_DiscoverResponse.Merge(dst, src) +} +func (m *DiscoverResponse) XXX_Size() int { + return xxx_messageInfo_DiscoverResponse.Size(m) +} +func (m *DiscoverResponse) XXX_DiscardUnknown() { + xxx_messageInfo_DiscoverResponse.DiscardUnknown(m) +} + +var xxx_messageInfo_DiscoverResponse proto.InternalMessageInfo + +func (m *DiscoverResponse) GetCode() uint32 { + if m != nil { + return m.Code + } + return 0 +} + +func (m *DiscoverResponse) GetInfo() string { + if m != nil { + return m.Info + } + return "" +} + +func (m *DiscoverResponse) GetType() DiscoverResponse_DiscoverResponseType { + if m != nil { + return m.Type + } + return DiscoverResponse_UNKNOWN +} + +func (m *DiscoverResponse) GetService() *Service { + if m != nil { + return m.Service + } + return nil +} + +func (m *DiscoverResponse) GetRoutings() []*Routing { + if m != nil { + return m.Routings + } + return nil +} + +func init() { + proto.RegisterType((*SimpleResponse)(nil), "v2.SimpleResponse") + proto.RegisterType((*Response)(nil), "v2.Response") + proto.RegisterType((*BatchWriteResponse)(nil), "v2.BatchWriteResponse") + proto.RegisterType((*BatchQueryResponse)(nil), "v2.BatchQueryResponse") + proto.RegisterType((*DiscoverResponse)(nil), "v2.DiscoverResponse") + proto.RegisterEnum("v2.DiscoverResponse_DiscoverResponseType", DiscoverResponse_DiscoverResponseType_name, DiscoverResponse_DiscoverResponseType_value) +} + +func init() { proto.RegisterFile("response_v2.proto", fileDescriptor_response_v2_32a9e06b08c12914) } + +var fileDescriptor_response_v2_32a9e06b08c12914 = []byte{ + // 504 bytes of a gzipped FileDescriptorProto + 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x94, 0x52, 0x5d, 0x6f, 0xd3, 0x30, + 0x14, 0x25, 0xab, 0xd7, 0x66, 0x4e, 0xd7, 0x19, 0x6f, 0x42, 0x65, 0x4f, 0x55, 0x24, 0x44, 0xe9, + 0x43, 0x26, 0x85, 0x17, 0x5e, 0x78, 0x48, 0x53, 0x77, 0xa4, 0x1f, 0x29, 0xdc, 0xa4, 0x1b, 0x6f, + 0x55, 0xd7, 0x79, 0x5d, 0xa4, 0x2d, 0x2e, 0x49, 0x5a, 0xa9, 0x88, 0x5f, 0xc1, 0x2f, 0xe0, 0x17, + 0xf1, 0x9b, 0x90, 0x9d, 0xa4, 0x43, 0x80, 0x90, 0xfa, 0x12, 0xdd, 0x73, 0x8e, 0xef, 0xb9, 0xc7, + 0x37, 0xc6, 0xcf, 0x13, 0x9e, 0xae, 0x44, 0x9c, 0xf2, 0xd9, 0xc6, 0xb6, 0x56, 0x89, 0xc8, 0x04, + 0x3d, 0xd8, 0xd8, 0xe7, 0x24, 0xe1, 0x5f, 0xd6, 0x3c, 0xcd, 0x76, 0xec, 0x39, 0x49, 0xc4, 0x3a, + 0x8b, 0xe2, 0xe5, 0x13, 0xf3, 0x72, 0x29, 0xc4, 0xf2, 0x81, 0x5f, 0x28, 0x74, 0xb3, 0xbe, 0xbb, + 0x98, 0xc7, 0xdb, 0x5c, 0x32, 0xdf, 0xe1, 0x46, 0x10, 0x3d, 0xae, 0x1e, 0x38, 0x14, 0xee, 0x94, + 0x62, 0xb4, 0x10, 0xb7, 0xbc, 0xa9, 0xb5, 0xb4, 0xf6, 0x31, 0xa8, 0x5a, 0x72, 0x51, 0x7c, 0x27, + 0x9a, 0x07, 0x2d, 0xad, 0x7d, 0x04, 0xaa, 0x36, 0xef, 0xb1, 0xbe, 0x6f, 0x0f, 0x6d, 0x63, 0x74, + 0x3b, 0xcf, 0xe6, 0xcd, 0x4a, 0x4b, 0x6b, 0x1b, 0xf6, 0x99, 0x95, 0xe7, 0xb2, 0xca, 0x5c, 0x96, + 0x13, 0x6f, 0x41, 0x9d, 0x18, 0x20, 0xbd, 0x4e, 0x4e, 0x06, 0x48, 0x27, 0xe4, 0xd4, 0xfc, 0x86, + 0x69, 0x77, 0x9e, 0x2d, 0xee, 0xaf, 0x93, 0x28, 0xdb, 0x3b, 0xa7, 0xe4, 0xd2, 0xe8, 0x2b, 0x57, + 0x33, 0x8f, 0x41, 0xd5, 0xb4, 0x83, 0x8f, 0xca, 0x6d, 0xa6, 0x4d, 0xd4, 0xaa, 0xb4, 0x0d, 0xbb, + 0x6e, 0x6d, 0x6c, 0xab, 0x34, 0x87, 0x27, 0xd9, 0xfc, 0xae, 0x15, 0xe3, 0x3f, 0xad, 0x79, 0xb2, + 0xdd, 0x7b, 0xfc, 0x0b, 0x5c, 0x9d, 0x3f, 0x8a, 0x75, 0x9c, 0x15, 0x01, 0x0a, 0xb4, 0x8b, 0x85, + 0x7e, 0x8b, 0x55, 0xae, 0xe7, 0x50, 0x25, 0xfa, 0xcf, 0x7a, 0xcc, 0x1f, 0x15, 0x4c, 0x7a, 0x51, + 0xba, 0x10, 0x1b, 0x9e, 0xec, 0x1d, 0xe9, 0x3d, 0x46, 0xd9, 0x76, 0x95, 0x6f, 0xa4, 0x61, 0xbf, + 0x91, 0x17, 0xff, 0xd3, 0xeb, 0x2f, 0x22, 0xdc, 0xae, 0x38, 0xa8, 0x36, 0xfa, 0x0a, 0xd7, 0x52, + 0x9e, 0x6c, 0xa2, 0x45, 0x1e, 0xde, 0xb0, 0x0d, 0xe9, 0x10, 0xe4, 0x14, 0x94, 0x1a, 0x7d, 0x8d, + 0xf5, 0xe2, 0x21, 0xa6, 0xcd, 0xaa, 0xba, 0x90, 0x3a, 0x07, 0x39, 0x07, 0x3b, 0xd1, 0xfc, 0xa9, + 0xe1, 0xb3, 0x7f, 0x8d, 0xa3, 0x06, 0xae, 0x4d, 0xfd, 0xa1, 0x3f, 0xb9, 0xf6, 0xc9, 0x33, 0x5a, + 0xc7, 0xba, 0xe7, 0x07, 0xa1, 0xe3, 0xbb, 0x8c, 0x68, 0x52, 0x72, 0x47, 0xd3, 0x20, 0x64, 0x40, + 0x0e, 0x24, 0x80, 0xc9, 0x34, 0xf4, 0xfc, 0x4b, 0x52, 0xa1, 0x0d, 0x8c, 0xc1, 0x09, 0xd9, 0x6c, + 0xe4, 0x8d, 0xbd, 0x90, 0x20, 0x7a, 0x8a, 0x4f, 0x5c, 0x0f, 0xdc, 0xa9, 0x17, 0xce, 0xba, 0xc0, + 0x9c, 0x21, 0x03, 0x72, 0x28, 0xcd, 0x02, 0x06, 0x57, 0x9e, 0xcb, 0x02, 0x52, 0x95, 0x2d, 0xbe, + 0x33, 0x66, 0xc1, 0x47, 0x47, 0xe2, 0xba, 0x89, 0xf4, 0x1a, 0x31, 0x3a, 0x68, 0xcc, 0x82, 0x0f, + 0x1d, 0x43, 0x7e, 0x67, 0xee, 0xc4, 0xef, 0x7b, 0x97, 0x9d, 0x46, 0x7f, 0x34, 0xfd, 0x3c, 0xeb, + 0x75, 0x81, 0xf5, 0x41, 0x8a, 0xba, 0xc2, 0x41, 0x6f, 0xd8, 0x31, 0xf2, 0x8a, 0xc1, 0x15, 0x83, + 0x01, 0xd2, 0x0d, 0xd2, 0xb8, 0xa9, 0xaa, 0xdf, 0xf6, 0xf6, 0x57, 0x00, 0x00, 0x00, 0xff, 0xff, + 0x47, 0x5a, 0x69, 0xa4, 0xb8, 0x03, 0x00, 0x00, +} diff --git a/common/api/v2/response_v2.proto b/common/api/v2/response_v2.proto new file mode 100644 index 000000000..3390d9252 --- /dev/null +++ b/common/api/v2/response_v2.proto @@ -0,0 +1,57 @@ +syntax = "proto3"; + +package v2; + +import "request_v2.proto"; +import "routing_v2.proto"; +import "google/protobuf/any.proto"; + +message SimpleResponse { + uint32 code = 1; + string info = 2; +} + +message Response { + uint32 code = 1; + string info = 2; + google.protobuf.Any data = 3; + reserved 12 to 14, 16 to 18; +} + +message BatchWriteResponse { + uint32 code = 1; + string info = 2; + uint32 size = 3; + repeated Response responses = 4; +} + +message BatchQueryResponse { + uint32 code = 1; + string info = 2; + uint32 amount = 3; + uint32 size = 4; + repeated google.protobuf.Any data = 5; +} + +message DiscoverResponse { + uint32 code = 1; + string info = 2; + + enum DiscoverResponseType { + UNKNOWN = 0; + INSTANCE = 1; + CLUSTER = 2; + ROUTING = 3; + RATE_LIMIT = 4; + CIRCUIT_BREAKER = 5; + SERVICES = 6; + reserved 7 to 11; + reserved "MESH", "MESH_CONFIG", "FLUX_DBREFRESH", "FLUX_SDK", "FLUX_SERVER"; + NAMESPACES = 12; + } + + DiscoverResponseType type = 3; + Service service = 4; + repeated Routing routings = 6; + reserved 11 to 13; +} diff --git a/common/api/v2/routing_v2.pb.go b/common/api/v2/routing_v2.pb.go new file mode 100644 index 000000000..d41f709b4 --- /dev/null +++ b/common/api/v2/routing_v2.pb.go @@ -0,0 +1,918 @@ +// Code generated by protoc-gen-go. DO NOT EDIT. +// source: routing_v2.proto + +package v2 + +import proto "github.com/golang/protobuf/proto" +import fmt "fmt" +import math "math" +import any "github.com/golang/protobuf/ptypes/any" + +// Reference imports to suppress errors if they are not otherwise used. +var _ = proto.Marshal +var _ = fmt.Errorf +var _ = math.Inf + +// This is a compile-time assertion to ensure that this generated file +// is compatible with the proto package it is being compiled against. +// A compilation error at this line likely means your copy of the +// proto package needs to be updated. +const _ = proto.ProtoPackageIsVersion2 // please upgrade the proto package + +type RoutingPolicy int32 + +const ( + // Route by rule rule => RuleRoutingConfig + RoutingPolicy_RulePolicy RoutingPolicy = 0 + // Route by destination metadata + RoutingPolicy_MetadataPolicy RoutingPolicy = 1 +) + +var RoutingPolicy_name = map[int32]string{ + 0: "RulePolicy", + 1: "MetadataPolicy", +} +var RoutingPolicy_value = map[string]int32{ + "RulePolicy": 0, + "MetadataPolicy": 1, +} + +func (x RoutingPolicy) String() string { + return proto.EnumName(RoutingPolicy_name, int32(x)) +} +func (RoutingPolicy) EnumDescriptor() ([]byte, []int) { + return fileDescriptor_routing_v2_caeedd2af6edc2ff, []int{0} +} + +type MetadataFailover_FailoverRange int32 + +const ( + // ALL return all instances + MetadataFailover_ALL MetadataFailover_FailoverRange = 0 + // OTHERS retuen without thie labels instances + MetadataFailover_OTHERS MetadataFailover_FailoverRange = 1 + // OTHER_KEYS return other instances which match keys + MetadataFailover_OTHER_KEYS MetadataFailover_FailoverRange = 2 +) + +var MetadataFailover_FailoverRange_name = map[int32]string{ + 0: "ALL", + 1: "OTHERS", + 2: "OTHER_KEYS", +} +var MetadataFailover_FailoverRange_value = map[string]int32{ + "ALL": 0, + "OTHERS": 1, + "OTHER_KEYS": 2, +} + +func (x MetadataFailover_FailoverRange) String() string { + return proto.EnumName(MetadataFailover_FailoverRange_name, int32(x)) +} +func (MetadataFailover_FailoverRange) EnumDescriptor() ([]byte, []int) { + return fileDescriptor_routing_v2_caeedd2af6edc2ff, []int{4, 0} +} + +// label type for gateway request +type SourceMatch_Type int32 + +const ( + // custom arguments + SourceMatch_CUSTOM SourceMatch_Type = 0 + // method, match the http post/get/put/delete or grpc method + SourceMatch_METHOD SourceMatch_Type = 1 + // header, match the http header, dubbo attachment, grpc header + SourceMatch_HEADER SourceMatch_Type = 2 + // query, match the http query, dubbo argument + SourceMatch_QUERY SourceMatch_Type = 3 + // caller host ip + SourceMatch_CALLER_IP SourceMatch_Type = 4 + // path, math the http url + SourceMatch_PATH SourceMatch_Type = 5 + // cookie match http cookie + SourceMatch_COOKIE SourceMatch_Type = 6 +) + +var SourceMatch_Type_name = map[int32]string{ + 0: "CUSTOM", + 1: "METHOD", + 2: "HEADER", + 3: "QUERY", + 4: "CALLER_IP", + 5: "PATH", + 6: "COOKIE", +} +var SourceMatch_Type_value = map[string]int32{ + "CUSTOM": 0, + "METHOD": 1, + "HEADER": 2, + "QUERY": 3, + "CALLER_IP": 4, + "PATH": 5, + "COOKIE": 6, +} + +func (x SourceMatch_Type) String() string { + return proto.EnumName(SourceMatch_Type_name, int32(x)) +} +func (SourceMatch_Type) EnumDescriptor() ([]byte, []int) { + return fileDescriptor_routing_v2_caeedd2af6edc2ff, []int{9, 0} +} + +// FlowStaining 流量染色 +type FlowStaining struct { + Id string `protobuf:"bytes,10,opt,name=id,proto3" json:"id,omitempty"` + // flow statining rule name + Name string `protobuf:"bytes,2,opt,name=name,proto3" json:"name,omitempty"` + // rules staining rules + Rules []*StaineRule `protobuf:"bytes,3,rep,name=rules,proto3" json:"rules,omitempty"` + XXX_NoUnkeyedLiteral struct{} `json:"-"` + XXX_unrecognized []byte `json:"-"` + XXX_sizecache int32 `json:"-"` +} + +func (m *FlowStaining) Reset() { *m = FlowStaining{} } +func (m *FlowStaining) String() string { return proto.CompactTextString(m) } +func (*FlowStaining) ProtoMessage() {} +func (*FlowStaining) Descriptor() ([]byte, []int) { + return fileDescriptor_routing_v2_caeedd2af6edc2ff, []int{0} +} +func (m *FlowStaining) XXX_Unmarshal(b []byte) error { + return xxx_messageInfo_FlowStaining.Unmarshal(m, b) +} +func (m *FlowStaining) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + return xxx_messageInfo_FlowStaining.Marshal(b, m, deterministic) +} +func (dst *FlowStaining) XXX_Merge(src proto.Message) { + xxx_messageInfo_FlowStaining.Merge(dst, src) +} +func (m *FlowStaining) XXX_Size() int { + return xxx_messageInfo_FlowStaining.Size(m) +} +func (m *FlowStaining) XXX_DiscardUnknown() { + xxx_messageInfo_FlowStaining.DiscardUnknown(m) +} + +var xxx_messageInfo_FlowStaining proto.InternalMessageInfo + +func (m *FlowStaining) GetId() string { + if m != nil { + return m.Id + } + return "" +} + +func (m *FlowStaining) GetName() string { + if m != nil { + return m.Name + } + return "" +} + +func (m *FlowStaining) GetRules() []*StaineRule { + if m != nil { + return m.Rules + } + return nil +} + +type StaineRule struct { + // Traffic matching rules + Arguments []*SourceMatch `protobuf:"bytes,1,rep,name=arguments,proto3" json:"arguments,omitempty"` + // Staining label + Labels []*StaineLabel `protobuf:"bytes,2,rep,name=labels,proto3" json:"labels,omitempty"` + // Stain Label + Priority uint32 `protobuf:"varint,3,opt,name=priority,proto3" json:"priority,omitempty"` + // rule is enabled + Enable bool `protobuf:"varint,4,opt,name=enable,proto3" json:"enable,omitempty"` + // Set the percentage of traffic that needs to be dyed + StainePercent uint32 `protobuf:"varint,5,opt,name=stainePercent,proto3" json:"stainePercent,omitempty"` + XXX_NoUnkeyedLiteral struct{} `json:"-"` + XXX_unrecognized []byte `json:"-"` + XXX_sizecache int32 `json:"-"` +} + +func (m *StaineRule) Reset() { *m = StaineRule{} } +func (m *StaineRule) String() string { return proto.CompactTextString(m) } +func (*StaineRule) ProtoMessage() {} +func (*StaineRule) Descriptor() ([]byte, []int) { + return fileDescriptor_routing_v2_caeedd2af6edc2ff, []int{1} +} +func (m *StaineRule) XXX_Unmarshal(b []byte) error { + return xxx_messageInfo_StaineRule.Unmarshal(m, b) +} +func (m *StaineRule) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + return xxx_messageInfo_StaineRule.Marshal(b, m, deterministic) +} +func (dst *StaineRule) XXX_Merge(src proto.Message) { + xxx_messageInfo_StaineRule.Merge(dst, src) +} +func (m *StaineRule) XXX_Size() int { + return xxx_messageInfo_StaineRule.Size(m) +} +func (m *StaineRule) XXX_DiscardUnknown() { + xxx_messageInfo_StaineRule.DiscardUnknown(m) +} + +var xxx_messageInfo_StaineRule proto.InternalMessageInfo + +func (m *StaineRule) GetArguments() []*SourceMatch { + if m != nil { + return m.Arguments + } + return nil +} + +func (m *StaineRule) GetLabels() []*StaineLabel { + if m != nil { + return m.Labels + } + return nil +} + +func (m *StaineRule) GetPriority() uint32 { + if m != nil { + return m.Priority + } + return 0 +} + +func (m *StaineRule) GetEnable() bool { + if m != nil { + return m.Enable + } + return false +} + +func (m *StaineRule) GetStainePercent() uint32 { + if m != nil { + return m.StainePercent + } + return 0 +} + +type StaineLabel struct { + Key string `protobuf:"bytes,1,opt,name=Key,proto3" json:"Key,omitempty"` + Value string `protobuf:"bytes,2,opt,name=Value,proto3" json:"Value,omitempty"` + XXX_NoUnkeyedLiteral struct{} `json:"-"` + XXX_unrecognized []byte `json:"-"` + XXX_sizecache int32 `json:"-"` +} + +func (m *StaineLabel) Reset() { *m = StaineLabel{} } +func (m *StaineLabel) String() string { return proto.CompactTextString(m) } +func (*StaineLabel) ProtoMessage() {} +func (*StaineLabel) Descriptor() ([]byte, []int) { + return fileDescriptor_routing_v2_caeedd2af6edc2ff, []int{2} +} +func (m *StaineLabel) XXX_Unmarshal(b []byte) error { + return xxx_messageInfo_StaineLabel.Unmarshal(m, b) +} +func (m *StaineLabel) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + return xxx_messageInfo_StaineLabel.Marshal(b, m, deterministic) +} +func (dst *StaineLabel) XXX_Merge(src proto.Message) { + xxx_messageInfo_StaineLabel.Merge(dst, src) +} +func (m *StaineLabel) XXX_Size() int { + return xxx_messageInfo_StaineLabel.Size(m) +} +func (m *StaineLabel) XXX_DiscardUnknown() { + xxx_messageInfo_StaineLabel.DiscardUnknown(m) +} + +var xxx_messageInfo_StaineLabel proto.InternalMessageInfo + +func (m *StaineLabel) GetKey() string { + if m != nil { + return m.Key + } + return "" +} + +func (m *StaineLabel) GetValue() string { + if m != nil { + return m.Value + } + return "" +} + +// configuration root for route +type Routing struct { + Id string `protobuf:"bytes,1,opt,name=id,proto3" json:"id,omitempty"` + // route rule name + Name string `protobuf:"bytes,2,opt,name=name,proto3" json:"name,omitempty"` + // namespace namingspace of routing rules + Namespace string `protobuf:"bytes,3,opt,name=namespace,proto3" json:"namespace,omitempty"` + // Enable this router + Enable bool `protobuf:"varint,4,opt,name=enable,proto3" json:"enable,omitempty"` + // Router type + RoutingPolicy RoutingPolicy `protobuf:"varint,5,opt,name=routing_policy,proto3,enum=v2.RoutingPolicy" json:"routing_policy,omitempty"` + // Routing configuration for router + RoutingConfig *any.Any `protobuf:"bytes,6,opt,name=routing_config,proto3" json:"routing_config,omitempty"` + // revision routing version + Revision string `protobuf:"bytes,7,opt,name=revision,proto3" json:"revision,omitempty"` + // ctime create time of the rules + Ctime string `protobuf:"bytes,8,opt,name=ctime,proto3" json:"ctime,omitempty"` + // mtime modify time of the rules + Mtime string `protobuf:"bytes,9,opt,name=mtime,proto3" json:"mtime,omitempty"` + // etime enable time of the rules + Etime string `protobuf:"bytes,10,opt,name=etime,proto3" json:"etime,omitempty"` + // priority rules priority + Priority uint32 `protobuf:"varint,11,opt,name=priority,proto3" json:"priority,omitempty"` + // description simple description rules + Description string `protobuf:"bytes,12,opt,name=description,proto3" json:"description,omitempty"` + // extendInfo 用于承载一些额外信息 + // case 1: 升级到 v2 版本时,记录对应到 v1 版本的 id 信息 + ExtendInfo map[string]string `protobuf:"bytes,20,rep,name=extendInfo,proto3" json:"extendInfo,omitempty" protobuf_key:"bytes,1,opt,name=key,proto3" protobuf_val:"bytes,2,opt,name=value,proto3"` + XXX_NoUnkeyedLiteral struct{} `json:"-"` + XXX_unrecognized []byte `json:"-"` + XXX_sizecache int32 `json:"-"` +} + +func (m *Routing) Reset() { *m = Routing{} } +func (m *Routing) String() string { return proto.CompactTextString(m) } +func (*Routing) ProtoMessage() {} +func (*Routing) Descriptor() ([]byte, []int) { + return fileDescriptor_routing_v2_caeedd2af6edc2ff, []int{3} +} +func (m *Routing) XXX_Unmarshal(b []byte) error { + return xxx_messageInfo_Routing.Unmarshal(m, b) +} +func (m *Routing) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + return xxx_messageInfo_Routing.Marshal(b, m, deterministic) +} +func (dst *Routing) XXX_Merge(src proto.Message) { + xxx_messageInfo_Routing.Merge(dst, src) +} +func (m *Routing) XXX_Size() int { + return xxx_messageInfo_Routing.Size(m) +} +func (m *Routing) XXX_DiscardUnknown() { + xxx_messageInfo_Routing.DiscardUnknown(m) +} + +var xxx_messageInfo_Routing proto.InternalMessageInfo + +func (m *Routing) GetId() string { + if m != nil { + return m.Id + } + return "" +} + +func (m *Routing) GetName() string { + if m != nil { + return m.Name + } + return "" +} + +func (m *Routing) GetNamespace() string { + if m != nil { + return m.Namespace + } + return "" +} + +func (m *Routing) GetEnable() bool { + if m != nil { + return m.Enable + } + return false +} + +func (m *Routing) GetRoutingPolicy() RoutingPolicy { + if m != nil { + return m.RoutingPolicy + } + return RoutingPolicy_RulePolicy +} + +func (m *Routing) GetRoutingConfig() *any.Any { + if m != nil { + return m.RoutingConfig + } + return nil +} + +func (m *Routing) GetRevision() string { + if m != nil { + return m.Revision + } + return "" +} + +func (m *Routing) GetCtime() string { + if m != nil { + return m.Ctime + } + return "" +} + +func (m *Routing) GetMtime() string { + if m != nil { + return m.Mtime + } + return "" +} + +func (m *Routing) GetEtime() string { + if m != nil { + return m.Etime + } + return "" +} + +func (m *Routing) GetPriority() uint32 { + if m != nil { + return m.Priority + } + return 0 +} + +func (m *Routing) GetDescription() string { + if m != nil { + return m.Description + } + return "" +} + +func (m *Routing) GetExtendInfo() map[string]string { + if m != nil { + return m.ExtendInfo + } + return nil +} + +type MetadataFailover struct { + // failover_range metadata route bottom type + FailoverRange MetadataFailover_FailoverRange `protobuf:"varint,1,opt,name=failover_range,json=failoverRange,proto3,enum=v2.MetadataFailover_FailoverRange" json:"failover_range,omitempty"` + // only use to failover_range == OTHER_KEYS + Labels map[string]string `protobuf:"bytes,2,rep,name=labels,proto3" json:"labels,omitempty" protobuf_key:"bytes,1,opt,name=key,proto3" protobuf_val:"bytes,2,opt,name=value,proto3"` + XXX_NoUnkeyedLiteral struct{} `json:"-"` + XXX_unrecognized []byte `json:"-"` + XXX_sizecache int32 `json:"-"` +} + +func (m *MetadataFailover) Reset() { *m = MetadataFailover{} } +func (m *MetadataFailover) String() string { return proto.CompactTextString(m) } +func (*MetadataFailover) ProtoMessage() {} +func (*MetadataFailover) Descriptor() ([]byte, []int) { + return fileDescriptor_routing_v2_caeedd2af6edc2ff, []int{4} +} +func (m *MetadataFailover) XXX_Unmarshal(b []byte) error { + return xxx_messageInfo_MetadataFailover.Unmarshal(m, b) +} +func (m *MetadataFailover) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + return xxx_messageInfo_MetadataFailover.Marshal(b, m, deterministic) +} +func (dst *MetadataFailover) XXX_Merge(src proto.Message) { + xxx_messageInfo_MetadataFailover.Merge(dst, src) +} +func (m *MetadataFailover) XXX_Size() int { + return xxx_messageInfo_MetadataFailover.Size(m) +} +func (m *MetadataFailover) XXX_DiscardUnknown() { + xxx_messageInfo_MetadataFailover.DiscardUnknown(m) +} + +var xxx_messageInfo_MetadataFailover proto.InternalMessageInfo + +func (m *MetadataFailover) GetFailoverRange() MetadataFailover_FailoverRange { + if m != nil { + return m.FailoverRange + } + return MetadataFailover_ALL +} + +func (m *MetadataFailover) GetLabels() map[string]string { + if m != nil { + return m.Labels + } + return nil +} + +// MetadataRoutingConfig metadata routing configuration +type MetadataRoutingConfig struct { + // service + Service string `protobuf:"bytes,1,opt,name=service,proto3" json:"service,omitempty"` + // namespace + Namespace string `protobuf:"bytes,2,opt,name=namespace,proto3" json:"namespace,omitempty"` + Labels map[string]string `protobuf:"bytes,3,rep,name=labels,proto3" json:"labels,omitempty" protobuf_key:"bytes,1,opt,name=key,proto3" protobuf_val:"bytes,2,opt,name=value,proto3"` + // When metadata not found, it will fall back to the + Failover *MetadataFailover `protobuf:"bytes,4,opt,name=failover,proto3" json:"failover,omitempty"` + XXX_NoUnkeyedLiteral struct{} `json:"-"` + XXX_unrecognized []byte `json:"-"` + XXX_sizecache int32 `json:"-"` +} + +func (m *MetadataRoutingConfig) Reset() { *m = MetadataRoutingConfig{} } +func (m *MetadataRoutingConfig) String() string { return proto.CompactTextString(m) } +func (*MetadataRoutingConfig) ProtoMessage() {} +func (*MetadataRoutingConfig) Descriptor() ([]byte, []int) { + return fileDescriptor_routing_v2_caeedd2af6edc2ff, []int{5} +} +func (m *MetadataRoutingConfig) XXX_Unmarshal(b []byte) error { + return xxx_messageInfo_MetadataRoutingConfig.Unmarshal(m, b) +} +func (m *MetadataRoutingConfig) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + return xxx_messageInfo_MetadataRoutingConfig.Marshal(b, m, deterministic) +} +func (dst *MetadataRoutingConfig) XXX_Merge(src proto.Message) { + xxx_messageInfo_MetadataRoutingConfig.Merge(dst, src) +} +func (m *MetadataRoutingConfig) XXX_Size() int { + return xxx_messageInfo_MetadataRoutingConfig.Size(m) +} +func (m *MetadataRoutingConfig) XXX_DiscardUnknown() { + xxx_messageInfo_MetadataRoutingConfig.DiscardUnknown(m) +} + +var xxx_messageInfo_MetadataRoutingConfig proto.InternalMessageInfo + +func (m *MetadataRoutingConfig) GetService() string { + if m != nil { + return m.Service + } + return "" +} + +func (m *MetadataRoutingConfig) GetNamespace() string { + if m != nil { + return m.Namespace + } + return "" +} + +func (m *MetadataRoutingConfig) GetLabels() map[string]string { + if m != nil { + return m.Labels + } + return nil +} + +func (m *MetadataRoutingConfig) GetFailover() *MetadataFailover { + if m != nil { + return m.Failover + } + return nil +} + +// RuleRoutingConfig routing configuration +type RuleRoutingConfig struct { + // source source info + Sources []*Source `protobuf:"bytes,1,rep,name=sources,proto3" json:"sources,omitempty"` + // destination destinations info + Destinations []*Destination `protobuf:"bytes,2,rep,name=destinations,proto3" json:"destinations,omitempty"` + XXX_NoUnkeyedLiteral struct{} `json:"-"` + XXX_unrecognized []byte `json:"-"` + XXX_sizecache int32 `json:"-"` +} + +func (m *RuleRoutingConfig) Reset() { *m = RuleRoutingConfig{} } +func (m *RuleRoutingConfig) String() string { return proto.CompactTextString(m) } +func (*RuleRoutingConfig) ProtoMessage() {} +func (*RuleRoutingConfig) Descriptor() ([]byte, []int) { + return fileDescriptor_routing_v2_caeedd2af6edc2ff, []int{6} +} +func (m *RuleRoutingConfig) XXX_Unmarshal(b []byte) error { + return xxx_messageInfo_RuleRoutingConfig.Unmarshal(m, b) +} +func (m *RuleRoutingConfig) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + return xxx_messageInfo_RuleRoutingConfig.Marshal(b, m, deterministic) +} +func (dst *RuleRoutingConfig) XXX_Merge(src proto.Message) { + xxx_messageInfo_RuleRoutingConfig.Merge(dst, src) +} +func (m *RuleRoutingConfig) XXX_Size() int { + return xxx_messageInfo_RuleRoutingConfig.Size(m) +} +func (m *RuleRoutingConfig) XXX_DiscardUnknown() { + xxx_messageInfo_RuleRoutingConfig.DiscardUnknown(m) +} + +var xxx_messageInfo_RuleRoutingConfig proto.InternalMessageInfo + +func (m *RuleRoutingConfig) GetSources() []*Source { + if m != nil { + return m.Sources + } + return nil +} + +func (m *RuleRoutingConfig) GetDestinations() []*Destination { + if m != nil { + return m.Destinations + } + return nil +} + +type Source struct { + // Main tuning service and namespace + Service string `protobuf:"bytes,1,opt,name=service,proto3" json:"service,omitempty"` + Namespace string `protobuf:"bytes,2,opt,name=namespace,proto3" json:"namespace,omitempty"` + // Master Control Service Example Tag or Request Label + // Value supports regular matching + Arguments []*SourceMatch `protobuf:"bytes,3,rep,name=arguments,proto3" json:"arguments,omitempty"` + XXX_NoUnkeyedLiteral struct{} `json:"-"` + XXX_unrecognized []byte `json:"-"` + XXX_sizecache int32 `json:"-"` +} + +func (m *Source) Reset() { *m = Source{} } +func (m *Source) String() string { return proto.CompactTextString(m) } +func (*Source) ProtoMessage() {} +func (*Source) Descriptor() ([]byte, []int) { + return fileDescriptor_routing_v2_caeedd2af6edc2ff, []int{7} +} +func (m *Source) XXX_Unmarshal(b []byte) error { + return xxx_messageInfo_Source.Unmarshal(m, b) +} +func (m *Source) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + return xxx_messageInfo_Source.Marshal(b, m, deterministic) +} +func (dst *Source) XXX_Merge(src proto.Message) { + xxx_messageInfo_Source.Merge(dst, src) +} +func (m *Source) XXX_Size() int { + return xxx_messageInfo_Source.Size(m) +} +func (m *Source) XXX_DiscardUnknown() { + xxx_messageInfo_Source.DiscardUnknown(m) +} + +var xxx_messageInfo_Source proto.InternalMessageInfo + +func (m *Source) GetService() string { + if m != nil { + return m.Service + } + return "" +} + +func (m *Source) GetNamespace() string { + if m != nil { + return m.Namespace + } + return "" +} + +func (m *Source) GetArguments() []*SourceMatch { + if m != nil { + return m.Arguments + } + return nil +} + +type Destination struct { + // Templated service and namespace + Service string `protobuf:"bytes,1,opt,name=service,proto3" json:"service,omitempty"` + Namespace string `protobuf:"bytes,2,opt,name=namespace,proto3" json:"namespace,omitempty"` + // Templated service example label + // Value supports regular matching + Labels map[string]*MatchString `protobuf:"bytes,3,rep,name=labels,proto3" json:"labels,omitempty" protobuf_key:"bytes,1,opt,name=key,proto3" protobuf_val:"bytes,2,opt,name=value,proto3"` + // According to the service name and service instance Metadata Filter the + // qualified service instance subset Service instance subset can set priority + // and weight Priority: integer, range [0, 9], the highest priority is 0 + // Weight: Integer + // Press priority routing, if there is high priority, low priority will not + // use If there is a subset of the same priority, then assign by weight + // Priority and weight can be not set / set up one / set two + // If the section is set priority, some are not set, it is considered that the + // priority is not set. If the part is set, some is not set, it is considered + // that the weight is not set to 0 If you have no weight, you think the weight + // is the same + Priority uint32 `protobuf:"varint,4,opt,name=priority,proto3" json:"priority,omitempty"` + Weight uint32 `protobuf:"varint,5,opt,name=weight,proto3" json:"weight,omitempty"` + // Forward requests to proxy service + Transfer string `protobuf:"bytes,6,opt,name=transfer,proto3" json:"transfer,omitempty"` + // Whether to isolate the SET, after isolation, no traffic will be allocated + Isolate bool `protobuf:"varint,7,opt,name=isolate,proto3" json:"isolate,omitempty"` + // name desition name + Name string `protobuf:"bytes,8,opt,name=name,proto3" json:"name,omitempty"` + XXX_NoUnkeyedLiteral struct{} `json:"-"` + XXX_unrecognized []byte `json:"-"` + XXX_sizecache int32 `json:"-"` +} + +func (m *Destination) Reset() { *m = Destination{} } +func (m *Destination) String() string { return proto.CompactTextString(m) } +func (*Destination) ProtoMessage() {} +func (*Destination) Descriptor() ([]byte, []int) { + return fileDescriptor_routing_v2_caeedd2af6edc2ff, []int{8} +} +func (m *Destination) XXX_Unmarshal(b []byte) error { + return xxx_messageInfo_Destination.Unmarshal(m, b) +} +func (m *Destination) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + return xxx_messageInfo_Destination.Marshal(b, m, deterministic) +} +func (dst *Destination) XXX_Merge(src proto.Message) { + xxx_messageInfo_Destination.Merge(dst, src) +} +func (m *Destination) XXX_Size() int { + return xxx_messageInfo_Destination.Size(m) +} +func (m *Destination) XXX_DiscardUnknown() { + xxx_messageInfo_Destination.DiscardUnknown(m) +} + +var xxx_messageInfo_Destination proto.InternalMessageInfo + +func (m *Destination) GetService() string { + if m != nil { + return m.Service + } + return "" +} + +func (m *Destination) GetNamespace() string { + if m != nil { + return m.Namespace + } + return "" +} + +func (m *Destination) GetLabels() map[string]*MatchString { + if m != nil { + return m.Labels + } + return nil +} + +func (m *Destination) GetPriority() uint32 { + if m != nil { + return m.Priority + } + return 0 +} + +func (m *Destination) GetWeight() uint32 { + if m != nil { + return m.Weight + } + return 0 +} + +func (m *Destination) GetTransfer() string { + if m != nil { + return m.Transfer + } + return "" +} + +func (m *Destination) GetIsolate() bool { + if m != nil { + return m.Isolate + } + return false +} + +func (m *Destination) GetName() string { + if m != nil { + return m.Name + } + return "" +} + +// SourceMatch +type SourceMatch struct { + Type SourceMatch_Type `protobuf:"varint,1,opt,name=type,proto3,enum=v2.SourceMatch_Type" json:"type,omitempty"` + // header key or query key + Key string `protobuf:"bytes,2,opt,name=key,proto3" json:"key,omitempty"` + // header value or query value + Value *MatchString `protobuf:"bytes,3,opt,name=value,proto3" json:"value,omitempty"` + XXX_NoUnkeyedLiteral struct{} `json:"-"` + XXX_unrecognized []byte `json:"-"` + XXX_sizecache int32 `json:"-"` +} + +func (m *SourceMatch) Reset() { *m = SourceMatch{} } +func (m *SourceMatch) String() string { return proto.CompactTextString(m) } +func (*SourceMatch) ProtoMessage() {} +func (*SourceMatch) Descriptor() ([]byte, []int) { + return fileDescriptor_routing_v2_caeedd2af6edc2ff, []int{9} +} +func (m *SourceMatch) XXX_Unmarshal(b []byte) error { + return xxx_messageInfo_SourceMatch.Unmarshal(m, b) +} +func (m *SourceMatch) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + return xxx_messageInfo_SourceMatch.Marshal(b, m, deterministic) +} +func (dst *SourceMatch) XXX_Merge(src proto.Message) { + xxx_messageInfo_SourceMatch.Merge(dst, src) +} +func (m *SourceMatch) XXX_Size() int { + return xxx_messageInfo_SourceMatch.Size(m) +} +func (m *SourceMatch) XXX_DiscardUnknown() { + xxx_messageInfo_SourceMatch.DiscardUnknown(m) +} + +var xxx_messageInfo_SourceMatch proto.InternalMessageInfo + +func (m *SourceMatch) GetType() SourceMatch_Type { + if m != nil { + return m.Type + } + return SourceMatch_CUSTOM +} + +func (m *SourceMatch) GetKey() string { + if m != nil { + return m.Key + } + return "" +} + +func (m *SourceMatch) GetValue() *MatchString { + if m != nil { + return m.Value + } + return nil +} + +func init() { + proto.RegisterType((*FlowStaining)(nil), "v2.FlowStaining") + proto.RegisterType((*StaineRule)(nil), "v2.StaineRule") + proto.RegisterType((*StaineLabel)(nil), "v2.StaineLabel") + proto.RegisterType((*Routing)(nil), "v2.Routing") + proto.RegisterMapType((map[string]string)(nil), "v2.Routing.ExtendInfoEntry") + proto.RegisterType((*MetadataFailover)(nil), "v2.MetadataFailover") + proto.RegisterMapType((map[string]string)(nil), "v2.MetadataFailover.LabelsEntry") + proto.RegisterType((*MetadataRoutingConfig)(nil), "v2.MetadataRoutingConfig") + proto.RegisterMapType((map[string]string)(nil), "v2.MetadataRoutingConfig.LabelsEntry") + proto.RegisterType((*RuleRoutingConfig)(nil), "v2.RuleRoutingConfig") + proto.RegisterType((*Source)(nil), "v2.Source") + proto.RegisterType((*Destination)(nil), "v2.Destination") + proto.RegisterMapType((map[string]*MatchString)(nil), "v2.Destination.LabelsEntry") + proto.RegisterType((*SourceMatch)(nil), "v2.SourceMatch") + proto.RegisterEnum("v2.RoutingPolicy", RoutingPolicy_name, RoutingPolicy_value) + proto.RegisterEnum("v2.MetadataFailover_FailoverRange", MetadataFailover_FailoverRange_name, MetadataFailover_FailoverRange_value) + proto.RegisterEnum("v2.SourceMatch_Type", SourceMatch_Type_name, SourceMatch_Type_value) +} + +func init() { proto.RegisterFile("routing_v2.proto", fileDescriptor_routing_v2_caeedd2af6edc2ff) } + +var fileDescriptor_routing_v2_caeedd2af6edc2ff = []byte{ + // 918 bytes of a gzipped FileDescriptorProto + 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xa4, 0x55, 0x4f, 0x8f, 0xdb, 0x44, + 0x14, 0xaf, 0xed, 0xfc, 0x7d, 0xd9, 0xb8, 0xee, 0x68, 0x41, 0x26, 0xe5, 0x10, 0x59, 0x5b, 0x11, + 0x21, 0xe1, 0xa2, 0x2c, 0x48, 0x2d, 0xd0, 0x43, 0xb4, 0xeb, 0x6a, 0x97, 0xcd, 0x2a, 0xcb, 0x24, + 0x45, 0x94, 0xcb, 0xca, 0xeb, 0x4c, 0xdc, 0x51, 0x9d, 0x71, 0x64, 0x4f, 0x52, 0xf2, 0x0d, 0xf8, + 0x54, 0x9c, 0x38, 0xf2, 0x71, 0xb8, 0x71, 0x41, 0x33, 0x63, 0x27, 0xb6, 0x09, 0xad, 0x58, 0x4e, + 0x9e, 0xf7, 0x9b, 0x37, 0xf3, 0xe6, 0xfd, 0xde, 0x7b, 0x3f, 0x83, 0x95, 0xc4, 0x6b, 0x4e, 0x59, + 0x78, 0xbb, 0x19, 0xba, 0xab, 0x24, 0xe6, 0x31, 0xd2, 0x37, 0xc3, 0x9e, 0xb9, 0x8c, 0xe7, 0x24, + 0xda, 0x61, 0xbd, 0x4f, 0xc2, 0x38, 0x0e, 0x23, 0xf2, 0x54, 0x5a, 0x77, 0xeb, 0xc5, 0x53, 0x9f, + 0x6d, 0xd5, 0x96, 0xf3, 0x13, 0x1c, 0xbd, 0x8c, 0xe2, 0x77, 0x53, 0xee, 0x53, 0x46, 0x59, 0x88, + 0x4c, 0xd0, 0xe9, 0xdc, 0x86, 0xbe, 0x36, 0x68, 0x63, 0x9d, 0xce, 0x11, 0x82, 0x1a, 0xf3, 0x97, + 0xc4, 0xd6, 0x25, 0x22, 0xd7, 0xe8, 0x04, 0xea, 0xc9, 0x3a, 0x22, 0xa9, 0x6d, 0xf4, 0x8d, 0x41, + 0x67, 0x68, 0xba, 0x9b, 0xa1, 0x2b, 0x2f, 0x20, 0x78, 0x1d, 0x11, 0xac, 0x36, 0x9d, 0xdf, 0x34, + 0x80, 0x3d, 0x8a, 0xbe, 0x80, 0xb6, 0x9f, 0x84, 0xeb, 0x25, 0x61, 0x3c, 0xb5, 0x35, 0x79, 0xf0, + 0xa1, 0x3c, 0x18, 0xaf, 0x93, 0x80, 0x5c, 0xfb, 0x3c, 0x78, 0x83, 0xf7, 0x1e, 0xe8, 0x33, 0x68, + 0x44, 0xfe, 0x1d, 0x89, 0x52, 0x5b, 0x2f, 0xf8, 0xca, 0xeb, 0xc6, 0x02, 0xc7, 0xd9, 0x36, 0xea, + 0x41, 0x6b, 0x95, 0xd0, 0x38, 0xa1, 0x7c, 0x6b, 0x1b, 0x7d, 0x6d, 0xd0, 0xc5, 0x3b, 0x1b, 0x7d, + 0x0c, 0x0d, 0xc2, 0xfc, 0xbb, 0x88, 0xd8, 0xb5, 0xbe, 0x36, 0x68, 0xe1, 0xcc, 0x42, 0x27, 0xd0, + 0x4d, 0xe5, 0x55, 0x37, 0x24, 0x09, 0x08, 0xe3, 0x76, 0x5d, 0x1e, 0x2c, 0x83, 0xce, 0xd7, 0xd0, + 0x29, 0x04, 0x44, 0x16, 0x18, 0x57, 0x64, 0x6b, 0x6b, 0x92, 0x08, 0xb1, 0x44, 0xc7, 0x50, 0xff, + 0xd1, 0x8f, 0xd6, 0x39, 0x39, 0xca, 0x70, 0xfe, 0x34, 0xa0, 0x89, 0x55, 0x55, 0x32, 0x36, 0xb5, + 0xf7, 0xb2, 0xf9, 0x29, 0xb4, 0xc5, 0x37, 0x5d, 0xf9, 0x01, 0x91, 0x19, 0xb4, 0xf1, 0x1e, 0xf8, + 0xd7, 0x14, 0x9e, 0x83, 0x99, 0x97, 0x7e, 0x15, 0x47, 0x34, 0xd8, 0xca, 0x1c, 0xcc, 0xe1, 0x23, + 0xc1, 0x53, 0x16, 0xfe, 0x46, 0x6e, 0xe0, 0x8a, 0x23, 0xfa, 0x6e, 0x7f, 0x34, 0x88, 0xd9, 0x82, + 0x86, 0x76, 0xa3, 0xaf, 0x0d, 0x3a, 0xc3, 0x63, 0x57, 0xb5, 0x89, 0x9b, 0xb7, 0x89, 0x3b, 0x62, + 0x85, 0xd3, 0xca, 0x57, 0xf0, 0x9d, 0x90, 0x0d, 0x4d, 0x69, 0xcc, 0xec, 0xa6, 0x7c, 0xed, 0xce, + 0x16, 0x84, 0x04, 0x9c, 0x2e, 0x89, 0xdd, 0x52, 0x84, 0x48, 0x43, 0xa0, 0x4b, 0x89, 0xb6, 0x15, + 0xba, 0xcc, 0x51, 0x22, 0x51, 0xd5, 0x6b, 0xca, 0x28, 0x55, 0xb3, 0x53, 0xa9, 0x66, 0x1f, 0x3a, + 0x73, 0x92, 0x06, 0x09, 0x5d, 0x71, 0x11, 0xfc, 0x48, 0x9e, 0x2b, 0x42, 0xe8, 0x5b, 0x00, 0xf2, + 0x0b, 0x27, 0x6c, 0x7e, 0xc9, 0x16, 0xb1, 0x7d, 0x2c, 0x1b, 0xe7, 0x71, 0x81, 0x10, 0xd7, 0xdb, + 0xed, 0x7a, 0x8c, 0x27, 0x5b, 0x5c, 0x70, 0xef, 0xbd, 0x80, 0x87, 0x95, 0x6d, 0x51, 0xf2, 0xb7, + 0xfb, 0x92, 0xbf, 0x55, 0x25, 0xdf, 0x14, 0x4b, 0x2e, 0x8d, 0x6f, 0xf4, 0x67, 0x9a, 0xf3, 0xab, + 0x0e, 0xd6, 0x35, 0xe1, 0xfe, 0xdc, 0xe7, 0xfe, 0x4b, 0x9f, 0x46, 0xf1, 0x86, 0x24, 0xe8, 0x12, + 0xcc, 0x45, 0xb6, 0xbe, 0x4d, 0x7c, 0x16, 0x12, 0x79, 0x97, 0x39, 0x74, 0xc4, 0xa3, 0xaa, 0xde, + 0x6e, 0xbe, 0xc0, 0xc2, 0x13, 0x77, 0x17, 0x45, 0x13, 0x3d, 0xab, 0x0c, 0x44, 0xff, 0xe0, 0x15, + 0xb2, 0x55, 0x53, 0x95, 0x5c, 0xe6, 0xdf, 0x7b, 0x0e, 0x9d, 0x02, 0xfc, 0x9f, 0x92, 0xfa, 0x0a, + 0xba, 0xa5, 0x47, 0xa1, 0x26, 0x18, 0xa3, 0xf1, 0xd8, 0x7a, 0x80, 0x00, 0x1a, 0x93, 0xd9, 0x85, + 0x87, 0xa7, 0x96, 0x86, 0x4c, 0x00, 0xb9, 0xbe, 0xbd, 0xf2, 0x5e, 0x4f, 0x2d, 0xdd, 0xf9, 0x4b, + 0x83, 0x8f, 0xf2, 0x97, 0x65, 0xcc, 0x9f, 0xa9, 0xe6, 0xb1, 0xa1, 0x99, 0x92, 0x64, 0x43, 0x03, + 0x92, 0xc5, 0xcf, 0xcd, 0xf2, 0x14, 0xe8, 0xd5, 0x29, 0x78, 0xb1, 0x4b, 0x5e, 0x49, 0xce, 0x93, + 0x62, 0xf2, 0xa5, 0x10, 0x87, 0x18, 0x40, 0x5f, 0x42, 0x2b, 0x27, 0x53, 0x8e, 0x91, 0xe8, 0xf5, + 0x03, 0xec, 0xe1, 0x9d, 0xd7, 0xff, 0xe1, 0x8c, 0xc1, 0x23, 0x29, 0x83, 0xa5, 0xc4, 0x4f, 0xa0, + 0x99, 0x4a, 0xa1, 0xcb, 0xb5, 0x0f, 0xf6, 0xda, 0x87, 0xf3, 0x2d, 0x74, 0x0a, 0x47, 0x73, 0x92, + 0x72, 0xca, 0x7c, 0xd1, 0xce, 0x25, 0xe9, 0x3b, 0xdf, 0xe3, 0xb8, 0xe4, 0xe4, 0xc4, 0xd0, 0x50, + 0xf7, 0xdc, 0x9b, 0xdd, 0x92, 0x34, 0x1b, 0x1f, 0x92, 0x66, 0xe7, 0x77, 0x1d, 0x3a, 0x85, 0xe7, + 0xdc, 0x3b, 0xec, 0x69, 0xa5, 0xa8, 0x8f, 0x2b, 0x79, 0x1e, 0x2c, 0x65, 0x51, 0x20, 0x6a, 0xff, + 0x94, 0xfb, 0x77, 0x84, 0x86, 0x6f, 0x72, 0x3d, 0xcf, 0x2c, 0x71, 0x86, 0x27, 0x3e, 0x4b, 0x17, + 0x24, 0x91, 0x52, 0xd7, 0xc6, 0x3b, 0x5b, 0x3c, 0x9e, 0xa6, 0x71, 0xe4, 0x73, 0x22, 0xd5, 0xac, + 0x85, 0x73, 0x73, 0xa7, 0xd5, 0xad, 0xbd, 0x56, 0xf7, 0xbe, 0xff, 0x50, 0x5b, 0x3c, 0x29, 0xb6, + 0x45, 0x46, 0xa3, 0x24, 0x70, 0xca, 0x13, 0xca, 0xc2, 0x62, 0x9f, 0xfc, 0xa1, 0x41, 0xa7, 0xc0, + 0x30, 0x1a, 0x40, 0x8d, 0x6f, 0x57, 0xb9, 0x42, 0x1c, 0x57, 0x0a, 0xe0, 0xce, 0xb6, 0x2b, 0x82, + 0xa5, 0x47, 0x1e, 0x56, 0x3f, 0x10, 0xd6, 0x78, 0x5f, 0x58, 0xe7, 0x67, 0xa8, 0x89, 0x6b, 0xc4, + 0xf0, 0x9e, 0xbd, 0x9a, 0xce, 0x26, 0xd7, 0x6a, 0x90, 0xaf, 0xbd, 0xd9, 0xc5, 0xe4, 0xdc, 0xd2, + 0xc4, 0xfa, 0xc2, 0x1b, 0x9d, 0x7b, 0xd8, 0xd2, 0x51, 0x1b, 0xea, 0x3f, 0xbc, 0xf2, 0xf0, 0x6b, + 0xcb, 0x40, 0x5d, 0x68, 0x9f, 0x8d, 0xc6, 0x63, 0x0f, 0xdf, 0x5e, 0xde, 0x58, 0x35, 0xd4, 0x82, + 0xda, 0xcd, 0x68, 0x76, 0x61, 0xd5, 0xe5, 0x3d, 0x93, 0xc9, 0xd5, 0xa5, 0x67, 0x35, 0x3e, 0x3f, + 0x85, 0x6e, 0xe9, 0xb7, 0x23, 0x54, 0x41, 0xcc, 0x81, 0xb2, 0xac, 0x07, 0x08, 0x81, 0x99, 0x0f, + 0x5c, 0x86, 0x69, 0x77, 0x0d, 0xf9, 0xab, 0x39, 0xfd, 0x3b, 0x00, 0x00, 0xff, 0xff, 0xbf, 0x9a, + 0xeb, 0x17, 0xc7, 0x08, 0x00, 0x00, +} diff --git a/common/api/v2/routing_v2.proto b/common/api/v2/routing_v2.proto new file mode 100644 index 000000000..19ffa02b9 --- /dev/null +++ b/common/api/v2/routing_v2.proto @@ -0,0 +1,174 @@ +syntax = "proto3"; + +package v2; + +import "model_v2.proto"; + +import "google/protobuf/any.proto"; + +// FlowStaining 流量染色 +message FlowStaining { + string id = 10; + // flow statining rule name + string name = 2; + // rules staining rules + repeated StaineRule rules = 3; +} + +message StaineRule { + // Traffic matching rules + repeated SourceMatch arguments = 1; + // Staining label + repeated StaineLabel labels = 2; + // Stain Label + uint32 priority = 3; + // rule is enabled + bool enable = 4; + // Set the percentage of traffic that needs to be dyed + uint32 stainePercent = 5; +} + +message StaineLabel { + string Key = 1; + string Value = 2; +} + +enum RoutingPolicy { + // Route by rule rule => RuleRoutingConfig + RulePolicy = 0; + // Route by destination metadata + MetadataPolicy = 1; +} + +// configuration root for route +message Routing { + string id = 1; + // route rule name + string name = 2; + // namespace namingspace of routing rules + string namespace = 3; + // Enable this router + bool enable = 4; + // Router type + RoutingPolicy routing_policy = 5 [ json_name = "routing_policy" ]; + // Routing configuration for router + google.protobuf.Any routing_config = 6 [ json_name = "routing_config" ]; + // revision routing version + string revision = 7; + // ctime create time of the rules + string ctime = 8; + // mtime modify time of the rules + string mtime = 9; + // etime enable time of the rules + string etime = 10; + // priority rules priority + uint32 priority = 11; + // description simple description rules + string description = 12; + // extendInfo 用于承载一些额外信息 + // case 1: 升级到 v2 版本时,记录对应到 v1 版本的 id 信息 + map extendInfo = 20; +} + +message MetadataFailover { + enum FailoverRange { + // ALL return all instances + ALL = 0; + // OTHERS retuen without thie labels instances + OTHERS = 1; + // OTHER_KEYS return other instances which match keys + OTHER_KEYS = 2; + } + // failover_range metadata route bottom type + FailoverRange failover_range = 1; + // only use to failover_range == OTHER_KEYS + map labels = 2; +} + +// MetadataRoutingConfig metadata routing configuration +message MetadataRoutingConfig { + // service + string service = 1; + // namespace + string namespace = 2; + map labels = 3; + // When metadata not found, it will fall back to the + MetadataFailover failover = 4; +} + +// RuleRoutingConfig routing configuration +message RuleRoutingConfig { + // source source info + repeated Source sources = 1; + // destination destinations info + repeated Destination destinations = 2; +} + +message Source { + // Main tuning service and namespace + string service = 1; + string namespace = 2; + + // Master Control Service Example Tag or Request Label + // Value supports regular matching + repeated SourceMatch arguments = 3; +} + +message Destination { + // Templated service and namespace + string service = 1; + string namespace = 2; + + // Templated service example label + // Value supports regular matching + map labels = 3; + + // According to the service name and service instance Metadata Filter the + // qualified service instance subset Service instance subset can set priority + // and weight Priority: integer, range [0, 9], the highest priority is 0 + // Weight: Integer + // Press priority routing, if there is high priority, low priority will not + // use If there is a subset of the same priority, then assign by weight + // Priority and weight can be not set / set up one / set two + // If the section is set priority, some are not set, it is considered that the + // priority is not set. If the part is set, some is not set, it is considered + // that the weight is not set to 0 If you have no weight, you think the weight + // is the same + uint32 priority = 4; + uint32 weight = 5; + + // Forward requests to proxy service + string transfer = 6; + + // Whether to isolate the SET, after isolation, no traffic will be allocated + bool isolate = 7; + + // name desition name + string name = 8; +} + +// SourceMatch +message SourceMatch { + // label type for gateway request + enum Type { + // custom arguments + CUSTOM = 0; + // method, match the http post/get/put/delete or grpc method + METHOD = 1; + // header, match the http header, dubbo attachment, grpc header + HEADER = 2; + // query, match the http query, dubbo argument + QUERY = 3; + // caller host ip + CALLER_IP = 4; + // path, math the http url + PATH = 5; + // cookie match http cookie + COOKIE = 6; + } + Type type = 1; + // header key or query key + string key = 2; + // header value or query value + MatchString value = 3; +} diff --git a/common/auth/auth.go b/common/auth/auth.go new file mode 100644 index 000000000..7b464d053 --- /dev/null +++ b/common/auth/auth.go @@ -0,0 +1,35 @@ +/** + * Tencent is pleased to support the open source community by making Polaris available. + * + * Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved. + * + * Licensed under the BSD 3-Clause License (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://opensource.org/licenses/BSD-3-Clause + * + * 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 auth + +import ( + "context" + + "github.com/polarismesh/polaris-server/common/model" + "github.com/polarismesh/polaris-server/common/utils" +) + +// ParseUserRole 从ctx中解析用户角色 +func ParseUserRole(ctx context.Context) model.UserRoleType { + if ctx == nil { + return model.SubAccountUserRole + } + + role, _ := ctx.Value(utils.ContextUserRoleIDKey).(model.UserRoleType) + return role +} diff --git a/common/utils/cl5.go b/common/cl5/cl5.go similarity index 99% rename from common/utils/cl5.go rename to common/cl5/cl5.go index dc7db2685..60f7d01d0 100644 --- a/common/utils/cl5.go +++ b/common/cl5/cl5.go @@ -15,7 +15,7 @@ * specific language governing permissions and limitations under the License. */ -package utils +package cl5 import ( "errors" diff --git a/common/log/type.go b/common/log/type.go index 8f322dcde..c2eb8a583 100644 --- a/common/log/type.go +++ b/common/log/type.go @@ -21,6 +21,8 @@ package log const ( // NamingLoggerName naming logger name, can use FindScope function to get the logger NamingLoggerName = "naming" + // HealthCheckLoggerName healthcheck logger name, can use FindScope function to get the logger + HealthCheckLoggerName = "healthcheck" // ConfigLoggerName config logger name, can use FindScope function to get the logger ConfigLoggerName = "config" // CacheLoggerName cache logger name, can use FindScope function to get the logger @@ -29,24 +31,37 @@ const ( AuthLoggerName = "auth" // StoreLoggerName store logger name, can use FindScope function to get the logger StoreLoggerName = "store" + // APIServerLoggerName apiserver logger name, can use FindScope function to get the logger + APIServerLoggerName = "apiserver" + // XDSLoggerName xdsv3 logger name, can use FindScope function to get the logger + XDSLoggerName = "xdsv3" ) var ( - namingScope = RegisterScope(NamingLoggerName, "naming logging messages.", 0) - configScope = RegisterScope(ConfigLoggerName, "naming logging messages.", 0) - cacheScope = RegisterScope(CacheLoggerName, "naming logging messages.", 0) - authScope = RegisterScope(AuthLoggerName, "naming logging messages.", 0) - storeScope = RegisterScope(StoreLoggerName, "store logging messages.", 0) + namingScope = RegisterScope(NamingLoggerName, "naming logging messages.", 0) + healthcheckScope = RegisterScope(HealthCheckLoggerName, "healthcheck logging messages.", 0) + configScope = RegisterScope(ConfigLoggerName, "config logging messages.", 0) + cacheScope = RegisterScope(CacheLoggerName, "cache logging messages.", 0) + authScope = RegisterScope(AuthLoggerName, "auth logging messages.", 0) + storeScope = RegisterScope(StoreLoggerName, "store logging messages.", 0) + apiserverScope = RegisterScope(APIServerLoggerName, "apiserver logging messages.", 0) + xdsScope = RegisterScope(XDSLoggerName, "xdsv3 logging messages.", 0) ) func allLoggerTypes() []string { return []string{NamingLoggerName, ConfigLoggerName, CacheLoggerName, - AuthLoggerName, StoreLoggerName, DefaultLoggerName} + AuthLoggerName, StoreLoggerName, APIServerLoggerName, HealthCheckLoggerName, + XDSLoggerName, DefaultLoggerName} +} + +// APIServerScope apiserver logging scope handler +func APIServerScope() *Scope { + return apiserverScope } // DefaultScope default logging scope handler func DefaultScope() *Scope { - return defaultScope + return apiserverScope } // NamingScope naming logging scope handler @@ -54,6 +69,11 @@ func NamingScope() *Scope { return namingScope } +// HealthCheckScope healthcheck logging scope handler +func HealthCheckScope() *Scope { + return healthcheckScope +} + // ConfigScope config logging scope handler func ConfigScope() *Scope { return configScope @@ -73,3 +93,8 @@ func AuthScope() *Scope { func StoreScope() *Scope { return storeScope } + +// XDSV3Scope xdsv3 logging scope handler +func XDSV3Scope() *Scope { + return xdsScope +} diff --git a/common/model/naming.go b/common/model/naming.go index 514727c2e..02c57f2aa 100644 --- a/common/model/naming.go +++ b/common/model/naming.go @@ -235,44 +235,58 @@ const ( ) // Arguments2Labels 将参数列表适配成旧的标签模型 -func (r *RateLimit) Arguments2Labels() bool { - if len(r.Proto.Arguments) > 0 { - r.Proto.Labels = make(map[string]*v1.MatchString) - for _, argument := range r.Proto.Arguments { +func Arguments2Labels(arguments []*v1.MatchArgument) map[string]*v1.MatchString { + if len(arguments) > 0 { + var labels = make(map[string]*v1.MatchString) + for _, argument := range arguments { switch argument.Type { case v1.MatchArgument_CUSTOM: - r.Proto.Labels[argument.Key] = argument.Value + labels[argument.Key] = argument.Value case v1.MatchArgument_METHOD: - r.Proto.Labels[LabelKeyMethod] = argument.Value + labels[LabelKeyMethod] = argument.Value case v1.MatchArgument_HEADER: - r.Proto.Labels[LabelKeyHeader+"."+argument.Key] = argument.Value + labels[LabelKeyHeader+"."+argument.Key] = argument.Value case v1.MatchArgument_QUERY: - r.Proto.Labels[LabelKeyQuery+"."+argument.Key] = argument.Value + labels[LabelKeyQuery+"."+argument.Key] = argument.Value case v1.MatchArgument_CALLER_SERVICE: - r.Proto.Labels[LabelKeyCallerService+"."+argument.Key] = argument.Value + labels[LabelKeyCallerService+"."+argument.Key] = argument.Value case v1.MatchArgument_CALLER_IP: - r.Proto.Labels[LabelKeyCallerIP] = argument.Value + labels[LabelKeyCallerIP] = argument.Value default: continue } } - return true + return labels } - return false + return nil } -// AdaptArgumentsAndLabels 对存量标签进行兼容 +// AdaptArgumentsAndLabels 对存量标签进行兼容,同时将argument适配成标签 func (r *RateLimit) AdaptArgumentsAndLabels() error { // 新的限流规则,需要适配老的SDK使用场景 - if !r.Arguments2Labels() { + labels := Arguments2Labels(r.Proto.GetArguments()) + if len(labels) > 0 { + r.Proto.Labels = labels + } else { + var err error // 存量限流规则,需要适配成新的规则 - labels, err := r.Labels2Arguments() + labels, err = r.Labels2Arguments() if nil != err { return err } r.Proto.Labels = labels } + return nil +} +// AdaptLabels 对存量标签进行兼容,对存量labels进行清空 +func (r *RateLimit) AdaptLabels() error { + // 存量限流规则,需要适配成新的规则 + _, err := r.Labels2Arguments() + if nil != err { + return err + } + r.Proto.Labels = nil return nil } @@ -411,6 +425,7 @@ const ( RNamespace Resource = "Namespace" RService Resource = "Service" RRouting Resource = "Routing" + RRoutingV2 Resource = "RoutingV2" RInstance Resource = "Instance" RRateLimit Resource = "RateLimit" RMeshResource Resource = "MeshResource" diff --git a/common/model/naming_test.go b/common/model/naming_test.go index adf264f69..932919836 100644 --- a/common/model/naming_test.go +++ b/common/model/naming_test.go @@ -77,7 +77,10 @@ func TestRateLimit_Arguments2Labels(t *testing.T) { }, }, } - rateLimit.Arguments2Labels() + labels := Arguments2Labels(rateLimit.Proto.GetArguments()) + if len(labels) > 0 { + rateLimit.Proto.Labels = labels + } var hasValue bool var value *api.MatchString value, hasValue = rateLimit.Proto.Labels["business.key"] diff --git a/common/model/v2/routing.go b/common/model/v2/routing.go new file mode 100644 index 000000000..9e2baf43c --- /dev/null +++ b/common/model/v2/routing.go @@ -0,0 +1,202 @@ +/** + * Tencent is pleased to support the open source community by making Polaris available. + * + * Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved. + * + * Licensed under the BSD 3-Clause License (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://opensource.org/licenses/BSD-3-Clause + * + * 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 v2 + +import ( + "time" + + "github.com/golang/protobuf/ptypes" + apiv2 "github.com/polarismesh/polaris-server/common/api/v2" + commontime "github.com/polarismesh/polaris-server/common/time" + "google.golang.org/protobuf/types/known/anypb" +) + +const ( + // V2RuleIDKey v2 版本的规则路由 ID + V2RuleIDKey = "__routing_v2_id__" + // V1RuleIDKey v1 版本的路由规则 ID + V1RuleIDKey = "__routing_v1_id__" + // V1RuleRouteIndexKey v1 版本 route 规则在自己 route 链中的 index 信息 + V1RuleRouteIndexKey = "__routing_v1_route_index__" + // V1RuleRouteTypeKey 标识当前 v2 路由规则在 v1 的 inBound 还是 outBound + V1RuleRouteTypeKey = "__routing_v1_route_type__" + // V1RuleInRoute inBound 类型 + V1RuleInRoute = "in" + // V1RuleOutRoute outBound 类型 + V1RuleOutRoute = "out" +) + +var ( + // RuleRoutingTypeUrl 记录 anypb.Any 中关于 RuleRoutingConfig 的 url 信息 + RuleRoutingTypeUrl string + // MetaRoutingTypeUrl 记录 anypb.Any 中关于 MetadataRoutingConfig 的 url 信息 + MetaRoutingTypeUrl string +) + +func init() { + ruleAny, _ := ptypes.MarshalAny(&apiv2.RuleRoutingConfig{}) + metaAny, _ := ptypes.MarshalAny(&apiv2.MetadataRoutingConfig{}) + + RuleRoutingTypeUrl = ruleAny.GetTypeUrl() + MetaRoutingTypeUrl = metaAny.GetTypeUrl() +} + +// ExtendRoutingConfig 路由信息的扩展 +type ExtendRoutingConfig struct { + *RoutingConfig + // MetadataRouting 元数据路由配置 + MetadataRouting *apiv2.MetadataRoutingConfig + // RuleRouting 规则路由配置 + RuleRouting *apiv2.RuleRoutingConfig + // ExtendInfo 额外信息数据 + ExtendInfo map[string]string +} + +// ToApi 转为 api 对象 +func (r *ExtendRoutingConfig) ToApi() (*apiv2.Routing, error) { + + var ( + any *anypb.Any + err error + ) + + if r.GetRoutingPolicy() == apiv2.RoutingPolicy_MetadataPolicy { + any, err = ptypes.MarshalAny(r.MetadataRouting) + if err != nil { + return nil, err + } + } else { + any, err = ptypes.MarshalAny(r.RuleRouting) + if err != nil { + return nil, err + } + } + + return &apiv2.Routing{ + Id: r.ID, + Name: r.Name, + Namespace: r.Namespace, + Enable: r.Enable, + RoutingPolicy: r.GetRoutingPolicy(), + RoutingConfig: any, + Revision: r.Revision, + Ctime: commontime.Time2String(r.CreateTime), + Mtime: commontime.Time2String(r.ModifyTime), + Etime: commontime.Time2String(r.EnableTime), + Priority: r.Priority, + Description: r.Description, + }, nil +} + +// RoutingConfig 路由规则 +type RoutingConfig struct { + // ID 规则唯一标识 + ID string `json:"id"` + // namespace 所属的命名空间 + Namespace string `json:"namespace"` + // name 规则名称 + Name string `json:"name"` + // policy 规则类型 + Policy string `json:"policy"` + // config 具体的路由规则内容 + Config string `json:"config"` + // enable 路由规则是否启用 + Enable bool `json:"enable"` + // priority 规则优先级 + Priority uint32 `json:"priority"` + // revision 路由规则的版本信息 + Revision string `json:"revision"` + // Description 规则简单描述 + Description string `json:"description"` + // valid 路由规则是否有效,没有被逻辑删除 + Valid bool `json:"flag"` + // createtime 规则创建时间 + CreateTime time.Time `json:"ctime"` + // modifytime 规则修改时间 + ModifyTime time.Time `json:"mtime"` + // enabletime 规则最近一次启用时间 + EnableTime time.Time `json:"etime"` +} + +// GetRoutingPolicy 查询路由规则类型 +func (r *RoutingConfig) GetRoutingPolicy() apiv2.RoutingPolicy { + v, ok := apiv2.RoutingPolicy_value[r.Policy] + + if !ok { + return apiv2.RoutingPolicy(-1) + } + + return apiv2.RoutingPolicy(v) +} + +// ToExpendRoutingConfig 转为扩展对象,提前序列化出相应的 pb struct +func (r *RoutingConfig) ToExpendRoutingConfig() (*ExtendRoutingConfig, error) { + ret := &ExtendRoutingConfig{ + RoutingConfig: r, + } + + policy := r.GetRoutingPolicy() + + if policy == apiv2.RoutingPolicy_RulePolicy { + rule := &apiv2.RuleRoutingConfig{} + if err := ptypes.UnmarshalAny(&anypb.Any{ + TypeUrl: RuleRoutingTypeUrl, + Value: []byte(r.Config), + }, rule); err != nil { + return nil, err + } + ret.RuleRouting = rule + } + + if policy == apiv2.RoutingPolicy_MetadataPolicy { + rule := &apiv2.MetadataRoutingConfig{} + if err := ptypes.UnmarshalAny(&anypb.Any{ + TypeUrl: MetaRoutingTypeUrl, + Value: []byte(r.Config), + }, rule); err != nil { + return nil, err + } + + ret.MetadataRouting = rule + } + + return ret, nil +} + +// ParseFromAPI 从 API 对象中转换出内部对象 +func (r *RoutingConfig) ParseFromAPI(routing *apiv2.Routing) error { + r.ID = routing.Id + r.Revision = routing.Revision + r.Name = routing.Name + r.Namespace = routing.Namespace + r.Enable = routing.Enable + r.Policy = routing.GetRoutingPolicy().String() + r.Priority = routing.Priority + r.Config = string(routing.GetRoutingConfig().GetValue()) + r.Description = routing.Description + + // 优先级区间范围 [0, 10] + if r.Priority > 10 { + r.Priority = 10 + } + if r.Priority < 0 { + r.Priority = 0 + } + + return nil +} diff --git a/common/routing/routing.go b/common/routing/routing.go new file mode 100644 index 000000000..0e54b30d0 --- /dev/null +++ b/common/routing/routing.go @@ -0,0 +1,559 @@ +/** + * Tencent is pleased to support the open source community by making Polaris available. + * + * Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved. + * + * Licensed under the BSD 3-Clause License (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://opensource.org/licenses/BSD-3-Clause + * + * 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 routing + +import ( + "encoding/json" + "fmt" + "sort" + + "github.com/golang/protobuf/ptypes" + apiv1 "github.com/polarismesh/polaris-server/common/api/v1" + apiv2 "github.com/polarismesh/polaris-server/common/api/v2" + "github.com/polarismesh/polaris-server/common/model" + v2 "github.com/polarismesh/polaris-server/common/model/v2" + commontime "github.com/polarismesh/polaris-server/common/time" + "github.com/polarismesh/polaris-server/common/utils" +) + +const ( + _labelKeyPath = "$path" + _labelKeyMethod = "$method" + _labelKeyHeader = "$header" + _labelKeyQuery = "$query" + _labelKeyCallerIP = "$caller_ip" + _labelKeyCookie = "$cookie" + + MatchAll = "*" +) + +// RoutingConfigV1ToAPI 把内部数据结构转换为API参数传递出去 +func RoutingConfigV1ToAPI(req *model.RoutingConfig, service string, namespace string) (*apiv1.Routing, error) { + if req == nil { + return nil, nil + } + + out := &apiv1.Routing{ + Service: utils.NewStringValue(service), + Namespace: utils.NewStringValue(namespace), + Revision: utils.NewStringValue(req.Revision), + Ctime: utils.NewStringValue(commontime.Time2String(req.CreateTime)), + Mtime: utils.NewStringValue(commontime.Time2String(req.ModifyTime)), + } + + if req.InBounds != "" { + var inBounds []*apiv1.Route + if err := json.Unmarshal([]byte(req.InBounds), &inBounds); err != nil { + return nil, err + } + out.Inbounds = inBounds + } + if req.OutBounds != "" { + var outBounds []*apiv1.Route + if err := json.Unmarshal([]byte(req.OutBounds), &outBounds); err != nil { + return nil, err + } + out.Outbounds = outBounds + } + + return out, nil +} + +// CompositeRoutingV1AndV2 合并 v1 版本的路由规则以及 v2 版本的规则路由 +func CompositeRoutingV1AndV2(v1rule *apiv1.Routing, level1, level2, + level3 []*v2.ExtendRoutingConfig) (*apiv1.Routing, []string) { + + // 先确保规则的排序是从最高优先级开始排序 + sort.Slice(level1, func(i, j int) bool { + return CompareRoutingV2(level1[i], level1[j]) + }) + + // 先确保规则的排序是从最高优先级开始排序 + sort.Slice(level2, func(i, j int) bool { + return CompareRoutingV2(level2[i], level2[j]) + }) + + // 先确保规则的排序是从最高优先级开始排序 + sort.Slice(level3, func(i, j int) bool { + return CompareRoutingV2(level3[i], level3[j]) + }) + + level1inRoutes, level1outRoutes, level1Revisions := BuildV1RoutesFromV2(v1rule.Service.Value, v1rule.Namespace.Value, level1) + level2inRoutes, level2outRoutes, level2Revisions := BuildV1RoutesFromV2(v1rule.Service.Value, v1rule.Namespace.Value, level2) + level3inRoutes, level3outRoutes, level3Revisions := BuildV1RoutesFromV2(v1rule.Service.Value, v1rule.Namespace.Value, level3) + + inBounds := v1rule.GetInbounds() + outBounds := v1rule.GetOutbounds() + + // 处理 inbounds 规则,level1 cache -> v1rules -> level2 cache -> level3 cache + if len(level1inRoutes) > 0 { + v1rule.Inbounds = append(level1inRoutes, inBounds...) + } + if len(level2inRoutes) > 0 { + v1rule.Inbounds = append(v1rule.Inbounds, level2inRoutes...) + } + if len(level3inRoutes) > 0 { + v1rule.Inbounds = append(v1rule.Inbounds, level3inRoutes...) + } + + // 处理 outbounds 规则,level1 cache -> v1rules -> level2 cache -> level3 cache + if len(level1outRoutes) > 0 { + v1rule.Outbounds = append(level1outRoutes, outBounds...) + } + if len(level2outRoutes) > 0 { + v1rule.Outbounds = append(v1rule.Outbounds, level2outRoutes...) + } + if len(level3outRoutes) > 0 { + v1rule.Outbounds = append(v1rule.Outbounds, level3outRoutes...) + } + + revisions := make([]string, 0, 1+len(level1Revisions)+len(level2Revisions)+len(level3Revisions)) + revisions = append(revisions, v1rule.GetRevision().GetValue()) + if len(level1Revisions) > 0 { + revisions = append(revisions, level1Revisions...) + } + if len(level2Revisions) > 0 { + revisions = append(revisions, level2Revisions...) + } + if len(level3Revisions) > 0 { + revisions = append(revisions, level3Revisions...) + } + + return v1rule, revisions +} + +// BuildV1RoutesFromV2 根据 v2 版本的路由规则适配成 v1 版本的路由规则,分为别 inBounds 以及 outBounds +// retuen inBound outBound revisions +func BuildV1RoutesFromV2(service, namespace string, entries []*v2.ExtendRoutingConfig) ([]*apiv1.Route, []*apiv1.Route, []string) { + if len(entries) == 0 { + return []*apiv1.Route{}, []*apiv1.Route{}, []string{} + } + + // 将 v2rules 分为 inbound 以及 outbound + revisions := make([]string, 0, len(entries)) + outRoutes := make([]*apiv1.Route, 0, 8) + inRoutes := make([]*apiv1.Route, 0, 8) + for i := range entries { + if !entries[i].Enable { + continue + } + outRoutes = append(outRoutes, BuildOutBoundsFromV2(service, namespace, entries[i])...) + inRoutes = append(inRoutes, BuildInBoundsFromV2(service, namespace, entries[i])...) + revisions = append(revisions, entries[i].Revision) + } + + return inRoutes, outRoutes, revisions +} + +// BuildOutBoundsFromV2 根据 v2 版本的路由规则适配成 v1 版本的路由规则中的 OutBounds +func BuildOutBoundsFromV2(service, namespace string, item *v2.ExtendRoutingConfig) []*apiv1.Route { + if item.GetRoutingPolicy() != apiv2.RoutingPolicy_RulePolicy { + return []*apiv1.Route{} + } + + var find bool + + matchService := func(source *apiv2.Source) bool { + if source.Service == service && source.Namespace == namespace { + return true + } + if source.Namespace == namespace && source.Service == MatchAll { + return true + } + if source.Namespace == MatchAll && source.Service == MatchAll { + return true + } + return false + } + + v1sources := make([]*apiv1.Source, 0, len(item.RuleRouting.Sources)) + sources := item.RuleRouting.Sources + for i := range sources { + if matchService(sources[i]) { + find = true + entry := &apiv1.Source{ + Service: utils.NewStringValue(service), + Namespace: utils.NewStringValue(namespace), + } + entry.Metadata = RoutingArguments2Labels(sources[i].GetArguments()) + v1sources = append(v1sources, entry) + } + } + + if !find { + return []*apiv1.Route{} + } + + v1destinations := make([]*apiv1.Destination, 0, len(item.RuleRouting.Destinations)) + destinations := item.RuleRouting.Destinations + for i := range destinations { + entry := &apiv1.Destination{ + Service: utils.NewStringValue(destinations[i].Service), + Namespace: utils.NewStringValue(destinations[i].Namespace), + Priority: utils.NewUInt32Value(destinations[i].GetPriority()), + Weight: utils.NewUInt32Value(destinations[i].GetWeight()), + Transfer: utils.NewStringValue(destinations[i].GetTransfer()), + Isolate: utils.NewBoolValue(destinations[i].GetIsolate()), + } + + v1labels := make(map[string]*apiv1.MatchString) + v2labels := destinations[i].GetLabels() + for index := range v2labels { + v1labels[index] = &apiv1.MatchString{ + Type: apiv1.MatchString_MatchStringType(v2labels[index].GetType()), + Value: v2labels[index].GetValue(), + ValueType: apiv1.MatchString_ValueType(v2labels[index].GetValueType()), + } + } + + entry.Metadata = v1labels + v1destinations = append(v1destinations, entry) + } + + return []*apiv1.Route{ + { + Sources: v1sources, + Destinations: v1destinations, + ExtendInfo: map[string]string{ + v2.V2RuleIDKey: item.ID, + }, + }, + } +} + +// BuildInBoundsFromV2 将 v2 的路由规则转为 v1 的路由规则中的 InBounds +func BuildInBoundsFromV2(service, namespace string, item *v2.ExtendRoutingConfig) []*apiv1.Route { + if item.GetRoutingPolicy() != apiv2.RoutingPolicy_RulePolicy { + return []*apiv1.Route{} + } + + var find bool + + matchService := func(destination *apiv2.Destination) bool { + if destination.Service == service && destination.Namespace == namespace { + return true + } + if destination.Namespace == namespace && destination.Service == MatchAll { + return true + } + if destination.Namespace == MatchAll && destination.Service == MatchAll { + return true + } + return false + } + + v1destinations := make([]*apiv1.Destination, 0, len(item.RuleRouting.Destinations)) + destinations := item.RuleRouting.Destinations + for i := range destinations { + if matchService(destinations[i]) { + find = true + entry := &apiv1.Destination{ + Service: utils.NewStringValue(service), + Namespace: utils.NewStringValue(namespace), + Priority: utils.NewUInt32Value(destinations[i].GetPriority()), + Weight: utils.NewUInt32Value(destinations[i].GetWeight()), + Transfer: utils.NewStringValue(destinations[i].GetTransfer()), + Isolate: utils.NewBoolValue(destinations[i].GetIsolate()), + } + + v1labels := make(map[string]*apiv1.MatchString) + v2labels := destinations[i].GetLabels() + for index := range v2labels { + v1labels[index] = &apiv1.MatchString{ + Type: apiv1.MatchString_MatchStringType(v2labels[index].GetType()), + Value: v2labels[index].GetValue(), + ValueType: apiv1.MatchString_ValueType(v2labels[index].GetValueType()), + } + } + + entry.Metadata = v1labels + v1destinations = append(v1destinations, entry) + } + } + + if !find { + return []*apiv1.Route{} + } + + v1sources := make([]*apiv1.Source, 0, len(item.RuleRouting.Sources)) + sources := item.RuleRouting.Sources + for i := range sources { + entry := &apiv1.Source{ + Service: utils.NewStringValue(sources[i].Service), + Namespace: utils.NewStringValue(sources[i].Namespace), + } + + entry.Metadata = RoutingArguments2Labels(sources[i].GetArguments()) + v1sources = append(v1sources, entry) + } + + return []*apiv1.Route{ + { + Sources: v1sources, + Destinations: v1destinations, + }, + } +} + +// RoutingLabels2Arguments 将旧的标签模型适配成参数列表 +func RoutingLabels2Arguments(labels map[string]*apiv1.MatchString) []*apiv2.SourceMatch { + if len(labels) == 0 { + return []*apiv2.SourceMatch{} + } + + arguments := make([]*apiv2.SourceMatch, 0, 4) + for index := range labels { + arguments = append(arguments, &apiv2.SourceMatch{ + Type: apiv2.SourceMatch_CUSTOM, + Key: index, + Value: &apiv2.MatchString{ + Type: apiv2.MatchString_MatchStringType(labels[index].GetType()), + Value: labels[index].GetValue(), + ValueType: apiv2.MatchString_ValueType(labels[index].GetValueType()), + }, + }) + } + + return arguments +} + +// RoutingArguments2Labels 将参数列表适配成旧的标签模型 +func RoutingArguments2Labels(args []*apiv2.SourceMatch) map[string]*apiv1.MatchString { + labels := make(map[string]*apiv1.MatchString) + for i := range args { + argument := args[i] + var key string + switch argument.Type { + case apiv2.SourceMatch_CUSTOM: + key = argument.Key + case apiv2.SourceMatch_METHOD: + key = _labelKeyMethod + case apiv2.SourceMatch_HEADER: + key = _labelKeyHeader + "." + argument.Key + case apiv2.SourceMatch_QUERY: + key = _labelKeyQuery + "." + argument.Key + case apiv2.SourceMatch_CALLER_IP: + key = _labelKeyCallerIP + case apiv2.SourceMatch_COOKIE: + key = _labelKeyCookie + "." + argument.Key + case apiv2.SourceMatch_PATH: + key = _labelKeyPath + "." + argument.Key + default: + continue + } + + labels[key] = &apiv1.MatchString{ + Type: apiv1.MatchString_MatchStringType(argument.GetValue().GetType()), + Value: argument.GetValue().GetValue(), + ValueType: apiv1.MatchString_ValueType(argument.GetValue().GetValueType()), + } + } + + return labels +} + +// BuildV2RoutingFromV1Route 构建 v2 版本的API数据对象路由规则 +func BuildV2RoutingFromV1Route(req *apiv1.Routing, route *apiv1.Route) (*apiv2.Routing, error) { + rule := ConvertV1RouteToV2Route(route) + any, err := ptypes.MarshalAny(rule) + if err != nil { + return nil, err + } + + var v2Id string + if extendInfo := route.GetExtendInfo(); len(extendInfo) > 0 { + v2Id = extendInfo[v2.V2RuleIDKey] + } else { + v2Id = utils.NewRoutingV2UUID() + } + + routing := &apiv2.Routing{ + Id: v2Id, + Name: "", + Enable: false, + RoutingPolicy: apiv2.RoutingPolicy_RulePolicy, + RoutingConfig: any, + Revision: utils.NewV2Revision(), + Priority: 0, + } + + return routing, nil +} + +// BuildV2ExtendRouting 构建 v2 版本的内部数据对象路由规则 +func BuildV2ExtendRouting(req *apiv1.Routing, route *apiv1.Route) (*v2.ExtendRoutingConfig, error) { + rule := ConvertV1RouteToV2Route(route) + + var v2Id string + if extendInfo := route.GetExtendInfo(); len(extendInfo) > 0 { + v2Id = extendInfo[v2.V2RuleIDKey] + } + if v2Id == "" { + v2Id = utils.NewRoutingV2UUID() + } + + routing := &v2.ExtendRoutingConfig{ + RoutingConfig: &v2.RoutingConfig{ + ID: v2Id, + Name: "", + Enable: true, + Policy: apiv2.RoutingPolicy_RulePolicy.String(), + Revision: req.GetRevision().GetValue(), + Priority: 0, + }, + RuleRouting: rule, + } + + return routing, nil +} + +// ConvertV1RouteToV2Route 将 v1 版本的路由规则转为 v2 版本的路由规则 +func ConvertV1RouteToV2Route(route *apiv1.Route) *apiv2.RuleRoutingConfig { + v2sources := make([]*apiv2.Source, 0, len(route.GetSources())) + v1sources := route.GetSources() + for i := range v1sources { + entry := &apiv2.Source{ + Service: v1sources[i].GetService().GetValue(), + Namespace: v1sources[i].GetNamespace().GetValue(), + } + + entry.Arguments = RoutingLabels2Arguments(v1sources[i].GetMetadata()) + v2sources = append(v2sources, entry) + } + + v2destinations := make([]*apiv2.Destination, 0, len(route.GetDestinations())) + v1destinations := route.GetDestinations() + for i := range v1destinations { + entry := &apiv2.Destination{ + Service: v1destinations[i].GetService().GetValue(), + Namespace: v1destinations[i].GetNamespace().GetValue(), + Priority: v1destinations[i].GetPriority().GetValue(), + Weight: v1destinations[i].GetWeight().GetValue(), + Transfer: v1destinations[i].GetTransfer().GetValue(), + Isolate: v1destinations[i].GetIsolate().GetValue(), + } + + v2labels := make(map[string]*apiv2.MatchString) + v1labels := v1destinations[i].GetMetadata() + for index := range v1labels { + v2labels[index] = &apiv2.MatchString{ + Type: apiv2.MatchString_MatchStringType(v1labels[index].GetType()), + Value: v1labels[index].GetValue(), + ValueType: apiv2.MatchString_ValueType(v1labels[index].GetValueType()), + } + } + + entry.Labels = v2labels + v2destinations = append(v2destinations, entry) + } + + return &apiv2.RuleRoutingConfig{ + Sources: v2sources, + Destinations: v2destinations, + } +} + +// CompareRoutingV2 +func CompareRoutingV2(a, b *v2.ExtendRoutingConfig) bool { + if a.Priority != b.Priority { + return a.Priority < b.Priority + } + return a.CreateTime.Before(b.CreateTime) +} + +// ConvertRoutingV1ToV2 v1 版本的路由规则转为 v2 版本进行存储 +func ConvertRoutingV1ToExtendV2(svcName, svcNamespace string, rule *model.RoutingConfig) ([]*v2.ExtendRoutingConfig, []*v2.ExtendRoutingConfig, error) { + inRet := make([]*v2.ExtendRoutingConfig, 0, 4) + outRet := make([]*v2.ExtendRoutingConfig, 0, 4) + + if rule.InBounds != "" { + var inBounds []*apiv1.Route + if err := json.Unmarshal([]byte(rule.InBounds), &inBounds); err != nil { + return nil, nil, err + } + + priorityMax := 0 + + for i := range inBounds { + routing, err := BuildV2ExtendRouting(&apiv1.Routing{ + Namespace: utils.NewStringValue(svcNamespace), + }, inBounds[i]) + if err != nil { + return nil, nil, err + } + routing.ID = fmt.Sprintf("%sin%d", rule.ID, i) + routing.Revision = rule.Revision + routing.Enable = true + routing.CreateTime = rule.CreateTime + routing.ModifyTime = rule.ModifyTime + routing.EnableTime = rule.CreateTime + routing.ExtendInfo = map[string]string{ + v2.V1RuleIDKey: rule.ID, + v2.V1RuleRouteIndexKey: fmt.Sprintf("%d", i), + v2.V1RuleRouteTypeKey: v2.V1RuleInRoute, + } + + if priorityMax > 10 { + priorityMax = 10 + } + + routing.Priority = uint32(priorityMax) + priorityMax++ + + inRet = append(inRet, routing) + } + } + if rule.OutBounds != "" { + var outBounds []*apiv1.Route + if err := json.Unmarshal([]byte(rule.OutBounds), &outBounds); err != nil { + return nil, nil, err + } + + priorityMax := 0 + + for i := range outBounds { + routing, err := BuildV2ExtendRouting(&apiv1.Routing{ + Namespace: utils.NewStringValue(svcNamespace), + }, outBounds[i]) + if err != nil { + return nil, nil, err + } + routing.ID = fmt.Sprintf("%sout%d", rule.ID, i) + routing.Revision = rule.Revision + routing.CreateTime = rule.CreateTime + routing.ModifyTime = rule.ModifyTime + routing.EnableTime = rule.CreateTime + routing.ExtendInfo = map[string]string{ + v2.V1RuleIDKey: rule.ID, + v2.V1RuleRouteIndexKey: fmt.Sprintf("%d", i), + v2.V1RuleRouteTypeKey: v2.V1RuleOutRoute, + } + + if priorityMax > 10 { + priorityMax = 10 + } + + routing.Priority = uint32(priorityMax) + priorityMax++ + + outRet = append(outRet, routing) + } + } + + return inRet, outRet, nil +} diff --git a/common/service/instance.go b/common/service/instance.go new file mode 100644 index 000000000..33606c1dc --- /dev/null +++ b/common/service/instance.go @@ -0,0 +1,160 @@ +/** + * Tencent is pleased to support the open source community by making Polaris available. + * + * Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved. + * + * Licensed under the BSD 3-Clause License (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://opensource.org/licenses/BSD-3-Clause + * + * 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 service + +import ( + "strings" + + api "github.com/polarismesh/polaris-server/common/api/v1" + "github.com/polarismesh/polaris-server/common/model" + "github.com/polarismesh/polaris-server/common/utils" +) + +type NamespaceSet struct { + container map[string]*model.Namespace +} + +func NewNamespaceSet() *NamespaceSet { + return &NamespaceSet{ + container: make(map[string]*model.Namespace), + } +} + +func (set *NamespaceSet) Add(val *model.Namespace) { + set.container[val.Name] = val +} + +func (set *NamespaceSet) Remove(val *model.Namespace) { + delete(set.container, val.Name) +} + +func (set *NamespaceSet) ToSlice() []*model.Namespace { + ret := make([]*model.Namespace, 0, len(set.container)) + + for _, v := range set.container { + ret = append(ret, v) + } + + return ret +} + +func (set *NamespaceSet) Range(fn func(val *model.Namespace) bool) { + for _, v := range set.container { + if !fn(v) { + break + } + } +} + +type ServiceSet struct { + container map[string]*model.Service +} + +func NewServiceSet() *ServiceSet { + return &ServiceSet{ + container: make(map[string]*model.Service), + } +} + +func (set *ServiceSet) Add(val *model.Service) { + set.container[val.ID] = val +} + +func (set *ServiceSet) Remove(val *model.Service) { + delete(set.container, val.ID) +} + +func (set *ServiceSet) ToSlice() []*model.Service { + ret := make([]*model.Service, 0, len(set.container)) + + for _, v := range set.container { + ret = append(ret, v) + } + + return ret +} + +func (set *ServiceSet) Range(fn func(val *model.Service) bool) { + for _, v := range set.container { + if !fn(v) { + break + } + } +} + +// CreateInstanceModel 创建存储层服务实例模型 +func CreateInstanceModel(serviceID string, req *api.Instance) *model.Instance { + // 默认为健康的 + healthy := true + if req.GetHealthy() != nil { + healthy = req.GetHealthy().GetValue() + } + + // 默认为不隔离的 + isolate := false + if req.GetIsolate() != nil { + isolate = req.GetIsolate().GetValue() + } + + // 权重默认是100 + var weight uint32 = 100 + if req.GetWeight() != nil { + weight = req.GetWeight().GetValue() + } + + instance := &model.Instance{ + ServiceID: serviceID, + } + + protoIns := &api.Instance{ + Id: req.GetId(), + Host: utils.NewStringValue(strings.TrimSpace(req.GetHost().GetValue())), + VpcId: req.GetVpcId(), + Port: req.GetPort(), + Protocol: req.GetProtocol(), + Version: req.GetVersion(), + Priority: req.GetPriority(), + Weight: utils.NewUInt32Value(weight), + Healthy: utils.NewBoolValue(healthy), + Isolate: utils.NewBoolValue(isolate), + Location: req.Location, + Metadata: req.Metadata, + LogicSet: req.GetLogicSet(), + Revision: utils.NewStringValue(utils.NewUUID()), // 更新版本号 + } + + // health Check,healthCheck不能为空,且没有显示把enable_health_check置为false + // 如果create的时候,打开了healthCheck,那么实例模式是unhealthy,必须要一次心跳才会healthy + if req.GetHealthCheck().GetHeartbeat() != nil && + (req.GetEnableHealthCheck() == nil || req.GetEnableHealthCheck().GetValue()) { + protoIns.EnableHealthCheck = utils.NewBoolValue(true) + protoIns.HealthCheck = req.HealthCheck + protoIns.HealthCheck.Type = api.HealthCheck_HEARTBEAT + // ttl range: (0, 60] + ttl := protoIns.GetHealthCheck().GetHeartbeat().GetTtl().GetValue() + if ttl == 0 || ttl > 60 { + if protoIns.HealthCheck.Heartbeat.Ttl == nil { + protoIns.HealthCheck.Heartbeat.Ttl = utils.NewUInt32Value(5) + } + protoIns.HealthCheck.Heartbeat.Ttl.Value = 5 + } + } + + instance.Proto = protoIns + return instance +} diff --git a/common/utils/collection.go b/common/utils/collection.go index 2fb2bb1de..1c2cba39e 100644 --- a/common/utils/collection.go +++ b/common/utils/collection.go @@ -17,8 +17,6 @@ package utils -import "github.com/polarismesh/polaris-server/common/model" - type StringSet interface { Add(val string) @@ -40,7 +38,7 @@ type stringSet struct { } func (set *stringSet) Add(val string) { - set.container[val] = emptyVal + set.container[val] = struct{}{} } func (set *stringSet) Remove(val string) { @@ -66,75 +64,3 @@ func (set *stringSet) Range(fn func(val string) bool) { } } - -type NamespaceSet struct { - container map[string]*model.Namespace -} - -func NewNamespaceSet() *NamespaceSet { - return &NamespaceSet{ - container: make(map[string]*model.Namespace), - } -} - -func (set *NamespaceSet) Add(val *model.Namespace) { - set.container[val.Name] = val -} - -func (set *NamespaceSet) Remove(val *model.Namespace) { - delete(set.container, val.Name) -} - -func (set *NamespaceSet) ToSlice() []*model.Namespace { - ret := make([]*model.Namespace, 0, len(set.container)) - - for _, v := range set.container { - ret = append(ret, v) - } - - return ret -} - -func (set *NamespaceSet) Range(fn func(val *model.Namespace) bool) { - for _, v := range set.container { - if !fn(v) { - break - } - } -} - -type ServiceSet struct { - container map[string]*model.Service -} - -func NewServiceSet() *ServiceSet { - return &ServiceSet{ - container: make(map[string]*model.Service), - } -} - -func (set *ServiceSet) Add(val *model.Service) { - set.container[val.ID] = val -} - -func (set *ServiceSet) Remove(val *model.Service) { - delete(set.container, val.ID) -} - -func (set *ServiceSet) ToSlice() []*model.Service { - ret := make([]*model.Service, 0, len(set.container)) - - for _, v := range set.container { - ret = append(ret, v) - } - - return ret -} - -func (set *ServiceSet) Range(fn func(val *model.Service) bool) { - for _, v := range set.container { - if !fn(v) { - break - } - } -} diff --git a/common/utils/common.go b/common/utils/common.go index 76d449c81..c3a2a8eeb 100644 --- a/common/utils/common.go +++ b/common/utils/common.go @@ -34,7 +34,6 @@ import ( api "github.com/polarismesh/polaris-server/common/api/v1" "github.com/polarismesh/polaris-server/common/log" - "github.com/polarismesh/polaris-server/common/model" "github.com/polarismesh/polaris-server/store" ) @@ -384,16 +383,6 @@ func ParseIsOwner(ctx context.Context) bool { return isOwner } -// ParseUserRole 从ctx中解析用户角色 -func ParseUserRole(ctx context.Context) model.UserRoleType { - if ctx == nil { - return model.SubAccountUserRole - } - - role, _ := ctx.Value(ContextUserRoleIDKey).(model.UserRoleType) - return role -} - // ParseUserID 从ctx中解析用户ID func ParseUserID(ctx context.Context) string { if ctx == nil { diff --git a/common/utils/funcs.go b/common/utils/funcs.go index a06c12ca9..b91f0bc44 100644 --- a/common/utils/funcs.go +++ b/common/utils/funcs.go @@ -19,75 +19,11 @@ package utils import ( "encoding/hex" - "strings" "github.com/google/uuid" - - api "github.com/polarismesh/polaris-server/common/api/v1" - "github.com/polarismesh/polaris-server/common/model" ) -// CreateInstanceModel 创建存储层服务实例模型 -func CreateInstanceModel(serviceID string, req *api.Instance) *model.Instance { - // 默认为健康的 - healthy := true - if req.GetHealthy() != nil { - healthy = req.GetHealthy().GetValue() - } - - // 默认为不隔离的 - isolate := false - if req.GetIsolate() != nil { - isolate = req.GetIsolate().GetValue() - } - - // 权重默认是100 - var weight uint32 = 100 - if req.GetWeight() != nil { - weight = req.GetWeight().GetValue() - } - - instance := &model.Instance{ - ServiceID: serviceID, - } - - protoIns := &api.Instance{ - Id: req.GetId(), - Host: NewStringValue(strings.TrimSpace(req.GetHost().GetValue())), - VpcId: req.GetVpcId(), - Port: req.GetPort(), - Protocol: req.GetProtocol(), - Version: req.GetVersion(), - Priority: req.GetPriority(), - Weight: NewUInt32Value(weight), - Healthy: NewBoolValue(healthy), - Isolate: NewBoolValue(isolate), - Location: req.Location, - Metadata: req.Metadata, - LogicSet: req.GetLogicSet(), - Revision: NewStringValue(NewUUID()), // 更新版本号 - } - - // health Check,healthCheck不能为空,且没有显示把enable_health_check置为false - // 如果create的时候,打开了healthCheck,那么实例模式是unhealthy,必须要一次心跳才会healthy - if req.GetHealthCheck().GetHeartbeat() != nil && - (req.GetEnableHealthCheck() == nil || req.GetEnableHealthCheck().GetValue()) { - protoIns.EnableHealthCheck = NewBoolValue(true) - protoIns.HealthCheck = req.HealthCheck - protoIns.HealthCheck.Type = api.HealthCheck_HEARTBEAT - // ttl range: (0, 60] - ttl := protoIns.GetHealthCheck().GetHeartbeat().GetTtl().GetValue() - if ttl == 0 || ttl > 60 { - if protoIns.HealthCheck.Heartbeat.Ttl == nil { - protoIns.HealthCheck.Heartbeat.Ttl = NewUInt32Value(5) - } - protoIns.HealthCheck.Heartbeat.Ttl.Value = 5 - } - } - - instance.Proto = protoIns - return instance -} +var emptyVal = struct{}{} // ConvertFilter map[string]string to map[string][]string func ConvertFilter(filters map[string]string) map[string][]string { @@ -124,7 +60,17 @@ func NewUUID() string { return hex.EncodeToString(uuidBytes[:]) } -var emptyVal = struct{}{} +// NewUUID 返回一个随机的UUID +func NewRoutingV2UUID() string { + uuidBytes := uuid.New() + return hex.EncodeToString(uuidBytes[:]) +} + +// NewV2Revision 返回一个随机的UUID +func NewV2Revision() string { + uuidBytes := uuid.New() + return "v2-" + hex.EncodeToString(uuidBytes[:]) +} // StringSliceDeDuplication 字符切片去重 func StringSliceDeDuplication(s []string) []string { diff --git a/common/utils/http.go b/common/utils/http.go deleted file mode 100644 index d1ff51873..000000000 --- a/common/utils/http.go +++ /dev/null @@ -1,196 +0,0 @@ -/** - * Tencent is pleased to support the open source community by making Polaris available. - * - * Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved. - * - * Licensed under the BSD 3-Clause License (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://opensource.org/licenses/BSD-3-Clause - * - * 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 utils - -import ( - "context" - "encoding/json" - "fmt" - "net/http" - "strings" - - "github.com/emicklei/go-restful/v3" - "github.com/golang/protobuf/jsonpb" - "github.com/golang/protobuf/proto" - "go.uber.org/zap" - - api "github.com/polarismesh/polaris-server/common/api/v1" - "github.com/polarismesh/polaris-server/common/log" -) - -// parseQueryParams 解析并获取HTTP的query params -func ParseQueryParams(req *restful.Request) map[string]string { - queryParams := make(map[string]string) - for key, value := range req.Request.URL.Query() { - if len(value) > 0 { - queryParams[key] = value[0] // 暂时默认只支持一个查询 - } - } - - return queryParams -} - -// Handler HTTP请求/回复处理器 -type Handler struct { - *restful.Request - *restful.Response -} - -// ParseArray 解析PB数组对象 -func (h *Handler) ParseArray(createMessage func() proto.Message) (context.Context, error) { - requestID := h.Request.HeaderParameter("Request-Id") - - jsonDecoder := json.NewDecoder(h.Request.Request.Body) - // read open bracket - _, err := jsonDecoder.Token() - if err != nil { - log.Error(err.Error(), zap.String("request-id", requestID)) - return nil, err - } - for jsonDecoder.More() { - protoMessage := createMessage() - err := jsonpb.UnmarshalNext(jsonDecoder, protoMessage) - if err != nil { - log.Error(err.Error(), zap.String("request-id", requestID)) - return nil, err - } - } - return h.postParseMessage(requestID) -} - -func (h *Handler) postParseMessage(requestID string) (context.Context, error) { - platformID := h.Request.HeaderParameter("Platform-Id") - platformToken := h.Request.HeaderParameter("Platform-Token") - token := h.Request.HeaderParameter("Polaris-Token") - authToken := h.Request.HeaderParameter(HeaderAuthTokenKey) - ctx := context.Background() - ctx = context.WithValue(ctx, StringContext("request-id"), requestID) - ctx = context.WithValue(ctx, StringContext("platform-id"), platformID) - ctx = context.WithValue(ctx, StringContext("platform-token"), platformToken) - if token != "" { - ctx = context.WithValue(ctx, StringContext("polaris-token"), token) - } - if authToken != "" { - ctx = context.WithValue(ctx, ContextAuthTokenKey, authToken) - } - - var operator string - addrSlice := strings.Split(h.Request.Request.RemoteAddr, ":") - if len(addrSlice) == 2 { - operator = "HTTP:" + addrSlice[0] - if platformID != "" { - operator += "(" + platformID + ")" - } - } - if staffName := h.Request.HeaderParameter("Staffname"); staffName != "" { - operator = staffName - } - ctx = context.WithValue(ctx, StringContext("operator"), operator) - - return ctx, nil -} - -// Parse 解析请求 -func (h *Handler) Parse(message proto.Message) (context.Context, error) { - requestID := h.Request.HeaderParameter("Request-Id") - if err := jsonpb.Unmarshal(h.Request.Request.Body, message); err != nil { - log.Error(err.Error(), zap.String("request-id", requestID)) - return nil, err - } - return h.postParseMessage(requestID) -} - -// ParseHeaderContext 将http请求header中携带的用户信息提取出来 -func (h *Handler) ParseHeaderContext() context.Context { - requestID := h.Request.HeaderParameter("Request-Id") - platformID := h.Request.HeaderParameter("Platform-Id") - platformToken := h.Request.HeaderParameter("Platform-Token") - token := h.Request.HeaderParameter("Polaris-Token") - authToken := h.Request.HeaderParameter(HeaderAuthTokenKey) - - ctx := context.Background() - ctx = context.WithValue(ctx, StringContext("request-id"), requestID) - ctx = context.WithValue(ctx, StringContext("platform-id"), platformID) - ctx = context.WithValue(ctx, StringContext("platform-token"), platformToken) - if token != "" { - ctx = context.WithValue(ctx, StringContext("polaris-token"), token) - } - if authToken != "" { - ctx = context.WithValue(ctx, ContextAuthTokenKey, authToken) - } - - var operator string - addrSlice := strings.Split(h.Request.Request.RemoteAddr, ":") - if len(addrSlice) == 2 { - operator = "HTTP:" + addrSlice[0] - if platformID != "" { - operator += "(" + platformID + ")" - } - } - if staffName := h.Request.HeaderParameter("Staffname"); staffName != "" { - operator = staffName - } - ctx = context.WithValue(ctx, StringContext("operator"), operator) - - return ctx -} - -// WriteHeader 仅返回Code -func (h *Handler) WriteHeader(polarisCode uint32, httpStatus int) { - requestID := h.Request.HeaderParameter(PolarisRequestID) - h.Request.SetAttribute(PolarisCode, polarisCode) // api统计的时候,用该code - - // 对于非200000的返回,补充实际的code到header中 - if polarisCode != api.ExecuteSuccess { - h.Response.AddHeader(PolarisCode, fmt.Sprintf("%d", polarisCode)) - h.Response.AddHeader(PolarisMessage, api.Code2Info(polarisCode)) - } - h.Response.AddHeader("Request-Id", requestID) - h.Response.WriteHeader(httpStatus) -} - -// WriteHeaderAndProto 返回Code和Proto -func (h *Handler) WriteHeaderAndProto(obj api.ResponseMessage) { - requestID := h.Request.HeaderParameter(PolarisRequestID) - h.Request.SetAttribute(PolarisCode, obj.GetCode().GetValue()) - status := api.CalcCode(obj) - - if status != http.StatusOK { - log.Error(obj.String(), zap.String("request-id", requestID)) - } - if code := obj.GetCode().GetValue(); code != api.ExecuteSuccess { - h.Response.AddHeader(PolarisCode, fmt.Sprintf("%d", code)) - h.Response.AddHeader(PolarisMessage, api.Code2Info(code)) - } - - h.Response.AddHeader(PolarisRequestID, requestID) - h.Response.WriteHeader(status) - - m := jsonpb.Marshaler{Indent: " ", EmitDefaults: true} - err := m.Marshal(h.Response, obj) - if err != nil { - log.Error(err.Error(), zap.String("request-id", requestID)) - } -} - -// HTTPResponse http答复简单封装 -func HTTPResponse(req *restful.Request, rsp *restful.Response, code uint32) { - handler := &Handler{req, rsp} - resp := api.NewResponse(code) - handler.WriteHeaderAndProto(resp) -} diff --git a/config/bootstrap_test.go b/config/bootstrap_test.go index 58b6322f5..fb49a302b 100644 --- a/config/bootstrap_test.go +++ b/config/bootstrap_test.go @@ -50,6 +50,7 @@ import ( _ "github.com/polarismesh/polaris-server/store/boltdb" "github.com/polarismesh/polaris-server/store/sqldb" _ "github.com/polarismesh/polaris-server/store/sqldb" + "github.com/polarismesh/polaris-server/testdata" ) type Bootstrap struct { @@ -113,14 +114,9 @@ func (c *ConfigCenterTest) doInitialize() error { } c.storage = s - if err := cache.TestCacheInitialize(ctx, &c.cfg.Cache, s); err != nil { - fmt.Printf("[ERROR] configure init cache fail: %v\n", err) - return err - } - - cacheMgr, err := cache.GetCacheManager() + cacheMgr, err := cache.TestCacheInitialize(ctx, &c.cfg.Cache, s) if err != nil { - fmt.Printf("[ERROR] configure get cache fail: %v\n", err) + fmt.Printf("[ERROR] configure init cache fail: %v\n", err) return err } @@ -149,7 +145,7 @@ func (c *ConfigCenterTest) doInitialize() error { } func (c *ConfigCenterTest) loadBootstrapConfig() error { - confFileName := "test.yaml" + confFileName := testdata.Path("config_test.yaml") // 初始化defaultCtx c.defaultCtx = context.WithValue(c.defaultCtx, utils.StringContext("request-id"), "config-test-request-id") @@ -157,7 +153,7 @@ func (c *ConfigCenterTest) loadBootstrapConfig() error { if os.Getenv("STORE_MODE") == "sqldb" { fmt.Printf("run store mode : sqldb\n") - confFileName = "test_sqldb.yaml" + confFileName = testdata.Path("config_test_sqldb.yaml") c.defaultCtx = context.WithValue(c.defaultCtx, utils.ContextAuthTokenKey, "nu/0WRA4EqSR1FagrjRj0fZwPXuGlMpX+zCuWu4uMqy8xr1vRjisSbA25aAC3mtU8MeeRsKhQiDAynUR09I=") } else { c.defaultCtx = context.WithValue(c.defaultCtx, utils.ContextAuthTokenKey, "nu/0WRA4EqSR1FagrjRj0fZwPXuGlMpX+zCuWu4uMqy8xr1vRjisSbA25aAC3mtU8MeeRsKhQiDAynUR09I=") diff --git a/config/config_file_template_test.go b/config/config_file_template_test.go index cf1e73f20..e3d2cde2b 100644 --- a/config/config_file_template_test.go +++ b/config/config_file_template_test.go @@ -72,7 +72,7 @@ func TestConfigFileTemplateCRUD(t *testing.T) { t.Run("query-all", func(t *testing.T) { rsp := testSuit.testService.GetAllConfigFileTemplates(testSuit.defaultCtx) assert.Equal(t, api.ExecuteSuccess, rsp.Code.GetValue()) - assert.Equal(t, 2, len(rsp.ConfigFileTemplates)) + assert.True(t, 2 <= len(rsp.ConfigFileTemplates)) }) } diff --git a/deploy/docker/prometheus/prometheus.yml b/deploy/docker/prometheus/prometheus.yml index 87a4a1c77..d8b206e01 100644 --- a/deploy/docker/prometheus/prometheus.yml +++ b/deploy/docker/prometheus/prometheus.yml @@ -31,4 +31,6 @@ scrape_configs: http_sd_configs: - url: http://polaris:9000/prometheus/v1/clients - honor_labels: true \ No newline at end of file + + honor_labels: true + diff --git a/deploy/helm/templates/polaris-console-config.yaml b/deploy/helm/templates/polaris-console-config.yaml index 87a7052ed..18345168c 100644 --- a/deploy/helm/templates/polaris-console-config.yaml +++ b/deploy/helm/templates/polaris-console-config.yaml @@ -15,7 +15,8 @@ data: mode: "release" listenIP: "0.0.0.0" listenPort: {{ .Values.service.webPort }} - namingURL: "/naming/v1" + namingV1URL: "/naming/v1" + namingV2URL: "/naming/v2" authURL: "/core/v1" requestURL: "/naming/v1" configURL: "/config/v1" diff --git a/deploy/helm/templates/polaris-limiter-config.yaml b/deploy/helm/templates/polaris-limiter-config.yaml new file mode 100644 index 000000000..c24715b6a --- /dev/null +++ b/deploy/helm/templates/polaris-limiter-config.yaml @@ -0,0 +1,53 @@ +apiVersion: v1 +kind: ConfigMap +metadata: + name: polaris-limiter-config + namespace: {{ .Values.installation.namespace }} +data: + polaris-limiter.yaml: |- + registry: + enable: true + polaris-server-address: polaris.{{ .Values.installation.namespace }}:{{ .Values.service.serviceGrpcPort }} + name: polaris.limiter + namespace: Polaris + health-check-enable: true + api-servers: + - name: http + option: + ip: 0.0.0.0 + port: {{ .Values.service.limiterHttpPort }} + - name: grpc + option: + ip: 0.0.0.0 + port: {{ .Values.service.limiterGrpcPort }} + limit: + myid: $MY_ID #节点ID, 集群中不同节点需设置不同的myid + counter-group: 64 # 计数器分组,不同组的计数器创建时不冲突 + max-counter: 1000000 + max-client: 1000 + push-worker: 4 + slide-count: 1 + purge-counter-interval: 30s + sync-remote-storage-interval: 1m + async-remote-wait-timeout: 200ms + update-remote-storage-threshold: 10m + flush-local-storage-threshold: 3s + plugin: + statis: + name: file + option: + ratelimit-app-name: 294_4423_polaris-limiter-stat #限流监控 + ratelimit_report_log_path: log/polaris-limiter-ratelimit-report.log + ratelimit_event_log_path: log/polaris-limiter-event.log + ratelimit_precision_log_path: log/polaris-limiter-stat.log + server-app-name: 294_11866_polaris_limit_server #服务端监控 + server_report_log_path: log/polaris-limiter-server-report.log + log_interval: 60 + precision_log_interval: 1 + logger: + RotateOutputPath: log/polaris-limiter.log + RotationMaxSize: 500 + RotationMaxAge: 30 + RotationMaxBackups: 100 + level: info + \ No newline at end of file diff --git a/deploy/helm/templates/polaris-limiter.yaml b/deploy/helm/templates/polaris-limiter.yaml new file mode 100644 index 000000000..229901ce6 --- /dev/null +++ b/deploy/helm/templates/polaris-limiter.yaml @@ -0,0 +1,43 @@ +apiVersion: apps/v1 +kind: StatefulSet +metadata: + labels: + app: polaris-limiter + name: polaris-limiter + namespace: {{ .Values.installation.namespace }} +spec: + podManagementPolicy: OrderedReady + replicas: {{ .Values.polaris.limiterReplicaCount }} + selector: + matchLabels: + app: polaris-limiter + serviceName: polaris-limiter + template: + metadata: + labels: + app: polaris-limiter + spec: + containers: + - image: {{ .Values.polaris.limiter.image.repository }}:{{ .Values.polaris.limiter.image.tag }} + imagePullPolicy: {{ .Values.polaris.limiter.image.pullPolicy }} + name: polaris-limiter + resources: + limits: + cpu: {{ .Values.polaris.limiter.limit.cpu }} + memory: {{ .Values.polaris.limiter.limit.memory }} + terminationMessagePath: /dev/termination-log + terminationMessagePolicy: File + volumeMounts: + - mountPath: /root/polaris-limiter.yaml.example + name: polaris-limiter-config + subPath: polaris-limiter.yaml + restartPolicy: Always + volumes: + - configMap: + defaultMode: 0640 + name: polaris-limiter-config + name: polaris-limiter-config + updateStrategy: + rollingUpdate: + partition: 0 + type: RollingUpdate diff --git a/deploy/helm/templates/polaris-server-config.yaml b/deploy/helm/templates/polaris-server-config.yaml index 4a80a318c..874ddafb7 100644 --- a/deploy/helm/templates/polaris-server-config.yaml +++ b/deploy/helm/templates/polaris-server-config.yaml @@ -64,6 +64,28 @@ data: - stdout errorOutputPaths: - stderr + healthcheck: + rotateOutputPath: log/polaris-healthcheck.log + errorRotateOutputPath: log/polaris-healthcheck-error.log + rotationMaxSize: 100 + rotationMaxBackups: 10 + rotationMaxAge: 7 + outputLevel: info + outputPaths: + - stdout + errorOutputPaths: + - stderr + xdsv3: + rotateOutputPath: log/polaris-xdsv3.log + errorRotateOutputPath: log/polaris-xdsv3-error.log + rotationMaxSize: 100 + rotationMaxBackups: 10 + rotationMaxAge: 7 + outputLevel: info + outputPaths: + - stdout + errorOutputPaths: + - stderr default: rotateOutputPath: log/polaris-default.log errorRotateOutputPath: log/polaris-default-error.log diff --git a/deploy/helm/templates/polaris-server.yaml b/deploy/helm/templates/polaris-server.yaml index eb5ea658e..80c81dd3e 100644 --- a/deploy/helm/templates/polaris-server.yaml +++ b/deploy/helm/templates/polaris-server.yaml @@ -73,7 +73,6 @@ spec: - image: {{.Values.polaris.console.image.repository}}:{{.Values.polaris.console.image.tag}} imagePullPolicy: {{ .Values.polaris.console.image.pullPolicy }} name: polaris-console - command: ["/bin/bash", "-ce", "tail -f /dev/null"] resources: limits: cpu: {{ .Values.polaris.console.limit.cpu }} diff --git a/deploy/helm/templates/prometheus.yaml b/deploy/helm/templates/prometheus.yaml index 850829dfe..2c886377a 100644 --- a/deploy/helm/templates/prometheus.yaml +++ b/deploy/helm/templates/prometheus.yaml @@ -43,27 +43,18 @@ spec: app: polaris-prometheus spec: containers: - - command: - - /bin/bash - - -c - - /root/prometheus/prometheus --config.file=/root/prometheus/prometheus.yml - --web.enable-lifecycle --web.enable-admin-api - image: ccr.ccs.tencentyun.com/polaris_mesh/polaris-prometheus:1.2 - imagePullPolicy: Always - name: polaris-prometheus - resources: - limits: - cpu: "500m" - memory: 1000Mi - - command: - - /bin/bash - - -c - - /root/pushgateway/pushgateway --web.enable-lifecycle --web.enable-admin-api - image: ccr.ccs.tencentyun.com/polaris_mesh/polaris-pushgateway:1.1.0 - imagePullPolicy: Always - name: polaris-pushgateway - resources: - limits: - cpu: "500m" - memory: 1000Mi + - image: {{ .Values.prometheus.image.repository }}:{{ .Values.prometheus.image.tag }} + imagePullPolicy: {{ .Values.prometheus.image.pullPolicy }} + name: polaris-prometheus + resources: + limits: + cpu: "500m" + memory: 1000Mi + - image: {{ .Values.prometheus.pushgateway.image.repository }}:{{ .Values.prometheus.pushgateway.image.tag }} + imagePullPolicy: {{ .Values.prometheus.pushgateway.image.pullPolicy }} + name: polaris-pushgateway + resources: + limits: + cpu: "500m" + memory: 1000Mi restartPolicy: Always diff --git a/deploy/helm/values.yaml b/deploy/helm/values.yaml index 2a35ef44e..535ad3273 100644 --- a/deploy/helm/values.yaml +++ b/deploy/helm/values.yaml @@ -9,7 +9,7 @@ global: polaris: image: repository: polarismesh/polaris-server - tag: latest + tag: ##POLARIS_SERVER_VERSION## pullPolicy: Always limit: cpu: "500m" @@ -17,12 +17,21 @@ polaris: console: image: repository: polarismesh/polaris-console - tag: latest + tag: ##POLARIS_CONSOLE_VERSION## + pullPolicy: Always + limit: + cpu: "500m" + memory: "1000Mi" + limiter: + image: + repository: polarismesh/polaris-limiter + tag: ##POLARIS_LIMITER_VERSION## pullPolicy: Always limit: cpu: "500m" memory: "1000Mi" replicaCount: 1 + limiterReplicaCount: 1 auth: consoleOpen: true clientOpen: false @@ -39,6 +48,17 @@ polaris: password: polaris@123456 # AUTH password below redis v6.0, or ACL password from redis v6.0 withTLS: false +prometheus: + image: + repository: polarismesh/polaris-prometheus + tag: ##POLARIS_PROMETHEUS_VERSION## + pullPolicy: Always + pushgateway: + image: + repository: prom/pushgateway + tag: latest + pullPolicy: Always + service: type: LoadBalancer webPort: 8080 @@ -48,6 +68,8 @@ service: xdsv3Port: 15010 configGrpcPort: 8093 prometheusPort: 9000 + limiterHttpPort: 8100 + limiterGrpcPort: 8101 monitor: port: 9091 diff --git a/deploy/standalone/docker-compose/console/polaris-console.yaml b/deploy/standalone/docker-compose/console/polaris-console.yaml index 8a99a553b..2cec1e9f9 100644 --- a/deploy/standalone/docker-compose/console/polaris-console.yaml +++ b/deploy/standalone/docker-compose/console/polaris-console.yaml @@ -8,7 +8,8 @@ webServer: mode: "release" listenIP: "0.0.0.0" listenPort: 8080 - namingURL: "/naming/v1" + namingV1URL: "/naming/v1" + namingV2URL: "/naming/v2" authURL: "/core/v1" requestURL: "/naming/v1" configURL: "/config/v1" diff --git a/deploy/standalone/docker-compose/docker-compose.yaml b/deploy/standalone/docker-compose/docker-compose.yaml index 73fe8eee0..be78aef3b 100644 --- a/deploy/standalone/docker-compose/docker-compose.yaml +++ b/deploy/standalone/docker-compose/docker-compose.yaml @@ -14,7 +14,7 @@ services: polaris-server: container_name: polaris-server hostname: polaris-server - image: polarismesh/polaris-server:latest + image: polarismesh/polaris-server:##POLARIS_SERVER_VERSION## restart: always volumes: - ./server/polaris-server.yaml:/root/polaris-server.yaml @@ -39,7 +39,7 @@ services: polaris-console: container_name: polaris-console hostname: polaris-console - image: polarismesh/polaris-console:latest + image: polarismesh/polaris-console:##POLARIS_CONSOLE_VERSION## volumes: - ./console/polaris-console.yaml:/root/polaris-console.yaml ports: @@ -52,6 +52,21 @@ services: links: - polaris-server - polaris-pushgateway + polaris-limiter: + container_name: polaris-limiter + hostname: polaris-limiter + image: polarismesh/polaris-limiter:##POLARIS_LIMITER_VERSION## + volumes: + - ./limiter/polaris-limiter.yaml:/root/polaris-limiter.yaml + ports: + - "8100:8100" + - "8101:8101" + networks: + - backend + depends_on: + - polaris-server + links: + - polaris-server mysql: container_name: mysql hostname: mysql @@ -90,7 +105,7 @@ services: polaris-prometheus: container_name: polaris-prometheus hostname: polaris-prometheus - image: polarismesh/prometheus:latest + image: polarismesh/polaris-prometheus:##POLARIS_PROMETHEUS_VERSION## networks: - backend expose: diff --git a/deploy/standalone/docker-compose/limiter/polaris-limiter.yaml b/deploy/standalone/docker-compose/limiter/polaris-limiter.yaml new file mode 100644 index 000000000..72d351120 --- /dev/null +++ b/deploy/standalone/docker-compose/limiter/polaris-limiter.yaml @@ -0,0 +1,45 @@ +registry: + enable: true + polaris-server-address: polaris-server:8091 + name: polaris.limiter + namespace: Polaris + health-check-enable: true +api-servers: + - name: http + option: + ip: 0.0.0.0 + port: 8100 + - name: grpc + option: + ip: 0.0.0.0 + port: 8101 +limit: + myid: 1 #节点ID,集群中不同节点需设置不同的myid + counter-group: 64 # 计数器分组,不同组的计数器创建时不冲突 + max-counter: 1000000 + max-client: 1000 + push-worker: 4 + slide-count: 1 + purge-counter-interval: 30s + sync-remote-storage-interval: 1m + async-remote-wait-timeout: 200ms + update-remote-storage-threshold: 10m + flush-local-storage-threshold: 3s +plugin: + statis: + name: file + option: + ratelimit-app-name: 294_4423_polaris-limiter-stat #限流监控 + ratelimit_report_log_path: log/polaris-limiter-ratelimit-report.log + ratelimit_event_log_path: log/polaris-limiter-event.log + ratelimit_precision_log_path: log/polaris-limiter-stat.log + server-app-name: 294_11866_polaris_limit_server #服务端监控 + server_report_log_path: log/polaris-limiter-server-report.log + log_interval: 60 + precision_log_interval: 1 +logger: + RotateOutputPath: log/polaris-limiter.log + RotationMaxSize: 500 + RotationMaxAge: 30 + RotationMaxBackups: 100 + level: info diff --git a/deploy/standalone/docker-compose/server/polaris-server.yaml b/deploy/standalone/docker-compose/server/polaris-server.yaml index cfe1cb7c7..70c897f33 100644 --- a/deploy/standalone/docker-compose/server/polaris-server.yaml +++ b/deploy/standalone/docker-compose/server/polaris-server.yaml @@ -74,25 +74,13 @@ bootstrap: key: sz # 全局锁 # 注册为北极星服务 polaris_service: - # probe_address: ##DB_ADDR## + probe_address: mysql:3306 enable_register: true isolated: false services: - - name: polaris.discover - protocols: - - service-grpc - - name: polaris.healthcheck - protocols: - - service-grpc - name: polaris.checker protocols: - service-grpc - - name: polaris.config - protocols: - - config-grpc - - name: polaris.monitor - protocols: - - service-grpc # apiserver配置 apiservers: - name: service-eureka @@ -294,7 +282,7 @@ store: dbName: polaris_server dbUser: root dbPwd: polaris - dbAddr: mysql + dbAddr: mysql:3306 maxOpenConns: 300 maxIdleConns: 50 connMaxLifetime: 300 # 单位秒 diff --git a/deploy/standalone/k8s/01-polaris-console-config.yaml b/deploy/standalone/k8s/01-polaris-console-config.yaml index 8e6ca38bf..cd72a8e30 100644 --- a/deploy/standalone/k8s/01-polaris-console-config.yaml +++ b/deploy/standalone/k8s/01-polaris-console-config.yaml @@ -11,7 +11,8 @@ data: mode: "release" listenIP: "0.0.0.0" listenPort: 8080 - namingURL: "/naming/v1" + namingV1URL: "/naming/v1" + namingV2URL: "/naming/v2" authURL: "/core/v1" requestURL: "/naming/v1" configURL: "/config/v1" diff --git a/deploy/standalone/k8s/02-polaris-server-config.yaml b/deploy/standalone/k8s/02-polaris-server-config.yaml index f991a6a86..0ba61194b 100644 --- a/deploy/standalone/k8s/02-polaris-server-config.yaml +++ b/deploy/standalone/k8s/02-polaris-server-config.yaml @@ -60,6 +60,28 @@ data: - stdout errorOutputPaths: - stderr + healthcheck: + rotateOutputPath: log/polaris-healthcheck.log + errorRotateOutputPath: log/polaris-healthcheck-error.log + rotationMaxSize: 100 + rotationMaxBackups: 10 + rotationMaxAge: 7 + outputLevel: info + outputPaths: + - stdout + errorOutputPaths: + - stderr + xdsv3: + rotateOutputPath: log/polaris-xdsv3.log + errorRotateOutputPath: log/polaris-xdsv3-error.log + rotationMaxSize: 100 + rotationMaxBackups: 10 + rotationMaxAge: 7 + outputLevel: info + outputPaths: + - stdout + errorOutputPaths: + - stderr default: rotateOutputPath: log/polaris-default.log errorRotateOutputPath: log/polaris-default-error.log @@ -84,9 +106,6 @@ data: - name: polaris.checker protocols: - service-grpc - - name: polaris.config - protocols: - - config-grpc # apiserver配置 apiservers: - name: service-eureka diff --git a/deploy/standalone/k8s/03-polaris-server.yaml b/deploy/standalone/k8s/03-polaris-server.yaml index c5b7477fe..e2cbaac49 100644 --- a/deploy/standalone/k8s/03-polaris-server.yaml +++ b/deploy/standalone/k8s/03-polaris-server.yaml @@ -53,7 +53,7 @@ spec: app: polaris spec: containers: - - image: polarismesh/polaris-server:latest + - image: polarismesh/polaris-server:##POLARIS_SERVER_VERSION## imagePullPolicy: Always name: polaris-server resources: @@ -66,7 +66,7 @@ spec: - mountPath: /root/polaris-server.yaml name: polaris-server-config subPath: polaris-server.yaml - - image: polarismesh/polaris-console:latest + - image: polarismesh/polaris-console:##POLARIS_CONSOLE_VERSION## imagePullPolicy: Always name: polaris-console resources: diff --git a/deploy/standalone/k8s/04-prometheus.yaml b/deploy/standalone/k8s/04-prometheus.yaml index 54b647ffc..048af1e50 100644 --- a/deploy/standalone/k8s/04-prometheus.yaml +++ b/deploy/standalone/k8s/04-prometheus.yaml @@ -43,7 +43,7 @@ spec: app: polaris-prometheus spec: containers: - - image: polarismesh/prometheus:latest + - image: polarismesh/polaris-prometheus:##POLARIS_PROMETHEUS_VERSION## imagePullPolicy: Always name: polaris-prometheus resources: diff --git a/deploy/standalone/k8s/05-polaris-limiter.yaml b/deploy/standalone/k8s/05-polaris-limiter.yaml new file mode 100644 index 000000000..a25081045 --- /dev/null +++ b/deploy/standalone/k8s/05-polaris-limiter.yaml @@ -0,0 +1,43 @@ +apiVersion: apps/v1 +kind: StatefulSet +metadata: + labels: + app: polaris-limiter + name: polaris-limiter + namespace: polaris-system +spec: + podManagementPolicy: OrderedReady + replicas: 1 + selector: + matchLabels: + app: polaris-limiter + serviceName: polaris-limiter + template: + metadata: + labels: + app: polaris-limiter + spec: + containers: + - image: polarismesh/polaris-limiter:##POLARIS_LIMITER_VERSION## + imagePullPolicy: Always + name: polaris-limiter + resources: + limits: + cpu: "500m" + memory: 1000Mi + terminationMessagePath: /dev/termination-log + terminationMessagePolicy: File + volumeMounts: + - mountPath: /root/polaris-limiter.yaml.example + name: polaris-limiter-config + subPath: polaris-limiter.yaml + restartPolicy: Always + volumes: + - configMap: + defaultMode: 0640 + name: polaris-limiter-config + name: polaris-limiter-config + updateStrategy: + rollingUpdate: + partition: 0 + type: RollingUpdate diff --git a/deploy/standalone/k8s/06-polaris-limiter-config.yaml b/deploy/standalone/k8s/06-polaris-limiter-config.yaml new file mode 100644 index 000000000..059518efe --- /dev/null +++ b/deploy/standalone/k8s/06-polaris-limiter-config.yaml @@ -0,0 +1,53 @@ +apiVersion: v1 +kind: ConfigMap +metadata: + name: polaris-limiter-config + namespace: polaris-system +data: + polaris-limiter.yaml: |- + registry: + enable: true + polaris-server-address: polaris.polaris-system:8090 + name: polaris.limiter + namespace: Polaris + health-check-enable: true + api-servers: + - name: http + option: + ip: 0.0.0.0 + port: 8100 + - name: grpc + option: + ip: 0.0.0.0 + port: 8101 + limit: + myid: $MY_ID #节点ID,集群中不同节点需设置不同的myid + counter-group: 64 # 计数器分组,不同组的计数器创建时不冲突 + max-counter: 1000000 + max-client: 1000 + push-worker: 4 + slide-count: 1 + purge-counter-interval: 30s + sync-remote-storage-interval: 1m + async-remote-wait-timeout: 200ms + update-remote-storage-threshold: 10m + flush-local-storage-threshold: 3s + plugin: + statis: + name: file + option: + ratelimit-app-name: 294_4423_polaris-limiter-stat #限流监控 + ratelimit_report_log_path: log/polaris-limiter-ratelimit-report.log + ratelimit_event_log_path: log/polaris-limiter-event.log + ratelimit_precision_log_path: log/polaris-limiter-stat.log + server-app-name: 294_11866_polaris_limit_server #服务端监控 + server_report_log_path: log/polaris-limiter-server-report.log + log_interval: 60 + precision_log_interval: 1 + logger: + RotateOutputPath: log/polaris-limiter.log + RotationMaxSize: 500 + RotationMaxAge: 30 + RotationMaxBackups: 100 + level: info + \ No newline at end of file diff --git a/deploy/standalone/vm/install-darwin.sh b/deploy/standalone/vm/install-darwin.sh index 5c80a143d..14f665782 100644 --- a/deploy/standalone/vm/install-darwin.sh +++ b/deploy/standalone/vm/install-darwin.sh @@ -53,6 +53,9 @@ api_http_port=$(getProperties "polaris_open_api_port") prometheus_port=$(getProperties prometheus_port) pushgateway_port=$(getProperties pushgateway_port) +limiter_http_port=$(getProperties "polaris_limiter_http_port") +limiter_grpc_port=$(getProperties "polaris_limiter_grpc_port") + echo "prepare install polaris standalone..." echo "polaris-console listen port info" @@ -66,6 +69,10 @@ echo "service_grpc_port=${service_grpc_port}" echo "config_grpc_port=${config_grpc_port}" echo "api_http_port=${api_http_port}" echo "" +echo "polaris-limiter-server listen port info" +echo "polaris_limiter_http_port=${limiter_http_port}" +echo "polaris_limiter_grpc_port=${limiter_grpc_port}" +echo "" echo "prometheus-server listen port info" echo "prometheus_server_port=${prometheus_port}" echo "" @@ -103,15 +110,15 @@ function installPolarisServer() { cp polaris-server.yaml polaris-server.yaml.bak # 修改 polaris-server eureka 端口信息 - sed -i "" "s/listenPort: 8080/listenPort: ${eureka_port}/g" polaris-server.yaml + sed -i "" "s/listenPort: 8761/listenPort: ${eureka_port}/g" polaris-server.yaml # 修改 polaris-server xdsv3 端口信息 - sed -i "" "s/listenPort: 8080/listenPort: ${xdsv3_port}/g" polaris-server.yaml + sed -i "" "s/listenPort: 15010/listenPort: ${xdsv3_port}/g" polaris-server.yaml # 修改 polaris-server prometheus-sd 端口信息 - sed -i "" "s/listenPort: 8080/listenPort: ${prometheus_sd_port}/g" polaris-server.yaml + sed -i "" "s/listenPort: 9000/listenPort: ${prometheus_sd_port}/g" polaris-server.yaml # 修改 polaris-server service-grpc 端口信息 - sed -i "" "s/listenPort: 8080/listenPort: ${service_grpc_port}/g" polaris-server.yaml + sed -i "" "s/listenPort: 8091/listenPort: ${service_grpc_port}/g" polaris-server.yaml # 修改 polaris-server config-grpc 端口信息 - sed -i "" "s/listenPort: 8080/listenPort: ${config_grpc_port}/g" polaris-server.yaml + sed -i "" "s/listenPort: 8093/listenPort: ${config_grpc_port}/g" polaris-server.yaml # 修改 polaris-server http-api 端口信息 sed -i "" "s/listenPort: 8090/listenPort: ${api_http_port}/g" polaris-server.yaml @@ -191,6 +198,7 @@ function installPrometheus() { fi tar -xf ${target_prometheus_pkg} >/dev/null + cp prometheus-help.sh ${prometheus_dirname}/ pushd ${prometheus_dirname} local push_count=$(cat prometheus.yml | grep "push-metrics" | wc -l) if [ $push_count -eq 0 ]; then @@ -202,38 +210,56 @@ function installPrometheus() { echo " - targets: ['localhost:9091']" >>prometheus.yml echo " honor_labels: true" >>prometheus.yml fi - nohup ./prometheus --web.enable-lifecycle --web.enable-admin-api --web.listen-address=:${prometheus_port} >>prometheus.out 2>&1 & - echo "install prometheus success" + mv prometheus polaris-prometheus + chmod +x polaris-prometheus + # nohup ./polaris-prometheus --web.enable-lifecycle --web.enable-admin-api --web.listen-address=:${prometheus_port} >>prometheus.out 2>&1 & + bash prometheus-help.sh start ${prometheus_port} + echo "install polaris-prometheus success" popd } -function installPushGateway() { - echo -e "install pushgateway ... " - local pgw_num=$(ps -ef | grep pushgateway | grep -v grep | wc -l) - if [ $pgw_num -ge 1 ]; then - echo -e "pushgateway is running, skip" +# 安装北极星分布式限流服务端 +function installPolarisLimiter() { + echo -e "install polaris limiter ... " + local polaris_limiter_num=$(ps -ef | grep polaris-limiter | grep -v grep | wc -l) + if [ $polaris_limiter_num -ge 1 ]; then + echo -e "polaris-limiter is running, skip." return fi - local pgw_pkg_num=$(find . -name "pushgateway-*.tar.gz" | wc -l) - if [ $pgw_pkg_num != 1 ]; then - echo -e "number of pushgateway package not equals to 1, exit" + local polaris_limiter_tarnum=$(find . -name "polaris-limiter-release*.zip" | wc -l) + if [ $polaris_limiter_tarnum != 1 ]; then + echo -e "number of polaris limiter tar not equal 1, exit." exit -1 fi - local target_pgw_pkg=$(find . -name "pushgateway-*.tar.gz") - local pgw_dirname=$(basename ${target_pgw_pkg} .tar.gz) - if [ -e ${pgw_dirname} ]; then - echo -e "${pgw_dirname} has exists, now remove it" + local polaris_limiter_tarname=$(find . -name "polaris-limiter-release*.zip") + local polaris_limiter_dirname=$(basename ${polaris_limiter_tarname} .zip) + if [ ! -e $polaris_limiter_dirname ]; then + unzip $polaris_limiter_tarname >/dev/null else - tar -xf ${target_pgw_pkg} + echo -e "polaris-limiter-release.tar.gz has been decompressed, skip." fi - tar -xf ${target_pgw_pkg} >/dev/null - pushd ${pgw_dirname} - nohup ./pushgateway --web.enable-lifecycle --web.enable-admin-api --web.listen-address=:${pushgateway_port} >>pgw.out 2>&1 & - echo "install pushgateway success" - popd + cd ${polaris_limiter_dirname} || ( + echo "no such directory ${polaris_limiter_dirname}" + exit -1 + ) + + # 备份 polaris-limiter.yaml + cp polaris-limiter.yaml polaris-limiter.yaml.bak + + # 修改监听的 polaris-limiter http 端口信息 + sed -i "" "s/port: 8100/port: ${limiter_http_port}/g" polaris-limiter.yaml + # 修改监听的 polaris-limiter grpc 端口信息 + sed -i "" "s/port: 8101/port: ${limiter_grpc_port}/g" polaris-limiter.yaml + + /bin/bash ./tool/start.sh + echo -e "install polaris limiter finish." + cd ${install_path} || ( + echo "no such directory ${install_path}" + exit -1 + ) } function checkPort() { @@ -266,10 +292,10 @@ checkPort installPolarisServer # 安装console installPolarisConsole +# 安装 polaris-limiter +installPolarisLimiter # 安装Prometheus installPrometheus -# 安装PushGateWay -# installPushGateway echo "now, we finish install polaris in your mac, we will exec rollback 'sudo spctl --master-enable'" diff --git a/deploy/standalone/vm/install-linux.sh b/deploy/standalone/vm/install-linux.sh index 9c4fc6b54..70013b522 100644 --- a/deploy/standalone/vm/install-linux.sh +++ b/deploy/standalone/vm/install-linux.sh @@ -54,6 +54,9 @@ api_http_port=$(getProperties polaris_open_api_port) prometheus_port=$(getProperties prometheus_port) pushgateway_port=$(getProperties pushgateway_port) +limiter_http_port=$(getProperties "polaris_limiter_http_port") +limiter_grpc_port=$(getProperties "polaris_limiter_grpc_port") + echo "prepare install polaris standalone..." echo "polaris-console listen port info" @@ -67,6 +70,10 @@ echo "service_grpc_port=${service_grpc_port}" echo "config_grpc_port=${config_grpc_port}" echo "api_http_port=${api_http_port}" echo "" +echo "polaris-limiter-server listen port info" +echo "polaris_limiter_http_port=${limiter_http_port}" +echo "polaris_limiter_grpc_port=${limiter_grpc_port}" +echo "" echo "prometheus-server listen port info" echo "prometheus_server_port=${prometheus_port}" echo "" @@ -95,22 +102,21 @@ function installPolarisServer() { echo -e "${target_polaris_server_pkg} has been decompressed, skip." fi - pushd ${polaris_server_dirname} # 备份 polaris-server.yaml cp polaris-server.yaml polaris-server.yaml.bak # 修改 polaris-server eureka 端口信息 - sed -i "s/listenPort: 8080/listenPort: ${eureka_port}/g" polaris-server.yaml + sed -i "s/listenPort: 8761/listenPort: ${eureka_port}/g" polaris-server.yaml # 修改 polaris-server xdsv3 端口信息 - sed -i "s/listenPort: 8080/listenPort: ${xdsv3_port}/g" polaris-server.yaml + sed -i "s/listenPort: 15010/listenPort: ${xdsv3_port}/g" polaris-server.yaml # 修改 polaris-server prometheus-sd 端口信息 - sed -i "s/listenPort: 8080/listenPort: ${prometheus_sd_port}/g" polaris-server.yaml + sed -i "s/listenPort: 9000/listenPort: ${prometheus_sd_port}/g" polaris-server.yaml # 修改 polaris-server service-grpc 端口信息 - sed -i "s/listenPort: 8080/listenPort: ${service_grpc_port}/g" polaris-server.yaml + sed -i "s/listenPort: 8091/listenPort: ${service_grpc_port}/g" polaris-server.yaml # 修改 polaris-server config-grpc 端口信息 - sed -i "s/listenPort: 8080/listenPort: ${config_grpc_port}/g" polaris-server.yaml + sed -i "s/listenPort: 8093/listenPort: ${config_grpc_port}/g" polaris-server.yaml # 修改 polaris-server http-api 端口信息 sed -i "s/listenPort: 8090/listenPort: ${api_http_port}/g" polaris-server.yaml @@ -160,10 +166,10 @@ function installPolarisConsole() { function installPrometheus() { echo -e "install prometheus ... " - local prometheus_num=$(ps -ef | grep prometheus | grep -v grep | wc -l) + local prometheus_num=$(ps -ef | grep polaris-prometheus | grep -v grep | wc -l) if [ ${prometheus_num} -ge 1 ]; then - echo -e "prometheus is running, exit" - return -1 + echo -e "polaris-prometheus is running, skip install polaris-prometheus" + return 0 fi local prometheus_pkg_num=$(find . -name "prometheus-*.tar.gz" | wc -l) @@ -179,8 +185,8 @@ function installPrometheus() { else echo -e "${target_prometheus_pkg} has been decompressed, skip." fi - + cp prometheus-help.sh ${prometheus_dirname}/ pushd ${prometheus_dirname} echo " http_sd_configs:" >>prometheus.yml echo " - url: http://localhost:9000/prometheus/v1/clients" >>prometheus.yml @@ -189,38 +195,57 @@ function installPrometheus() { echo " static_configs:" >>prometheus.yml echo " - targets: ['localhost:9091']" >>prometheus.yml echo " honor_labels: true" >>prometheus.yml - nohup ./prometheus --web.enable-lifecycle --web.enable-admin-api --web.listen-address=:${prometheus_port} >>prometheus.out 2>&1 & - echo "install prometheus success" + mv prometheus polaris-prometheus + chmod +x polaris-prometheus + # nohup ./polaris-prometheus --web.enable-lifecycle --web.enable-admin-api --web.listen-address=:${prometheus_port} >>prometheus.out 2>&1 & + bash prometheus-help.sh start ${prometheus_port} + echo "install polaris-prometheus success" popd } -function installPushGateway() { - echo -e "install pushgateway ... " - local pgw_num=$(ps -ef | grep pushgateway | grep -v grep | wc -l) - if [ $pgw_num -ge 1 ]; then - echo -e "pushgateway is running, exit" - return -1 +# 安装北极星分布式限流服务端 +# 安装北极星分布式限流服务端 +function installPolarisLimiter() { + echo -e "install polaris limiter ... " + local polaris_limiter_num=$(ps -ef | grep polaris-limiter | grep -v grep | wc -l) + if [ $polaris_limiter_num -ge 1 ]; then + echo -e "polaris-limiter is running, skip." + return fi - local pgw_pkg_num=$(find . -name "pushgateway-*.tar.gz" | wc -l) - if [ $pgw_pkg_num != 1 ]; then - echo -e "number of pushgateway package not equals to 1, exit" + local polaris_limiter_tarnum=$(find . -name "polaris-limiter-release*.zip" | wc -l) + if [ $polaris_limiter_tarnum != 1 ]; then + echo -e "number of polaris limiter tar not equal 1, exit." exit -1 fi - local target_pgw_pkg=$(find . -name "pushgateway-*.tar.gz") - local pgw_dirname=$(basename ${target_pgw_pkg} .tar.gz) - if [ ! -e ${pgw_dirname} ]; then - tar -xf ${target_pgw_pkg} >/dev/null + local polaris_limiter_tarname=$(find . -name "polaris-limiter-release*.zip") + local polaris_limiter_dirname=$(basename ${polaris_limiter_tarname} .zip) + if [ ! -e $polaris_limiter_dirname ]; then + unzip $polaris_limiter_tarname >/dev/null else - echo -e "${target_pgw_pkg} has been decompressed, skip." + echo -e "polaris-limiter-release.tar.gz has been decompressed, skip." fi - - pushd ${pgw_dirname} - nohup ./pushgateway --web.enable-lifecycle --web.enable-admin-api --web.listen-address=:${pushgateway_port} >>pgw.out 2>&1 & - echo "install pushgateway success" - popd + cd ${polaris_limiter_dirname} || ( + echo "no such directory ${polaris_limiter_dirname}" + exit -1 + ) + + # 备份 polaris-limiter.yaml + cp polaris-limiter.yaml polaris-limiter.yaml.bak + + # 修改监听的 polaris-limiter http 端口信息 + sed -i "s/port: 8100/port: ${limiter_http_port}/g" polaris-limiter.yaml + # 修改监听的 polaris-limiter grpc 端口信息 + sed -i "s/port: 8101/port: ${limiter_grpc_port}/g" polaris-limiter.yaml + + /bin/bash ./tool/start.sh + echo -e "install polaris limiter finish." + cd ${install_path} || ( + echo "no such directory ${install_path}" + exit -1 + ) } function checkPort() { @@ -250,7 +275,7 @@ checkPort installPolarisServer # 安装console installPolarisConsole +# 安装 polaris-limiter +installPolarisLimiter # 安装Prometheus installPrometheus -# 安装PushGateWay -# installPushGateway diff --git a/deploy/standalone/vm/install-windows.ps1 b/deploy/standalone/vm/install-windows.ps1 index 6e8d2b432..4616eea9e 100644 --- a/deploy/standalone/vm/install-windows.ps1 +++ b/deploy/standalone/vm/install-windows.ps1 @@ -66,6 +66,32 @@ function installPolarisConsole() { Pop-Location } +function installPolarisLimiter() { + Write-Output "install polaris limiter ... " + $polaris_limiter_num = (Get-Process | findstr "polaris-limiter" | Measure-Object -Line).Lines + if ($polaris_limiter_num -gt 0) { + Write-Output "polaris-limiter is running, skip" + return + } + $polaris_limiter_pkg_num = (Get-ChildItem "polaris-limiter-release*.zip" | Measure-Object -Line).Lines + if ($polaris_limiter_pkg_num -ne 1) { + Write-Output "number of polaris limiter package not equals to 1, exit" + exit -1 + } + $target_polaris_limiter_pkg = (Get-ChildItem "polaris-limiter-release*.zip")[0].Name + $polaris_limiter_dirname = ([io.fileinfo]$target_polaris_limiter_pkg).basename + if (Test-Path $polaris_limiter_dirname) { + Write-Output "$polaris_limiter_dirname has exists, now remove it" + Remove-Item $polaris_limiter_dirname -Recurse + } + Expand-Archive -Path $target_polaris_limiter_pkg -DestinationPath . + Push-Location $polaris_limiter_dirname + Start-Process -FilePath ".\\polaris-limiter.exe" -ArgumentList ('start') -WindowStyle Hidden + Write-Output "install polaris limiter success" + Pop-Location +} + + function installPrometheus() { Write-Output "install prometheus ... " $prometheus_num = (Get-Process | findstr "prometheus" | Measure-Object -Line).Lines @@ -98,31 +124,6 @@ function installPrometheus() { Pop-Location } -function installPushGateway() { - Write-Output "install pushgateway ... " - $pgw_num = (Get-Process | findstr "pushgateway" | Measure-Object -Line).Lines - if ($pgw_num -gt 0) { - Write-Output "pushgateway is running, skip" - return - } - $pgw_pkg_num = (Get-ChildItem "pushgateway-*.zip" | Measure-Object -Line).Lines - if ($pgw_pkg_num -ne 1) { - Write-Output "number of pushgateway package not equals to 1, exit" - exit -1 - } - $target_pgw_pkg = (Get-ChildItem "pushgateway-*.zip")[0].Name - $pgw_dirname = ([io.fileinfo]$target_pgw_pkg).basename - if (Test-Path $pgw_dirname) { - Write-Output "$pgw_dirname has exists, now remove it" - Remove-Item $pgw_dirname -Recurse - } - Expand-Archive -Path $target_pgw_pkg -DestinationPath . - Push-Location $pgw_dirname - Start-Process -FilePath ".\\pushgateway.exe" -ArgumentList ('--web.enable-lifecycle', '--web.enable-admin-api') -RedirectStandardOutput pgw.out -RedirectStandardError pgw.err -WindowStyle Hidden - Write-Output "install pushgateway success" - Pop-Location -} - function checkPort() { $ports = "8080", "8090", "8091", "9090", "9091" foreach ($port in $ports) @@ -143,8 +144,8 @@ checkPort installPolarisServer # 安装console installPolarisConsole +# 安装polaris-limiter +installPolarisLimiter # 安装Prometheus installPrometheus -# 安装PushGateWay -# installPushGateway diff --git a/deploy/standalone/vm/port.properties b/deploy/standalone/vm/port.properties index ef83737a4..4f0374f4b 100644 --- a/deploy/standalone/vm/port.properties +++ b/deploy/standalone/vm/port.properties @@ -5,4 +5,6 @@ polaris_config_grpc_port=8093 polaris_prometheus_sd_port=9000 polaris_xdsv3_port=15010 polaris_console_port=8080 +polaris_limiter_http_port=8100 +polaris_limiter_grpc_port=8101 prometheus_port=9090 diff --git a/deploy/standalone/vm/prometheus-help.sh b/deploy/standalone/vm/prometheus-help.sh new file mode 100644 index 000000000..22f87c540 --- /dev/null +++ b/deploy/standalone/vm/prometheus-help.sh @@ -0,0 +1,27 @@ +#!/bin/bash + +if [ $# -lt 1 ]; then + echo "$0 start port|stop" + exit 0 +fi + +command=$1 + +if [ ${command} == "start" ]; then + prometheus_port=$2 + if [ "${prometheus_port}w" == "w" ]; then + prometheus_port="9090" + fi + + nohup ./polaris-prometheus --web.enable-lifecycle --web.enable-admin-api --web.listen-address=:${prometheus_port} >>prometheus.out 2>&1 & +fi + +if [ ${command} == "stop" ]; then + local pid=$(ps -ef | grep polaris-prometheus | grep -v grep | awk '{print $2}') + if [ "${pid}" != "" ]; then + echo -e "start to kill polaris-prometheus process ${pid}" + kill ${pid} + else + echo "not found running polaris-prometheus" + fi +fi diff --git a/deploy/standalone/vm/uninstall-darwin.sh b/deploy/standalone/vm/uninstall-darwin.sh index fdc293c1b..0fa4a564c 100644 --- a/deploy/standalone/vm/uninstall-darwin.sh +++ b/deploy/standalone/vm/uninstall-darwin.sh @@ -17,10 +17,10 @@ function uninstallPolarisServer() { echo -e "uninstall polaris server ... " - local polaris_server_dirname=$(find . -name "polaris-server-release*" -type d | awk 'NR==1{print}') + local polaris_server_dirname=$(find . -name "polaris-server-release*" -type d | awk 'NR==1{print}') if [ ! -e ${polaris_server_dirname} ]; then - echo -e "${polaris_server_dirname} not exists, skip" - return + echo -e "${polaris_server_dirname} not exists, skip" + return fi pushd ${polaris_server_dirname} echo -e "start to execute polaris-server uninstall script" @@ -33,25 +33,41 @@ function uninstallPolarisServer() { function uninstallPolarisConsole() { echo -e "uninstall polaris console ... " - local polaris_console_dirname=$(find . -name "polaris-console-release*" -type d | awk 'NR==1{print}') + local polaris_console_dirname=$(find . -name "polaris-console-release*" -type d | awk 'NR==1{print}') if [ ! -e ${polaris_console_dirname} ]; then - echo -e "${polaris_console_dirname} not exists, skip" - return + echo -e "${polaris_console_dirname} not exists, skip" + return fi pushd ${polaris_console_dirname} echo -e "start to execute polaris-console uninstall script" /bin/bash ./tool/stop.sh popd - echo -e "start to remove ${polaris_console_dirname}" + echo -e "start to remove ${polaris_console_dirname}" rm -rf ${polaris_console_dirname} echo -e "uninstall polaris console success" } +function uninstallPolarisLimiter() { + echo -e "uninstall polaris limiter ... " + local polaris_limiter_dirname=$(find . -name "polaris-limiter-release*" -type d | awk 'NR==1{print}') + if [ ! -e ${polaris_limiter_dirname} ]; then + echo -e "${polaris_limiter_dirname} not exists, skip" + return + fi + pushd ${polaris_limiter_dirname} + echo -e "start to execute polaris-limiter uninstall script" + /bin/bash ./tool/stop.sh + popd + echo -e "start to remove ${polaris_limiter_dirname}" + rm -rf ${polaris_limiter_dirname} + echo -e "uninstall polaris limiter success" +} + function uninstallPrometheus() { - echo -e "uninstall prometheus ... " - local pid=$(ps -ef | grep prometheus | grep -v grep | awk '{print $2}') + echo -e "uninstall polaris-prometheus ... " + local pid=$(ps -ef | grep polaris-prometheus | grep -v grep | awk '{print $2}') if [ "${pid}" != "" ]; then - echo -e "start to kill prometheus process ${pid}" + echo -e "start to kill polaris-prometheus process ${pid}" kill ${pid} fi local prometheus_dirname=$(find . -name "prometheus*" -type d | awk 'NR==1{print}') @@ -59,29 +75,14 @@ function uninstallPrometheus() { echo -e "start to remove ${prometheus_dirname}" rm -rf ${prometheus_dirname} fi - echo -e "uninstall prometheus success" -} - -function uninstallPushGateway() { - echo -e "uninstall pushgateway ... " - local pid=$(ps -ef | grep pushgateway | grep -v grep | awk '{print $2}') - if [ "${pid}" != "" ]; then - echo -e "start to kill pushgateway process ${pid}" - kill ${pid} - fi - local pushgateway_dirname=$(find . -name "pushgateway*" -type d | awk 'NR==1{print}') - if [ -e ${pushgateway_dirname} ]; then - echo -e "start to remove ${pushgateway_dirname}" - rm -rf ${pushgateway_dirname} - fi - echo -e "uninstall pushgateway success" + echo -e "uninstall polaris-prometheus success" } -# 卸载server +# 卸载 server uninstallPolarisServer -# 安装console +# 卸载 console uninstallPolarisConsole -# 安装Prometheus +# 卸载 polaris-limiter +uninstallPolarisLimiter +# 卸载 prometheus uninstallPrometheus -# 安装PushGateWay -uninstallPushGateway \ No newline at end of file diff --git a/deploy/standalone/vm/uninstall-linux.sh b/deploy/standalone/vm/uninstall-linux.sh index caa2e63c9..a9149ea14 100644 --- a/deploy/standalone/vm/uninstall-linux.sh +++ b/deploy/standalone/vm/uninstall-linux.sh @@ -19,8 +19,8 @@ function uninstallPolarisServer() { echo -e "uninstall polaris server ... " local polaris_server_dirname=$(find . -name "polaris-server-release*" -type d | awk 'NR==1{print}') if [ ! -e ${polaris_server_dirname} ]; then - echo -e "${polaris_server_dirname} not exists, skip" - return + echo -e "${polaris_server_dirname} not exists, skip" + return fi pushd ${polaris_server_dirname} echo -e "start to execute polaris-server uninstall script" @@ -35,8 +35,8 @@ function uninstallPolarisConsole() { echo -e "uninstall polaris console ... " local polaris_console_dirname=$(find . -name "polaris-console-release*" -type d | awk 'NR==1{print}') if [ ! -e ${polaris_console_dirname} ]; then - echo -e "${polaris_console_dirname} not exists, skip" - return + echo -e "${polaris_console_dirname} not exists, skip" + return fi pushd ${polaris_console_dirname} echo -e "start to execute polaris-console uninstall script" @@ -47,11 +47,27 @@ function uninstallPolarisConsole() { echo -e "uninstall polaris console success" } +function uninstallPolarisLimiter() { + echo -e "uninstall polaris limiter ... " + local polaris_limiter_dirname=$(find . -name "polaris-limiter-release*" -type d | awk 'NR==1{print}') + if [ ! -e ${polaris_limiter_dirname} ]; then + echo -e "${polaris_limiter_dirname} not exists, skip" + return + fi + pushd ${polaris_limiter_dirname} + echo -e "start to execute polaris-limiter uninstall script" + /bin/bash ./tool/stop.sh + popd + echo -e "start to remove ${polaris_limiter_dirname}" + rm -rf ${polaris_limiter_dirname} + echo -e "uninstall polaris limiter success" +} + function uninstallPrometheus() { - echo -e "uninstall prometheus ... " - local pid=$(ps -ef | grep prometheus | grep -v grep | awk '{print $2}') + echo -e "uninstall polaris-prometheus ... " + local pid=$(ps -ef | grep polaris-prometheus | grep -v grep | awk '{print $2}') if [ "${pid}" != "" ]; then - echo -e "start to kill prometheus process ${pid}" + echo -e "start to kill polaris-prometheus process ${pid}" kill ${pid} fi local prometheus_dirname=$(find . -name "prometheus*" -type d | awk 'NR==1{print}') @@ -59,29 +75,14 @@ function uninstallPrometheus() { echo -e "start to remove ${prometheus_dirname}" rm -rf ${prometheus_dirname} fi - echo -e "uninstall prometheus success" -} - -function uninstallPushGateway() { - echo -e "uninstall pushgateway ... " - local pid=$(ps -ef | grep pushgateway | grep -v grep | awk '{print $2}') - if [ "${pid}" != "" ]; then - echo -e "start to kill pushgateway process ${pid}" - kill ${pid} - fi - local pushgateway_dirname=$(find . -name "pushgateway*" -type d | awk 'NR==1{print}') - if [ -e ${pushgateway_dirname} ]; then - echo -e "start to remove ${pushgateway_dirname}" - rm -rf ${pushgateway_dirname} - fi - echo -e "uninstall pushgateway success" + echo -e "uninstall polaris-prometheus success" } -# 卸载server +# 卸载 server uninstallPolarisServer -# 安装console +# 卸载 console uninstallPolarisConsole -# 安装Prometheus +# 卸载 limiter +uninstallPolarisLimiter +# 卸载 prometheus uninstallPrometheus -# 安装PushGateWay -uninstallPushGateway \ No newline at end of file diff --git a/deploy/standalone/vm/uninstall-windows.ps1 b/deploy/standalone/vm/uninstall-windows.ps1 index c82bdac0d..e196a0130 100644 --- a/deploy/standalone/vm/uninstall-windows.ps1 +++ b/deploy/standalone/vm/uninstall-windows.ps1 @@ -55,52 +55,51 @@ function uninstallPolarisConsole { Write-Output "uninstall polaris console success" } -function uninstallPrometheus { - Write-Output "uninstall prometheus ... " +function uninstallPolarisLimiter { + Write-Output "uninstall polaris-limiter ... " Get-Process | ForEach-Object($_.name) { - if($_.name -eq "prometheus") { + if($_.name -eq "polaris-limiter") { $process_pid = $_.Id - Write-Output "start to kill prometheus process $process_pid" + Write-Output "start to kill polaris-limiter process $process_pid" Stop-Process -Id $process_pid Start-Sleep -Seconds 2 } } - $target_prometheus_pkg = (Get-ChildItem "prometheus-*.zip")[0].Name - $prometheus_dirname = ([io.fileinfo]$target_prometheus_pkg).basename - $exists = (Test-Path $prometheus_dirname) + $target_polaris_limiter_pkg = (Get-ChildItem "polaris-limiter-release*.zip")[0].Name + $polaris_limiter_dirname = ([io.fileinfo]$target_polaris_limiter_pkg).basename + $exists = (Test-Path $polaris_limiter_dirname) if ($exists) { - Write-Output "start to remove $prometheus_dirname" - Remove-Item ".\\${prometheus_dirname}" -Recurse + Write-Output "start to remove $polaris_limiter_dirname" + Remove-Item ".\\${polaris_limiter_dirname}" -Recurse } - Write-Output "uninstall prometheus success" + Write-Output "uninstall polaris limiter success" } -function uninstallPushGateway { - Write-Output "uninstall pushgateway ... " +function uninstallPrometheus { + Write-Output "uninstall prometheus ... " Get-Process | ForEach-Object($_.name) { - if($_.name -eq "pushgateway") { + if($_.name -eq "prometheus") { $process_pid = $_.Id - Write-Output "start to kill pushgateway process $process_pid" + Write-Output "start to kill prometheus process $process_pid" Stop-Process -Id $process_pid Start-Sleep -Seconds 2 } } - $target_pgw_pkg = (Get-ChildItem "pushgateway-*.zip")[0].Name - $pgw_dirname = ([io.fileinfo]$target_pgw_pkg).basename - $exists = (Test-Path $pgw_dirname) + $target_prometheus_pkg = (Get-ChildItem "prometheus-*.zip")[0].Name + $prometheus_dirname = ([io.fileinfo]$target_prometheus_pkg).basename + $exists = (Test-Path $prometheus_dirname) if ($exists) { - Write-Output "start to remove $pgw_dirname" - Remove-Item ".\\${pgw_dirname}" -Recurse - return + Write-Output "start to remove $prometheus_dirname" + Remove-Item ".\\${prometheus_dirname}" -Recurse } - Write-Output "uninstall pushgateway success" + Write-Output "uninstall prometheus success" } -# 卸载server +# 卸载 server uninstallPolarisServer -# 安装console +# 卸载 console uninstallPolarisConsole -# 安装Prometheus +# 卸载 limiter +uninstallPolarisLimiter +# 卸载 prometheus uninstallPrometheus -# 安装PushGateWay -uninstallPushGateway \ No newline at end of file diff --git a/go.mod b/go.mod index 30dd5cac5..0d57577ff 100644 --- a/go.mod +++ b/go.mod @@ -32,7 +32,7 @@ require ( golang.org/x/sync v0.0.0-20210220032951-036812b2e83c golang.org/x/text v0.3.7 golang.org/x/time v0.0.0-20211116232009-f0f3c7e86c11 - google.golang.org/grpc v1.47.0 + google.golang.org/grpc v1.49.0 google.golang.org/protobuf v1.28.0 gopkg.in/yaml.v2 v2.4.0 ) @@ -52,11 +52,9 @@ require ( github.com/inconshreveable/mousetrap v1.0.0 // indirect github.com/json-iterator/go v1.1.12 // indirect github.com/jtolds/gls v4.20.0+incompatible // indirect - github.com/kr/text v0.2.0 // indirect github.com/matttproud/golang_protobuf_extensions v1.0.2-0.20181231171920-c182affec369 // indirect github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect github.com/modern-go/reflect2 v1.0.2 // indirect - github.com/niemeyer/pretty v0.0.0-20200227124842-a10e7caefd8e // indirect github.com/pmezard/go-difflib v1.0.0 // indirect github.com/prometheus/client_model v0.2.0 // indirect github.com/prometheus/common v0.32.1 // indirect @@ -67,11 +65,22 @@ require ( go.uber.org/multierr v1.7.0 // indirect golang.org/x/sys v0.0.0-20220702020025-31831981b65f // indirect google.golang.org/genproto v0.0.0-20220630174209-ad1d48641aa7 // indirect - gopkg.in/check.v1 v1.0.0-20200227125254-8fa46927fb4f // indirect gopkg.in/natefinch/lumberjack.v2 v2.0.0 // indirect gopkg.in/yaml.v3 v3.0.1 // indirect ) -require github.com/emicklei/go-restful/v3 v3.9.0 +require ( + github.com/emicklei/go-restful/v3 v3.9.0 + github.com/go-openapi/spec v0.20.7 + github.com/polarismesh/go-restful-openapi/v2 v2.0.0-20220915080537-fbc8c2ec9c38 +) + +require ( + github.com/go-openapi/jsonpointer v0.19.5 // indirect + github.com/go-openapi/jsonreference v0.20.0 // indirect + github.com/go-openapi/swag v0.19.15 // indirect + github.com/josharian/intern v1.0.0 // indirect + github.com/mailru/easyjson v0.7.6 // indirect +) replace gopkg.in/yaml.v2 => gopkg.in/yaml.v2 v2.2.2 diff --git a/go.sum b/go.sum index 857ff352f..e29031179 100644 --- a/go.sum +++ b/go.sum @@ -43,6 +43,8 @@ github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03 github.com/BurntSushi/toml v1.0.0 h1:dtDWrepsVPfW9H/4y7dDgFc2MBUSeJhlaDtK13CxFlU= github.com/BurntSushi/toml v1.0.0/go.mod h1:CxXYINrC8qIiEnFrOxCa7Jy5BFHlXnUU2pbicEuybxQ= github.com/BurntSushi/xgb v0.0.0-20160522181843-27f122750802/go.mod h1:IVnqGOEym/WlBOVXweHU+Q+/VP0lqqI8lqeDx9IjBqo= +github.com/PuerkitoBio/purell v1.1.1/go.mod h1:c11w/QuzBsJSee3cPx9rAFu61PvFxuPbtSwDGJws/X0= +github.com/PuerkitoBio/urlesc v0.0.0-20170810143723-de5bf2ad4578/go.mod h1:uGdkoq3SwY9Y+13GIhn11/XLaGBb4BfwItxLd5jeuXE= github.com/alecthomas/template v0.0.0-20160405071501-a0175ee3bccc/go.mod h1:LOuyumcjzFXgccqObfd/Ljyb9UuFJ6TxHnclSeseNhc= github.com/alecthomas/template v0.0.0-20190718012654-fb15b899a751/go.mod h1:LOuyumcjzFXgccqObfd/Ljyb9UuFJ6TxHnclSeseNhc= github.com/alecthomas/units v0.0.0-20151022065526-2efee857e7cf/go.mod h1:ybxpYRFXyAe+OPACYpWeL0wqObRcbAqCMya13uyzqw0= @@ -90,6 +92,8 @@ github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f h1:lO4WD4F/rVNCu3HqELle0jiPLLBs70cWOduZpkS1E78= github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f/go.mod h1:cuUVRXasLTGF7a8hSLbxyZXjz+1KgoB3wDUb6vlszIc= +github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f/go.mod h1:cuUVRXasLTGF7a8hSLbxyZXjz+1KgoB3wDUb6vlszIc= +github.com/emicklei/go-restful/v3 v3.7.3/go.mod h1:6n3XBCmQQb25CM2LCACGz8ukIrRry+4bhvbpWn3mrbc= github.com/emicklei/go-restful/v3 v3.9.0 h1:XwGDlfxEnQZzuopoqxwSEllNcCOM9DhhFyhFIIGKwxE= github.com/emicklei/go-restful/v3 v3.9.0/go.mod h1:6n3XBCmQQb25CM2LCACGz8ukIrRry+4bhvbpWn3mrbc= github.com/envoyproxy/go-control-plane v0.9.0/go.mod h1:YTl/9mNaCwkRvm6d1a2C3ymFceY/DCBVvsKhRF0iEA4= @@ -117,6 +121,18 @@ github.com/go-kit/log v0.1.0/go.mod h1:zbhenjAZHb184qTLMA9ZjW7ThYL0H2mk7Q6pNt4vb github.com/go-logfmt/logfmt v0.3.0/go.mod h1:Qt1PoO58o5twSAckw1HlFXLmHsOX5/0LbT9GBnD5lWE= github.com/go-logfmt/logfmt v0.4.0/go.mod h1:3RMwSq7FuexP4Kalkev3ejPJsZTpXXBr9+V4qmtdjCk= github.com/go-logfmt/logfmt v0.5.0/go.mod h1:wCYkCAKZfumFQihp8CzCvQ3paCTfi41vtzG1KdI/P7A= +github.com/go-openapi/jsonpointer v0.19.3/go.mod h1:Pl9vOtqEWErmShwVjC8pYs9cog34VGT37dQOVbmoatg= +github.com/go-openapi/jsonpointer v0.19.5 h1:gZr+CIYByUqjcgeLXnQu2gHYQC9o73G2XUeOFYEICuY= +github.com/go-openapi/jsonpointer v0.19.5/go.mod h1:Pl9vOtqEWErmShwVjC8pYs9cog34VGT37dQOVbmoatg= +github.com/go-openapi/jsonreference v0.19.6/go.mod h1:diGHMEHg2IqXZGKxqyvWdfWU/aim5Dprw5bqpKkTvns= +github.com/go-openapi/jsonreference v0.20.0 h1:MYlu0sBgChmCfJxxUKZ8g1cPWFOB37YSZqewK7OKeyA= +github.com/go-openapi/jsonreference v0.20.0/go.mod h1:Ag74Ico3lPc+zR+qjn4XBUmXymS4zJbYVCZmcgkasdo= +github.com/go-openapi/spec v0.20.4/go.mod h1:faYFR1CvsJZ0mNsmsphTMSoRrNV3TEDoAM7FOEWeq8I= +github.com/go-openapi/spec v0.20.7 h1:1Rlu/ZrOCCob0n+JKKJAWhNWMPW8bOZRg8FJaY+0SKI= +github.com/go-openapi/spec v0.20.7/go.mod h1:2OpW+JddWPrpXSCIX8eOx7lZ5iyuWj3RYR6VaaBKcWA= +github.com/go-openapi/swag v0.19.5/go.mod h1:POnQmlKehdgb5mhVOsnJFsivZCEZ/vjK9gh66Z9tfKk= +github.com/go-openapi/swag v0.19.15 h1:D2NRCBzS9/pEY3gP9Nl8aDqGUcPFrwG2p+CNFrLyrCM= +github.com/go-openapi/swag v0.19.15/go.mod h1:QYRuS/SOXUCsnplDa677K7+DxSOj6IPNl/eQntq43wQ= github.com/go-redis/redis/v8 v8.11.5 h1:AcZZR7igkdvfVmQTPnu9WE37LRrO/YrBH5zWyjDC0oI= github.com/go-redis/redis/v8 v8.11.5/go.mod h1:gREzHqY1hg6oD9ngVRbLStwAWKhA0FEgq8Jd4h5lpwo= github.com/go-sql-driver/mysql v1.6.0 h1:BCTh4TKNUYmOmMUcQ3IipzF5prigylS7XXjEkfCHuOE= @@ -232,6 +248,8 @@ github.com/ianlancetaylor/demangle v0.0.0-20181102032728-5e5cf60278f6/go.mod h1: github.com/ianlancetaylor/demangle v0.0.0-20200824232613-28f6c0f3b639/go.mod h1:aSSvb/t6k1mPoxDqO4vJh6VOCGPwU4O0C2/Eqndh1Sc= github.com/inconshreveable/mousetrap v1.0.0 h1:Z8tu5sraLXCXIcARxBp/8cbvlwVa7Z1NHg9XEKhtSvM= github.com/inconshreveable/mousetrap v1.0.0/go.mod h1:PxqpIevigyE2G7u3NXJIT2ANytuPF1OarO4DADm73n8= +github.com/josharian/intern v1.0.0 h1:vlS4z54oSdjm0bgjRigI+G1HpF+tI+9rE5LLzOg8HmY= +github.com/josharian/intern v1.0.0/go.mod h1:5DoeVV0s6jJacbCEi61lwdGj/aVlrQvzHFFd8Hwg//Y= github.com/jpillora/backoff v1.0.0/go.mod h1:J/6gKK9jxlEcS3zixgDgUAsiuZ7yrSoa/FX5e0EB2j4= github.com/json-iterator/go v1.1.6/go.mod h1:+SdeFBvtyEkXs7REEP0seUULqWtbJapLOCVDaaPEHmU= github.com/json-iterator/go v1.1.10/go.mod h1:KdQUCv79m/52Kvf8AW2vK1V8akMuk1QjK/uOdHXbAo4= @@ -257,6 +275,10 @@ github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY= github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE= github.com/lyft/protoc-gen-star v0.5.3/go.mod h1:V0xaHgaf5oCCqmcxYcWiDfTiKsZsRc87/1qhoTACD8w= github.com/magiconair/properties v1.8.5/go.mod h1:y3VJvCyxH9uVvJTWEGAELF3aiYNyPKd5NZ3oSwXrF60= +github.com/mailru/easyjson v0.0.0-20190614124828-94de47d64c63/go.mod h1:C1wdFJiN94OJF2b5HbByQZoLdCWB1Yqtg26g4irojpc= +github.com/mailru/easyjson v0.0.0-20190626092158-b2ccc519800e/go.mod h1:C1wdFJiN94OJF2b5HbByQZoLdCWB1Yqtg26g4irojpc= +github.com/mailru/easyjson v0.7.6 h1:8yTIVnZgCoiM1TgqoeTl+LfU5Jg6/xL3QhGQnimLYnA= +github.com/mailru/easyjson v0.7.6/go.mod h1:xzfreul335JAWq5oZzymOObrkdz5UnU4kGfJJLY9Nlc= github.com/mattn/go-colorable v0.0.9/go.mod h1:9vuHe8Xs5qXnSaW/c/ABM9alt+Vo+STaOChaDxuIBZU= github.com/mattn/go-isatty v0.0.3/go.mod h1:M+lRXTBqGeGNdLjl/ufCoiOlB5xdOkqRJdNxMWT7Zi4= github.com/matttproud/golang_protobuf_extensions v1.0.1/go.mod h1:D8He9yQNgCq6Z5Ld7szi9bcBfOoFv/3dc6xSMkL2PC0= @@ -311,6 +333,8 @@ github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINE github.com/pkg/sftp v1.10.1/go.mod h1:lYOWFsE0bwd1+KfKJaKeuokY15vzFx25BLbzYYoAxZI= github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/polarismesh/go-restful-openapi/v2 v2.0.0-20220915080537-fbc8c2ec9c38 h1:yTaogvIiOs9aNPW6RAO2J7nf/34rK2kQlKiY6dJAE1s= +github.com/polarismesh/go-restful-openapi/v2 v2.0.0-20220915080537-fbc8c2ec9c38/go.mod h1:4WhwBysTom9Eoy0hQ4W69I0FmO+T0EpjEW9/5sgHoUk= github.com/posener/complete v1.1.1/go.mod h1:em0nMJCgc9GFtwrmVmEMR/ZL6WyhyjMBndrE9hABlRI= github.com/prometheus/client_golang v0.9.1/go.mod h1:7SWBe2y4D6OKWSNQJUaRYU/AaXPKyh/dDVn+NZz0KFw= github.com/prometheus/client_golang v1.0.0/go.mod h1:db9x61etRT2tGnBNRi70OPL5FsnadC4Ky3P0J6CfImo= @@ -482,6 +506,7 @@ golang.org/x/net v0.0.0-20210119194325-5f4716e94777/go.mod h1:m0MpNAwzfU5UDzcl9v golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg= golang.org/x/net v0.0.0-20210316092652-d523dce5a7f4/go.mod h1:RBQZq4jEuRlivfhVLdyRGr576XBO4/greRjx4P4O3yc= golang.org/x/net v0.0.0-20210405180319-a5a99cb37ef4/go.mod h1:p54w0d4576C0XHj96bSt6lcn1PtDYWL6XObtHCRCNQM= +golang.org/x/net v0.0.0-20210421230115-4e50805a0758/go.mod h1:72T/g9IO56b78aLF+1Kcs5dz7/ng1VjMUvfKvpfy+jM= golang.org/x/net v0.0.0-20210428140749-89ef3d95e781/go.mod h1:OJAsFXCWl8Ukc7SiCT/9KSuxbyM7479/AVlXFRxuMCk= golang.org/x/net v0.0.0-20210525063256-abc453219eb5/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y= golang.org/x/net v0.0.0-20210813160813-60bc85c4be6d/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y= @@ -564,6 +589,7 @@ golang.org/x/sys v0.0.0-20210315160823-c6e025ad8005/go.mod h1:h1NjWce9XRLGQEsW7w golang.org/x/sys v0.0.0-20210320140829-1e4c9ba3b0c4/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20210330210617-4fbd30eecc44/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20210403161142-5e06dd20ab57/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20210420072515-93ed5bcd2bfe/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20210423082822-04245dca01da/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20210510120138-977fb7262007/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20210603081109-ebe580a85c40/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= @@ -742,8 +768,9 @@ google.golang.org/grpc v1.35.0/go.mod h1:qjiiYl8FncCW8feJPdyg3v6XW24KsRHe+dy9BAG google.golang.org/grpc v1.36.0/go.mod h1:qjiiYl8FncCW8feJPdyg3v6XW24KsRHe+dy9BAGRRjU= google.golang.org/grpc v1.36.1/go.mod h1:qjiiYl8FncCW8feJPdyg3v6XW24KsRHe+dy9BAGRRjU= google.golang.org/grpc v1.38.0/go.mod h1:NREThFqKR1f3iQ6oBuvc5LadQuXVGo9rkm5ZGrQdJfM= -google.golang.org/grpc v1.47.0 h1:9n77onPX5F3qfFCqjy9dhn8PbNQsIKeVU04J9G7umt8= google.golang.org/grpc v1.47.0/go.mod h1:vN9eftEi1UMyUsIF80+uQXhHjbXYbm0uXoFCACuMGWk= +google.golang.org/grpc v1.49.0 h1:WTLtQzmQori5FUH25Pq4WT22oCsv8USpQ+F6rqtsmxw= +google.golang.org/grpc v1.49.0/go.mod h1:ZgQEeidpAuNRZ8iRrlBKXZQP1ghovWIVhdJRyCDK+GI= google.golang.org/protobuf v0.0.0-20200109180630-ec00e32a8dfd/go.mod h1:DFci5gLYBciE7Vtevhsrf46CRTquxDuWsQurQQe4oz8= google.golang.org/protobuf v0.0.0-20200221191635-4d8936d0db64/go.mod h1:kwYJMbMJ01Woi6D6+Kah6886xMZcty6N08ah7+eCXa0= google.golang.org/protobuf v0.0.0-20200228230310-ab0ca4ff8a60/go.mod h1:cfTl7dwQJ+fmap5saPgwCLgHXTUD7jkjRqWcaiX5VyM= @@ -775,6 +802,7 @@ gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7/go.mod h1:dt/ZhP58zS4L8KSrWD gopkg.in/yaml.v2 v2.2.2 h1:ZCJp+EgiOT7lHqUV2J862kp8Qj64Jo6az82+3Td9dZw= gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= +gopkg.in/yaml.v3 v3.0.0-20200615113413-eeeca48fe776/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= gopkg.in/yaml.v3 v3.0.0-20210107192922-496545a6307b/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= diff --git a/namespace/namespace.go b/namespace/namespace.go index 0ebae5a87..4b4eb1849 100644 --- a/namespace/namespace.go +++ b/namespace/namespace.go @@ -208,6 +208,19 @@ func (s *Server) DeleteNamespace(ctx context.Context, req *api.Namespace) *api.R return api.NewNamespaceResponse(api.NamespaceExistedCircuitBreakers, req) } + // 判断属于该命名空间的服务是否都已经被删除 + total, err = s.getConfigGroupCountWithNamespace(namespace.Name) + if err != nil { + log.Error("get config group count with namespace err", + zap.String("request-id", requestID), + zap.String("err", err.Error())) + return api.NewNamespaceResponse(api.StoreLayerException, req) + } + if total != 0 { + log.Error("the removed namespace has remain config-group", zap.String("request-id", requestID)) + return api.NewNamespaceResponse(api.NamespaceExistedConfigGroups, req) + } + // 存储层操作 if err := tx.DeleteNamespace(namespace.Name); err != nil { log.Error(err.Error(), zap.String("request-id", requestID)) @@ -336,7 +349,7 @@ func (s *Server) GetNamespaces(ctx context.Context, query map[string][]string) * out.Size = utils.NewUInt32Value(uint32(len(namespaces))) for _, namespace := range namespaces { - nsCntInfo := s.caches.Service().GetNamesapceCntInfo(namespace.Name) + nsCntInfo := s.caches.Service().GetNamespaceCntInfo(namespace.Name) out.AddNamespace(&api.Namespace{ Id: utils.NewStringValue(namespace.Name), @@ -383,6 +396,15 @@ func (s *Server) getServicesCountWithNamespace(namespace string) (uint32, error) return total, nil } +// 根据命名空间查询配置分组总数 +func (s *Server) getConfigGroupCountWithNamespace(namespace string) (uint32, error) { + total, _, err := s.storage.QueryConfigFileGroups(namespace, "", 0, 1) + if err != nil { + return 0, err + } + return total, nil +} + // 根据命名空间查询熔断规则数量 func (s *Server) getCircuitBreakerCountWithNamespace(namespace string) (uint32, error) { filter := map[string]string{"namespace": namespace} diff --git a/plugin/healthchecker/heartbeatredis/checker_redis.go b/plugin/healthchecker/heartbeatredis/checker_redis.go index d6ccbdfc7..743e79693 100644 --- a/plugin/healthchecker/heartbeatredis/checker_redis.go +++ b/plugin/healthchecker/heartbeatredis/checker_redis.go @@ -31,7 +31,7 @@ import ( "github.com/polarismesh/polaris-server/plugin" ) -var log = commonlog.NamingScope() +var log = commonlog.HealthCheckScope() // 把操作记录记录到日志文件中 const ( diff --git a/polaris-server.yaml b/polaris-server.yaml index fe26c3115..e87ffa7fb 100644 --- a/polaris-server.yaml +++ b/polaris-server.yaml @@ -10,9 +10,9 @@ bootstrap: rotationMaxAge: 7 outputLevel: info # outputPaths: - # - stdout + # - stdout # errorOutputPaths: - # - stderr + # - stderr auth: rotateOutputPath: log/polaris-auth.log errorRotateOutputPath: log/polaris-auth-error.log @@ -57,6 +57,28 @@ bootstrap: # - stdout # errorOutputPaths: # - stderr + healthcheck: + rotateOutputPath: log/polaris-healthcheck.log + errorRotateOutputPath: log/polaris-healthcheck-error.log + rotationMaxSize: 100 + rotationMaxBackups: 10 + rotationMaxAge: 7 + outputLevel: info + # outputPaths: + # - stdout + # errorOutputPaths: + # - stderr + xdsv3: + rotateOutputPath: log/polaris-xdsv3.log + errorRotateOutputPath: log/polaris-xdsv3-error.log + rotationMaxSize: 100 + rotationMaxBackups: 10 + rotationMaxAge: 7 + outputLevel: info + # outputPaths: + # - stdout + # errorOutputPaths: + # - stderr default: rotateOutputPath: log/polaris-default.log errorRotateOutputPath: log/polaris-default-error.log @@ -78,18 +100,9 @@ bootstrap: enable_register: true isolated: false services: - - name: polaris.discover - protocols: - - service-grpc - - name: polaris.healthcheck - protocols: - - service-grpc - name: polaris.checker protocols: - service-grpc - - name: polaris.config - protocols: - - config-grpc # apiserver配置 apiservers: - name: service-eureka @@ -113,6 +126,7 @@ apiservers: listenIP: "0.0.0.0" listenPort: 8090 enablePprof: true # debug pprof + enableSwagger: true connLimit: openConnLimit: false maxConnPerHost: 128 @@ -369,4 +383,4 @@ plugin: - name: "GET:/v1/naming/services" rule: store-read - name: "GET:/v1/naming/services/count" - rule: store-read \ No newline at end of file + rule: store-read diff --git a/service/api.go b/service/api.go index 50c9a18ef..9b06eeaaa 100644 --- a/service/api.go +++ b/service/api.go @@ -18,235 +18,16 @@ package service import ( - "context" - "github.com/polarismesh/polaris-server/cache" - "github.com/polarismesh/polaris-server/common/api/l5" - api "github.com/polarismesh/polaris-server/common/api/v1" "github.com/polarismesh/polaris-server/common/model" ) -// CircuitBreakerOperateServer Melting rule related treatment -type CircuitBreakerOperateServer interface { - - // CreateCircuitBreakers Create a CircuitBreaker rule - CreateCircuitBreakers(ctx context.Context, req []*api.CircuitBreaker) *api.BatchWriteResponse - - // CreateCircuitBreakerVersions Create a melt rule version - CreateCircuitBreakerVersions(ctx context.Context, req []*api.CircuitBreaker) *api.BatchWriteResponse - - // DeleteCircuitBreakers Delete CircuitBreaker rules - DeleteCircuitBreakers(ctx context.Context, req []*api.CircuitBreaker) *api.BatchWriteResponse - - // UpdateCircuitBreakers Modify the CircuitBreaker rule - UpdateCircuitBreakers(ctx context.Context, req []*api.CircuitBreaker) *api.BatchWriteResponse - - // ReleaseCircuitBreakers Release CircuitBreaker rule - ReleaseCircuitBreakers(ctx context.Context, req []*api.ConfigRelease) *api.BatchWriteResponse - - // UnBindCircuitBreakers Solution CircuitBreaker rule - UnBindCircuitBreakers(ctx context.Context, req []*api.ConfigRelease) *api.BatchWriteResponse - - // GetCircuitBreaker Get CircuitBreaker regular according to ID and VERSION - GetCircuitBreaker(ctx context.Context, query map[string]string) *api.BatchQueryResponse - - // GetCircuitBreakerVersions Query all versions of the CircuitBreaker rule - GetCircuitBreakerVersions(ctx context.Context, query map[string]string) *api.BatchQueryResponse - - // GetMasterCircuitBreakers Query Master CircuitBreaker rules - GetMasterCircuitBreakers(ctx context.Context, query map[string]string) *api.BatchQueryResponse - - // GetReleaseCircuitBreakers Query the released CircuitBreaker rule according to the rule ID - GetReleaseCircuitBreakers(ctx context.Context, query map[string]string) *api.BatchQueryResponse - - // GetCircuitBreakerByService Binding CircuitBreaker rule based on service query - GetCircuitBreakerByService(ctx context.Context, query map[string]string) *api.BatchQueryResponse - - // GetCircuitBreakerToken Get CircuitBreaker rules token - GetCircuitBreakerToken(ctx context.Context, req *api.CircuitBreaker) *api.Response -} - -// RateLimitOperateServer Lamflow rule related operation -type RateLimitOperateServer interface { - - // CreateRateLimits Create a RateLimit rule - CreateRateLimits(ctx context.Context, request []*api.Rule) *api.BatchWriteResponse - - // DeleteRateLimits Delete current RateLimit rules - DeleteRateLimits(ctx context.Context, request []*api.Rule) *api.BatchWriteResponse - - // EnableRateLimits Enable the RateLimit rule - EnableRateLimits(ctx context.Context, request []*api.Rule) *api.BatchWriteResponse - - // UpdateRateLimits Modify the RateLimit rule - UpdateRateLimits(ctx context.Context, request []*api.Rule) *api.BatchWriteResponse - - // GetRateLimits Query RateLimit rules - GetRateLimits(ctx context.Context, query map[string]string) *api.BatchQueryResponse -} - -// RouteRuleOperateServer Routing rules related operations -type RouteRuleOperateServer interface { - - // CreateRoutingConfigs Batch creation routing configuration - CreateRoutingConfigs(ctx context.Context, req []*api.Routing) *api.BatchWriteResponse - - // DeleteRoutingConfigs Batch delete routing configuration - DeleteRoutingConfigs(ctx context.Context, req []*api.Routing) *api.BatchWriteResponse - - // UpdateRoutingConfigs Batch update routing configuration - UpdateRoutingConfigs(ctx context.Context, req []*api.Routing) *api.BatchWriteResponse - - // GetRoutingConfigs Inquiry route configuration to OSS - GetRoutingConfigs(ctx context.Context, query map[string]string) *api.BatchQueryResponse -} - -// ServiceOperateServer Service related operations -type ServiceOperateServer interface { - - // CreateServices Batch creation service - CreateServices(ctx context.Context, req []*api.Service) *api.BatchWriteResponse - - // DeleteServices Batch delete service - DeleteServices(ctx context.Context, req []*api.Service) *api.BatchWriteResponse - - // UpdateServices Batch update service - UpdateServices(ctx context.Context, req []*api.Service) *api.BatchWriteResponse - - // UpdateServiceToken Update service token - UpdateServiceToken(ctx context.Context, req *api.Service) *api.Response - - // GetServices Get a list of service - GetServices(ctx context.Context, query map[string]string) *api.BatchQueryResponse - - // GetServicesCount Total number of services - GetServicesCount(ctx context.Context) *api.BatchQueryResponse - - // GetServiceToken Get service token - GetServiceToken(ctx context.Context, req *api.Service) *api.Response - - // GetServiceOwner Owner for obtaining service - GetServiceOwner(ctx context.Context, req []*api.Service) *api.BatchQueryResponse -} - -// ServiceAliasOperateServer Service alias related operations -type ServiceAliasOperateServer interface { - - // CreateServiceAlias Create a service alias - CreateServiceAlias(ctx context.Context, req *api.ServiceAlias) *api.Response - - // DeleteServiceAliases Batch delete service alias - DeleteServiceAliases(ctx context.Context, req []*api.ServiceAlias) *api.BatchWriteResponse - - // UpdateServiceAlias Update service alias - UpdateServiceAlias(ctx context.Context, req *api.ServiceAlias) *api.Response - - // GetServiceAliases Get a list of service alias - GetServiceAliases(ctx context.Context, query map[string]string) *api.BatchQueryResponse -} - -// InstanceOperateServer Example related operations -type InstanceOperateServer interface { - - // CreateInstances Batch creation instance - CreateInstances(ctx context.Context, reqs []*api.Instance) *api.BatchWriteResponse - - // DeleteInstances Batch delete instance - DeleteInstances(ctx context.Context, req []*api.Instance) *api.BatchWriteResponse - - // DeleteInstancesByHost Delete instance according to HOST information batch - DeleteInstancesByHost(ctx context.Context, req []*api.Instance) *api.BatchWriteResponse - - // UpdateInstances Batch update instance - UpdateInstances(ctx context.Context, req []*api.Instance) *api.BatchWriteResponse - - // UpdateInstancesIsolate Batch update instance isolation state - UpdateInstancesIsolate(ctx context.Context, req []*api.Instance) *api.BatchWriteResponse - - // GetInstances Get an instance list - GetInstances(ctx context.Context, query map[string]string) *api.BatchQueryResponse - - // GetInstancesCount Get an instance quantity - GetInstancesCount(ctx context.Context) *api.BatchQueryResponse - - // CleanInstance Clean up instance - CleanInstance(ctx context.Context, req *api.Instance) *api.Response -} - -// ClientServer Client related operation Client operation interface definition -type ClientServer interface { - - // RegisterInstance create one instance by client - RegisterInstance(ctx context.Context, req *api.Instance) *api.Response - - // DeregisterInstance delete onr instance by client - DeregisterInstance(ctx context.Context, req *api.Instance) *api.Response - - // ReportClient Client gets geographic location information - ReportClient(ctx context.Context, req *api.Client) *api.Response - - // GetReportClientWithCache Used to obtain the ReportClient information and serve as the SD result of Prometheus - GetReportClientWithCache(ctx context.Context, query map[string]string) *model.PrometheusDiscoveryResponse - - // GetServiceWithCache Used for client acquisition service information - GetServiceWithCache(ctx context.Context, req *api.Service) *api.DiscoverResponse - - // ServiceInstancesCache Used for client acquisition service instance information - ServiceInstancesCache(ctx context.Context, req *api.Service) *api.DiscoverResponse - - // GetRoutingConfigWithCache User Client Get Service Routing Configuration Information - GetRoutingConfigWithCache(ctx context.Context, req *api.Service) *api.DiscoverResponse - - // GetRateLimitWithCache User Client Get Service Limit Configuration Information - GetRateLimitWithCache(ctx context.Context, req *api.Service) *api.DiscoverResponse - - // GetCircuitBreakerWithCache Fuse configuration information for obtaining services for clients - GetCircuitBreakerWithCache(ctx context.Context, req *api.Service) *api.DiscoverResponse -} - -// PlatformOperateServer Position of the platform -type PlatformOperateServer interface { - - // CreatePlatforms Batch creation related platform - CreatePlatforms(ctx context.Context, req []*api.Platform) *api.BatchWriteResponse - - // UpdatePlatforms Batch update platform information - UpdatePlatforms(ctx context.Context, req []*api.Platform) *api.BatchWriteResponse - - // DeletePlatforms Batch delete platform information - DeletePlatforms(ctx context.Context, req []*api.Platform) *api.BatchWriteResponse - - // GetPlatforms Get a list of platforms - GetPlatforms(ctx context.Context, query map[string]string) *api.BatchQueryResponse - - // GetPlatformToken Get the platform token - GetPlatformToken(ctx context.Context, req *api.Platform) *api.Response -} - -// L5OperateServer L5 related operations -type L5OperateServer interface { - - // SyncByAgentCmd Get routing information according to SID list - SyncByAgentCmd(ctx context.Context, sbac *l5.Cl5SyncByAgentCmd) (*l5.Cl5SyncByAgentAckCmd, error) - - // RegisterByNameCmd Look for the corresponding SID list according to the list of service names - RegisterByNameCmd(rbnc *l5.Cl5RegisterByNameCmd) (*l5.Cl5RegisterByNameAckCmd, error) -} - -// ReportClientOperateServer Report information operation interface on the client -type ReportClientOperateServer interface { - // GetReportClients Query the client information reported - GetReportClients(ctx context.Context, query map[string]string) *api.BatchQueryResponse -} - // DiscoverServer Server discovered by the service type DiscoverServer interface { - // Fuse rule operation interface definition - CircuitBreakerOperateServer - // Lamflow rule operation interface definition - RateLimitOperateServer - // Routing rules operation interface definition - RouteRuleOperateServer + // DiscoverServerV1 + DiscoverServerV1 + // DiscoverServerV2 + DiscoverServerV2 // Service alias operation interface definition ServiceAliasOperateServer // Service operation interface definition diff --git a/service/api_v1.go b/service/api_v1.go new file mode 100644 index 000000000..aeabb9b0e --- /dev/null +++ b/service/api_v1.go @@ -0,0 +1,250 @@ +/** + * Tencent is pleased to support the open source community by making Polaris available. + * + * Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved. + * + * Licensed under the BSD 3-Clause License (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://opensource.org/licenses/BSD-3-Clause + * + * 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 service + +import ( + "context" + + "github.com/polarismesh/polaris-server/common/api/l5" + api "github.com/polarismesh/polaris-server/common/api/v1" + "github.com/polarismesh/polaris-server/common/model" +) + +// CircuitBreakerOperateServer Melting rule related treatment +type CircuitBreakerOperateServer interface { + + // CreateCircuitBreakers Create a CircuitBreaker rule + CreateCircuitBreakers(ctx context.Context, req []*api.CircuitBreaker) *api.BatchWriteResponse + + // CreateCircuitBreakerVersions Create a melt rule version + CreateCircuitBreakerVersions(ctx context.Context, req []*api.CircuitBreaker) *api.BatchWriteResponse + + // DeleteCircuitBreakers Delete CircuitBreaker rules + DeleteCircuitBreakers(ctx context.Context, req []*api.CircuitBreaker) *api.BatchWriteResponse + + // UpdateCircuitBreakers Modify the CircuitBreaker rule + UpdateCircuitBreakers(ctx context.Context, req []*api.CircuitBreaker) *api.BatchWriteResponse + + // ReleaseCircuitBreakers Release CircuitBreaker rule + ReleaseCircuitBreakers(ctx context.Context, req []*api.ConfigRelease) *api.BatchWriteResponse + + // UnBindCircuitBreakers Solution CircuitBreaker rule + UnBindCircuitBreakers(ctx context.Context, req []*api.ConfigRelease) *api.BatchWriteResponse + + // GetCircuitBreaker Get CircuitBreaker regular according to ID and VERSION + GetCircuitBreaker(ctx context.Context, query map[string]string) *api.BatchQueryResponse + + // GetCircuitBreakerVersions Query all versions of the CircuitBreaker rule + GetCircuitBreakerVersions(ctx context.Context, query map[string]string) *api.BatchQueryResponse + + // GetMasterCircuitBreakers Query Master CircuitBreaker rules + GetMasterCircuitBreakers(ctx context.Context, query map[string]string) *api.BatchQueryResponse + + // GetReleaseCircuitBreakers Query the released CircuitBreaker rule according to the rule ID + GetReleaseCircuitBreakers(ctx context.Context, query map[string]string) *api.BatchQueryResponse + + // GetCircuitBreakerByService Binding CircuitBreaker rule based on service query + GetCircuitBreakerByService(ctx context.Context, query map[string]string) *api.BatchQueryResponse + + // GetCircuitBreakerToken Get CircuitBreaker rules token + GetCircuitBreakerToken(ctx context.Context, req *api.CircuitBreaker) *api.Response +} + +// RateLimitOperateServer Lamflow rule related operation +type RateLimitOperateServer interface { + + // CreateRateLimits Create a RateLimit rule + CreateRateLimits(ctx context.Context, request []*api.Rule) *api.BatchWriteResponse + + // DeleteRateLimits Delete current RateLimit rules + DeleteRateLimits(ctx context.Context, request []*api.Rule) *api.BatchWriteResponse + + // EnableRateLimits Enable the RateLimit rule + EnableRateLimits(ctx context.Context, request []*api.Rule) *api.BatchWriteResponse + + // UpdateRateLimits Modify the RateLimit rule + UpdateRateLimits(ctx context.Context, request []*api.Rule) *api.BatchWriteResponse + + // GetRateLimits Query RateLimit rules + GetRateLimits(ctx context.Context, query map[string]string) *api.BatchQueryResponse +} + +// RouteRuleOperateServer Routing rules related operations +type RouteRuleOperateServer interface { + // CreateRoutingConfigs Batch creation routing configuration + CreateRoutingConfigs(ctx context.Context, req []*api.Routing) *api.BatchWriteResponse + + // DeleteRoutingConfigs Batch delete routing configuration + DeleteRoutingConfigs(ctx context.Context, req []*api.Routing) *api.BatchWriteResponse + + // UpdateRoutingConfigs Batch update routing configuration + UpdateRoutingConfigs(ctx context.Context, req []*api.Routing) *api.BatchWriteResponse + + // GetRoutingConfigs Inquiry route configuration to OSS + GetRoutingConfigs(ctx context.Context, query map[string]string) *api.BatchQueryResponse +} + +// ServiceOperateServer Service related operations +type ServiceOperateServer interface { + + // CreateServices Batch creation service + CreateServices(ctx context.Context, req []*api.Service) *api.BatchWriteResponse + + // DeleteServices Batch delete service + DeleteServices(ctx context.Context, req []*api.Service) *api.BatchWriteResponse + + // UpdateServices Batch update service + UpdateServices(ctx context.Context, req []*api.Service) *api.BatchWriteResponse + + // UpdateServiceToken Update service token + UpdateServiceToken(ctx context.Context, req *api.Service) *api.Response + + // GetServices Get a list of service + GetServices(ctx context.Context, query map[string]string) *api.BatchQueryResponse + + // GetServicesCount Total number of services + GetServicesCount(ctx context.Context) *api.BatchQueryResponse + + // GetServiceToken Get service token + GetServiceToken(ctx context.Context, req *api.Service) *api.Response + + // GetServiceOwner Owner for obtaining service + GetServiceOwner(ctx context.Context, req []*api.Service) *api.BatchQueryResponse +} + +// ServiceAliasOperateServer Service alias related operations +type ServiceAliasOperateServer interface { + + // CreateServiceAlias Create a service alias + CreateServiceAlias(ctx context.Context, req *api.ServiceAlias) *api.Response + + // DeleteServiceAliases Batch delete service alias + DeleteServiceAliases(ctx context.Context, req []*api.ServiceAlias) *api.BatchWriteResponse + + // UpdateServiceAlias Update service alias + UpdateServiceAlias(ctx context.Context, req *api.ServiceAlias) *api.Response + + // GetServiceAliases Get a list of service alias + GetServiceAliases(ctx context.Context, query map[string]string) *api.BatchQueryResponse +} + +// InstanceOperateServer Example related operations +type InstanceOperateServer interface { + + // CreateInstances Batch creation instance + CreateInstances(ctx context.Context, reqs []*api.Instance) *api.BatchWriteResponse + + // DeleteInstances Batch delete instance + DeleteInstances(ctx context.Context, req []*api.Instance) *api.BatchWriteResponse + + // DeleteInstancesByHost Delete instance according to HOST information batch + DeleteInstancesByHost(ctx context.Context, req []*api.Instance) *api.BatchWriteResponse + + // UpdateInstances Batch update instance + UpdateInstances(ctx context.Context, req []*api.Instance) *api.BatchWriteResponse + + // UpdateInstancesIsolate Batch update instance isolation state + UpdateInstancesIsolate(ctx context.Context, req []*api.Instance) *api.BatchWriteResponse + + // GetInstances Get an instance list + GetInstances(ctx context.Context, query map[string]string) *api.BatchQueryResponse + + // GetInstancesCount Get an instance quantity + GetInstancesCount(ctx context.Context) *api.BatchQueryResponse + + // GetInstanceLabels Get an instance tag under a service + GetInstanceLabels(ctx context.Context, query map[string]string) *api.Response + + // CleanInstance Clean up instance + CleanInstance(ctx context.Context, req *api.Instance) *api.Response +} + +// ClientServer Client related operation Client operation interface definition +type ClientServer interface { + + // RegisterInstance create one instance by client + RegisterInstance(ctx context.Context, req *api.Instance) *api.Response + + // DeregisterInstance delete onr instance by client + DeregisterInstance(ctx context.Context, req *api.Instance) *api.Response + + // ReportClient Client gets geographic location information + ReportClient(ctx context.Context, req *api.Client) *api.Response + + // GetReportClientWithCache Used to obtain the ReportClient information and serve as the SD result of Prometheus + GetReportClientWithCache(ctx context.Context, query map[string]string) *model.PrometheusDiscoveryResponse + + // GetServiceWithCache Used for client acquisition service information + GetServiceWithCache(ctx context.Context, req *api.Service) *api.DiscoverResponse + + // ServiceInstancesCache Used for client acquisition service instance information + ServiceInstancesCache(ctx context.Context, req *api.Service) *api.DiscoverResponse + + // GetRoutingConfigWithCache User Client Get Service Routing Configuration Information + GetRoutingConfigWithCache(ctx context.Context, req *api.Service) *api.DiscoverResponse + + // GetRateLimitWithCache User Client Get Service Limit Configuration Information + GetRateLimitWithCache(ctx context.Context, req *api.Service) *api.DiscoverResponse + + // GetCircuitBreakerWithCache Fuse configuration information for obtaining services for clients + GetCircuitBreakerWithCache(ctx context.Context, req *api.Service) *api.DiscoverResponse +} + +// PlatformOperateServer Position of the platform +type PlatformOperateServer interface { + + // CreatePlatforms Batch creation related platform + CreatePlatforms(ctx context.Context, req []*api.Platform) *api.BatchWriteResponse + + // UpdatePlatforms Batch update platform information + UpdatePlatforms(ctx context.Context, req []*api.Platform) *api.BatchWriteResponse + + // DeletePlatforms Batch delete platform information + DeletePlatforms(ctx context.Context, req []*api.Platform) *api.BatchWriteResponse + + // GetPlatforms Get a list of platforms + GetPlatforms(ctx context.Context, query map[string]string) *api.BatchQueryResponse + + // GetPlatformToken Get the platform token + GetPlatformToken(ctx context.Context, req *api.Platform) *api.Response +} + +// L5OperateServer L5 related operations +type L5OperateServer interface { + + // SyncByAgentCmd Get routing information according to SID list + SyncByAgentCmd(ctx context.Context, sbac *l5.Cl5SyncByAgentCmd) (*l5.Cl5SyncByAgentAckCmd, error) + + // RegisterByNameCmd Look for the corresponding SID list according to the list of service names + RegisterByNameCmd(rbnc *l5.Cl5RegisterByNameCmd) (*l5.Cl5RegisterByNameAckCmd, error) +} + +// ReportClientOperateServer Report information operation interface on the client +type ReportClientOperateServer interface { + // GetReportClients Query the client information reported + GetReportClients(ctx context.Context, query map[string]string) *api.BatchQueryResponse +} + +type DiscoverServerV1 interface { + // Fuse rule operation interface definition + CircuitBreakerOperateServer + // Lamflow rule operation interface definition + RateLimitOperateServer + // Routing rules operation interface definition + RouteRuleOperateServer +} diff --git a/service/api_v2.go b/service/api_v2.go new file mode 100644 index 000000000..a7165365d --- /dev/null +++ b/service/api_v2.go @@ -0,0 +1,54 @@ +/** + * Tencent is pleased to support the open source community by making Polaris available. + * + * Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved. + * + * Licensed under the BSD 3-Clause License (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://opensource.org/licenses/BSD-3-Clause + * + * 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 service + +import ( + "context" + + apiv2 "github.com/polarismesh/polaris-server/common/api/v2" +) + +// ClientV2Server Client related operation Client operation interface definition +type ClientV2Server interface { + // GetRoutingConfigWithCache User Client Get Service Routing Configuration Information + GetRoutingConfigV2WithCache(ctx context.Context, req *apiv2.Service) *apiv2.DiscoverResponse + + // GetCircuitBreakerWithCache Fuse configuration information for obtaining services for clients + GetCircuitBreakerV2WithCache(ctx context.Context, req *apiv2.Service) *apiv2.DiscoverResponse +} + +// RouteRuleV2OperateServer Routing rules related operations +type RouteRuleV2OperateServer interface { + // CreateRoutingConfigs Batch creation routing configuration + CreateRoutingConfigsV2(ctx context.Context, req []*apiv2.Routing) *apiv2.BatchWriteResponse + // DeleteRoutingConfigs Batch delete routing configuration + DeleteRoutingConfigsV2(ctx context.Context, req []*apiv2.Routing) *apiv2.BatchWriteResponse + // UpdateRoutingConfigs Batch update routing configuration + UpdateRoutingConfigsV2(ctx context.Context, req []*apiv2.Routing) *apiv2.BatchWriteResponse + // GetRoutingConfigs Inquiry route configuration to OSS + GetRoutingConfigsV2(ctx context.Context, query map[string]string) *apiv2.BatchQueryResponse + // EnableRoutings batch enable routing rules + EnableRoutings(ctx context.Context, req []*apiv2.Routing) *apiv2.BatchWriteResponse +} + +type DiscoverServerV2 interface { + // ClientV2Server + ClientV2Server + // RouteRuleV2OperateServer Routing rules operation interface definition + RouteRuleV2OperateServer +} diff --git a/service/batch/instance.go b/service/batch/instance.go index 69e639b5c..8a3914174 100644 --- a/service/batch/instance.go +++ b/service/batch/instance.go @@ -29,6 +29,7 @@ import ( "github.com/polarismesh/polaris-server/cache" api "github.com/polarismesh/polaris-server/common/api/v1" "github.com/polarismesh/polaris-server/common/model" + instancecommon "github.com/polarismesh/polaris-server/common/service" "github.com/polarismesh/polaris-server/common/utils" "github.com/polarismesh/polaris-server/store" ) @@ -294,7 +295,7 @@ func (ctrl *InstanceCtrl) registerHandler(futures []*InstanceFuture) error { // 构造model数据 for _, entry := range remains { - ins := utils.CreateInstanceModel(entry.serviceId, entry.request) + ins := instancecommon.CreateInstanceModel(entry.serviceId, entry.request) if _, ok := firstRegisInstances[ins.ID()]; ok { ins.FirstRegis = true } diff --git a/service/client.go b/service/client.go index c4b6eaadb..1f5448603 100644 --- a/service/client.go +++ b/service/client.go @@ -25,14 +25,15 @@ import ( api "github.com/polarismesh/polaris-server/common/api/v1" "github.com/polarismesh/polaris-server/common/model" "github.com/polarismesh/polaris-server/common/utils" + "go.uber.org/zap" ) -// CreateInstances create one instance +// RegisterInstance create one instance func (s *Server) RegisterInstance(ctx context.Context, req *api.Instance) *api.Response { return s.CreateInstance(ctx, req) } -// DeleteInstance delete onr instance +// DeregisterInstance delete one instance func (s *Server) DeregisterInstance(ctx context.Context, req *api.Instance) *api.Response { return s.DeleteInstance(ctx, req) } @@ -120,9 +121,7 @@ func (s *Server) GetReportClientWithCache(ctx context.Context, } } -/** - * GetServiceWithCache 根据元数据查询服务 - */ +// GetServiceWithCache 根据元数据查询服务 func (s *Server) GetServiceWithCache(ctx context.Context, req *api.Service) *api.DiscoverResponse { if s.caches == nil { return api.NewDiscoverServiceResponse(api.ClientAPINotOpen, req) @@ -257,7 +256,6 @@ func (s *Server) GetRoutingConfigWithCache(ctx context.Context, req *api.Service if s.caches == nil { return api.NewDiscoverRoutingResponse(api.ClientAPINotOpen, req) } - rid := ParseRequestID(ctx) if req == nil { return api.NewDiscoverRoutingResponse(api.EmptyRequest, req) } @@ -276,30 +274,29 @@ func (s *Server) GetRoutingConfigWithCache(ctx context.Context, req *api.Service } // 先从缓存获取ServiceID,这里返回的是源服务 - service := s.getServiceCache(req.GetName().GetValue(), req.GetNamespace().GetValue()) - if service == nil { + svc := s.getServiceCache(req.GetName().GetValue(), req.GetNamespace().GetValue()) + if svc == nil { return api.NewDiscoverRoutingResponse(api.NotFoundService, req) } - out := s.caches.RoutingConfig().GetRoutingConfig(service.ID) + out, err := s.caches.RoutingConfig().GetRoutingConfigV1(svc.ID, svc.Name, svc.Namespace) + if err != nil { + log.Error("[Server][Service][Routing] discover routing", utils.ZapRequestIDByCtx(ctx), zap.Error(err)) + return api.NewDiscoverRoutingResponse(api.ExecuteException, req) + } + if out == nil { return resp } // 获取路由数据,并对比revision - if out.Revision == req.GetRevision().GetValue() { + if out.GetRevision().GetValue() == req.GetRevision().GetValue() { return api.NewDiscoverRoutingResponse(api.DataNoChange, req) } // 数据不一致,发生了改变 // 数据格式转换,service只需要返回二元组与routing的revision - var err error - resp.Service.Revision = utils.NewStringValue(out.Revision) - resp.Routing, err = routingConfig2API(out, req.GetName().GetValue(), req.GetNamespace().GetValue()) - if err != nil { - log.Error(err.Error(), ZapRequestID(rid)) - return api.NewDiscoverRoutingResponse(api.ExecuteException, req) - } - + resp.Service.Revision = out.GetRevision() + resp.Routing = out return resp } diff --git a/service/client_v2.go b/service/client_v2.go new file mode 100644 index 000000000..8c3a6354e --- /dev/null +++ b/service/client_v2.go @@ -0,0 +1,81 @@ +/** + * Tencent is pleased to support the open source community by making Polaris available. + * + * Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved. + * + * Licensed under the BSD 3-Clause License (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://opensource.org/licenses/BSD-3-Clause + * + * 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 service + +import ( + "context" + + api "github.com/polarismesh/polaris-server/common/api/v1" + apiv2 "github.com/polarismesh/polaris-server/common/api/v2" + "github.com/polarismesh/polaris-server/common/utils" + "go.uber.org/zap" +) + +// GetRoutingConfigWithCache User Client Get Service Routing Configuration Information +func (s *Server) GetRoutingConfigV2WithCache(ctx context.Context, req *apiv2.Service) *apiv2.DiscoverResponse { + if s.caches == nil { + return apiv2.NewDiscoverRoutingResponse(api.ClientAPINotOpen, req) + } + if req == nil { + return apiv2.NewDiscoverRoutingResponse(api.EmptyRequest, req) + } + + if req.GetName() == "" { + return apiv2.NewDiscoverRoutingResponse(api.InvalidServiceName, req) + } + if req.GetNamespace() == "" { + return apiv2.NewDiscoverRoutingResponse(api.InvalidNamespaceName, req) + } + + resp := apiv2.NewDiscoverRoutingResponse(api.ExecuteSuccess, nil) + resp.Service = &apiv2.Service{ + Name: req.GetName(), + Namespace: req.GetNamespace(), + } + + // 先从缓存获取ServiceID,这里返回的是源服务 + svc := s.getServiceCache(req.GetName(), req.GetNamespace()) + if svc == nil { + return apiv2.NewDiscoverRoutingResponse(api.NotFoundService, req) + } + out, err := s.caches.RoutingConfig().GetRoutingConfigV2(svc.ID, svc.Name, svc.Namespace) + if err != nil { + log.Error("[Server][Service][Routing] discover routing v2", utils.ZapRequestIDByCtx(ctx), zap.Error(err)) + return apiv2.NewDiscoverRoutingResponse(api.ExecuteException, req) + } + + if out == nil { + return resp + } + + // // 获取路由数据,并对比revision + // if out.GetRevision() == req.GetRevision() { + // return apiv2.NewDiscoverRoutingResponse(api.DataNoChange, req) + // } + + // 数据不一致,发生了改变 + // 数据格式转换,service只需要返回二元组与routing的revision + resp.Service.Revision = utils.NewV2Revision() + resp.Routings = out + return resp +} + +// GetCircuitBreakerWithCache Fuse configuration information for obtaining services for clients +func (s *Server) GetCircuitBreakerV2WithCache(ctx context.Context, req *apiv2.Service) *apiv2.DiscoverResponse { + return apiv2.NewDiscoverRoutingResponse(api.NotFoundService, req) +} diff --git a/service/client_v2_authability.go b/service/client_v2_authability.go new file mode 100644 index 000000000..5cb51ac34 --- /dev/null +++ b/service/client_v2_authability.go @@ -0,0 +1,36 @@ +/** + * Tencent is pleased to support the open source community by making Polaris available. + * + * Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved. + * + * Licensed under the BSD 3-Clause License (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://opensource.org/licenses/BSD-3-Clause + * + * 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 service + +import ( + "context" + + apiv2 "github.com/polarismesh/polaris-server/common/api/v2" +) + +// GetRoutingConfigV2WithCache User Client Get Service Routing Configuration Information +func (svr *serverAuthAbility) GetRoutingConfigV2WithCache(ctx context.Context, req *apiv2.Service) *apiv2.DiscoverResponse { + + return svr.targetServer.GetRoutingConfigV2WithCache(ctx, req) +} + +// GetCircuitBreakerV2WithCache Fuse configuration information for obtaining services for clients +func (svr *serverAuthAbility) GetCircuitBreakerV2WithCache(ctx context.Context, req *apiv2.Service) *apiv2.DiscoverResponse { + + return svr.targetServer.GetCircuitBreakerV2WithCache(ctx, req) +} diff --git a/service/healthcheck/log.go b/service/healthcheck/log.go index b8924d09b..7a6390456 100644 --- a/service/healthcheck/log.go +++ b/service/healthcheck/log.go @@ -21,4 +21,4 @@ import ( commonlog "github.com/polarismesh/polaris-server/common/log" ) -var log = commonlog.NamingScope() +var log = commonlog.HealthCheckScope() diff --git a/service/healthcheck/report.go b/service/healthcheck/report.go index 4037fa9e6..faff48006 100644 --- a/service/healthcheck/report.go +++ b/service/healthcheck/report.go @@ -50,6 +50,12 @@ func (s *Server) doReport(ctx context.Context, instance *api.Instance) *api.Resp if errRsp != nil { return errRsp } + + ins := s.instanceCache.GetInstance(id) + if ins == nil { + return api.NewResponse(api.NotFoundResource) + } + instance.Id = utils.NewStringValue(id) insCache := s.cacheProvider.GetInstance(id) if insCache == nil { diff --git a/service/healthcheck/server.go b/service/healthcheck/server.go index 2fb4716a4..5d9f1cda0 100644 --- a/service/healthcheck/server.go +++ b/service/healthcheck/server.go @@ -55,6 +55,7 @@ type Server struct { discoverCh chan eventWrapper bc *batch.Controller serviceCache cache.ServiceCache + instanceCache cache.InstanceCache } // Initialize 初始化 @@ -123,7 +124,7 @@ func (s *Server) Report(ctx context.Context, req *api.Instance) *api.Response { return s.doReport(ctx, req) } -// Report report heartbeat request by client +// ReportByClient report heartbeat request by client func (s *Server) ReportByClient(ctx context.Context, req *api.Client) *api.Response { return s.doReportByClient(ctx, req) } @@ -142,6 +143,11 @@ func (s *Server) SetServiceCache(serviceCache cache.ServiceCache) { s.serviceCache = serviceCache } +// SetInstanceCache 设置服务实例缓存 +func (s *Server) SetInstanceCache(instanceCache cache.InstanceCache) { + s.instanceCache = instanceCache +} + // CacheProvider get cache provider func (s *Server) CacheProvider() (*CacheProvider, error) { if !finishInit { diff --git a/service/instance.go b/service/instance.go index 963748574..20f8ced15 100644 --- a/service/instance.go +++ b/service/instance.go @@ -29,6 +29,7 @@ import ( api "github.com/polarismesh/polaris-server/common/api/v1" "github.com/polarismesh/polaris-server/common/model" + instancecommon "github.com/polarismesh/polaris-server/common/service" "github.com/polarismesh/polaris-server/common/utils" ) @@ -161,7 +162,7 @@ func (s *Server) asyncCreateInstance(ctx context.Context, svcId string, req *api return nil, api.NewInstanceResponse(future.Code(), req) } - return utils.CreateInstanceModel(svcId, req), nil + return instancecommon.CreateInstanceModel(svcId, req), nil } // 同步串行创建实例 @@ -182,7 +183,7 @@ func (s *Server) serialCreateInstance(ctx context.Context, svcId string, req *ap ins.Isolate = instance.Proto.Isolate } // 直接同步创建服务实例 - data := utils.CreateInstanceModel(svcId, ins) + data := instancecommon.CreateInstanceModel(svcId, ins) if err := s.storage.AddInstance(data); err != nil { log.Error(err.Error(), ZapRequestID(rid), ZapPlatformID(pid)) return nil, wrapperInstanceStoreResponse(req, err) @@ -552,11 +553,17 @@ func (s *Server) updateInstanceAttribute(req *api.Instance, instance *model.Inst insProto.Metadata = req.GetMetadata() needUpdate = true } + if ok := instanceLocationNeedUpdate(req.GetLocation(), instance.Proto.GetLocation()); ok { insProto.Location = req.Location needUpdate = true } + // if !needUpdate { + // // 不需要更新metadata,则置空 + // insProto.Metadata = nil + // } + if req.GetProtocol() != nil && req.GetProtocol().GetValue() != instance.Protocol() { insProto.Protocol = req.GetProtocol() needUpdate = true @@ -705,6 +712,37 @@ func (s *Server) GetInstances(ctx context.Context, query map[string]string) *api return out } +func (s *Server) GetInstanceLabels(ctx context.Context, query map[string]string) *api.Response { + var ( + serviceId string + namespace = DefaultNamespace + ) + + if val, ok := query["namespace"]; ok { + namespace = val + } + + if service, ok := query["service"]; ok { + svc := s.Cache().Service().GetServiceByName(service, namespace) + if svc != nil { + serviceId = svc.ID + } + } + + if id, ok := query["service_id"]; ok { + serviceId = id + } + + if serviceId == "" { + return api.NewResponse(api.NotFoundService) + } + + ret := s.Cache().Instance().GetInstanceLabels(serviceId) + resp := api.NewResponse(api.ExecuteSuccess) + resp.InstanceLabels = ret + return resp +} + // GetInstancesCount 查询总的服务实例,不带过滤条件的 func (s *Server) GetInstancesCount(ctx context.Context) *api.BatchQueryResponse { count, err := s.storage.GetInstancesCount() diff --git a/service/instance_authability.go b/service/instance_authability.go index 859e9fee7..230c0164e 100644 --- a/service/instance_authability.go +++ b/service/instance_authability.go @@ -23,6 +23,7 @@ import ( api "github.com/polarismesh/polaris-server/common/api/v1" "github.com/polarismesh/polaris-server/common/model" "github.com/polarismesh/polaris-server/common/utils" + authcommon "github.com/polarismesh/polaris-server/common/auth" ) // CreateInstances create instances @@ -73,7 +74,7 @@ func (svr *serverAuthAbility) DeleteInstancesByHost(ctx context.Context, } ctx = authCtx.GetRequestContext() ctx = context.WithValue(ctx, utils.ContextAuthContextKey, authCtx) - if utils.ParseUserRole(ctx) == model.SubAccountUserRole { + if authcommon.ParseUserRole(ctx) == model.SubAccountUserRole { ret := api.NewBatchWriteResponse(api.ExecuteSuccess) ret.Collect(api.NewResponse(api.NotAllowedAccess)) return ret @@ -157,3 +158,17 @@ func (svr *serverAuthAbility) CleanInstance(ctx context.Context, req *api.Instan return svr.targetServer.CleanInstance(ctx, req) } + + +func (svr *serverAuthAbility) GetInstanceLabels(ctx context.Context, query map[string]string) *api.Response { + + authCtx := svr.collectInstanceAuthContext(ctx, nil, model.Read, "GetInstanceLabels") + _, err := svr.authMgn.CheckConsolePermission(authCtx) + if err != nil { + return api.NewResponseWithMsg(convertToErrCode(err), err.Error()) + } + ctx = authCtx.GetRequestContext() + ctx = context.WithValue(ctx, utils.ContextAuthContextKey, authCtx) + + return svr.targetServer.GetInstanceLabels(ctx, query) +} diff --git a/service/l5_service.go b/service/l5_service.go index fa7ff274e..f9e9b9a51 100644 --- a/service/l5_service.go +++ b/service/l5_service.go @@ -29,7 +29,7 @@ import ( "github.com/polarismesh/polaris-server/common/api/l5" "github.com/polarismesh/polaris-server/common/model" - "github.com/polarismesh/polaris-server/common/utils" + cl5common "github.com/polarismesh/polaris-server/common/cl5" ) var ( @@ -235,7 +235,7 @@ func (s *Server) RegisterByNameCmd(rbnc *l5.Cl5RegisterByNameCmd) (*l5.Cl5Regist } func (s *Server) computeService(modID uint32, cmdID uint32) *model.Service { - sidStr := utils.MarshalModCmd(modID, cmdID) + sidStr := cl5common.MarshalModCmd(modID, cmdID) // 根据sid找到所述命名空间 namespaces := ComputeNamespace(modID, cmdID) for _, namespace := range namespaces { @@ -339,7 +339,7 @@ func (s *Server) getCalleeByRoute(route *model.Route) []*model.Callee { // 注意,sid--> reference,通过索引服务才能拿到真实的数据 func (s *Server) getSidConfig(modID uint32, cmdID uint32) *model.SidConfig { sid := &model.Sid{ModID: modID, CmdID: cmdID} - sidStr := utils.MarshalSid(sid) + sidStr := cl5common.MarshalSid(sid) // 先获取一下namespace namespaces := ComputeNamespace(modID, cmdID) @@ -384,7 +384,7 @@ func (s *Server) getSidConfigByName(name string) *model.SidConfig { return nil } - sid, err := utils.UnmarshalSid(sidMeta) + sid, err := cl5common.UnmarshalSid(sidMeta) if err != nil { log.Errorf("[Server] unmarshal sid(%s) err: %s", sidMeta, err.Error()) return nil @@ -428,12 +428,12 @@ func (s *Server) getRealSidConfigMeta(service *model.Service) *model.SidConfig { // 获取cl5.discover func (s *Server) getCl5DiscoverList(ctx context.Context, clientIP uint32) *l5.Cl5L5SvrList { - clusterName, _ := ctx.Value(utils.Cl5ServerCluster{}).(string) + clusterName, _ := ctx.Value(cl5common.Cl5ServerCluster{}).(string) if clusterName == "" { log.Warnf("[Cl5] get server cluster name is empty") return nil } - protocol, _ := ctx.Value(utils.Cl5ServerProtocol{}).(string) + protocol, _ := ctx.Value(cl5common.Cl5ServerProtocol{}).(string) service := s.getCl5DiscoverService(clusterName, clientIP) if service == nil { diff --git a/service/main_test.go b/service/main_test.go index 702086d3d..2eb178912 100644 --- a/service/main_test.go +++ b/service/main_test.go @@ -31,6 +31,7 @@ import ( "github.com/boltdb/bolt" _ "github.com/go-sql-driver/mysql" + "github.com/golang/protobuf/ptypes" "github.com/golang/protobuf/ptypes/duration" "github.com/golang/protobuf/ptypes/wrappers" "gopkg.in/yaml.v2" @@ -40,6 +41,7 @@ import ( "github.com/polarismesh/polaris-server/cache" _ "github.com/polarismesh/polaris-server/cache" api "github.com/polarismesh/polaris-server/common/api/v1" + apiv2 "github.com/polarismesh/polaris-server/common/api/v2" commonlog "github.com/polarismesh/polaris-server/common/log" "github.com/polarismesh/polaris-server/common/metrics" "github.com/polarismesh/polaris-server/common/utils" @@ -64,6 +66,7 @@ import ( _ "github.com/polarismesh/polaris-server/store/boltdb" "github.com/polarismesh/polaris-server/store/sqldb" _ "github.com/polarismesh/polaris-server/store/sqldb" + "github.com/polarismesh/polaris-server/testdata" ) const ( @@ -77,6 +80,7 @@ const ( tblCircuitBreakerRelation = "circuitbreaker_rule_relation" tblPlatform = "platform" tblNameL5 = "l5" + tblNameRoutingV2 = "routing_config_v2" ) type Bootstrap struct { @@ -111,10 +115,10 @@ func (d *DiscoverTestSuit) loadConfig() error { d.cfg = new(TestConfig) - confFileName := "test.yaml" + confFileName := testdata.Path("service_test.yaml") if os.Getenv("STORE_MODE") == "sqldb" { fmt.Printf("run store mode : sqldb\n") - confFileName = "test_sqldb.yaml" + confFileName = testdata.Path("service_test_sqldb.yaml") d.defaultCtx = context.WithValue(d.defaultCtx, utils.ContextAuthTokenKey, "nu/0WRA4EqSR1FagrjRj0fZwPXuGlMpX+zCuWu4uMqy8xr1vRjisSbA25aAC3mtU8MeeRsKhQiDAynUR09I=") } @@ -141,6 +145,13 @@ func respSuccess(resp api.ResponseMessage) bool { return ret } +// 判断一个resp是否执行成功 +func respSuccessV2(resp apiv2.ResponseMessage) bool { + ret := apiv2.CalcCode(resp) == 200 + + return ret +} + type options func(cfg *TestConfig) // 内部初始化函数 @@ -186,11 +197,7 @@ func (d *DiscoverTestSuit) initialize(opts ...options) error { d.cancel = cancel // 初始化缓存模块 - if err := cache.TestCacheInitialize(ctx, &d.cfg.Cache, s); err != nil { - panic(err) - } - - cacheMgn, err := cache.GetCacheManager() + cacheMgn, err := cache.TestCacheInitialize(ctx, &d.cfg.Cache, s) if err != nil { panic(err) } @@ -245,6 +252,7 @@ func (d *DiscoverTestSuit) initialize(opts ...options) error { panic(err) } healthCheckServer.SetServiceCache(cacheMgn.Service()) + healthCheckServer.SetInstanceCache(cacheMgn.Instance()) // 为 instance 的 cache 添加 健康检查的 Listener cacheMgn.AddListener(cache.CacheNameInstance, []cache.Listener{cacheProvider}) @@ -702,8 +710,8 @@ func (d *DiscoverTestSuit) createCommonRoutingConfig(t *testing.T, service *api. }, } destination := &api.Destination{ - Service: utils.NewStringValue(fmt.Sprintf("in-destination-service-%d", i)), - Namespace: utils.NewStringValue(fmt.Sprintf("in-destination-service-%d", i)), + Service: service.Name, + Namespace: service.Namespace, Metadata: map[string]*api.MatchString{ fmt.Sprintf("in-metadata-%d", i): matchString, }, @@ -736,6 +744,185 @@ func (d *DiscoverTestSuit) createCommonRoutingConfig(t *testing.T, service *api. return conf, resp.Responses[0].GetRouting() } +// 创建一个路由配置 +func (d *DiscoverTestSuit) createCommonRoutingConfigV1IntoOldStore(t *testing.T, service *api.Service, + inCount int, outCount int) (*api.Routing, *api.Routing) { + + inBounds := make([]*api.Route, 0, inCount) + for i := 0; i < inCount; i++ { + matchString := &api.MatchString{ + Type: api.MatchString_EXACT, + Value: utils.NewStringValue(fmt.Sprintf("in-meta-value-%d", i)), + } + source := &api.Source{ + Service: utils.NewStringValue(fmt.Sprintf("in-source-service-%d", i)), + Namespace: utils.NewStringValue(fmt.Sprintf("in-source-service-%d", i)), + Metadata: map[string]*api.MatchString{ + fmt.Sprintf("in-metadata-%d", i): matchString, + }, + } + destination := &api.Destination{ + Service: service.Name, + Namespace: service.Namespace, + Metadata: map[string]*api.MatchString{ + fmt.Sprintf("in-metadata-%d", i): matchString, + }, + Priority: utils.NewUInt32Value(120), + Weight: utils.NewUInt32Value(100), + Transfer: utils.NewStringValue("abcdefg"), + } + + entry := &api.Route{ + Sources: []*api.Source{source}, + Destinations: []*api.Destination{destination}, + } + inBounds = append(inBounds, entry) + } + + conf := &api.Routing{ + Service: utils.NewStringValue(service.GetName().GetValue()), + Namespace: utils.NewStringValue(service.GetNamespace().GetValue()), + Inbounds: inBounds, + ServiceToken: utils.NewStringValue(service.GetToken().GetValue()), + } + + resp := d.server.(*serverAuthAbility).targetServer.CreateRoutingConfig(d.defaultCtx, conf) + if !respSuccess(resp) { + t.Fatalf("error: %+v", resp) + } + + return conf, resp.GetRouting() +} + +func mockRoutingV1(serviceName, serviceNamespace string, inCount int) *api.Routing { + inBounds := make([]*api.Route, 0, inCount) + for i := 0; i < inCount; i++ { + matchString := &api.MatchString{ + Type: api.MatchString_EXACT, + Value: utils.NewStringValue(fmt.Sprintf("in-meta-value-%d", i)), + } + source := &api.Source{ + Service: utils.NewStringValue(fmt.Sprintf("in-source-service-%d", i)), + Namespace: utils.NewStringValue(fmt.Sprintf("in-source-service-%d", i)), + Metadata: map[string]*api.MatchString{ + fmt.Sprintf("in-metadata-%d", i): matchString, + }, + } + destination := &api.Destination{ + Service: utils.NewStringValue(serviceName), + Namespace: utils.NewStringValue(serviceNamespace), + Metadata: map[string]*api.MatchString{ + fmt.Sprintf("in-metadata-%d", i): matchString, + }, + Priority: utils.NewUInt32Value(120), + Weight: utils.NewUInt32Value(100), + Transfer: utils.NewStringValue("abcdefg"), + } + + entry := &api.Route{ + Sources: []*api.Source{source}, + Destinations: []*api.Destination{destination}, + } + inBounds = append(inBounds, entry) + } + + conf := &api.Routing{ + Service: utils.NewStringValue(serviceName), + Namespace: utils.NewStringValue(serviceNamespace), + Inbounds: inBounds, + } + + return conf +} + +func mockRoutingV2(t *testing.T, cnt int32) []*apiv2.Routing { + rules := make([]*apiv2.Routing, 0, cnt) + for i := int32(0); i < cnt; i++ { + matchString := &apiv2.MatchString{ + Type: apiv2.MatchString_EXACT, + Value: utils.NewStringValue(fmt.Sprintf("in-meta-value-%d", i)), + } + source := &apiv2.Source{ + Service: fmt.Sprintf("in-source-service-%d", i), + Namespace: fmt.Sprintf("in-source-service-%d", i), + Arguments: []*apiv2.SourceMatch{ + {}, + }, + } + destination := &apiv2.Destination{ + Service: fmt.Sprintf("in-destination-service-%d", i), + Namespace: fmt.Sprintf("in-destination-service-%d", i), + Labels: map[string]*apiv2.MatchString{ + fmt.Sprintf("in-metadata-%d", i): matchString, + }, + Priority: 120, + Weight: 100, + Transfer: "abcdefg", + } + + entry := &apiv2.RuleRoutingConfig{ + Sources: []*apiv2.Source{source}, + Destinations: []*apiv2.Destination{destination}, + } + + any, err := ptypes.MarshalAny(entry) + if err != nil { + t.Fatal(err) + } + + item := &apiv2.Routing{ + Id: "", + Name: fmt.Sprintf("test-routing-name-%d", i), + Namespace: "", + Enable: false, + RoutingPolicy: apiv2.RoutingPolicy_RulePolicy, + RoutingConfig: any, + Revision: "", + Etime: "", + Priority: 0, + Description: "", + } + + rules = append(rules, item) + } + + return rules +} + +// 创建一个路由配置 +func (d *DiscoverTestSuit) createCommonRoutingConfigV2(t *testing.T, cnt int32) []*apiv2.Routing { + rules := mockRoutingV2(t, cnt) + + return d.createCommonRoutingConfigV2WithReq(t, rules) +} + +// 创建一个路由配置 +func (d *DiscoverTestSuit) createCommonRoutingConfigV2WithReq(t *testing.T, rules []*apiv2.Routing) []*apiv2.Routing { + resp := d.server.CreateRoutingConfigsV2(d.defaultCtx, rules) + if !respSuccessV2(resp) { + t.Fatalf("error: %+v", resp) + } + + if len(rules) != len(resp.GetResponses()) { + t.Fatal("error: create v2 routings not equal resp") + } + + ret := []*apiv2.Routing{} + for i := range resp.GetResponses() { + item := resp.GetResponses()[i] + msg := &apiv2.Routing{} + + if err := ptypes.UnmarshalAny(item.GetData(), msg); err != nil { + t.Fatal(err) + return nil + } + + ret = append(ret, msg) + } + + return ret +} + // 删除一个路由配置 func (d *DiscoverTestSuit) deleteCommonRoutingConfig(t *testing.T, req *api.Routing) { resp := d.server.DeleteRoutingConfigs(d.defaultCtx, []*api.Routing{req}) @@ -744,6 +931,14 @@ func (d *DiscoverTestSuit) deleteCommonRoutingConfig(t *testing.T, req *api.Rout } } +// 删除一个路由配置 +func (d *DiscoverTestSuit) deleteCommonRoutingConfigV2(t *testing.T, req *apiv2.Routing) { + resp := d.server.DeleteRoutingConfigsV2(d.defaultCtx, []*apiv2.Routing{req}) + if !respSuccessV2(resp) { + t.Fatalf("%s", resp.GetInfo()) + } +} + // 更新一个路由配置 func (d *DiscoverTestSuit) updateCommonRoutingConfig(t *testing.T, req *api.Routing) { resp := d.server.UpdateRoutingConfigs(d.defaultCtx, []*api.Routing{req}) @@ -771,12 +966,16 @@ func (d *DiscoverTestSuit) cleanCommonRoutingConfig(service string, namespace st if _, err := dbTx.Exec(str, service, namespace); err != nil { panic(err) } + str = "delete from routing_config_v2" + // fmt.Printf("%s %s %s\n", str, service, namespace) + if _, err := dbTx.Exec(str); err != nil { + panic(err) + } dbTx.Commit() }() } else if d.storage.Name() == boltdb.STORENAME { func() { - svc, err := d.storage.GetService(service, namespace) if err != nil { panic(err) @@ -792,8 +991,19 @@ func (d *DiscoverTestSuit) cleanCommonRoutingConfig(service string, namespace st } dbTx := tx.GetDelegateTx().(*bolt.Tx) + defer dbTx.Rollback() + + v1Bucket := dbTx.Bucket([]byte(tblNameRouting)) + if v1Bucket != nil { + if err := v1Bucket.DeleteBucket([]byte(svc.ID)); err != nil { + if !errors.Is(err, bolt.ErrBucketNotFound) { + dbTx.Rollback() + panic(err) + } + } + } - if err := dbTx.Bucket([]byte(tblNameRouting)).DeleteBucket([]byte(svc.ID)); err != nil { + if err := dbTx.DeleteBucket([]byte(tblNameRoutingV2)); err != nil { if !errors.Is(err, bolt.ErrBucketNotFound) { dbTx.Rollback() panic(err) @@ -804,6 +1014,102 @@ func (d *DiscoverTestSuit) cleanCommonRoutingConfig(service string, namespace st } } +func (d *DiscoverTestSuit) truncateCommonRoutingConfigV2() { + if d.storage.Name() == sqldb.STORENAME { + func() { + tx, err := d.storage.StartTx() + if err != nil { + panic(err) + } + + dbTx := tx.GetDelegateTx().(*sqldb.BaseTx) + defer dbTx.Rollback() + + str := "delete from routing_config_v2" + if _, err := dbTx.Exec(str); err != nil { + panic(err) + } + + dbTx.Commit() + }() + } else if d.storage.Name() == boltdb.STORENAME { + func() { + + tx, err := d.storage.StartTx() + if err != nil { + panic(err) + } + + dbTx := tx.GetDelegateTx().(*bolt.Tx) + defer dbTx.Rollback() + + if err := dbTx.DeleteBucket([]byte(tblNameRoutingV2)); err != nil { + if !errors.Is(err, bolt.ErrBucketNotFound) { + dbTx.Rollback() + panic(err) + } + } + + dbTx.Commit() + }() + } +} + +// 彻底删除一个路由配置 +func (d *DiscoverTestSuit) cleanCommonRoutingConfigV2(rules []*apiv2.Routing) { + + if d.storage.Name() == sqldb.STORENAME { + func() { + tx, err := d.storage.StartTx() + if err != nil { + panic(err) + } + + dbTx := tx.GetDelegateTx().(*sqldb.BaseTx) + defer dbTx.Rollback() + + str := "delete from routing_config_v2 where id in (%s)" + + places := []string{} + args := []interface{}{} + for i := range rules { + places = append(places, "?") + args = append(args, rules[i].Id) + } + + str = fmt.Sprintf(str, strings.Join(places, ",")) + // fmt.Printf("%s %s %s\n", str, service, namespace) + if _, err := dbTx.Exec(str, args...); err != nil { + panic(err) + } + + dbTx.Commit() + }() + } else if d.storage.Name() == boltdb.STORENAME { + func() { + + tx, err := d.storage.StartTx() + if err != nil { + panic(err) + } + + dbTx := tx.GetDelegateTx().(*bolt.Tx) + defer dbTx.Rollback() + + for i := range rules { + if err := dbTx.Bucket([]byte(tblNameRoutingV2)).DeleteBucket([]byte(rules[i].Id)); err != nil { + if !errors.Is(err, bolt.ErrBucketNotFound) { + dbTx.Rollback() + panic(err) + } + } + } + + dbTx.Commit() + }() + } +} + // func (d *DiscoverTestSuit) CheckGetService(t *testing.T, expectReqs []*api.Service, actualReqs []*api.Service) { if len(expectReqs) != len(actualReqs) { @@ -969,14 +1275,22 @@ func (d *DiscoverTestSuit) createCommonRateLimit(t *testing.T, service *api.Serv Priority: utils.NewUInt32Value(uint32(index)), Resource: api.Rule_QPS, Type: api.Rule_GLOBAL, - Labels: map[string]*api.MatchString{ - fmt.Sprintf("name-%d", index): { - Type: api.MatchString_EXACT, - Value: utils.NewStringValue(fmt.Sprintf("value-%d", index)), + Arguments: []*api.MatchArgument{ + { + Type: api.MatchArgument_CUSTOM, + Key: fmt.Sprintf("name-%d", index), + Value: &api.MatchString{ + Type: api.MatchString_EXACT, + Value: utils.NewStringValue(fmt.Sprintf("value-%d", index)), + }, }, - fmt.Sprintf("name-%d", index+1): { - Type: api.MatchString_REGEX, - Value: utils.NewStringValue(fmt.Sprintf("value-%d", index+1)), + { + Type: api.MatchArgument_CUSTOM, + Key: fmt.Sprintf("name-%d", index+1), + Value: &api.MatchString{ + Type: api.MatchString_EXACT, + Value: utils.NewStringValue(fmt.Sprintf("value-%d", index+1)), + }, }, }, Amounts: []*api.Amount{ @@ -1182,11 +1496,11 @@ func checkRateLimit(t *testing.T, expect *api.Rule, actual *api.Rule) { t.Fatal("error subset") } - expectLabels, err := json.Marshal(expect.GetLabels()) + expectLabels, err := json.Marshal(expect.GetArguments()) if err != nil { panic(err) } - actualLabels, err := json.Marshal(actual.GetLabels()) + actualLabels, err := json.Marshal(actual.GetArguments()) if err != nil { panic(err) } diff --git a/service/ratelimit_config.go b/service/ratelimit_config.go index 68d128829..c1eb3df7c 100644 --- a/service/ratelimit_config.go +++ b/service/ratelimit_config.go @@ -94,7 +94,7 @@ func (s *Server) CreateRateLimit(ctx context.Context, req *api.Rule, svcId strin }() // 构造底层数据结构 - data, err := api2RateLimit(svcId, req) + data, err := api2RateLimit(svcId, req, nil) if err != nil { log.Error(err.Error(), ZapRequestID(requestID)) return api.NewRateLimitResponse(api.ParseRateLimitException, req) @@ -261,7 +261,7 @@ func (s *Server) UpdateRateLimit(ctx context.Context, req *api.Rule) *api.Respon return api.NewRateLimitResponse(code, req) } // 构造底层数据结构 - rateLimit, err := api2RateLimit(svcId, req) + rateLimit, err := api2RateLimit(svcId, req, data) if err != nil { log.Error(err.Error(), ZapRequestID(requestID), ZapPlatformID(platformID)) return api.NewRateLimitResponse(api.ParseRateLimitException, req) @@ -423,16 +423,18 @@ const ( ) // api2RateLimit 把API参数转化为内部数据结构 -func api2RateLimit(serviceID string, req *api.Rule) (*model.RateLimit, error) { +func api2RateLimit(serviceID string, req *api.Rule, old *model.RateLimit) (*model.RateLimit, error) { rule, err := marshalRateLimitRules(req) if err != nil { return nil, err } + labels := req.GetLabels() var labelStr []byte if len(labels) > 0 { labelStr, err = json.Marshal(labels) } + out := &model.RateLimit{ Name: req.GetName().GetValue(), ServiceID: serviceID, @@ -459,7 +461,7 @@ func rateLimit2Console( return nil, err } // 存量标签适配到参数列表 - if err := rateLimit.AdaptArgumentsAndLabels(); err != nil { + if err := rateLimit.AdaptLabels(); err != nil { return nil, err } } diff --git a/service/ratelimit_config_test.go b/service/ratelimit_config_test.go index 8ccd697eb..1e3735679 100644 --- a/service/ratelimit_config_test.go +++ b/service/ratelimit_config_test.go @@ -19,7 +19,6 @@ package service import ( "context" - "encoding/json" "fmt" "sync" "testing" @@ -426,8 +425,6 @@ func TestGetRateLimit(t *testing.T) { rateLimits := make([]*api.Rule, rateLimitsNum) serviceName := "" namespaceName := "" - labels := make(map[string]*api.MatchString) - labelsKey := "name-0" for i := 0; i < serviceNum; i++ { _, serviceResp := discoverSuit.createCommonService(t, i) if i == 5 { @@ -438,16 +435,11 @@ func TestGetRateLimit(t *testing.T) { defer discoverSuit.cleanRateLimitRevision(serviceResp.GetName().GetValue(), serviceResp.GetNamespace().GetValue()) for j := 0; j < rateLimitsNum/serviceNum; j++ { _, rateLimitResp := discoverSuit.createCommonRateLimit(t, serviceResp, j) - if j == 0 { - labels = rateLimitResp.GetLabels() - } defer discoverSuit.cleanRateLimit(rateLimitResp.GetId().GetValue()) rateLimits = append(rateLimits, rateLimitResp) } } - labelsValue := labels[labelsKey] - t.Run("查询限流规则,过滤条件为service", func(t *testing.T) { filters := map[string]string{ "service": serviceName, @@ -520,19 +512,6 @@ func TestGetRateLimit(t *testing.T) { t.Logf("pass: num is %d", resp.GetSize().GetValue()) }) - t.Run("查询限流规则,过滤条件为labels中的key", func(t *testing.T) { - filters := map[string]string{ - "labels": labelsKey, - } - resp := discoverSuit.server.GetRateLimits(discoverSuit.defaultCtx, filters) - if !respSuccess(resp) { - t.Fatalf("error: %s", resp.GetInfo().GetValue()) - } - if resp.GetSize().GetValue() != uint32(serviceNum) { - t.Fatalf("expect num is %d, actual num is %d", serviceNum, resp.GetSize().GetValue()) - } - }) - t.Run("查询限流规则列表,过滤条件为name", func(t *testing.T) { filters := map[string]string{ "name": "rule_name_0", @@ -547,35 +526,48 @@ func TestGetRateLimit(t *testing.T) { } }) - t.Run("查询限流规则,过滤条件为labels中的value", func(t *testing.T) { - filters := map[string]string{ - "labels": labelsValue.GetValue().GetValue(), - } - resp := discoverSuit.server.GetRateLimits(discoverSuit.defaultCtx, filters) - if !respSuccess(resp) { - t.Fatalf("error: %s", resp.GetInfo().GetValue()) - } - if resp.GetSize().GetValue() != uint32(serviceNum) { - t.Fatalf("expect num is %d, actual num is %d", serviceNum, resp.GetSize().GetValue()) - } - }) + // t.Run("查询限流规则,过滤条件为arguments中的key", func(t *testing.T) { + // filters := map[string]string{ + // "labels": labelsKey, + // } + // resp := discoverSuit.server.GetRateLimits(discoverSuit.defaultCtx, filters) + // if !respSuccess(resp) { + // t.Fatalf("error: %s", resp.GetInfo().GetValue()) + // } + // if resp.GetSize().GetValue() != uint32(serviceNum) { + // t.Fatalf("expect num is %d, actual num is %d", serviceNum, resp.GetSize().GetValue()) + // } + // }) - t.Run("查询限流规则,过滤条件为labels中的key和value", func(t *testing.T) { - labelsString, err := json.Marshal(labels) - if err != nil { - panic(err) - } - filters := map[string]string{ - "labels": string(labelsString), - } - resp := discoverSuit.server.GetRateLimits(discoverSuit.defaultCtx, filters) - if !respSuccess(resp) { - t.Fatalf("error: %s", resp.GetInfo().GetValue()) - } - if resp.GetSize().GetValue() != uint32(serviceNum) { - t.Fatalf("expect num is %d, actual num is %d", serviceNum, resp.GetSize().GetValue()) - } - }) + // t.Run("查询限流规则,过滤条件为arguments中的value", func(t *testing.T) { + // filters := map[string]string{ + // "labels": labelsValue.GetValue().GetValue(), + // } + // resp := discoverSuit.server.GetRateLimits(discoverSuit.defaultCtx, filters) + // if !respSuccess(resp) { + // t.Fatalf("error: %s", resp.GetInfo().GetValue()) + // } + // if resp.GetSize().GetValue() != uint32(serviceNum) { + // t.Fatalf("expect num is %d, actual num is %d", serviceNum, resp.GetSize().GetValue()) + // } + // }) + + // t.Run("查询限流规则,过滤条件为arguments中的key和value", func(t *testing.T) { + // labelsString, err := json.Marshal(labels) + // if err != nil { + // panic(err) + // } + // filters := map[string]string{ + // "labels": string(labelsString), + // } + // resp := discoverSuit.server.GetRateLimits(discoverSuit.defaultCtx, filters) + // if !respSuccess(resp) { + // t.Fatalf("error: %s", resp.GetInfo().GetValue()) + // } + // if resp.GetSize().GetValue() != uint32(serviceNum) { + // t.Fatalf("expect num is %d, actual num is %d", serviceNum, resp.GetSize().GetValue()) + // } + // }) t.Run("查询限流规则,offset为负数,返回错误", func(t *testing.T) { filters := map[string]string{ diff --git a/service/routing_config.go b/service/routing_config_v1.go similarity index 92% rename from service/routing_config.go rename to service/routing_config_v1.go index 0ca2eba55..177d25157 100644 --- a/service/routing_config.go +++ b/service/routing_config_v1.go @@ -24,7 +24,9 @@ import ( "time" api "github.com/polarismesh/polaris-server/common/api/v1" + apiv2 "github.com/polarismesh/polaris-server/common/api/v2" "github.com/polarismesh/polaris-server/common/model" + v2 "github.com/polarismesh/polaris-server/common/model/v2" commontime "github.com/polarismesh/polaris-server/common/time" "github.com/polarismesh/polaris-server/common/utils" ) @@ -47,12 +49,13 @@ func (s *Server) CreateRoutingConfigs(ctx context.Context, req []*api.Routing) * resp := api.NewBatchWriteResponse(api.ExecuteSuccess) for _, entry := range req { - resp.Collect(s.CreateRoutingConfig(ctx, entry)) + resp.Collect(s.createRoutingConfigV1toV2(ctx, entry)) } return api.FormatBatchWriteResponse(resp) } +// Deprecated 该方法准备舍弃 // CreateRoutingConfig 创建一个路由配置 // 创建路由配置需要锁住服务,防止服务被删除 func (s *Server) CreateRoutingConfig(ctx context.Context, req *api.Routing) *api.Response { @@ -123,6 +126,7 @@ func (s *Server) DeleteRoutingConfigs(ctx context.Context, req []*api.Routing) * return api.FormatBatchWriteResponse(out) } +// Deprecated 该方法准备舍弃 // DeleteRoutingConfig 删除一个路由配置 func (s *Server) DeleteRoutingConfig(ctx context.Context, req *api.Routing) *api.Response { rid := ParseRequestID(ctx) @@ -133,13 +137,14 @@ func (s *Server) DeleteRoutingConfig(ctx context.Context, req *api.Routing) *api } // store操作 + // TODO 需要进行多表事务一致性保证 if err := s.storage.DeleteRoutingConfig(service.ID); err != nil { log.Error(err.Error(), ZapRequestID(rid), ZapPlatformID(pid)) return wrapperRoutingStoreResponse(req, err) } s.RecordHistory(routingRecordEntry(ctx, req, nil, model.ODelete)) - return api.NewRoutingResponse(api.ExecuteSuccess, req) + return api.NewResponse(api.ExecuteSuccess) } // UpdateRoutingConfigs 批量更新路由配置 @@ -150,13 +155,14 @@ func (s *Server) UpdateRoutingConfigs(ctx context.Context, req []*api.Routing) * out := api.NewBatchWriteResponse(api.ExecuteSuccess) for _, entry := range req { - resp := s.UpdateRoutingConfig(ctx, entry) + resp := s.updateRoutingConfigV1toV2(ctx, entry) out.Collect(resp) } return api.FormatBatchWriteResponse(out) } +// Deprecated 该方法准备舍弃 // UpdateRoutingConfig 更新单个路由配置 func (s *Server) UpdateRoutingConfig(ctx context.Context, req *api.Routing) *api.Response { rid := ParseRequestID(ctx) @@ -192,6 +198,7 @@ func (s *Server) UpdateRoutingConfig(ctx context.Context, req *api.Routing) *api return api.NewRoutingResponse(api.ExecuteSuccess, req) } +// Deprecated 该方法准备舍弃 // GetRoutingConfigs 提供给OSS的查询路由配置的接口 func (s *Server) GetRoutingConfigs(ctx context.Context, query map[string]string) *api.BatchQueryResponse { rid := ParseRequestID(ctx) @@ -396,6 +403,24 @@ func routingRecordEntry(ctx context.Context, req *api.Routing, md *model.Routing return entry } +// routingV2RecordEntry 构建routingConfig的记录entry +func routingV2RecordEntry(ctx context.Context, req *apiv2.Routing, md *v2.RoutingConfig, + opt model.OperationType) *model.RecordEntry { + entry := &model.RecordEntry{ + ResourceType: model.RRoutingV2, + OperationType: opt, + Namespace: req.GetNamespace(), + Operator: ParseOperator(ctx), + CreateTime: time.Now(), + } + + if md != nil { + entry.Context = fmt.Sprintf("name:%s,policy:%s,config:%s,revision:%s", + md.Name, md.GetRoutingPolicy().String(), md.Config, md.Revision) + } + return entry +} + // wrapperRoutingStoreResponse 封装路由存储层错误 func wrapperRoutingStoreResponse(routing *api.Routing, err error) *api.Response { resp := storeError2Response(err) diff --git a/service/routing_config_authability.go b/service/routing_config_v1_authability.go similarity index 100% rename from service/routing_config_authability.go rename to service/routing_config_v1_authability.go diff --git a/service/routing_config_test.go b/service/routing_config_v1_test.go similarity index 58% rename from service/routing_config_test.go rename to service/routing_config_v1_test.go index e201a1ba7..0539ccf43 100644 --- a/service/routing_config_test.go +++ b/service/routing_config_v1_test.go @@ -19,12 +19,18 @@ package service import ( "encoding/json" + "fmt" + "reflect" "testing" "time" + "github.com/golang/protobuf/ptypes" . "github.com/smartystreets/goconvey/convey" + "github.com/stretchr/testify/assert" + "google.golang.org/protobuf/types/known/wrapperspb" api "github.com/polarismesh/polaris-server/common/api/v1" + apiv2 "github.com/polarismesh/polaris-server/common/api/v2" "github.com/polarismesh/polaris-server/common/utils" ) @@ -36,12 +42,24 @@ func checkSameRoutingConfig(t *testing.T, lhs *api.Routing, rhs *api.Routing) { } checkFunc := func(in []*api.Route, out []*api.Route) bool { - if in == nil && out == nil { + if len(in) == 0 && len(out) == 0 { return true } + inStr, err := json.Marshal(in) + if err != nil { + t.Fatalf("error: %s", err.Error()) + return false + } + + outStr, err := json.Marshal(out) + if err != nil { + t.Fatalf("error: %s", err.Error()) + return false + } + if in == nil || out == nil { - t.Fatalf("error: empty") + t.Fatalf("error: empty (%s), (%s)", string(inStr), string(outStr)) return false } @@ -50,19 +68,30 @@ func checkSameRoutingConfig(t *testing.T, lhs *api.Routing, rhs *api.Routing) { return false } - inStr, err := json.Marshal(in) - if err != nil { - t.Fatalf("error: %s", err.Error()) - return false + inRoutes := []*api.Route{} + outRoutes := []*api.Route{} + + if err := json.Unmarshal(inStr, &inRoutes); err != nil { + t.Fatal(err) } - outStr, err := json.Marshal(out) - if err != nil { - t.Fatalf("error: %s", err.Error()) - return false + if err := json.Unmarshal(outStr, &outRoutes); err != nil { + t.Fatal(err) + } + + for i := range inRoutes { + for j := range inRoutes[i].Destinations { + inRoutes[i].Destinations[j].Isolate = nil + } } - if string(inStr) != string(outStr) { + for i := range outRoutes { + for j := range outRoutes[i].Destinations { + outRoutes[i].Destinations[j].Isolate = nil + } + } + + if !reflect.DeepEqual(inRoutes, outRoutes) { t.Fatalf("error: (%s), (%s)", string(inStr), string(outStr)) return false } @@ -86,7 +115,7 @@ func TestCreateRoutingConfig(t *testing.T) { Convey("正常创建路由配置配置请求", t, func() { _, serviceResp := discoverSuit.createCommonService(t, 200) defer discoverSuit.cleanServiceName(serviceResp.GetName().GetValue(), serviceResp.GetNamespace().GetValue()) - req, _ := discoverSuit.createCommonRoutingConfig(t, serviceResp, 3, 0) + _, _ = discoverSuit.createCommonRoutingConfig(t, serviceResp, 3, 0) // 对写进去的数据进行查询 time.Sleep(discoverSuit.updateCacheInterval) @@ -95,32 +124,19 @@ func TestCreateRoutingConfig(t *testing.T) { if !respSuccess(out) { t.Fatalf("error: %+v", out) } - checkSameRoutingConfig(t, req, out.GetRouting()) - }) - - Convey("同一个服务重复创建路由配置,报错", t, func() { - _, serviceResp := discoverSuit.createCommonService(t, 10) - defer discoverSuit.cleanServiceName(serviceResp.GetName().GetValue(), serviceResp.GetNamespace().GetValue()) - - req, _ := discoverSuit.createCommonRoutingConfig(t, serviceResp, 1, 0) - defer discoverSuit.cleanCommonRoutingConfig(serviceResp.GetName().GetValue(), serviceResp.GetNamespace().GetValue()) - - resp := discoverSuit.server.CreateRoutingConfigs(discoverSuit.defaultCtx, []*api.Routing{req}) - So(respSuccess(resp), ShouldEqual, false) - t.Logf("%s", resp.GetInfo().GetValue()) }) } // 测试创建路由配置 func TestCreateRoutingConfig2(t *testing.T) { - discoverSuit := &DiscoverTestSuit{} - if err := discoverSuit.initialize(); err != nil { - t.Fatal(err) - } - defer discoverSuit.Destroy() - Convey("参数缺失,报错", t, func() { + discoverSuit := &DiscoverTestSuit{} + if err := discoverSuit.initialize(); err != nil { + t.Fatal(err) + } + defer discoverSuit.Destroy() + _, serviceResp := discoverSuit.createCommonService(t, 20) defer discoverSuit.cleanServiceName(serviceResp.GetName().GetValue(), serviceResp.GetNamespace().GetValue()) @@ -142,6 +158,12 @@ func TestCreateRoutingConfig2(t *testing.T) { }) Convey("服务不存在,创建路由配置,报错", t, func() { + discoverSuit := &DiscoverTestSuit{} + if err := discoverSuit.initialize(); err != nil { + t.Fatal(err) + } + defer discoverSuit.Destroy() + _, serviceResp := discoverSuit.createCommonService(t, 120) discoverSuit.cleanServiceName(serviceResp.GetName().GetValue(), serviceResp.GetNamespace().GetValue()) @@ -155,70 +177,16 @@ func TestCreateRoutingConfig2(t *testing.T) { }) } -// 测试删除路由配置 -func TestDeleteRoutingConfig(t *testing.T) { - - discoverSuit := &DiscoverTestSuit{} - if err := discoverSuit.initialize(); err != nil { - t.Fatal(err) - } - defer discoverSuit.Destroy() - - Convey("可以正常删除路由配置", t, func() { - _, serviceResp := discoverSuit.createCommonService(t, 100) - defer discoverSuit.cleanServiceName(serviceResp.GetName().GetValue(), serviceResp.GetNamespace().GetValue()) - - _, resp := discoverSuit.createCommonRoutingConfig(t, serviceResp, 3, 0) - resp.ServiceToken = utils.NewStringValue(serviceResp.GetToken().GetValue()) - discoverSuit.deleteCommonRoutingConfig(t, resp) - defer discoverSuit.cleanCommonRoutingConfig(serviceResp.GetName().GetValue(), serviceResp.GetNamespace().GetValue()) - - // 删除之后,数据不见 - time.Sleep(discoverSuit.updateCacheInterval) - out := discoverSuit.server.GetRoutingConfigWithCache(discoverSuit.defaultCtx, serviceResp) - So(out.GetRouting(), ShouldBeNil) - }) -} - -// 测试更新路由配置 -func TestUpdateRoutingConfig(t *testing.T) { - - discoverSuit := &DiscoverTestSuit{} - if err := discoverSuit.initialize(); err != nil { - t.Fatal(err) - } - defer discoverSuit.Destroy() - - Convey("可以正常更新路由配置", t, func() { - _, serviceResp := discoverSuit.createCommonService(t, 50) - serviceName := serviceResp.GetName().GetValue() - namespace := serviceResp.GetNamespace().GetValue() - defer discoverSuit.cleanServiceName(serviceName, namespace) - - _, resp := discoverSuit.createCommonRoutingConfig(t, serviceResp, 2, 0) - defer discoverSuit.cleanCommonRoutingConfig(serviceName, namespace) - resp.ServiceToken = utils.NewStringValue(serviceResp.GetToken().GetValue()) - - resp.Outbounds = resp.Inbounds - resp.Inbounds = make([]*api.Route, 0) - discoverSuit.updateCommonRoutingConfig(t, resp) - - time.Sleep(discoverSuit.updateCacheInterval) - out := discoverSuit.server.GetRoutingConfigWithCache(discoverSuit.defaultCtx, serviceResp) - checkSameRoutingConfig(t, resp, out.GetRouting()) - }) -} - // 测试缓存获取路由配置 func TestGetRoutingConfigWithCache(t *testing.T) { - discoverSuit := &DiscoverTestSuit{} - if err := discoverSuit.initialize(); err != nil { - t.Fatal(err) - } - defer discoverSuit.Destroy() - Convey("多个服务的,多个路由配置,都可以查询到", t, func() { + discoverSuit := &DiscoverTestSuit{} + if err := discoverSuit.initialize(); err != nil { + t.Fatal(err) + } + defer discoverSuit.Destroy() + total := 20 serviceResps := make([]*api.Service, 0, total) routingResps := make([]*api.Routing, 0, total) @@ -234,18 +202,182 @@ func TestGetRoutingConfigWithCache(t *testing.T) { time.Sleep(discoverSuit.updateCacheInterval) for i := 0; i < total; i++ { + t.Logf("service : name=%s namespace=%s", serviceResps[i].GetName().GetValue(), serviceResps[i].GetNamespace().GetValue()) out := discoverSuit.server.GetRoutingConfigWithCache(discoverSuit.defaultCtx, serviceResps[i]) checkSameRoutingConfig(t, routingResps[i], out.GetRouting()) } }) + + Convey("走v2接口创建路由规则,不启用查不到,启用可以查到", t, func() { + discoverSuit := &DiscoverTestSuit{} + if err := discoverSuit.initialize(); err != nil { + t.Fatal(err) + } + defer discoverSuit.Destroy() + + resp := discoverSuit.createCommonRoutingConfigV2(t, 1) + assert.Equal(t, 1, len(resp)) + + svcName := fmt.Sprintf("in-source-service-%d", 0) + namespaceName := fmt.Sprintf("in-source-service-%d", 0) + + svcResp := discoverSuit.server.CreateServices(discoverSuit.defaultCtx, []*api.Service{{ + Name: utils.NewStringValue(svcName), + Namespace: utils.NewStringValue(namespaceName), + }}) + defer discoverSuit.cleanServiceName(svcName, namespaceName) + if !respSuccess(svcResp) { + t.Fatal(svcResp.Info) + } + + time.Sleep(discoverSuit.updateCacheInterval) + t.Logf("service : name=%s namespace=%s", svcName, namespaceName) + out := discoverSuit.server.GetRoutingConfigWithCache(discoverSuit.defaultCtx, &api.Service{ + Name: utils.NewStringValue(svcName), + Namespace: utils.NewStringValue(namespaceName), + }) + + assert.True(t, len(out.GetRouting().GetOutbounds()) == 0, "inBounds must be zero") + + time.Sleep(discoverSuit.updateCacheInterval) + + enableResp := discoverSuit.server.EnableRoutings(discoverSuit.defaultCtx, []*apiv2.Routing{ + { + Id: resp[0].Id, + Enable: true, + }, + }) + + if !respSuccessV2(enableResp) { + t.Fatal(enableResp.Info) + } + + time.Sleep(discoverSuit.updateCacheInterval) + out = discoverSuit.server.GetRoutingConfigWithCache(discoverSuit.defaultCtx, &api.Service{ + Name: utils.NewStringValue(svcName), + Namespace: utils.NewStringValue(namespaceName), + }) + + assert.True(t, len(out.GetRouting().GetOutbounds()) == 1, "inBounds must be one") + }) + + Convey("走v2接口创建路由规则,通配服务", t, func() { + discoverSuit := &DiscoverTestSuit{} + if err := discoverSuit.initialize(); err != nil { + t.Fatal(err) + } + defer discoverSuit.Destroy() + + rules := mockRoutingV2(t, 1) + ruleRoutings := &apiv2.RuleRoutingConfig{ + Sources: []*apiv2.Source{ + { + Service: "*", + Namespace: "*", + Arguments: []*apiv2.SourceMatch{ + { + Type: apiv2.SourceMatch_CUSTOM, + Key: "key", + Value: &apiv2.MatchString{ + Type: apiv2.MatchString_EXACT, + Value: &wrapperspb.StringValue{ + Value: "123", + }, + ValueType: apiv2.MatchString_TEXT, + }, + }, + }, + }, + }, + Destinations: []*apiv2.Destination{ + { + Service: "mock-servcie-test1", + Namespace: "mock-namespace-test1", + Labels: map[string]*apiv2.MatchString{ + "key": { + Type: apiv2.MatchString_EXACT, + Value: &wrapperspb.StringValue{ + Value: "value", + }, + ValueType: apiv2.MatchString_TEXT, + }, + }, + Priority: 0, + Weight: 0, + Transfer: "", + Isolate: false, + Name: "123", + }, + }, + } + + any, err := ptypes.MarshalAny(ruleRoutings) + if err != nil { + t.Fatal(err) + return + } + rules[0].RoutingPolicy = apiv2.RoutingPolicy_RulePolicy + rules[0].RoutingConfig = any + + resp := discoverSuit.createCommonRoutingConfigV2WithReq(t, rules) + defer discoverSuit.truncateCommonRoutingConfigV2() + assert.Equal(t, 1, len(resp)) + + svcName := fmt.Sprintf("mock-source-service-%d", 0) + namespaceName := fmt.Sprintf("mock-source-service-%d", 0) + + svcResp := discoverSuit.server.CreateServices(discoverSuit.defaultCtx, []*api.Service{{ + Name: utils.NewStringValue(svcName), + Namespace: utils.NewStringValue(namespaceName), + }}) + defer discoverSuit.cleanServiceName(svcName, namespaceName) + if !respSuccess(svcResp) { + t.Fatal(svcResp.Info) + } + + time.Sleep(discoverSuit.updateCacheInterval) + t.Logf("service : name=%s namespace=%s", svcName, namespaceName) + out := discoverSuit.server.GetRoutingConfigWithCache(discoverSuit.defaultCtx, &api.Service{ + Name: utils.NewStringValue(svcName), + Namespace: utils.NewStringValue(namespaceName), + }) + + assert.True(t, len(out.GetRouting().GetOutbounds()) == 0, "inBounds must be zero") + time.Sleep(discoverSuit.updateCacheInterval) + enableResp := discoverSuit.server.EnableRoutings(discoverSuit.defaultCtx, []*apiv2.Routing{ + { + Id: resp[0].Id, + Enable: true, + }, + }) + + if !respSuccessV2(enableResp) { + t.Fatal(enableResp.Info) + } + + time.Sleep(discoverSuit.updateCacheInterval) + out = discoverSuit.server.GetRoutingConfigWithCache(discoverSuit.defaultCtx, &api.Service{ + Name: utils.NewStringValue(svcName), + Namespace: utils.NewStringValue(namespaceName), + }) + + assert.True(t, len(out.GetRouting().GetOutbounds()) == 1, "inBounds must be one") + }) + Convey("服务路由数据不改变,传递了路由revision,不返回数据", t, func() { + discoverSuit := &DiscoverTestSuit{} + if err := discoverSuit.initialize(); err != nil { + t.Fatal(err) + } + defer discoverSuit.Destroy() + _, serviceResp := discoverSuit.createCommonService(t, 10) defer discoverSuit.cleanServiceName(serviceResp.GetName().GetValue(), serviceResp.GetNamespace().GetValue()) _, routingResp := discoverSuit.createCommonRoutingConfig(t, serviceResp, 2, 0) defer discoverSuit.cleanCommonRoutingConfig(serviceResp.GetName().GetValue(), serviceResp.GetNamespace().GetValue()) - time.Sleep(discoverSuit.updateCacheInterval) + time.Sleep(discoverSuit.updateCacheInterval * 10) firstResp := discoverSuit.server.GetRoutingConfigWithCache(discoverSuit.defaultCtx, serviceResp) checkSameRoutingConfig(t, routingResp, firstResp.GetRouting()) @@ -260,6 +392,12 @@ func TestGetRoutingConfigWithCache(t *testing.T) { t.Logf("%+v", secondResp) }) Convey("路由不存在,不会出异常", t, func() { + discoverSuit := &DiscoverTestSuit{} + if err := discoverSuit.initialize(); err != nil { + t.Fatal(err) + } + defer discoverSuit.Destroy() + _, serviceResp := discoverSuit.createCommonService(t, 10) defer discoverSuit.cleanServiceName(serviceResp.GetName().GetValue(), serviceResp.GetNamespace().GetValue()) time.Sleep(discoverSuit.updateCacheInterval) @@ -269,50 +407,6 @@ func TestGetRoutingConfigWithCache(t *testing.T) { }) } -// 测试直接从数据库读取路由配置数据 -func TestGetRoutings(t *testing.T) { - - discoverSuit := &DiscoverTestSuit{} - if err := discoverSuit.initialize(); err != nil { - t.Fatal(err) - } - defer discoverSuit.Destroy() - - Convey("直接从数据库查询数据,可以查询成功", t, func() { - total := 10 - var serviceResp *api.Service - for i := 0; i < total; i++ { - tmp, resp := discoverSuit.createCommonService(t, i) - serviceResp = tmp - defer discoverSuit.cleanServiceName(resp.GetName().GetValue(), resp.GetNamespace().GetValue()) - - discoverSuit.createCommonRoutingConfig(t, resp, 2, 0) - defer discoverSuit.cleanCommonRoutingConfig(resp.GetName().GetValue(), resp.GetNamespace().GetValue()) - } - - resp := discoverSuit.server.GetRoutingConfigs(discoverSuit.defaultCtx, nil) - So(api.CalcCode(resp), ShouldEqual, 200) - So(len(resp.GetRoutings()), ShouldBeGreaterThanOrEqualTo, total) - - resp = discoverSuit.server.GetRoutingConfigs(discoverSuit.defaultCtx, map[string]string{"limit": "5"}) - So(api.CalcCode(resp), ShouldEqual, 200) - So(len(resp.GetRoutings()), ShouldEqual, 5) - - resp = discoverSuit.server.GetRoutingConfigs(discoverSuit.defaultCtx, map[string]string{"namespace": DefaultNamespace}) - So(api.CalcCode(resp), ShouldEqual, 200) - So(len(resp.GetRoutings()), ShouldBeGreaterThanOrEqualTo, total) - - // 按命名空间和名字过滤,得到一个 - filter := map[string]string{ - "namespace": DefaultNamespace, - "service": serviceResp.GetName().GetValue(), - } - resp = discoverSuit.server.GetRoutingConfigs(discoverSuit.defaultCtx, filter) - So(api.CalcCode(resp), ShouldEqual, 200) - So(len(resp.GetRoutings()), ShouldEqual, 1) - }) -} - // test对routing字段进行校验 func TestCheckRoutingFieldLen(t *testing.T) { diff --git a/service/routing_config_v1tov2.go b/service/routing_config_v1tov2.go new file mode 100644 index 000000000..9f9cfb330 --- /dev/null +++ b/service/routing_config_v1tov2.go @@ -0,0 +1,211 @@ +/** + * Tencent is pleased to support the open source community by making Polaris available. + * + * Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved. + * + * Licensed under the BSD 3-Clause License (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://opensource.org/licenses/BSD-3-Clause + * + * 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 service + +import ( + "context" + + api "github.com/polarismesh/polaris-server/common/api/v1" + apiv1 "github.com/polarismesh/polaris-server/common/api/v1" + apiv2 "github.com/polarismesh/polaris-server/common/api/v2" + "github.com/polarismesh/polaris-server/common/model" + v2 "github.com/polarismesh/polaris-server/common/model/v2" + routingcommon "github.com/polarismesh/polaris-server/common/routing" + "github.com/polarismesh/polaris-server/common/utils" + "go.uber.org/zap" +) + +// createRoutingConfigV1toV2 这里需要兼容 v1 版本的创建路由规则动作,将 v1 的数据转为 v2 进行存储 +func (s *Server) createRoutingConfigV1toV2(ctx context.Context, req *apiv1.Routing) *apiv1.Response { + if resp := checkRoutingConfig(req); resp != nil { + return resp + } + + serviceTx, err := s.storage.CreateTransaction() + if err != nil { + log.Error(err.Error(), utils.ZapRequestIDByCtx(ctx)) + return api.NewRoutingResponse(api.StoreLayerException, req) + } + // 释放对于服务的锁 + defer serviceTx.Commit() + + serviceName := req.GetService().GetValue() + namespaceName := req.GetNamespace().GetValue() + svc, err := serviceTx.RLockService(serviceName, namespaceName) + if err != nil { + log.Error("[Service][Routing] get read lock for service", zap.String("service", serviceName), + zap.String("namespace", namespaceName), utils.ZapRequestIDByCtx(ctx), zap.Error(err)) + return api.NewRoutingResponse(api.StoreLayerException, req) + } + if svc == nil { + return api.NewRoutingResponse(api.NotFoundService, req) + } + if svc.IsAlias() { + return api.NewRoutingResponse(api.NotAllowAliasCreateRouting, req) + } + + inDatas, outDatas, resp := batchBuildV2Routings(req) + if resp != nil { + return resp + } + + if resp := s.saveRoutingV1toV2(ctx, svc.ID, inDatas, outDatas); resp.GetCode().GetValue() != apiv1.ExecuteSuccess { + return resp + } + + return apiv1.NewRoutingResponse(apiv1.ExecuteSuccess, req) +} + +// updateRoutingConfigV1toV2 这里需要兼容 v1 版本的更新路由规则动作,将 v1 的数据转为 v2 进行存储 +// 一旦将 v1 规则转为 v2 规则,那么原本的 v1 规则将从存储中移除 +func (s *Server) updateRoutingConfigV1toV2(ctx context.Context, req *apiv1.Routing) *apiv1.Response { + svc, resp := s.routingConfigCommonCheck(ctx, req) + if resp != nil { + return resp + } + + serviceTx, err := s.storage.CreateTransaction() + if err != nil { + log.Error(err.Error(), utils.ZapRequestIDByCtx(ctx)) + return api.NewRoutingResponse(api.StoreLayerException, req) + } + // 释放对于服务的锁 + defer serviceTx.Commit() + + // 需要禁止对 v1 规则的并发修改 + _, err = serviceTx.LockService(svc.Name, svc.Namespace) + if err != nil { + log.Error("[Service][Routing] get service x-lock", zap.String("service", svc.Name), + zap.String("namespace", svc.Namespace), utils.ZapRequestIDByCtx(ctx), zap.Error(err)) + return api.NewRoutingResponse(api.StoreLayerException, req) + } + + // 检查路由配置是否存在 + conf, err := s.storage.GetRoutingConfigWithService(svc.Name, svc.Namespace) + if err != nil { + log.Error(err.Error(), utils.ZapRequestIDByCtx(ctx)) + return api.NewRoutingResponse(api.StoreLayerException, req) + } + if conf == nil { + return api.NewRoutingResponse(api.NotFoundRouting, req) + } + + inDatas, outDatas, resp := batchBuildV2Routings(req) + if resp != nil { + return resp + } + + if resp := s.saveRoutingV1toV2(ctx, svc.ID, inDatas, outDatas); resp.GetCode().GetValue() != apiv1.ExecuteSuccess { + return resp + } + + return apiv1.NewRoutingResponse(apiv1.ExecuteSuccess, req) +} + +// saveRoutingV1toV2 将目标的 v1 规则转为 v2 规则 +func (s *Server) saveRoutingV1toV2(ctx context.Context, svcId string, + inRules, outRules []*apiv2.Routing) *apiv1.Response { + + tx, err := s.storage.StartTx() + if err != nil { + log.Error("[Service][Routing] create routing v2 from v1 open tx", + utils.ZapRequestIDByCtx(ctx), zap.Error(err)) + return apiv1.NewResponse(apiv1.StoreLayerException) + } + defer tx.Rollback() + + // 这里需要删除掉 v1 的路由规则 + if err := s.storage.DeleteRoutingConfigTx(tx, svcId); err != nil { + log.Error("[Service][Routing] clean routing v1 from store", + utils.ZapRequestIDByCtx(ctx), zap.Error(err)) + return apiv1.NewResponse(apiv1.StoreLayerException) + } + + saveOperation := func(routings []*apiv2.Routing) *apiv1.Response { + priorityMax := 0 + for i := range routings { + item := routings[i] + if item.Id == "" { + item.Id = utils.NewRoutingV2UUID() + } + item.Revision = utils.NewV2Revision() + data := &v2.RoutingConfig{} + if err := data.ParseFromAPI(item); err != nil { + return apiv1.NewResponse(apiv1.ExecuteException) + } + + data.Valid = true + data.Enable = true + if priorityMax > 10 { + priorityMax = 10 + } + + data.Priority = uint32(priorityMax) + priorityMax++ + + if err := s.storage.CreateRoutingConfigV2Tx(tx, data); err != nil { + log.Error("[Routing][V2] create routing v2 from v1 into store", + utils.ZapRequestIDByCtx(ctx), zap.Error(err)) + return apiv1.NewResponse(apiv1.StoreLayerException) + } + s.RecordHistory(routingV2RecordEntry(ctx, item, data, model.OCreate)) + } + + return nil + } + + if resp := saveOperation(inRules); resp != nil { + return resp + } + if resp := saveOperation(outRules); resp != nil { + return resp + } + + if err := tx.Commit(); err != nil { + log.Error("[Service][Routing] create routing v2 from v1 commit", + utils.ZapRequestIDByCtx(ctx), zap.Error(err)) + return apiv1.NewResponse(apiv1.ExecuteException) + } + + return apiv1.NewResponse(apiv1.ExecuteSuccess) +} + +func batchBuildV2Routings(req *apiv1.Routing) ([]*apiv2.Routing, []*apiv2.Routing, *apiv1.Response) { + inBounds := req.GetInbounds() + outBounds := req.GetOutbounds() + inRoutings := make([]*apiv2.Routing, 0, len(inBounds)) + outRoutings := make([]*apiv2.Routing, 0, len(outBounds)) + for i := range inBounds { + routing, err := routingcommon.BuildV2RoutingFromV1Route(req, inBounds[i]) + if err != nil { + return nil, nil, apiv1.NewResponse(apiv1.ExecuteException) + } + routing.Name = req.GetNamespace().GetValue() + "." + req.GetService().GetValue() + inRoutings = append(inRoutings, routing) + } + + for i := range outBounds { + routing, err := routingcommon.BuildV2RoutingFromV1Route(req, outBounds[i]) + if err != nil { + return nil, nil, apiv1.NewResponse(apiv1.ExecuteException) + } + outRoutings = append(outRoutings, routing) + } + + return inRoutings, outRoutings, nil +} diff --git a/service/routing_config_v2.go b/service/routing_config_v2.go new file mode 100644 index 000000000..9f5754519 --- /dev/null +++ b/service/routing_config_v2.go @@ -0,0 +1,530 @@ +/** + * Tencent is pleased to support the open source community by making Polaris available. + * + * Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved. + * + * Licensed under the BSD 3-Clause License (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://opensource.org/licenses/BSD-3-Clause + * + * 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 service + +import ( + "context" + "strconv" + + "github.com/golang/protobuf/ptypes" + "github.com/golang/protobuf/ptypes/any" + "github.com/polarismesh/polaris-server/cache" + api "github.com/polarismesh/polaris-server/common/api/v1" + apiv1 "github.com/polarismesh/polaris-server/common/api/v1" + apiv2 "github.com/polarismesh/polaris-server/common/api/v2" + "github.com/polarismesh/polaris-server/common/model" + v2 "github.com/polarismesh/polaris-server/common/model/v2" + routingcommon "github.com/polarismesh/polaris-server/common/routing" + "github.com/polarismesh/polaris-server/common/utils" + "github.com/polarismesh/polaris-server/store" + "go.uber.org/zap" +) + +var ( + // RoutingConfigV2FilterAttrs router config filter attrs + RoutingConfigV2FilterAttrs = map[string]bool{ + "id": true, + "name": true, + "service": true, + "namespace": true, + "source_service": true, + "enable": true, + "offset": true, + "limit": true, + "order_field": true, + "order_type": true, + } +) + +// CreateRoutingConfigsV2 批量创建路由配置 +func (s *Server) CreateRoutingConfigsV2(ctx context.Context, req []*apiv2.Routing) *apiv2.BatchWriteResponse { + if err := checkBatchRoutingConfigV2(req); err != nil { + return err + } + + resp := apiv2.NewBatchWriteResponse(apiv1.ExecuteSuccess) + for _, entry := range req { + resp.Collect(s.createRoutingConfigV2(ctx, entry)) + } + + return apiv2.FormatBatchWriteResponse(resp) +} + +// createRoutingConfigV2 创建一个路由配置 +func (s *Server) createRoutingConfigV2(ctx context.Context, req *apiv2.Routing) *apiv2.Response { + if resp := checkRoutingConfigV2(req); resp != nil { + return resp + } + + // 构造底层数据结构,并且写入store + conf, err := api2RoutingConfigV2(req) + if err != nil { + log.Error("[Routing][V2] parse routing config v2 from request for create", + utils.ZapRequestIDByCtx(ctx), zap.Error(err)) + return apiv2.NewResponse(api.ExecuteException) + } + + if err := s.storage.CreateRoutingConfigV2(conf); err != nil { + log.Error("[Routing][V2] create routing config v2 store layer", + utils.ZapRequestIDByCtx(ctx), zap.Error(err)) + return apiv2.NewResponse(api.StoreLayerException) + } + + s.RecordHistory(routingV2RecordEntry(ctx, req, conf, model.OCreate)) + + req.Id = conf.ID + return apiv2.NewRoutingResponse(api.ExecuteSuccess, req) +} + +// DeleteRoutingConfigsV2 批量删除路由配置 +func (s *Server) DeleteRoutingConfigsV2(ctx context.Context, req []*apiv2.Routing) *apiv2.BatchWriteResponse { + if err := checkBatchRoutingConfigV2(req); err != nil { + return err + } + + out := apiv2.NewBatchWriteResponse(apiv1.ExecuteSuccess) + for _, entry := range req { + resp := s.deleteRoutingConfigV2(ctx, entry) + out.Collect(resp) + } + + return apiv2.FormatBatchWriteResponse(out) +} + +// DeleteRoutingConfigV2 删除一个路由配置 +func (s *Server) deleteRoutingConfigV2(ctx context.Context, req *apiv2.Routing) *apiv2.Response { + if resp := checkRoutingConfigIDV2(req); resp != nil { + return resp + } + + // 判断当前的路由规则是否只是从 v1 版本中的内存中转换过来的 + if _, ok := s.Cache().RoutingConfig().IsConvertFromV1(req.Id); ok { + resp := s.transferV1toV2OnModify(ctx, req) + if resp.GetCode() != apiv1.ExecuteSuccess { + return resp + } + } + + if err := s.storage.DeleteRoutingConfigV2(req.Id); err != nil { + log.Error("[Routing][V2] delete routing config v2 store layer", + utils.ZapRequestIDByCtx(ctx), zap.Error(err)) + return apiv2.NewResponse(api.StoreLayerException) + } + + s.RecordHistory(routingV2RecordEntry(ctx, req, nil, model.ODelete)) + return apiv2.NewRoutingResponse(api.ExecuteSuccess, req) +} + +// UpdateRoutingConfigsV2 批量更新路由配置 +func (s *Server) UpdateRoutingConfigsV2(ctx context.Context, req []*apiv2.Routing) *apiv2.BatchWriteResponse { + if err := checkBatchRoutingConfigV2(req); err != nil { + return err + } + + out := apiv2.NewBatchWriteResponse(apiv1.ExecuteSuccess) + for _, entry := range req { + resp := s.updateRoutingConfigV2(ctx, entry) + out.Collect(resp) + } + + return apiv2.FormatBatchWriteResponse(out) +} + +// updateRoutingConfigV2 更新单个路由配置 +func (s *Server) updateRoutingConfigV2(ctx context.Context, req *apiv2.Routing) *apiv2.Response { + // 如果当前待修改的 v2 路由规则,其实是从 v1 规则在 cache 中转换而来的,则需要先做以下几个步骤 + // step 1: 将 v1 规则真实的转为 v2 规则 + // step 2: 将本次要修改的 v2 规则,在 v1 规则中的 inBound 或者 outBound 找到对应的 route,设置其规则 ID + // step 3: 进行存储持久化 + // 判断当前的路由规则是否只是从 v1 版本中的内存中转换过来的 + if _, ok := s.Cache().RoutingConfig().IsConvertFromV1(req.Id); ok { + resp := s.transferV1toV2OnModify(ctx, req) + if resp.GetCode() != apiv1.ExecuteSuccess { + return resp + } + } + + if resp := checkUpdateRoutingConfigV2(req); resp != nil { + return resp + } + + // 检查路由配置是否存在 + conf, err := s.storage.GetRoutingConfigV2WithID(req.Id) + if err != nil { + log.Error("[Routing][V2] get routing config v2 store layer", + utils.ZapRequestIDByCtx(ctx), zap.Error(err)) + return apiv2.NewResponse(api.StoreLayerException) + } + if conf == nil { + return apiv2.NewResponse(api.NotFoundRouting) + } + + // 作为一个整体进行Update,所有参数都要传递 + reqModel, err := api2RoutingConfigV2(req) + reqModel.Revision = utils.NewV2Revision() + if err != nil { + log.Error("[Routing][V2] parse routing config v2 from request for update", + utils.ZapRequestIDByCtx(ctx), zap.Error(err)) + return apiv2.NewResponse(api.ExecuteException) + } + + if err := s.storage.UpdateRoutingConfigV2(reqModel); err != nil { + log.Error("[Routing][V2] update routing config v2 store layer", + utils.ZapRequestIDByCtx(ctx), zap.Error(err)) + return apiv2.NewResponse(apiv1.StoreLayerException) + } + + s.RecordHistory(routingV2RecordEntry(ctx, req, reqModel, model.OUpdate)) + return apiv2.NewResponse(api.ExecuteSuccess) +} + +// GetRoutingConfigsV2 提供给OSS的查询路由配置的接口 +func (s *Server) GetRoutingConfigsV2(ctx context.Context, query map[string]string) *apiv2.BatchQueryResponse { + args, presp := parseRoutingArgs(query, ctx) + if presp != nil { + return apiv2.NewBatchQueryResponse(presp.GetCode()) + } + + total, ret, err := s.Cache().RoutingConfig().GetRoutingConfigsV2(args) + if err != nil { + log.Error("[Routing][V2] query routing list from cache", utils.ZapRequestIDByCtx(ctx), zap.Error(err)) + return apiv2.NewBatchQueryResponse(api.ExecuteException) + } + + data, err := marshalRoutingV2toAnySlice(ret) + if err != nil { + log.Error("[Routing][V2] marshal routing list to anypb.Any list", + utils.ZapRequestIDByCtx(ctx), zap.Error(err)) + return apiv2.NewBatchQueryResponse(api.ExecuteException) + } + + resp := apiv2.NewBatchQueryResponse(api.ExecuteSuccess) + resp.Amount = total + resp.Size = uint32(len(ret)) + resp.Data = data + return resp +} + +// EnableRoutings batch enable routing rules +func (s *Server) EnableRoutings(ctx context.Context, req []*apiv2.Routing) *apiv2.BatchWriteResponse { + out := apiv2.NewBatchWriteResponse(apiv1.ExecuteSuccess) + for _, entry := range req { + resp := s.enableRoutings(ctx, entry) + out.Collect(resp) + } + + return apiv2.FormatBatchWriteResponse(out) +} + +func (s *Server) enableRoutings(ctx context.Context, req *apiv2.Routing) *apiv2.Response { + if resp := checkRoutingConfigIDV2(req); resp != nil { + return resp + } + + // 判断当前的路由规则是否只是从 v1 版本中的内存中转换过来的 + if _, ok := s.Cache().RoutingConfig().IsConvertFromV1(req.Id); ok { + resp := s.transferV1toV2OnModify(ctx, req) + if resp.GetCode() != apiv1.ExecuteSuccess { + return resp + } + } + + // 检查路由配置是否存在 + conf, err := s.storage.GetRoutingConfigV2WithID(req.Id) + if err != nil { + log.Error("[Routing][V2] get routing config v2 store layer", + utils.ZapRequestIDByCtx(ctx), zap.Error(err)) + return apiv2.NewResponse(api.StoreLayerException) + } + if conf == nil { + return apiv2.NewResponse(api.NotFoundRouting) + } + + conf.Enable = req.GetEnable() + conf.Revision = utils.NewV2Revision() + + if err := s.storage.EnableRouting(conf); err != nil { + log.Error("[Routing][V2] enable routing config v2 store layer", + utils.ZapRequestIDByCtx(ctx), zap.Error(err)) + return apiv2.NewResponse(apiv1.StoreLayerException) + } + + s.RecordHistory(routingV2RecordEntry(ctx, req, conf, model.OUpdate)) + return apiv2.NewResponse(api.ExecuteSuccess) +} + +// transferV1toV2OnModify 在针对 v2 规则进行启用或者禁止时,需要将 v1 规则转为 v2 规则并执行持久化存储 +func (s *Server) transferV1toV2OnModify(ctx context.Context, req *apiv2.Routing) *apiv2.Response { + svcId, _ := s.Cache().RoutingConfig().IsConvertFromV1(req.Id) + v1conf, err := s.storage.GetRoutingConfigWithID(svcId) + if err != nil { + log.Error("[Routing][V2] get routing config v1 store layer", + utils.ZapRequestIDByCtx(ctx), zap.Error(err)) + return apiv2.NewResponse(api.StoreLayerException) + } + if v1conf != nil { + svc := s.Cache().Service().GetServiceByID(svcId) + if svc == nil { + _svc, err := s.storage.GetServiceByID(svcId) + if err != nil { + return nil + } + svc = _svc + } + if svc == nil { + log.Error("[Routing][V2] convert routing config v1 to v2 find svc", + utils.ZapRequestIDByCtx(ctx), zap.Error(err)) + return apiv2.NewResponse(api.NotFoundService) + } + + // 这里需要将 apiModel 的 id 全部生成一遍 extendInfo 信息 + inV2, outV2, err := routingcommon.ConvertRoutingV1ToExtendV2(svc.Name, svc.Namespace, v1conf) + if err != nil { + log.Error("[Routing][V2] convert routing config v1 to v2", + utils.ZapRequestIDByCtx(ctx), zap.Error(err)) + return apiv2.NewResponse(api.ExecuteException) + } + + formatApi := func(rules []*v2.ExtendRoutingConfig) ([]*apiv2.Routing, *apiv2.Response) { + ret := make([]*apiv2.Routing, 0, len(rules)) + for i := range rules { + item, err := rules[i].ToApi() + if err != nil { + log.Error("[Routing][V2] convert routing config v1 to v2, format v2 to api", + utils.ZapRequestIDByCtx(ctx), zap.Error(err)) + return nil, apiv2.NewResponse(api.ExecuteException) + } + ret = append(ret, item) + } + + return ret, nil + } + + inDatas, resp := formatApi(inV2) + if resp != nil { + return resp + } + outDatas, resp := formatApi(outV2) + if resp != nil { + return resp + } + + if resp := s.saveRoutingV1toV2(ctx, svcId, inDatas, outDatas); resp.GetCode().GetValue() != apiv1.ExecuteSuccess { + return apiv2.NewResponse(resp.GetCode().GetValue()) + } + } + + return apiv2.NewResponse(apiv1.ExecuteSuccess) +} + +// parseServiceArgs 解析服务的查询条件 +func parseRoutingArgs(query map[string]string, ctx context.Context) (*cache.RoutingArgs, *apiv2.Response) { + // 先处理offset和limit + offset, limit, err := ParseOffsetAndLimit(query) + if err != nil { + return nil, apiv2.NewResponse(api.InvalidParameter) + } + + filter := make(map[string]string) + for key, value := range query { + if _, ok := RoutingConfigV2FilterAttrs[key]; !ok { + log.Errorf("[Routing][V2][Query] attribute(%s) is not allowed", key) + return nil, apiv2.NewResponse(api.InvalidParameter) + } + filter[key] = value + } + + res := &cache.RoutingArgs{ + Filter: filter, + ID: filter["id"], + Namespace: filter["namespace"], + Service: filter["service"], + OrderField: filter["order_field"], + OrderType: filter["order_type"], + Offset: offset, + Limit: limit, + } + var ok bool + if res.Name, ok = filter["name"]; ok && store.IsWildName(res.Name) { + log.Infof("[Routing][V2][Query] fuzzy search with name %s", res.Name) + res.FuzzyName = true + } + if enableStr, ok := filter["enable"]; ok { + enable, err := strconv.ParseBool(enableStr) + if err == nil { + res.Enable = &enable + } else { + log.Error("[Service][Routing][Query] search with routing enable", zap.Error(err)) + } + } + log.Infof("[Service][Routing][Query] routing query args: %+v", res) + return res, nil +} + +// checkBatchRoutingConfig 检查批量请求 +func checkBatchRoutingConfigV2(req []*apiv2.Routing) *apiv2.BatchWriteResponse { + if len(req) == 0 { + return apiv2.NewBatchWriteResponse(apiv1.EmptyRequest) + } + + if len(req) > MaxBatchSize { + return apiv2.NewBatchWriteResponse(apiv1.BatchSizeOverLimit) + } + + return nil +} + +// checkRoutingConfig 检查路由配置基础参数有效性 +func checkRoutingConfigV2(req *apiv2.Routing) *apiv2.Response { + if req == nil { + return apiv2.NewRoutingResponse(api.EmptyRequest, req) + } + + if err := checkRoutingNameAndNamespace(req); err != nil { + return err + } + + if err := checkRoutingConfigPriorityV2(req); err != nil { + return err + } + + if err := checkRoutingPolicyV2(req); err != nil { + return err + } + + return nil +} + +// checkUpdateRoutingConfigV2 检查路由配置基础参数有效性 +func checkUpdateRoutingConfigV2(req *apiv2.Routing) *apiv2.Response { + if resp := checkRoutingConfigIDV2(req); resp != nil { + return resp + } + + if err := checkRoutingNameAndNamespace(req); err != nil { + return err + } + + if err := checkRoutingConfigPriorityV2(req); err != nil { + return err + } + + if err := checkRoutingPolicyV2(req); err != nil { + return err + } + + return nil +} + +func checkRoutingNameAndNamespace(req *apiv2.Routing) *apiv2.Response { + if err := CheckDbStrFieldLen(utils.NewStringValue(req.GetName()), MaxDbRoutingName); err != nil { + return apiv2.NewRoutingResponse(api.InvalidRoutingName, req) + } + + if err := CheckDbStrFieldLen(utils.NewStringValue(req.GetNamespace()), + MaxDbServiceNamespaceLength); err != nil { + return apiv2.NewRoutingResponse(api.InvalidNamespaceName, req) + } + + return nil +} + +func checkRoutingConfigIDV2(req *apiv2.Routing) *apiv2.Response { + if req == nil { + return apiv2.NewRoutingResponse(api.EmptyRequest, req) + } + + if req.Id == "" { + return apiv2.NewResponse(api.InvalidRoutingID) + } + + return nil +} + +func checkRoutingConfigPriorityV2(req *apiv2.Routing) *apiv2.Response { + if req == nil { + return apiv2.NewRoutingResponse(api.EmptyRequest, req) + } + + if req.Priority < 0 || req.Priority > 10 { + return apiv2.NewResponse(api.InvalidRoutingPriority) + } + + return nil +} + +func checkRoutingPolicyV2(req *apiv2.Routing) *apiv2.Response { + if req == nil { + return apiv2.NewRoutingResponse(api.EmptyRequest, req) + } + + if req.GetRoutingPolicy() != apiv2.RoutingPolicy_RulePolicy { + return apiv2.NewRoutingResponse(api.InvalidRoutingPolicy, req) + } + + // 自动根据 policy 补充 @type 属性 + if req.RoutingConfig.TypeUrl == "" { + if req.GetRoutingPolicy() == apiv2.RoutingPolicy_RulePolicy { + req.RoutingConfig.TypeUrl = v2.RuleRoutingTypeUrl + } + if req.GetRoutingPolicy() == apiv2.RoutingPolicy_MetadataPolicy { + req.RoutingConfig.TypeUrl = v2.MetaRoutingTypeUrl + } + } + + return nil +} + +// api2RoutingConfig 把API参数转换为内部的数据结构 +func api2RoutingConfigV2(req *apiv2.Routing) (*v2.RoutingConfig, error) { + out := &v2.RoutingConfig{ + Valid: true, + } + + if req.Id == "" { + req.Id = utils.NewRoutingV2UUID() + } + if req.Revision == "" { + req.Revision = utils.NewV2Revision() + } + + if err := out.ParseFromAPI(req); err != nil { + return nil, err + } + return out, nil +} + +// marshalRoutingV2toAnySlice 转换为 []*anypb.Any 数组 +func marshalRoutingV2toAnySlice(routings []*v2.ExtendRoutingConfig) ([]*any.Any, error) { + ret := make([]*any.Any, 0, len(routings)) + + for i := range routings { + entry, err := routings[i].ToApi() + if err != nil { + return nil, err + } + item, err := ptypes.MarshalAny(entry) + if err != nil { + return nil, err + } + + ret = append(ret, item) + } + + return ret, nil +} diff --git a/service/routing_config_v2_authability.go b/service/routing_config_v2_authability.go new file mode 100644 index 000000000..be76f826b --- /dev/null +++ b/service/routing_config_v2_authability.go @@ -0,0 +1,54 @@ +/** + * Tencent is pleased to support the open source community by making Polaris available. + * + * Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved. + * + * Licensed under the BSD 3-Clause License (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://opensource.org/licenses/BSD-3-Clause + * + * 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 service + +import ( + "context" + + apiv2 "github.com/polarismesh/polaris-server/common/api/v2" +) + +// CreateRoutingConfigsV2 批量创建路由配置 +func (s *serverAuthAbility) CreateRoutingConfigsV2(ctx context.Context, req []*apiv2.Routing) *apiv2.BatchWriteResponse { + + return s.targetServer.CreateRoutingConfigsV2(ctx, req) +} + +// DeleteRoutingConfigsV2 批量删除路由配置 +func (s *serverAuthAbility) DeleteRoutingConfigsV2(ctx context.Context, req []*apiv2.Routing) *apiv2.BatchWriteResponse { + + return s.targetServer.DeleteRoutingConfigsV2(ctx, req) +} + +// UpdateRoutingConfigsV2 批量更新路由配置 +func (s *serverAuthAbility) UpdateRoutingConfigsV2(ctx context.Context, req []*apiv2.Routing) *apiv2.BatchWriteResponse { + + return s.targetServer.UpdateRoutingConfigsV2(ctx, req) +} + +// EnableRoutings batch enable routing rules +func (s *serverAuthAbility) EnableRoutings(ctx context.Context, req []*apiv2.Routing) *apiv2.BatchWriteResponse { + + return s.targetServer.EnableRoutings(ctx, req) +} + +// GetRoutingConfigs 提供给OSS的查询路由配置的接口 +func (s *serverAuthAbility) GetRoutingConfigsV2(ctx context.Context, query map[string]string) *apiv2.BatchQueryResponse { + + return s.targetServer.GetRoutingConfigsV2(ctx, query) +} diff --git a/service/routing_config_v2_test.go b/service/routing_config_v2_test.go new file mode 100644 index 000000000..fda10c2b3 --- /dev/null +++ b/service/routing_config_v2_test.go @@ -0,0 +1,478 @@ +/** + * Tencent is pleased to support the open source community by making Polaris available. + * + * Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved. + * + * Licensed under the BSD 3-Clause License (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://opensource.org/licenses/BSD-3-Clause + * + * 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 service + +import ( + "fmt" + "testing" + "time" + + "github.com/golang/protobuf/ptypes" + "github.com/stretchr/testify/assert" + "google.golang.org/protobuf/types/known/anypb" + + api "github.com/polarismesh/polaris-server/common/api/v1" + apiv2 "github.com/polarismesh/polaris-server/common/api/v2" + "github.com/polarismesh/polaris-server/common/utils" +) + +// checkSameRoutingConfigV2 检查routingConfig前后是否一致 +func checkSameRoutingConfigV2V2(t *testing.T, lhs []*apiv2.Routing, rhs []*apiv2.Routing) { + if len(lhs) != len(rhs) { + t.Fatal("error: len(lhs) != len(rhs)") + } +} + +// TestCreateRoutingConfigV2 测试创建路由配置 +func TestCreateRoutingConfigV2(t *testing.T) { + + discoverSuit := &DiscoverTestSuit{} + if err := discoverSuit.initialize(); err != nil { + t.Fatal(err) + } + defer discoverSuit.Destroy() + + t.Run("正常创建路由配置配置请求", func(t *testing.T) { + req := discoverSuit.createCommonRoutingConfigV2(t, 3) + defer discoverSuit.truncateCommonRoutingConfigV2() + + // 对写进去的数据进行查询 + time.Sleep(discoverSuit.updateCacheInterval * 5) + out := discoverSuit.server.GetRoutingConfigsV2(discoverSuit.defaultCtx, map[string]string{ + "limit": "100", + "offset": "0", + }) + if !respSuccessV2(out) { + t.Fatalf("error: %+v", out) + } + + ret, _ := unmarshalRoutingV2toAnySlice(out.GetData()) + t.Logf("query routing v2 : %#v", ret) + + // assert.Equal(t, int(3), int(out.Amount), "query routing size") + + // 按照名字查询 + + out = discoverSuit.server.GetRoutingConfigsV2(discoverSuit.defaultCtx, map[string]string{ + "limit": "100", + "offset": "0", + "name": req[0].Name, + }) + if !respSuccessV2(out) { + t.Fatalf("error: %+v", out) + } + + assert.Equal(t, int(1), int(out.Amount), "query routing size") + }) +} + +// TestCompatibleRoutingConfigV2AndV1 测试V2版本的路由规则和V1版本的路由规则 +func TestCompatibleRoutingConfigV2AndV1(t *testing.T) { + + discoverSuit := &DiscoverTestSuit{} + if err := discoverSuit.initialize(); err != nil { + t.Fatal(err) + } + defer discoverSuit.Destroy() + + svc := &api.Service{ + Name: utils.NewStringValue("compatible-routing"), + Namespace: utils.NewStringValue("compatible"), + } + + createSvcResp := discoverSuit.server.CreateServices(discoverSuit.defaultCtx, []*api.Service{svc}) + if !respSuccess(createSvcResp) { + t.Fatalf("error: %s", createSvcResp.GetInfo().GetValue()) + } + + _ = createSvcResp.Responses[0].GetService() + defer discoverSuit.cleanServices([]*api.Service{svc}) + + t.Run("V1的存量规则-走V2接口可以查询到,ExtendInfo符合要求", func(t *testing.T) { + _, _ = discoverSuit.createCommonRoutingConfigV1IntoOldStore(t, svc, 3, 0) + defer func() { + discoverSuit.cleanCommonRoutingConfig(svc.GetName().GetValue(), svc.GetNamespace().GetValue()) + discoverSuit.truncateCommonRoutingConfigV2() + }() + + time.Sleep(discoverSuit.updateCacheInterval * 5) + // 从缓存中查询应该查到 3+3 条 v2 的路由规则 + out := discoverSuit.server.GetRoutingConfigsV2(discoverSuit.defaultCtx, map[string]string{ + "limit": "100", + "offset": "0", + }) + if !respSuccessV2(out) { + t.Fatalf("error: %+v", out) + } + assert.Equal(t, int(3), int(out.Amount), "query routing size") + + rulesV2, err := unmarshalRoutingV2toAnySlice(out.GetData()) + assert.NoError(t, err) + + for i := range rulesV2 { + item := rulesV2[i] + assert.True(t, item.Enable, "v1 to v2 need default open enable") + } + }) + + t.Run("V1的存量规则-走v2规则的启用可正常迁移v1规则", func(t *testing.T) { + _, _ = discoverSuit.createCommonRoutingConfigV1IntoOldStore(t, svc, 3, 0) + defer func() { + discoverSuit.cleanCommonRoutingConfig(svc.GetName().GetValue(), svc.GetNamespace().GetValue()) + discoverSuit.truncateCommonRoutingConfigV2() + }() + + time.Sleep(discoverSuit.updateCacheInterval * 5) + // 从缓存中查询应该查到 3+3 条 v2 的路由规则 + out := discoverSuit.server.GetRoutingConfigsV2(discoverSuit.defaultCtx, map[string]string{ + "limit": "100", + "offset": "0", + }) + if !respSuccessV2(out) { + t.Fatalf("error: %+v", out) + } + assert.Equal(t, int(3), int(out.Amount), "query routing size") + + rulesV2, err := unmarshalRoutingV2toAnySlice(out.GetData()) + assert.NoError(t, err) + + // 选择其中一条规则进行enable操作 + v2resp := discoverSuit.server.EnableRoutings(discoverSuit.defaultCtx, []*apiv2.Routing{rulesV2[0]}) + if !respSuccessV2(v2resp) { + t.Fatalf("error: %+v", v2resp) + } + // 直接查询存储无法查询到 v1 的路由规则 + total, routingsV1, err := discoverSuit.storage.GetRoutingConfigs(map[string]string{}, 0, 100) + assert.NoError(t, err, err) + assert.Equal(t, uint32(0), total, "v1 routing must delete and transfer to v1") + assert.Equal(t, 0, len(routingsV1), "v1 routing ret len need zero") + }) + + t.Run("V1的存量规则-走v2规则的删除可正常迁移v1规则", func(t *testing.T) { + _, _ = discoverSuit.createCommonRoutingConfigV1IntoOldStore(t, svc, 3, 0) + defer func() { + discoverSuit.cleanCommonRoutingConfig(svc.GetName().GetValue(), svc.GetNamespace().GetValue()) + discoverSuit.truncateCommonRoutingConfigV2() + }() + + time.Sleep(discoverSuit.updateCacheInterval * 5) + // 从缓存中查询应该查到 3+3 条 v2 的路由规则 + out := discoverSuit.server.GetRoutingConfigsV2(discoverSuit.defaultCtx, map[string]string{ + "limit": "100", + "offset": "0", + }) + if !respSuccessV2(out) { + t.Fatalf("error: %+v", out) + } + assert.Equal(t, int(3), int(out.Amount), "query routing size") + + rulesV2, err := unmarshalRoutingV2toAnySlice(out.GetData()) + assert.NoError(t, err) + + // 选择其中一条规则进行删除操作 + v2resp := discoverSuit.server.DeleteRoutingConfigsV2(discoverSuit.defaultCtx, []*apiv2.Routing{rulesV2[0]}) + if !respSuccessV2(v2resp) { + t.Fatalf("error: %+v", v2resp) + } + // 直接查询存储无法查询到 v1 的路由规则 + total, routingsV1, err := discoverSuit.storage.GetRoutingConfigs(map[string]string{}, 0, 100) + assert.NoError(t, err, err) + assert.Equal(t, uint32(0), total, "v1 routing must delete and transfer to v1") + assert.Equal(t, 0, len(routingsV1), "v1 routing ret len need zero") + + // 查询对应的 v2 规则也查询不到 + ruleV2, err := discoverSuit.storage.GetRoutingConfigV2WithID(rulesV2[0].Id) + assert.NoError(t, err, err) + assert.Nil(t, ruleV2, "v2 routing must delete") + }) + + t.Run("V1的存量规则-走v2规则的编辑可正常迁移v1规则", func(t *testing.T) { + _, _ = discoverSuit.createCommonRoutingConfigV1IntoOldStore(t, svc, 3, 0) + defer func() { + discoverSuit.cleanCommonRoutingConfig(svc.GetName().GetValue(), svc.GetNamespace().GetValue()) + discoverSuit.truncateCommonRoutingConfigV2() + }() + + time.Sleep(discoverSuit.updateCacheInterval * 5) + // 从缓存中查询应该查到 3+3 条 v2 的路由规则 + out := discoverSuit.server.GetRoutingConfigsV2(discoverSuit.defaultCtx, map[string]string{ + "limit": "100", + "offset": "0", + }) + if !respSuccessV2(out) { + t.Fatalf("error: %+v", out) + } + assert.Equal(t, int(3), int(out.Amount), "query routing size") + + rulesV2, err := unmarshalRoutingV2toAnySlice(out.GetData()) + assert.NoError(t, err) + + // 需要将 v2 规则的 extendInfo 规则清理掉 + // 选择其中一条规则进行enable操作 + rulesV2[0].Description = "update v2 rule and transfer v1 to v2" + v2resp := discoverSuit.server.UpdateRoutingConfigsV2(discoverSuit.defaultCtx, []*apiv2.Routing{rulesV2[0]}) + if !respSuccessV2(v2resp) { + t.Fatalf("error: %+v", v2resp) + } + // 直接查询存储无法查询到 v1 的路由规则 + total, routingsV1, err := discoverSuit.storage.GetRoutingConfigs(map[string]string{}, 0, 100) + assert.NoError(t, err, err) + assert.Equal(t, uint32(0), total, "v1 routing must delete and transfer to v1") + assert.Equal(t, 0, len(routingsV1), "v1 routing ret len need zero") + + // 查询对应的 v2 规则也查询不到 + ruleV2, err := discoverSuit.storage.GetRoutingConfigV2WithID(rulesV2[0].Id) + assert.NoError(t, err, err) + assert.NotNil(t, ruleV2, "v2 routing must exist") + assert.Equal(t, rulesV2[0].Description, ruleV2.Description) + }) +} + +// TestDeleteRoutingConfigV2 测试删除路由配置 +func TestDeleteRoutingConfigV2(t *testing.T) { + + discoverSuit := &DiscoverTestSuit{} + if err := discoverSuit.initialize(); err != nil { + t.Fatal(err) + } + defer discoverSuit.Destroy() + + t.Run("可以正常删除路由配置", func(t *testing.T) { + resp := discoverSuit.createCommonRoutingConfigV2(t, 1) + discoverSuit.deleteCommonRoutingConfigV2(t, resp[0]) + defer discoverSuit.cleanCommonRoutingConfigV2(resp) + + serviceName := fmt.Sprintf("in-source-service-%d", 0) + namespaceName := fmt.Sprintf("in-source-service-%d", 0) + + // 删除之后,数据不见 + time.Sleep(discoverSuit.updateCacheInterval) + out := discoverSuit.server.GetRoutingConfigWithCache(discoverSuit.defaultCtx, &api.Service{ + Name: utils.NewStringValue(serviceName), + Namespace: utils.NewStringValue(namespaceName), + }) + assert.Nil(t, out.GetRouting()) + }) +} + +// TestUpdateRoutingConfigV2 测试更新路由配置 +func TestUpdateRoutingConfigV2(t *testing.T) { + + discoverSuit := &DiscoverTestSuit{} + if err := discoverSuit.initialize(); err != nil { + t.Fatal(err) + } + defer discoverSuit.Destroy() + + t.Run("可以正常更新路由配置", func(t *testing.T) { + req := discoverSuit.createCommonRoutingConfigV2(t, 1) + defer discoverSuit.cleanCommonRoutingConfigV2(req) + // 对写进去的数据进行查询 + time.Sleep(discoverSuit.updateCacheInterval) + out := discoverSuit.server.GetRoutingConfigsV2(discoverSuit.defaultCtx, map[string]string{ + "limit": "100", + "offset": "0", + }) + if !respSuccessV2(out) { + t.Fatalf("error: %+v", out) + } + + assert.Equal(t, uint32(1), out.Size, "query routing size") + + ret, err := unmarshalRoutingV2toAnySlice(out.GetData()) + assert.NoError(t, err) + routing := ret[0] + + updateName := "update routing second" + routing.Name = updateName + + discoverSuit.server.UpdateRoutingConfigsV2(discoverSuit.defaultCtx, []*apiv2.Routing{routing}) + time.Sleep(discoverSuit.updateCacheInterval) + out = discoverSuit.server.GetRoutingConfigsV2(discoverSuit.defaultCtx, map[string]string{ + "limit": "100", + "offset": "0", + "id": routing.Id, + }) + + if !respSuccessV2(out) { + t.Fatalf("error: %+v", out) + } + + assert.Equal(t, uint32(1), out.Size, "query routing size") + ret, err = unmarshalRoutingV2toAnySlice(out.GetData()) + assert.NoError(t, err) + assert.Equal(t, updateName, ret[0].Name) + }) +} + +// test对routing字段进行校验 +func TestCreateCheckRoutingFieldLenV2(t *testing.T) { + + discoverSuit := &DiscoverTestSuit{} + if err := discoverSuit.initialize(); err != nil { + t.Fatal(err) + } + defer discoverSuit.Destroy() + + any, _ := ptypes.MarshalAny(&apiv2.RuleRoutingConfig{}) + + req := &apiv2.Routing{ + Id: "", + Name: "test-routing", + Namespace: "", + Enable: false, + RoutingPolicy: apiv2.RoutingPolicy_RulePolicy, + RoutingConfig: any, + Revision: "", + Ctime: "", + Mtime: "", + Etime: "", + Priority: 0, + Description: "", + } + + t.Run("创建路由规则,规则名称超长", func(t *testing.T) { + str := genSpecialStr(129) + oldName := req.Name + req.Name = str + resp := discoverSuit.server.CreateRoutingConfigsV2(discoverSuit.defaultCtx, []*apiv2.Routing{req}) + req.Name = oldName + if resp.Code != api.InvalidRoutingName { + t.Fatalf("%+v", resp) + } + }) + t.Run("创建路由规则,路由规则类型不正确", func(t *testing.T) { + oldPolicy := req.RoutingPolicy + req.RoutingPolicy = apiv2.RoutingPolicy(123) + resp := discoverSuit.server.CreateRoutingConfigsV2(discoverSuit.defaultCtx, []*apiv2.Routing{req}) + req.RoutingPolicy = oldPolicy + if resp.Code != api.InvalidRoutingPolicy { + t.Fatalf("%+v", resp) + } + }) + t.Run("创建路由规则,路由规则类型不正确", func(t *testing.T) { + oldPolicy := req.RoutingPolicy + req.RoutingPolicy = apiv2.RoutingPolicy_MetadataPolicy + resp := discoverSuit.server.CreateRoutingConfigsV2(discoverSuit.defaultCtx, []*apiv2.Routing{req}) + req.RoutingPolicy = oldPolicy + if resp.Code != api.InvalidRoutingPolicy { + t.Fatalf("%+v", resp) + } + }) + t.Run("创建路由规则,路由优先级不正确", func(t *testing.T) { + oldPriority := req.Priority + req.Priority = 11 + resp := discoverSuit.server.CreateRoutingConfigsV2(discoverSuit.defaultCtx, []*apiv2.Routing{req}) + req.Priority = oldPriority + if resp.Code != api.InvalidRoutingPriority { + t.Fatalf("%+v", resp) + } + }) +} + +// TestUpdateCheckRoutingFieldLenV2 test对routing字段进行校验 +func TestUpdateCheckRoutingFieldLenV2(t *testing.T) { + + discoverSuit := &DiscoverTestSuit{} + if err := discoverSuit.initialize(); err != nil { + t.Fatal(err) + } + defer discoverSuit.Destroy() + + any, _ := ptypes.MarshalAny(&apiv2.RuleRoutingConfig{}) + + req := &apiv2.Routing{ + Id: "12312312312312313", + Name: "test-routing", + Namespace: "", + Enable: false, + RoutingPolicy: apiv2.RoutingPolicy_RulePolicy, + RoutingConfig: any, + Revision: "", + Ctime: "", + Mtime: "", + Etime: "", + Priority: 0, + Description: "", + } + + t.Run("更新路由规则,规则ID为空", func(t *testing.T) { + oldId := req.Id + req.Id = "" + resp := discoverSuit.server.UpdateRoutingConfigsV2(discoverSuit.defaultCtx, []*apiv2.Routing{req}) + req.Id = oldId + if resp.Code != api.InvalidRoutingID { + t.Fatalf("%+v", resp) + } + }) + t.Run("更新路由规则,规则名称超长", func(t *testing.T) { + str := genSpecialStr(129) + oldName := req.Name + req.Name = str + resp := discoverSuit.server.UpdateRoutingConfigsV2(discoverSuit.defaultCtx, []*apiv2.Routing{req}) + req.Name = oldName + if resp.Code != api.InvalidRoutingName { + t.Fatalf("%+v", resp) + } + }) + t.Run("更新路由规则,路由规则类型不正确", func(t *testing.T) { + oldPolicy := req.RoutingPolicy + req.RoutingPolicy = apiv2.RoutingPolicy(123) + resp := discoverSuit.server.UpdateRoutingConfigsV2(discoverSuit.defaultCtx, []*apiv2.Routing{req}) + req.RoutingPolicy = oldPolicy + if resp.Code != api.InvalidRoutingPolicy { + t.Fatalf("%+v", resp) + } + }) + t.Run("更新路由规则,路由规则类型不正确", func(t *testing.T) { + oldPolicy := req.RoutingPolicy + req.RoutingPolicy = apiv2.RoutingPolicy_MetadataPolicy + resp := discoverSuit.server.UpdateRoutingConfigsV2(discoverSuit.defaultCtx, []*apiv2.Routing{req}) + req.RoutingPolicy = oldPolicy + if resp.Code != api.InvalidRoutingPolicy { + t.Fatalf("%+v", resp) + } + }) + t.Run("更新路由规则,路由优先级不正确", func(t *testing.T) { + oldPriority := req.Priority + req.Priority = 11 + resp := discoverSuit.server.UpdateRoutingConfigsV2(discoverSuit.defaultCtx, []*apiv2.Routing{req}) + req.Priority = oldPriority + if resp.Code != api.InvalidRoutingPriority { + t.Fatalf("%+v", resp) + } + }) +} + +// marshalRoutingV2toAnySlice 转换为 []*apiv2.Routing 数组 +func unmarshalRoutingV2toAnySlice(routings []*anypb.Any) ([]*apiv2.Routing, error) { + ret := make([]*apiv2.Routing, 0, len(routings)) + + for i := range routings { + entry := routings[i] + + msg := &apiv2.Routing{} + if err := ptypes.UnmarshalAny(entry, msg); err != nil { + return nil, err + } + + ret = append(ret, msg) + } + + return ret, nil +} diff --git a/service/server_authability.go b/service/server_authability.go index ee42f3830..ab8c31eee 100644 --- a/service/server_authability.go +++ b/service/server_authability.go @@ -29,6 +29,7 @@ import ( commonlog "github.com/polarismesh/polaris-server/common/log" "github.com/polarismesh/polaris-server/common/model" "github.com/polarismesh/polaris-server/common/utils" + servicecommon "github.com/polarismesh/polaris-server/common/service" ) // serverAuthAbility 带有鉴权能力的 discoverServer @@ -218,7 +219,7 @@ func (svr *serverAuthAbility) queryServiceResource( } names := utils.NewStringSet() - svcSet := utils.NewServiceSet() + svcSet := servicecommon.NewServiceSet() for index := range req { names.Add(req[index].Namespace.GetValue()) @@ -241,7 +242,7 @@ func (svr *serverAuthAbility) queryServiceAliasResource( } names := utils.NewStringSet() - svcSet := utils.NewServiceSet() + svcSet := servicecommon.NewServiceSet() for index := range req { names.Add(req[index].Namespace.GetValue()) @@ -269,7 +270,7 @@ func (svr *serverAuthAbility) queryInstanceResource( } names := utils.NewStringSet() - svcSet := utils.NewServiceSet() + svcSet := servicecommon.NewServiceSet() for index := range req { item := req[index] @@ -307,7 +308,7 @@ func (svr *serverAuthAbility) queryCircuitBreakerResource( } names := utils.NewStringSet() - svcSet := utils.NewServiceSet() + svcSet := servicecommon.NewServiceSet() for index := range req { svc := svr.Cache().Service().GetServiceByName(req[index].Service.GetValue(), @@ -329,7 +330,7 @@ func (svr *serverAuthAbility) queryCircuitBreakerReleaseResource( } names := utils.NewStringSet() - svcSet := utils.NewServiceSet() + svcSet := servicecommon.NewServiceSet() for index := range req { svc := svr.Cache().Service().GetServiceByName(req[index].Service.Name.GetValue(), @@ -352,7 +353,7 @@ func (svr *serverAuthAbility) queryRouteRuleResource( } names := utils.NewStringSet() - svcSet := utils.NewServiceSet() + svcSet := servicecommon.NewServiceSet() for index := range req { svc := svr.Cache().Service().GetServiceByName(req[index].Service.GetValue(), @@ -375,7 +376,7 @@ func (svr *serverAuthAbility) queryRateLimitConfigResource( } names := utils.NewStringSet() - svcSet := utils.NewServiceSet() + svcSet := servicecommon.NewServiceSet() for index := range req { svc := svr.Cache().Service().GetServiceByName(req[index].Service.GetValue(), @@ -392,7 +393,7 @@ func (svr *serverAuthAbility) queryRateLimitConfigResource( // convertToDiscoverResourceEntryMaps 通用方法,进行转换为期望的、服务相关的 ResourceEntry func (svr *serverAuthAbility) convertToDiscoverResourceEntryMaps(nsSet utils.StringSet, - svcSet *utils.ServiceSet) map[api.ResourceType][]model.ResourceEntry { + svcSet *servicecommon.ServiceSet) map[api.ResourceType][]model.ResourceEntry { param := nsSet.ToSlice() nsArr := svr.Cache().Namespace().GetNamespacesByName(param) diff --git a/service/service_alias_test.go b/service/service_alias_test.go index 4e8dbd216..88799e274 100644 --- a/service/service_alias_test.go +++ b/service/service_alias_test.go @@ -553,17 +553,17 @@ func TestServiceAliasRelated(t *testing.T) { So(respSuccess(routingResp), ShouldEqual, false) t.Logf("create routing ret code(%d), info(%s)", routingResp.Code.Value, routingResp.Info.Value) }) - Convey("路由Discover,别名查询路由,返回源服务的路由信息", t, func() { - discoverSuit.createCommonRoutingConfig(t, serviceResp, 1, 0) // in=1, out=0 - defer discoverSuit.cleanCommonRoutingConfig(serviceResp.GetName().GetValue(), serviceResp.GetNamespace().GetValue()) - - time.Sleep(discoverSuit.updateCacheInterval) - service := &api.Service{Name: resp.Alias.Alias, Namespace: resp.Alias.Namespace} - disResp := discoverSuit.server.GetRoutingConfigWithCache(discoverSuit.defaultCtx, service) - So(respSuccess(disResp), ShouldEqual, true) - So(len(disResp.Routing.Inbounds), ShouldEqual, 1) - So(len(disResp.Routing.Outbounds), ShouldEqual, 0) - }) + // Convey("路由Discover,别名查询路由,返回源服务的路由信息", t, func() { + // discoverSuit.createCommonRoutingConfig(t, serviceResp, 1, 0) // in=1, out=0 + // defer discoverSuit.cleanCommonRoutingConfig(serviceResp.GetName().GetValue(), serviceResp.GetNamespace().GetValue()) + + // time.Sleep(discoverSuit.updateCacheInterval) + // service := &api.Service{Name: resp.Alias.Alias, Namespace: resp.Alias.Namespace} + // disResp := discoverSuit.server.GetRoutingConfigWithCache(discoverSuit.defaultCtx, service) + // So(respSuccess(disResp), ShouldEqual, true) + // So(len(disResp.Routing.Inbounds), ShouldEqual, 1) + // So(len(disResp.Routing.Outbounds), ShouldEqual, 0) + // }) } // 测试获取别名列表 diff --git a/service/service_test.go b/service/service_test.go index b2a4a6eee..517336b4a 100644 --- a/service/service_test.go +++ b/service/service_test.go @@ -231,20 +231,6 @@ func TestDeleteService2(t *testing.T) { } defer discoverSuit.Destroy() - t.Run("存在路由配置的情况下,删除服务会失败", func(t *testing.T) { - serviceReq, serviceResp := discoverSuit.createCommonService(t, 20) - defer discoverSuit.cleanServiceName(serviceReq.GetName().GetValue(), serviceReq.GetNamespace().GetValue()) - - // 创建一个服务配置 - discoverSuit.createCommonRoutingConfig(t, serviceResp, 10, 10) - defer discoverSuit.cleanCommonRoutingConfig(serviceReq.GetName().GetValue(), serviceReq.GetNamespace().GetValue()) - // 删除服务 - resp := discoverSuit.server.DeleteServices(discoverSuit.defaultCtx, []*api.Service{serviceResp}) - if respSuccess(resp) { - t.Fatalf("error") - } - t.Logf("pass: %s", resp.GetInfo().GetValue()) - }) t.Run("重复删除服务,返回成功", func(t *testing.T) { serviceReq, serviceResp := discoverSuit.createCommonService(t, 20) defer discoverSuit.cleanServiceName(serviceReq.GetName().GetValue(), serviceReq.GetNamespace().GetValue()) diff --git a/service/utils.go b/service/utils.go index 597af92b4..128fc4ffb 100644 --- a/service/utils.go +++ b/service/utils.go @@ -89,6 +89,9 @@ const ( // ratelimit表 MaxDbRateLimitName = 64 + + // routing_config_v2 表 + MaxDbRoutingName = 64 ) // checkResourceName 检查资源Name diff --git a/store/api.go b/store/api.go index a3a591ab1..ee9fe49ee 100644 --- a/store/api.go +++ b/store/api.go @@ -103,7 +103,7 @@ type Transaction interface { type Tx interface { // Commit Transaction Commit() error - // Rollback Rollback transaction + // Rollback transaction Rollback() error // GetDelegateTx Get the original proxy transaction object.Different storage types have no business implementation GetDelegateTx() interface{} diff --git a/store/boltdb/default.go b/store/boltdb/default.go index 8b2959734..a0f0bb273 100644 --- a/store/boltdb/default.go +++ b/store/boltdb/default.go @@ -64,6 +64,9 @@ type boltStore struct { *configFileTagStore *configFileTemplateStore + // v2 存储 + *routingStoreV2 + handler BoltHandler start bool } @@ -111,11 +114,7 @@ const ( var ( namespacesToInit = []string{"default", namespacePolaris} servicesToInit = map[string]string{ - "polaris.discover": "1866010b40be6542db1a2cc846c7f51f", - "polaris.healthcheck": "846c1866010b40b7f51fe6542db1a2cc", "polaris.checker": "fbca9bfa04ae4ead86e1ecf5811e32a9", - "polaris.monitor": "bbfdda174ea64e11ac862adf14593c03", - "polaris.config": "e6542db1a2cc846c1866010b40b7f51f", } mainUser = &model.User{ @@ -281,6 +280,8 @@ func (m *boltStore) newDiscoverModuleStore() error { m.circuitBreakerStore = &circuitBreakerStore{handler: m.handler} + m.routingStoreV2 = &routingStoreV2{handler: m.handler} + return nil } diff --git a/store/boltdb/routing.go b/store/boltdb/routing.go index 49e9d4cdd..f393daad4 100644 --- a/store/boltdb/routing.go +++ b/store/boltdb/routing.go @@ -18,10 +18,12 @@ package boltdb import ( + "errors" "sort" "strings" "time" + "github.com/boltdb/bolt" "github.com/polarismesh/polaris-server/common/model" "github.com/polarismesh/polaris-server/store" ) @@ -122,6 +124,30 @@ func (r *routingStore) DeleteRoutingConfig(serviceID string) error { return nil } +func (r *routingStore) DeleteRoutingConfigTx(tx store.Tx, serviceID string) error { + if tx == nil { + return errors.New("tx is nil") + } + + if serviceID == "" { + log.Errorf("[Store][boltdb] delete routing config missing service id") + return store.NewStatusError(store.EmptyParamsErr, "missing service id") + } + + properties := make(map[string]interface{}) + properties[routingFieldValid] = false + properties[routingFieldModifyTime] = time.Now() + + boltTx := tx.GetDelegateTx().(*bolt.Tx) + err := updateValue(boltTx, tblNameRouting, serviceID, properties) + if err != nil { + log.Errorf("[Store][boltdb] delete route config to kv error, %v", err) + return err + } + + return nil +} + // GetRoutingConfigsForCache Get incremental routing configuration information through mtime func (r *routingStore) GetRoutingConfigsForCache(mtime time.Time, firstUpdate bool) ([]*model.RoutingConfig, error) { diff --git a/store/boltdb/routing_config_v2.go b/store/boltdb/routing_config_v2.go new file mode 100644 index 000000000..d474e0d07 --- /dev/null +++ b/store/boltdb/routing_config_v2.go @@ -0,0 +1,284 @@ +/** + * Tencent is pleased to support the open source community by making Polaris available. + * + * Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved. + * + * Licensed under the BSD 3-Clause License (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://opensource.org/licenses/BSD-3-Clause + * + * 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 boltdb + +import ( + "errors" + "time" + + "github.com/boltdb/bolt" + v2 "github.com/polarismesh/polaris-server/common/model/v2" + "github.com/polarismesh/polaris-server/store" + "go.uber.org/zap" +) + +var ( + MultipleRoutingV2Found error = errors.New("multiple routing v2 found") +) + +const ( + tblNameRoutingV2 = "routing_config_v2" + + routingV2FieldID = "ID" + routingV2FieldName = "Name" + routingV2FieldNamespace = "Namespace" + routingV2FieldPolicy = "Policy" + routingV2FieldConfig = "Config" + routingV2FieldEnable = "Enable" + routingV2FieldRevision = "Revision" + routingV2FieldCreateTime = "CreateTime" + routingV2FieldModifyTime = "ModifyTime" + routingV2FieldEnableTime = "EnableTime" + routingV2FieldValid = "Valid" + routingV2FieldPriority = "Priority" + routingV2FieldDescription = "Description" +) + +type routingStoreV2 struct { + handler BoltHandler +} + +// CreateRoutingConfigV2 新增一个路由配置 +func (r *routingStoreV2) CreateRoutingConfigV2(conf *v2.RoutingConfig) error { + if conf.ID == "" || conf.Revision == "" { + log.Errorf("[Store][boltdb] create routing config v2 missing id or revision") + return store.NewStatusError(store.EmptyParamsErr, "missing id or revision") + } + if conf.Policy == "" || conf.Config == "" { + log.Errorf("[Store][boltdb] create routing config v2 missing params") + return store.NewStatusError(store.EmptyParamsErr, "missing some params") + } + + return r.handler.Execute(true, func(tx *bolt.Tx) error { + return r.createRoutingConfigV2(tx, conf) + }) +} + +// cleanRoutingConfig 从数据库彻底清理路由配置 +func (r *routingStoreV2) cleanRoutingConfig(tx *bolt.Tx, ruleID string) error { + err := deleteValues(tx, tblNameRoutingV2, []string{ruleID}, false) + if err != nil { + log.Errorf("[Store][boltdb] delete invalid route config v2 error, %v", err) + return err + } + return nil +} + +func (r *routingStoreV2) CreateRoutingConfigV2Tx(tx store.Tx, conf *v2.RoutingConfig) error { + if tx == nil { + return errors.New("transaction is nil") + } + + dbTx := tx.GetDelegateTx().(*bolt.Tx) + return r.createRoutingConfigV2(dbTx, conf) +} + +func (r *routingStoreV2) createRoutingConfigV2(tx *bolt.Tx, conf *v2.RoutingConfig) error { + if err := r.cleanRoutingConfig(tx, conf.ID); err != nil { + return err + } + + currTime := time.Now() + conf.CreateTime = currTime + conf.ModifyTime = currTime + conf.EnableTime = time.Time{} + conf.Valid = true + + if conf.Enable { + conf.EnableTime = time.Now() + } else { + conf.EnableTime = time.Time{} + } + + err := saveValue(tx, tblNameRoutingV2, conf.ID, conf) + if err != nil { + log.Errorf("[Store][boltdb] add routing config v2 to kv error, %v", err) + return err + } + return nil +} + +// UpdateRoutingConfigV2 更新一个路由配置 +func (r *routingStoreV2) UpdateRoutingConfigV2(conf *v2.RoutingConfig) error { + if conf.ID == "" || conf.Revision == "" { + log.Errorf("[Store][boltdb] update routing config v2 missing id or revision") + return store.NewStatusError(store.EmptyParamsErr, "missing id or revision") + } + if conf.Policy == "" || conf.Config == "" { + log.Errorf("[Store][boltdb] create routing config v2 missing params") + return store.NewStatusError(store.EmptyParamsErr, "missing some params") + } + + return r.handler.Execute(true, func(tx *bolt.Tx) error { + return r.updateRoutingConfigV2Tx(tx, conf) + }) +} + +func (r *routingStoreV2) UpdateRoutingConfigV2Tx(tx store.Tx, conf *v2.RoutingConfig) error { + if tx == nil { + return errors.New("tx is nil") + } + + dbTx := tx.GetDelegateTx().(*bolt.Tx) + return r.updateRoutingConfigV2Tx(dbTx, conf) +} + +func (r *routingStoreV2) updateRoutingConfigV2Tx(tx *bolt.Tx, conf *v2.RoutingConfig) error { + properties := make(map[string]interface{}) + properties[routingV2FieldEnable] = conf.Enable + properties[routingV2FieldName] = conf.Name + properties[routingV2FieldPolicy] = conf.Policy + properties[routingV2FieldConfig] = conf.Config + properties[routingV2FieldPriority] = conf.Priority + properties[routingV2FieldRevision] = conf.Revision + properties[routingV2FieldDescription] = conf.Description + properties[routingV2FieldModifyTime] = time.Now() + + err := updateValue(tx, tblNameRoutingV2, conf.ID, properties) + if err != nil { + log.Errorf("[Store][boltdb] update route config v2 to kv error, %v", err) + return err + } + return nil +} + +// EnableRouting +func (r *routingStoreV2) EnableRouting(conf *v2.RoutingConfig) error { + if conf.ID == "" || conf.Revision == "" { + return errors.New("[Store][database] enable routing config v2 missing some params") + } + + if conf.Enable { + conf.EnableTime = time.Now() + } else { + conf.EnableTime = time.Time{} + } + + properties := make(map[string]interface{}) + properties[routingV2FieldEnable] = conf.Enable + properties[routingV2FieldEnableTime] = conf.EnableTime + properties[routingV2FieldRevision] = conf.Revision + properties[routingV2FieldModifyTime] = time.Now() + + err := r.handler.UpdateValue(tblNameRoutingV2, conf.ID, properties) + if err != nil { + log.Errorf("[Store][boltdb] enable route config v2 to kv error, %v", err) + return err + } + return nil +} + +// DeleteRoutingConfigV2 删除一个路由配置 +func (r *routingStoreV2) DeleteRoutingConfigV2(ruleID string) error { + if ruleID == "" { + log.Errorf("[Store][boltdb] update routing config v2 missing id") + return store.NewStatusError(store.EmptyParamsErr, "missing id") + } + properties := make(map[string]interface{}) + properties[routingV2FieldValid] = false + properties[routingV2FieldModifyTime] = time.Now() + + err := r.handler.UpdateValue(tblNameRoutingV2, ruleID, properties) + if err != nil { + log.Errorf("[Store][boltdb] update route config v2 to kv error, %v", err) + return err + } + return nil +} + +// GetRoutingConfigsV2ForCache 通过mtime拉取增量的路由配置信息 +// 此方法用于 cache 增量更新,需要注意 mtime 应为数据库时间戳 +func (r *routingStoreV2) GetRoutingConfigsV2ForCache(mtime time.Time, firstUpdate bool) ([]*v2.RoutingConfig, error) { + if firstUpdate { + mtime = time.Time{} + } + + fields := []string{routingV2FieldModifyTime} + + routes, err := r.handler.LoadValuesByFilter(tblNameRoutingV2, fields, &v2.RoutingConfig{}, + func(m map[string]interface{}) bool { + rMtime, ok := m[routingV2FieldModifyTime] + if !ok { + return false + } + routeMtime := rMtime.(time.Time) + return !routeMtime.Before(mtime) + }) + if err != nil { + log.Errorf("[Store][boltdb] load route config v2 from kv error, %v", err) + return nil, err + } + + return toRouteConfV2(routes), nil +} + +func toRouteConfV2(m map[string]interface{}) []*v2.RoutingConfig { + var routeConf []*v2.RoutingConfig + for _, r := range m { + routeConf = append(routeConf, r.(*v2.RoutingConfig)) + } + + return routeConf +} + +// GetRoutingConfigV2WithID 根据服务ID拉取路由配置 +func (r *routingStoreV2) GetRoutingConfigV2WithID(id string) (*v2.RoutingConfig, error) { + tx, err := r.handler.StartTx() + if err != nil { + return nil, err + } + + boldTx := tx.GetDelegateTx().(*bolt.Tx) + defer boldTx.Rollback() + + return r.getRoutingConfigV2WithIDTx(boldTx, id) +} + +// GetRoutingConfigV2WithID 根据服务ID拉取路由配置 +func (r *routingStoreV2) GetRoutingConfigV2WithIDTx(tx store.Tx, id string) (*v2.RoutingConfig, error) { + + if tx == nil { + return nil, errors.New("tx is nil") + } + + boldTx := tx.GetDelegateTx().(*bolt.Tx) + return r.getRoutingConfigV2WithIDTx(boldTx, id) +} + +func (r *routingStoreV2) getRoutingConfigV2WithIDTx(tx *bolt.Tx, id string) (*v2.RoutingConfig, error) { + ret := make(map[string]interface{}) + if err := loadValues(tx, tblNameRoutingV2, []string{id}, &v2.RoutingConfig{}, ret); err != nil { + log.Error("[Store][boltdb] load route config v2 from kv", zap.String("routing-id", id), zap.Error(err)) + return nil, err + } + + if len(ret) == 0 { + return nil, nil + } + + if len(ret) > 1 { + return nil, MultipleRoutingV2Found + } + + val := ret[id].(*v2.RoutingConfig) + if !val.Valid { + return nil, nil + } + + return val, nil +} diff --git a/store/boltdb/routing_test.go b/store/boltdb/routing_test.go index d8d6caef3..ee48aaca8 100644 --- a/store/boltdb/routing_test.go +++ b/store/boltdb/routing_test.go @@ -221,7 +221,7 @@ func TestRoutingStore_GetRoutingConfigWithService(t *testing.T) { if err != nil { t.Fatal(err) } - fmt.Printf("get routing config with service %+v", rc) + t.Logf("get routing config with service %+v", rc) } func TestRoutingStore_GetRoutingConfigWithID(t *testing.T) { diff --git a/store/boltdb/strategy.go b/store/boltdb/strategy.go index b473fc270..f62cfc06c 100644 --- a/store/boltdb/strategy.go +++ b/store/boltdb/strategy.go @@ -165,6 +165,8 @@ func (ss *strategyStore) updateStrategy(tx *bolt.Tx, modify *model.ModifyStrateg computeResources(false, modify.AddResources, saveVal) computeResources(true, modify.RemoveResources, saveVal) + saveVal.ModifyTime = time.Now() + if err := saveValue(tx, tblStrategy, saveVal.ID, saveVal); err != nil { logger.StoreScope().Error("[Store][Strategy] update auth_strategy", zap.Error(err), zap.String("id", saveVal.ID)) @@ -279,6 +281,7 @@ func (ss *strategyStore) operateStrategyResources(remove bool, resources []model } computeResources(remove, ress, rule) + rule.ModifyTime = time.Now() if err := saveValue(tx, tblStrategy, rule.ID, rule); err != nil { logger.StoreScope().Error("[Store][Strategy] operate strategy resource", zap.Error(err), zap.Bool("remove", remove), zap.String("id", id)) diff --git a/store/boltdb/tool.go b/store/boltdb/tool.go index c5ae5c156..61777f43d 100644 --- a/store/boltdb/tool.go +++ b/store/boltdb/tool.go @@ -23,7 +23,7 @@ import "time" type toolStore struct { } -// GetNow 获取当前时间,单位秒 +// GetUnixSecond 获取当前时间,单位秒 func (t *toolStore) GetUnixSecond() (int64, error) { return time.Now().Unix(), nil } diff --git a/store/boltdb/user.go b/store/boltdb/user.go index ef4fc0c52..633469d5b 100644 --- a/store/boltdb/user.go +++ b/store/boltdb/user.go @@ -141,6 +141,8 @@ func (us *userStore) UpdateUser(user *model.User) error { properties[UserFieldComment] = user.Comment properties[UserFieldToken] = user.Token properties[UserFieldTokenEnable] = user.TokenEnable + properties[UserFieldEmail] = user.Email + properties[UserFieldMobile] = user.Mobile properties[UserFieldPassword] = user.Password properties[UserFieldModifyTime] = time.Now() diff --git a/store/discover_api.go b/store/discover_api.go index 0debbfa42..e7878ba9c 100644 --- a/store/discover_api.go +++ b/store/discover_api.go @@ -21,45 +21,37 @@ import ( "time" "github.com/polarismesh/polaris-server/common/model" + v2 "github.com/polarismesh/polaris-server/common/model/v2" ) // NamingModuleStore Service discovery, governance center module storage interface type NamingModuleStore interface { // BusinessStore 服务业务集接口 BusinessStore - // ServiceStore 服务接口 ServiceStore - // InstanceStore 实例接口 InstanceStore - // RoutingConfigStore 路由配置接口 RoutingConfigStore - // L5Store L5扩展接口 L5Store - // RateLimitStore 限流规则接口 RateLimitStore - // RateLimitStore 熔断规则接口 CircuitBreakerStore - // PlatformStore 平台信息接口 PlatformStore - // ToolStore 函数及工具接口 ToolStore - // UserStore 用户接口 UserStore - // GroupStore 用户组接口 GroupStore - // StrategyStore 鉴权策略接口 StrategyStore + // RoutingConfigStoreV2 路由策略 v2 接口 + RoutingConfigStoreV2 } // BusinessStore 业务集存储接口 @@ -220,23 +212,19 @@ type L5Store interface { type RoutingConfigStore interface { // CreateRoutingConfig 新增一个路由配置 CreateRoutingConfig(conf *model.RoutingConfig) error - // UpdateRoutingConfig 更新一个路由配置 UpdateRoutingConfig(conf *model.RoutingConfig) error - // DeleteRoutingConfig 删除一个路由配置 DeleteRoutingConfig(serviceID string) error - + // DeleteRoutingConfigTx 删除一个路由配置 + DeleteRoutingConfigTx(tx Tx, serviceID string) error // GetRoutingConfigsForCache 通过mtime拉取增量的路由配置信息 // 此方法用于 cache 增量更新,需要注意 mtime 应为数据库时间戳 GetRoutingConfigsForCache(mtime time.Time, firstUpdate bool) ([]*model.RoutingConfig, error) - // GetRoutingConfigWithService 根据服务名和命名空间拉取路由配置 GetRoutingConfigWithService(name string, namespace string) (*model.RoutingConfig, error) - // GetRoutingConfigWithID 根据服务ID拉取路由配置 GetRoutingConfigWithID(id string) (*model.RoutingConfig, error) - // GetRoutingConfigs 查询路由配置列表 GetRoutingConfigs(filter map[string]string, offset uint32, limit uint32) (uint32, []*model.ExtendRoutingConfig, error) } @@ -337,14 +325,34 @@ type PlatformStore interface { // ClientStore store interface for client info type ClientStore interface { - // BatchAddClients insert the client info BatchAddClients(clients []*model.Client) error - // BatchDeleteClients delete the client info BatchDeleteClients(ids []string) error - // GetMoreClients 根据mtime获取增量clients,返回所有store的变更信息 // 此方法用于 cache 增量更新,需要注意 mtime 应为数据库时间戳 GetMoreClients(mtime time.Time, firstUpdate bool) (map[string]*model.Client, error) } + +// RoutingConfigStoreV2 路由配置表的存储接口 +type RoutingConfigStoreV2 interface { + // EnableRouting 设置路由规则是否启用 + EnableRouting(conf *v2.RoutingConfig) error + // CreateRoutingConfigV2 新增一个路由配置 + CreateRoutingConfigV2(conf *v2.RoutingConfig) error + // CreateRoutingConfigV2Tx 新增一个路由配置 + CreateRoutingConfigV2Tx(tx Tx, conf *v2.RoutingConfig) error + // UpdateRoutingConfigV2 更新一个路由配置 + UpdateRoutingConfigV2(conf *v2.RoutingConfig) error + // UpdateRoutingConfigV2Tx 更新一个路由配置 + UpdateRoutingConfigV2Tx(tx Tx, conf *v2.RoutingConfig) error + // DeleteRoutingConfigV2 删除一个路由配置 + DeleteRoutingConfigV2(serviceID string) error + // GetRoutingConfigsV2ForCache 通过mtime拉取增量的路由配置信息 + // 此方法用于 cache 增量更新,需要注意 mtime 应为数据库时间戳 + GetRoutingConfigsV2ForCache(mtime time.Time, firstUpdate bool) ([]*v2.RoutingConfig, error) + // GetRoutingConfigV2WithID 根据服务ID拉取路由配置 + GetRoutingConfigV2WithID(id string) (*v2.RoutingConfig, error) + // GetRoutingConfigV2WithIDTx 根据服务ID拉取路由配置 + GetRoutingConfigV2WithIDTx(tx Tx, id string) (*v2.RoutingConfig, error) +} diff --git a/store/mock/api_mock.go b/store/mock/api_mock.go index 162a7d1c8..33f4979bb 100644 --- a/store/mock/api_mock.go +++ b/store/mock/api_mock.go @@ -5,946 +5,1060 @@ package mock import ( - reflect "reflect" - time "time" - gomock "github.com/golang/mock/gomock" - model "github.com/polarismesh/polaris-server/common/model" + v2 "github.com/polarismesh/polaris-server/common/model/v2" store "github.com/polarismesh/polaris-server/store" + reflect "reflect" + time "time" ) -// MockStore is a mock of Store interface. +// MockStore is a mock of Store interface type MockStore struct { ctrl *gomock.Controller recorder *MockStoreMockRecorder } -// MockStoreMockRecorder is the mock recorder for MockStore. +// MockStoreMockRecorder is the mock recorder for MockStore type MockStoreMockRecorder struct { mock *MockStore } -// NewMockStore creates a new mock instance. +// NewMockStore creates a new mock instance func NewMockStore(ctrl *gomock.Controller) *MockStore { mock := &MockStore{ctrl: ctrl} mock.recorder = &MockStoreMockRecorder{mock} return mock } -// EXPECT returns an object that allows the caller to indicate expected use. +// EXPECT returns an object that allows the caller to indicate expected use func (m *MockStore) EXPECT() *MockStoreMockRecorder { return m.recorder } -// AddBusiness mocks base method. -func (m *MockStore) AddBusiness(business *model.Business) error { +// Name mocks base method +func (m *MockStore) Name() string { m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "AddBusiness", business) - ret0, _ := ret[0].(error) + ret := m.ctrl.Call(m, "Name") + ret0, _ := ret[0].(string) return ret0 } -// AddBusiness indicates an expected call of AddBusiness. -func (mr *MockStoreMockRecorder) AddBusiness(business interface{}) *gomock.Call { +// Name indicates an expected call of Name +func (mr *MockStoreMockRecorder) Name() *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "AddBusiness", reflect.TypeOf((*MockStore)(nil).AddBusiness), business) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Name", reflect.TypeOf((*MockStore)(nil).Name)) } -// AddGroup mocks base method. -func (m *MockStore) AddGroup(group *model.UserGroupDetail) error { +// Initialize mocks base method +func (m *MockStore) Initialize(c *store.Config) error { m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "AddGroup", group) + ret := m.ctrl.Call(m, "Initialize", c) ret0, _ := ret[0].(error) return ret0 } -// AddGroup indicates an expected call of AddGroup. -func (mr *MockStoreMockRecorder) AddGroup(group interface{}) *gomock.Call { +// Initialize indicates an expected call of Initialize +func (mr *MockStoreMockRecorder) Initialize(c interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "AddGroup", reflect.TypeOf((*MockStore)(nil).AddGroup), group) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Initialize", reflect.TypeOf((*MockStore)(nil).Initialize), c) } -// AddInstance mocks base method. -func (m *MockStore) AddInstance(instance *model.Instance) error { +// Destroy mocks base method +func (m *MockStore) Destroy() error { m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "AddInstance", instance) + ret := m.ctrl.Call(m, "Destroy") ret0, _ := ret[0].(error) return ret0 } -// AddInstance indicates an expected call of AddInstance. -func (mr *MockStoreMockRecorder) AddInstance(instance interface{}) *gomock.Call { +// Destroy indicates an expected call of Destroy +func (mr *MockStoreMockRecorder) Destroy() *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "AddInstance", reflect.TypeOf((*MockStore)(nil).AddInstance), instance) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Destroy", reflect.TypeOf((*MockStore)(nil).Destroy)) } -// AddNamespace mocks base method. -func (m *MockStore) AddNamespace(namespace *model.Namespace) error { +// CreateTransaction mocks base method +func (m *MockStore) CreateTransaction() (store.Transaction, error) { m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "AddNamespace", namespace) - ret0, _ := ret[0].(error) - return ret0 + ret := m.ctrl.Call(m, "CreateTransaction") + ret0, _ := ret[0].(store.Transaction) + ret1, _ := ret[1].(error) + return ret0, ret1 } -// AddNamespace indicates an expected call of AddNamespace. -func (mr *MockStoreMockRecorder) AddNamespace(namespace interface{}) *gomock.Call { +// CreateTransaction indicates an expected call of CreateTransaction +func (mr *MockStoreMockRecorder) CreateTransaction() *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "AddNamespace", reflect.TypeOf((*MockStore)(nil).AddNamespace), namespace) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "CreateTransaction", reflect.TypeOf((*MockStore)(nil).CreateTransaction)) } -// AddService mocks base method. -func (m *MockStore) AddService(service *model.Service) error { +// StartTx mocks base method +func (m *MockStore) StartTx() (store.Tx, error) { m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "AddService", service) - ret0, _ := ret[0].(error) - return ret0 + ret := m.ctrl.Call(m, "StartTx") + ret0, _ := ret[0].(store.Tx) + ret1, _ := ret[1].(error) + return ret0, ret1 } -// AddService indicates an expected call of AddService. -func (mr *MockStoreMockRecorder) AddService(service interface{}) *gomock.Call { +// StartTx indicates an expected call of StartTx +func (mr *MockStoreMockRecorder) StartTx() *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "AddService", reflect.TypeOf((*MockStore)(nil).AddService), service) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "StartTx", reflect.TypeOf((*MockStore)(nil).StartTx)) } -// AddStrategy mocks base method. -func (m *MockStore) AddStrategy(strategy *model.StrategyDetail) error { +// AddNamespace mocks base method +func (m *MockStore) AddNamespace(namespace *model.Namespace) error { m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "AddStrategy", strategy) + ret := m.ctrl.Call(m, "AddNamespace", namespace) ret0, _ := ret[0].(error) return ret0 } -// AddStrategy indicates an expected call of AddStrategy. -func (mr *MockStoreMockRecorder) AddStrategy(strategy interface{}) *gomock.Call { +// AddNamespace indicates an expected call of AddNamespace +func (mr *MockStoreMockRecorder) AddNamespace(namespace interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "AddStrategy", reflect.TypeOf((*MockStore)(nil).AddStrategy), strategy) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "AddNamespace", reflect.TypeOf((*MockStore)(nil).AddNamespace), namespace) } -// AddUser mocks base method. -func (m *MockStore) AddUser(user *model.User) error { +// UpdateNamespace mocks base method +func (m *MockStore) UpdateNamespace(namespace *model.Namespace) error { m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "AddUser", user) + ret := m.ctrl.Call(m, "UpdateNamespace", namespace) ret0, _ := ret[0].(error) return ret0 } -// AddUser indicates an expected call of AddUser. -func (mr *MockStoreMockRecorder) AddUser(user interface{}) *gomock.Call { +// UpdateNamespace indicates an expected call of UpdateNamespace +func (mr *MockStoreMockRecorder) UpdateNamespace(namespace interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "AddUser", reflect.TypeOf((*MockStore)(nil).AddUser), user) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "UpdateNamespace", reflect.TypeOf((*MockStore)(nil).UpdateNamespace), namespace) } -// BatchAddClients mocks base method. -func (m *MockStore) BatchAddClients(clients []*model.Client) error { +// UpdateNamespaceToken mocks base method +func (m *MockStore) UpdateNamespaceToken(name, token string) error { m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "BatchAddClients", clients) + ret := m.ctrl.Call(m, "UpdateNamespaceToken", name, token) ret0, _ := ret[0].(error) return ret0 } -// BatchAddClients indicates an expected call of BatchAddClients. -func (mr *MockStoreMockRecorder) BatchAddClients(clients interface{}) *gomock.Call { +// UpdateNamespaceToken indicates an expected call of UpdateNamespaceToken +func (mr *MockStoreMockRecorder) UpdateNamespaceToken(name, token interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "BatchAddClients", reflect.TypeOf((*MockStore)(nil).BatchAddClients), clients) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "UpdateNamespaceToken", reflect.TypeOf((*MockStore)(nil).UpdateNamespaceToken), name, token) } -// BatchAddInstances mocks base method. -func (m *MockStore) BatchAddInstances(instances []*model.Instance) error { +// ListNamespaces mocks base method +func (m *MockStore) ListNamespaces(owner string) ([]*model.Namespace, error) { m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "BatchAddInstances", instances) - ret0, _ := ret[0].(error) - return ret0 + ret := m.ctrl.Call(m, "ListNamespaces", owner) + ret0, _ := ret[0].([]*model.Namespace) + ret1, _ := ret[1].(error) + return ret0, ret1 } -// BatchAddInstances indicates an expected call of BatchAddInstances. -func (mr *MockStoreMockRecorder) BatchAddInstances(instances interface{}) *gomock.Call { +// ListNamespaces indicates an expected call of ListNamespaces +func (mr *MockStoreMockRecorder) ListNamespaces(owner interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "BatchAddInstances", reflect.TypeOf((*MockStore)(nil).BatchAddInstances), instances) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ListNamespaces", reflect.TypeOf((*MockStore)(nil).ListNamespaces), owner) } -// BatchDeleteClients mocks base method. -func (m *MockStore) BatchDeleteClients(ids []string) error { +// GetNamespace mocks base method +func (m *MockStore) GetNamespace(name string) (*model.Namespace, error) { m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "BatchDeleteClients", ids) - ret0, _ := ret[0].(error) - return ret0 + ret := m.ctrl.Call(m, "GetNamespace", name) + ret0, _ := ret[0].(*model.Namespace) + ret1, _ := ret[1].(error) + return ret0, ret1 } -// BatchDeleteClients indicates an expected call of BatchDeleteClients. -func (mr *MockStoreMockRecorder) BatchDeleteClients(ids interface{}) *gomock.Call { +// GetNamespace indicates an expected call of GetNamespace +func (mr *MockStoreMockRecorder) GetNamespace(name interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "BatchDeleteClients", reflect.TypeOf((*MockStore)(nil).BatchDeleteClients), ids) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetNamespace", reflect.TypeOf((*MockStore)(nil).GetNamespace), name) } -// BatchDeleteInstances mocks base method. -func (m *MockStore) BatchDeleteInstances(ids []interface{}) error { +// GetNamespaces mocks base method +func (m *MockStore) GetNamespaces(filter map[string][]string, offset, limit int) ([]*model.Namespace, uint32, error) { m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "BatchDeleteInstances", ids) - ret0, _ := ret[0].(error) - return ret0 + ret := m.ctrl.Call(m, "GetNamespaces", filter, offset, limit) + ret0, _ := ret[0].([]*model.Namespace) + ret1, _ := ret[1].(uint32) + ret2, _ := ret[2].(error) + return ret0, ret1, ret2 } -// BatchDeleteInstances indicates an expected call of BatchDeleteInstances. -func (mr *MockStoreMockRecorder) BatchDeleteInstances(ids interface{}) *gomock.Call { +// GetNamespaces indicates an expected call of GetNamespaces +func (mr *MockStoreMockRecorder) GetNamespaces(filter, offset, limit interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "BatchDeleteInstances", reflect.TypeOf((*MockStore)(nil).BatchDeleteInstances), ids) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetNamespaces", reflect.TypeOf((*MockStore)(nil).GetNamespaces), filter, offset, limit) } -// BatchGetInstanceIsolate mocks base method. -func (m *MockStore) BatchGetInstanceIsolate(ids map[string]bool) (map[string]bool, error) { +// GetMoreNamespaces mocks base method +func (m *MockStore) GetMoreNamespaces(mtime time.Time) ([]*model.Namespace, error) { m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "BatchGetInstanceIsolate", ids) - ret0, _ := ret[0].(map[string]bool) + ret := m.ctrl.Call(m, "GetMoreNamespaces", mtime) + ret0, _ := ret[0].([]*model.Namespace) ret1, _ := ret[1].(error) return ret0, ret1 } -// BatchGetInstanceIsolate indicates an expected call of BatchGetInstanceIsolate. -func (mr *MockStoreMockRecorder) BatchGetInstanceIsolate(ids interface{}) *gomock.Call { +// GetMoreNamespaces indicates an expected call of GetMoreNamespaces +func (mr *MockStoreMockRecorder) GetMoreNamespaces(mtime interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "BatchGetInstanceIsolate", reflect.TypeOf((*MockStore)(nil).BatchGetInstanceIsolate), ids) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetMoreNamespaces", reflect.TypeOf((*MockStore)(nil).GetMoreNamespaces), mtime) } -// BatchSetInstanceHealthStatus mocks base method. -func (m *MockStore) BatchSetInstanceHealthStatus(ids []interface{}, healthy int, revision string) error { +// AddBusiness mocks base method +func (m *MockStore) AddBusiness(business *model.Business) error { m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "BatchSetInstanceHealthStatus", ids, healthy, revision) + ret := m.ctrl.Call(m, "AddBusiness", business) ret0, _ := ret[0].(error) return ret0 } -// BatchSetInstanceHealthStatus indicates an expected call of BatchSetInstanceHealthStatus. -func (mr *MockStoreMockRecorder) BatchSetInstanceHealthStatus(ids, healthy, revision interface{}) *gomock.Call { +// AddBusiness indicates an expected call of AddBusiness +func (mr *MockStoreMockRecorder) AddBusiness(business interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "BatchSetInstanceHealthStatus", reflect.TypeOf((*MockStore)(nil).BatchSetInstanceHealthStatus), ids, healthy, revision) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "AddBusiness", reflect.TypeOf((*MockStore)(nil).AddBusiness), business) } -// BatchSetInstanceIsolate mocks base method. -func (m *MockStore) BatchSetInstanceIsolate(ids []interface{}, isolate int, revision string) error { +// DeleteBusiness mocks base method +func (m *MockStore) DeleteBusiness(bid string) error { m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "BatchSetInstanceIsolate", ids, isolate, revision) + ret := m.ctrl.Call(m, "DeleteBusiness", bid) ret0, _ := ret[0].(error) return ret0 } -// BatchSetInstanceIsolate indicates an expected call of BatchSetInstanceIsolate. -func (mr *MockStoreMockRecorder) BatchSetInstanceIsolate(ids, isolate, revision interface{}) *gomock.Call { +// DeleteBusiness indicates an expected call of DeleteBusiness +func (mr *MockStoreMockRecorder) DeleteBusiness(bid interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "BatchSetInstanceIsolate", reflect.TypeOf((*MockStore)(nil).BatchSetInstanceIsolate), ids, isolate, revision) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "DeleteBusiness", reflect.TypeOf((*MockStore)(nil).DeleteBusiness), bid) } -// CleanInstance mocks base method. -func (m *MockStore) CleanInstance(instanceID string) error { +// UpdateBusiness mocks base method +func (m *MockStore) UpdateBusiness(business *model.Business) error { m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "CleanInstance", instanceID) + ret := m.ctrl.Call(m, "UpdateBusiness", business) ret0, _ := ret[0].(error) return ret0 } -// CleanInstance indicates an expected call of CleanInstance. -func (mr *MockStoreMockRecorder) CleanInstance(instanceID interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "CleanInstance", reflect.TypeOf((*MockStore)(nil).CleanInstance), instanceID) -} - -// CountByConfigFileGroup mocks base method. -func (m *MockStore) CountByConfigFileGroup(namespace, group string) (uint64, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "CountByConfigFileGroup", namespace, group) - ret0, _ := ret[0].(uint64) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// CountByConfigFileGroup indicates an expected call of CountByConfigFileGroup. -func (mr *MockStoreMockRecorder) CountByConfigFileGroup(namespace, group interface{}) *gomock.Call { +// UpdateBusiness indicates an expected call of UpdateBusiness +func (mr *MockStoreMockRecorder) UpdateBusiness(business interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "CountByConfigFileGroup", reflect.TypeOf((*MockStore)(nil).CountByConfigFileGroup), namespace, group) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "UpdateBusiness", reflect.TypeOf((*MockStore)(nil).UpdateBusiness), business) } -// CreateCircuitBreaker mocks base method. -func (m *MockStore) CreateCircuitBreaker(circuitBreaker *model.CircuitBreaker) error { +// UpdateBusinessToken mocks base method +func (m *MockStore) UpdateBusinessToken(bid, token string) error { m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "CreateCircuitBreaker", circuitBreaker) + ret := m.ctrl.Call(m, "UpdateBusinessToken", bid, token) ret0, _ := ret[0].(error) return ret0 } -// CreateCircuitBreaker indicates an expected call of CreateCircuitBreaker. -func (mr *MockStoreMockRecorder) CreateCircuitBreaker(circuitBreaker interface{}) *gomock.Call { +// UpdateBusinessToken indicates an expected call of UpdateBusinessToken +func (mr *MockStoreMockRecorder) UpdateBusinessToken(bid, token interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "CreateCircuitBreaker", reflect.TypeOf((*MockStore)(nil).CreateCircuitBreaker), circuitBreaker) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "UpdateBusinessToken", reflect.TypeOf((*MockStore)(nil).UpdateBusinessToken), bid, token) } -// CreateConfigFile mocks base method. -func (m *MockStore) CreateConfigFile(tx store.Tx, file *model.ConfigFile) (*model.ConfigFile, error) { +// ListBusiness mocks base method +func (m *MockStore) ListBusiness(owner string) ([]*model.Business, error) { m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "CreateConfigFile", tx, file) - ret0, _ := ret[0].(*model.ConfigFile) + ret := m.ctrl.Call(m, "ListBusiness", owner) + ret0, _ := ret[0].([]*model.Business) ret1, _ := ret[1].(error) return ret0, ret1 } -// CreateConfigFile indicates an expected call of CreateConfigFile. -func (mr *MockStoreMockRecorder) CreateConfigFile(tx, file interface{}) *gomock.Call { +// ListBusiness indicates an expected call of ListBusiness +func (mr *MockStoreMockRecorder) ListBusiness(owner interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "CreateConfigFile", reflect.TypeOf((*MockStore)(nil).CreateConfigFile), tx, file) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ListBusiness", reflect.TypeOf((*MockStore)(nil).ListBusiness), owner) } -// CreateConfigFileGroup mocks base method. -func (m *MockStore) CreateConfigFileGroup(fileGroup *model.ConfigFileGroup) (*model.ConfigFileGroup, error) { +// GetBusinessByID mocks base method +func (m *MockStore) GetBusinessByID(id string) (*model.Business, error) { m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "CreateConfigFileGroup", fileGroup) - ret0, _ := ret[0].(*model.ConfigFileGroup) + ret := m.ctrl.Call(m, "GetBusinessByID", id) + ret0, _ := ret[0].(*model.Business) ret1, _ := ret[1].(error) return ret0, ret1 } -// CreateConfigFileGroup indicates an expected call of CreateConfigFileGroup. -func (mr *MockStoreMockRecorder) CreateConfigFileGroup(fileGroup interface{}) *gomock.Call { +// GetBusinessByID indicates an expected call of GetBusinessByID +func (mr *MockStoreMockRecorder) GetBusinessByID(id interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "CreateConfigFileGroup", reflect.TypeOf((*MockStore)(nil).CreateConfigFileGroup), fileGroup) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetBusinessByID", reflect.TypeOf((*MockStore)(nil).GetBusinessByID), id) } -// CreateConfigFileRelease mocks base method. -func (m *MockStore) CreateConfigFileRelease(tx store.Tx, fileRelease *model.ConfigFileRelease) (*model.ConfigFileRelease, error) { +// GetMoreBusiness mocks base method +func (m *MockStore) GetMoreBusiness(mtime time.Time) ([]*model.Business, error) { m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "CreateConfigFileRelease", tx, fileRelease) - ret0, _ := ret[0].(*model.ConfigFileRelease) + ret := m.ctrl.Call(m, "GetMoreBusiness", mtime) + ret0, _ := ret[0].([]*model.Business) ret1, _ := ret[1].(error) return ret0, ret1 } -// CreateConfigFileRelease indicates an expected call of CreateConfigFileRelease. -func (mr *MockStoreMockRecorder) CreateConfigFileRelease(tx, fileRelease interface{}) *gomock.Call { +// GetMoreBusiness indicates an expected call of GetMoreBusiness +func (mr *MockStoreMockRecorder) GetMoreBusiness(mtime interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "CreateConfigFileRelease", reflect.TypeOf((*MockStore)(nil).CreateConfigFileRelease), tx, fileRelease) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetMoreBusiness", reflect.TypeOf((*MockStore)(nil).GetMoreBusiness), mtime) } -// CreateConfigFileReleaseHistory mocks base method. -func (m *MockStore) CreateConfigFileReleaseHistory(tx store.Tx, fileReleaseHistory *model.ConfigFileReleaseHistory) error { +// AddService mocks base method +func (m *MockStore) AddService(service *model.Service) error { m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "CreateConfigFileReleaseHistory", tx, fileReleaseHistory) + ret := m.ctrl.Call(m, "AddService", service) ret0, _ := ret[0].(error) return ret0 } -// CreateConfigFileReleaseHistory indicates an expected call of CreateConfigFileReleaseHistory. -func (mr *MockStoreMockRecorder) CreateConfigFileReleaseHistory(tx, fileReleaseHistory interface{}) *gomock.Call { +// AddService indicates an expected call of AddService +func (mr *MockStoreMockRecorder) AddService(service interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "CreateConfigFileReleaseHistory", reflect.TypeOf((*MockStore)(nil).CreateConfigFileReleaseHistory), tx, fileReleaseHistory) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "AddService", reflect.TypeOf((*MockStore)(nil).AddService), service) } -// CreateConfigFileTag mocks base method. -func (m *MockStore) CreateConfigFileTag(tx store.Tx, fileTag *model.ConfigFileTag) error { +// DeleteService mocks base method +func (m *MockStore) DeleteService(id, serviceName, namespaceName string) error { m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "CreateConfigFileTag", tx, fileTag) + ret := m.ctrl.Call(m, "DeleteService", id, serviceName, namespaceName) ret0, _ := ret[0].(error) return ret0 } -// CreateConfigFileTag indicates an expected call of CreateConfigFileTag. -func (mr *MockStoreMockRecorder) CreateConfigFileTag(tx, fileTag interface{}) *gomock.Call { +// DeleteService indicates an expected call of DeleteService +func (mr *MockStoreMockRecorder) DeleteService(id, serviceName, namespaceName interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "CreateConfigFileTag", reflect.TypeOf((*MockStore)(nil).CreateConfigFileTag), tx, fileTag) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "DeleteService", reflect.TypeOf((*MockStore)(nil).DeleteService), id, serviceName, namespaceName) } -// CreateConfigFileTemplate mocks base method. -func (m *MockStore) CreateConfigFileTemplate(template *model.ConfigFileTemplate) (*model.ConfigFileTemplate, error) { +// DeleteServiceAlias mocks base method +func (m *MockStore) DeleteServiceAlias(name, namespace string) error { m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "CreateConfigFileTemplate", template) - ret0, _ := ret[0].(*model.ConfigFileTemplate) - ret1, _ := ret[1].(error) - return ret0, ret1 + ret := m.ctrl.Call(m, "DeleteServiceAlias", name, namespace) + ret0, _ := ret[0].(error) + return ret0 } -// CreateConfigFileTemplate indicates an expected call of CreateConfigFileTemplate. -func (mr *MockStoreMockRecorder) CreateConfigFileTemplate(template interface{}) *gomock.Call { +// DeleteServiceAlias indicates an expected call of DeleteServiceAlias +func (mr *MockStoreMockRecorder) DeleteServiceAlias(name, namespace interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "CreateConfigFileTemplate", reflect.TypeOf((*MockStore)(nil).CreateConfigFileTemplate), template) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "DeleteServiceAlias", reflect.TypeOf((*MockStore)(nil).DeleteServiceAlias), name, namespace) } -// CreatePlatform mocks base method. -func (m *MockStore) CreatePlatform(platform *model.Platform) error { +// UpdateServiceAlias mocks base method +func (m *MockStore) UpdateServiceAlias(alias *model.Service, needUpdateOwner bool) error { m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "CreatePlatform", platform) + ret := m.ctrl.Call(m, "UpdateServiceAlias", alias, needUpdateOwner) ret0, _ := ret[0].(error) return ret0 } -// CreatePlatform indicates an expected call of CreatePlatform. -func (mr *MockStoreMockRecorder) CreatePlatform(platform interface{}) *gomock.Call { +// UpdateServiceAlias indicates an expected call of UpdateServiceAlias +func (mr *MockStoreMockRecorder) UpdateServiceAlias(alias, needUpdateOwner interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "CreatePlatform", reflect.TypeOf((*MockStore)(nil).CreatePlatform), platform) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "UpdateServiceAlias", reflect.TypeOf((*MockStore)(nil).UpdateServiceAlias), alias, needUpdateOwner) } -// CreateRateLimit mocks base method. -func (m *MockStore) CreateRateLimit(limiting *model.RateLimit) error { +// UpdateService mocks base method +func (m *MockStore) UpdateService(service *model.Service, needUpdateOwner bool) error { m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "CreateRateLimit", limiting) + ret := m.ctrl.Call(m, "UpdateService", service, needUpdateOwner) ret0, _ := ret[0].(error) return ret0 } -// CreateRateLimit indicates an expected call of CreateRateLimit. -func (mr *MockStoreMockRecorder) CreateRateLimit(limiting interface{}) *gomock.Call { +// UpdateService indicates an expected call of UpdateService +func (mr *MockStoreMockRecorder) UpdateService(service, needUpdateOwner interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "CreateRateLimit", reflect.TypeOf((*MockStore)(nil).CreateRateLimit), limiting) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "UpdateService", reflect.TypeOf((*MockStore)(nil).UpdateService), service, needUpdateOwner) } -// CreateRoutingConfig mocks base method. -func (m *MockStore) CreateRoutingConfig(conf *model.RoutingConfig) error { +// UpdateServiceToken mocks base method +func (m *MockStore) UpdateServiceToken(serviceID, token, revision string) error { m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "CreateRoutingConfig", conf) + ret := m.ctrl.Call(m, "UpdateServiceToken", serviceID, token, revision) ret0, _ := ret[0].(error) return ret0 } -// CreateRoutingConfig indicates an expected call of CreateRoutingConfig. -func (mr *MockStoreMockRecorder) CreateRoutingConfig(conf interface{}) *gomock.Call { +// UpdateServiceToken indicates an expected call of UpdateServiceToken +func (mr *MockStoreMockRecorder) UpdateServiceToken(serviceID, token, revision interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "CreateRoutingConfig", reflect.TypeOf((*MockStore)(nil).CreateRoutingConfig), conf) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "UpdateServiceToken", reflect.TypeOf((*MockStore)(nil).UpdateServiceToken), serviceID, token, revision) } -// CreateTransaction mocks base method. -func (m *MockStore) CreateTransaction() (store.Transaction, error) { +// GetSourceServiceToken mocks base method +func (m *MockStore) GetSourceServiceToken(name, namespace string) (*model.Service, error) { m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "CreateTransaction") - ret0, _ := ret[0].(store.Transaction) + ret := m.ctrl.Call(m, "GetSourceServiceToken", name, namespace) + ret0, _ := ret[0].(*model.Service) ret1, _ := ret[1].(error) return ret0, ret1 } -// CreateTransaction indicates an expected call of CreateTransaction. -func (mr *MockStoreMockRecorder) CreateTransaction() *gomock.Call { +// GetSourceServiceToken indicates an expected call of GetSourceServiceToken +func (mr *MockStoreMockRecorder) GetSourceServiceToken(name, namespace interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "CreateTransaction", reflect.TypeOf((*MockStore)(nil).CreateTransaction)) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetSourceServiceToken", reflect.TypeOf((*MockStore)(nil).GetSourceServiceToken), name, namespace) } -// DeleteBusiness mocks base method. -func (m *MockStore) DeleteBusiness(bid string) error { +// GetService mocks base method +func (m *MockStore) GetService(name, namespace string) (*model.Service, error) { m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "DeleteBusiness", bid) - ret0, _ := ret[0].(error) - return ret0 + ret := m.ctrl.Call(m, "GetService", name, namespace) + ret0, _ := ret[0].(*model.Service) + ret1, _ := ret[1].(error) + return ret0, ret1 } -// DeleteBusiness indicates an expected call of DeleteBusiness. -func (mr *MockStoreMockRecorder) DeleteBusiness(bid interface{}) *gomock.Call { +// GetService indicates an expected call of GetService +func (mr *MockStoreMockRecorder) GetService(name, namespace interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "DeleteBusiness", reflect.TypeOf((*MockStore)(nil).DeleteBusiness), bid) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetService", reflect.TypeOf((*MockStore)(nil).GetService), name, namespace) } -// DeleteConfigFile mocks base method. -func (m *MockStore) DeleteConfigFile(tx store.Tx, namespace, group, name string) error { +// GetServiceByID mocks base method +func (m *MockStore) GetServiceByID(id string) (*model.Service, error) { m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "DeleteConfigFile", tx, namespace, group, name) - ret0, _ := ret[0].(error) - return ret0 + ret := m.ctrl.Call(m, "GetServiceByID", id) + ret0, _ := ret[0].(*model.Service) + ret1, _ := ret[1].(error) + return ret0, ret1 } -// DeleteConfigFile indicates an expected call of DeleteConfigFile. -func (mr *MockStoreMockRecorder) DeleteConfigFile(tx, namespace, group, name interface{}) *gomock.Call { +// GetServiceByID indicates an expected call of GetServiceByID +func (mr *MockStoreMockRecorder) GetServiceByID(id interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "DeleteConfigFile", reflect.TypeOf((*MockStore)(nil).DeleteConfigFile), tx, namespace, group, name) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetServiceByID", reflect.TypeOf((*MockStore)(nil).GetServiceByID), id) } -// DeleteConfigFileGroup mocks base method. -func (m *MockStore) DeleteConfigFileGroup(namespace, name string) error { +// GetServices mocks base method +func (m *MockStore) GetServices(serviceFilters, serviceMetas map[string]string, instanceFilters *store.InstanceArgs, offset, limit uint32) (uint32, []*model.Service, error) { m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "DeleteConfigFileGroup", namespace, name) - ret0, _ := ret[0].(error) - return ret0 + ret := m.ctrl.Call(m, "GetServices", serviceFilters, serviceMetas, instanceFilters, offset, limit) + ret0, _ := ret[0].(uint32) + ret1, _ := ret[1].([]*model.Service) + ret2, _ := ret[2].(error) + return ret0, ret1, ret2 } -// DeleteConfigFileGroup indicates an expected call of DeleteConfigFileGroup. -func (mr *MockStoreMockRecorder) DeleteConfigFileGroup(namespace, name interface{}) *gomock.Call { +// GetServices indicates an expected call of GetServices +func (mr *MockStoreMockRecorder) GetServices(serviceFilters, serviceMetas, instanceFilters, offset, limit interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "DeleteConfigFileGroup", reflect.TypeOf((*MockStore)(nil).DeleteConfigFileGroup), namespace, name) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetServices", reflect.TypeOf((*MockStore)(nil).GetServices), serviceFilters, serviceMetas, instanceFilters, offset, limit) } -// DeleteConfigFileRelease mocks base method. -func (m *MockStore) DeleteConfigFileRelease(tx store.Tx, namespace, group, fileName, deleteBy string) error { +// GetServicesCount mocks base method +func (m *MockStore) GetServicesCount() (uint32, error) { m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "DeleteConfigFileRelease", tx, namespace, group, fileName, deleteBy) - ret0, _ := ret[0].(error) - return ret0 + ret := m.ctrl.Call(m, "GetServicesCount") + ret0, _ := ret[0].(uint32) + ret1, _ := ret[1].(error) + return ret0, ret1 } -// DeleteConfigFileRelease indicates an expected call of DeleteConfigFileRelease. -func (mr *MockStoreMockRecorder) DeleteConfigFileRelease(tx, namespace, group, fileName, deleteBy interface{}) *gomock.Call { +// GetServicesCount indicates an expected call of GetServicesCount +func (mr *MockStoreMockRecorder) GetServicesCount() *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "DeleteConfigFileRelease", reflect.TypeOf((*MockStore)(nil).DeleteConfigFileRelease), tx, namespace, group, fileName, deleteBy) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetServicesCount", reflect.TypeOf((*MockStore)(nil).GetServicesCount)) } -// DeleteConfigFileTag mocks base method. -func (m *MockStore) DeleteConfigFileTag(tx store.Tx, namespace, group, fileName, key, value string) error { +// GetMoreServices mocks base method +func (m *MockStore) GetMoreServices(mtime time.Time, firstUpdate, disableBusiness, needMeta bool) (map[string]*model.Service, error) { m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "DeleteConfigFileTag", tx, namespace, group, fileName, key, value) - ret0, _ := ret[0].(error) - return ret0 + ret := m.ctrl.Call(m, "GetMoreServices", mtime, firstUpdate, disableBusiness, needMeta) + ret0, _ := ret[0].(map[string]*model.Service) + ret1, _ := ret[1].(error) + return ret0, ret1 } -// DeleteConfigFileTag indicates an expected call of DeleteConfigFileTag. -func (mr *MockStoreMockRecorder) DeleteConfigFileTag(tx, namespace, group, fileName, key, value interface{}) *gomock.Call { +// GetMoreServices indicates an expected call of GetMoreServices +func (mr *MockStoreMockRecorder) GetMoreServices(mtime, firstUpdate, disableBusiness, needMeta interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "DeleteConfigFileTag", reflect.TypeOf((*MockStore)(nil).DeleteConfigFileTag), tx, namespace, group, fileName, key, value) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetMoreServices", reflect.TypeOf((*MockStore)(nil).GetMoreServices), mtime, firstUpdate, disableBusiness, needMeta) } -// DeleteGroup mocks base method. -func (m *MockStore) DeleteGroup(group *model.UserGroupDetail) error { +// GetServiceAliases mocks base method +func (m *MockStore) GetServiceAliases(filter map[string]string, offset, limit uint32) (uint32, []*model.ServiceAlias, error) { m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "DeleteGroup", group) - ret0, _ := ret[0].(error) - return ret0 + ret := m.ctrl.Call(m, "GetServiceAliases", filter, offset, limit) + ret0, _ := ret[0].(uint32) + ret1, _ := ret[1].([]*model.ServiceAlias) + ret2, _ := ret[2].(error) + return ret0, ret1, ret2 } -// DeleteGroup indicates an expected call of DeleteGroup. -func (mr *MockStoreMockRecorder) DeleteGroup(group interface{}) *gomock.Call { +// GetServiceAliases indicates an expected call of GetServiceAliases +func (mr *MockStoreMockRecorder) GetServiceAliases(filter, offset, limit interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "DeleteGroup", reflect.TypeOf((*MockStore)(nil).DeleteGroup), group) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetServiceAliases", reflect.TypeOf((*MockStore)(nil).GetServiceAliases), filter, offset, limit) } -// DeleteInstance mocks base method. -func (m *MockStore) DeleteInstance(instanceID string) error { +// GetSystemServices mocks base method +func (m *MockStore) GetSystemServices() ([]*model.Service, error) { m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "DeleteInstance", instanceID) - ret0, _ := ret[0].(error) - return ret0 + ret := m.ctrl.Call(m, "GetSystemServices") + ret0, _ := ret[0].([]*model.Service) + ret1, _ := ret[1].(error) + return ret0, ret1 } -// DeleteInstance indicates an expected call of DeleteInstance. -func (mr *MockStoreMockRecorder) DeleteInstance(instanceID interface{}) *gomock.Call { +// GetSystemServices indicates an expected call of GetSystemServices +func (mr *MockStoreMockRecorder) GetSystemServices() *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "DeleteInstance", reflect.TypeOf((*MockStore)(nil).DeleteInstance), instanceID) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetSystemServices", reflect.TypeOf((*MockStore)(nil).GetSystemServices)) } -// DeleteMasterCircuitBreaker mocks base method. -func (m *MockStore) DeleteMasterCircuitBreaker(id string) error { +// GetServicesBatch mocks base method +func (m *MockStore) GetServicesBatch(services []*model.Service) ([]*model.Service, error) { m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "DeleteMasterCircuitBreaker", id) - ret0, _ := ret[0].(error) - return ret0 + ret := m.ctrl.Call(m, "GetServicesBatch", services) + ret0, _ := ret[0].([]*model.Service) + ret1, _ := ret[1].(error) + return ret0, ret1 } -// DeleteMasterCircuitBreaker indicates an expected call of DeleteMasterCircuitBreaker. -func (mr *MockStoreMockRecorder) DeleteMasterCircuitBreaker(id interface{}) *gomock.Call { +// GetServicesBatch indicates an expected call of GetServicesBatch +func (mr *MockStoreMockRecorder) GetServicesBatch(services interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "DeleteMasterCircuitBreaker", reflect.TypeOf((*MockStore)(nil).DeleteMasterCircuitBreaker), id) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetServicesBatch", reflect.TypeOf((*MockStore)(nil).GetServicesBatch), services) } -// DeletePlatform mocks base method. -func (m *MockStore) DeletePlatform(id string) error { +// AddInstance mocks base method +func (m *MockStore) AddInstance(instance *model.Instance) error { m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "DeletePlatform", id) + ret := m.ctrl.Call(m, "AddInstance", instance) ret0, _ := ret[0].(error) return ret0 } -// DeletePlatform indicates an expected call of DeletePlatform. -func (mr *MockStoreMockRecorder) DeletePlatform(id interface{}) *gomock.Call { +// AddInstance indicates an expected call of AddInstance +func (mr *MockStoreMockRecorder) AddInstance(instance interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "DeletePlatform", reflect.TypeOf((*MockStore)(nil).DeletePlatform), id) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "AddInstance", reflect.TypeOf((*MockStore)(nil).AddInstance), instance) } -// DeleteRateLimit mocks base method. -func (m *MockStore) DeleteRateLimit(limiting *model.RateLimit) error { +// BatchAddInstances mocks base method +func (m *MockStore) BatchAddInstances(instances []*model.Instance) error { m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "DeleteRateLimit", limiting) + ret := m.ctrl.Call(m, "BatchAddInstances", instances) ret0, _ := ret[0].(error) return ret0 } -// DeleteRateLimit indicates an expected call of DeleteRateLimit. -func (mr *MockStoreMockRecorder) DeleteRateLimit(limiting interface{}) *gomock.Call { +// BatchAddInstances indicates an expected call of BatchAddInstances +func (mr *MockStoreMockRecorder) BatchAddInstances(instances interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "DeleteRateLimit", reflect.TypeOf((*MockStore)(nil).DeleteRateLimit), limiting) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "BatchAddInstances", reflect.TypeOf((*MockStore)(nil).BatchAddInstances), instances) } -// DeleteRoutingConfig mocks base method. -func (m *MockStore) DeleteRoutingConfig(serviceID string) error { +// UpdateInstance mocks base method +func (m *MockStore) UpdateInstance(instance *model.Instance) error { m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "DeleteRoutingConfig", serviceID) + ret := m.ctrl.Call(m, "UpdateInstance", instance) ret0, _ := ret[0].(error) return ret0 } -// DeleteRoutingConfig indicates an expected call of DeleteRoutingConfig. -func (mr *MockStoreMockRecorder) DeleteRoutingConfig(serviceID interface{}) *gomock.Call { +// UpdateInstance indicates an expected call of UpdateInstance +func (mr *MockStoreMockRecorder) UpdateInstance(instance interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "DeleteRoutingConfig", reflect.TypeOf((*MockStore)(nil).DeleteRoutingConfig), serviceID) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "UpdateInstance", reflect.TypeOf((*MockStore)(nil).UpdateInstance), instance) } -// DeleteService mocks base method. -func (m *MockStore) DeleteService(id, serviceName, namespaceName string) error { +// DeleteInstance mocks base method +func (m *MockStore) DeleteInstance(instanceID string) error { m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "DeleteService", id, serviceName, namespaceName) + ret := m.ctrl.Call(m, "DeleteInstance", instanceID) ret0, _ := ret[0].(error) return ret0 } -// DeleteService indicates an expected call of DeleteService. -func (mr *MockStoreMockRecorder) DeleteService(id, serviceName, namespaceName interface{}) *gomock.Call { +// DeleteInstance indicates an expected call of DeleteInstance +func (mr *MockStoreMockRecorder) DeleteInstance(instanceID interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "DeleteService", reflect.TypeOf((*MockStore)(nil).DeleteService), id, serviceName, namespaceName) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "DeleteInstance", reflect.TypeOf((*MockStore)(nil).DeleteInstance), instanceID) } -// DeleteServiceAlias mocks base method. -func (m *MockStore) DeleteServiceAlias(name, namespace string) error { +// BatchDeleteInstances mocks base method +func (m *MockStore) BatchDeleteInstances(ids []interface{}) error { m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "DeleteServiceAlias", name, namespace) + ret := m.ctrl.Call(m, "BatchDeleteInstances", ids) ret0, _ := ret[0].(error) return ret0 } -// DeleteServiceAlias indicates an expected call of DeleteServiceAlias. -func (mr *MockStoreMockRecorder) DeleteServiceAlias(name, namespace interface{}) *gomock.Call { +// BatchDeleteInstances indicates an expected call of BatchDeleteInstances +func (mr *MockStoreMockRecorder) BatchDeleteInstances(ids interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "DeleteServiceAlias", reflect.TypeOf((*MockStore)(nil).DeleteServiceAlias), name, namespace) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "BatchDeleteInstances", reflect.TypeOf((*MockStore)(nil).BatchDeleteInstances), ids) } -// DeleteStrategy mocks base method. -func (m *MockStore) DeleteStrategy(id string) error { +// CleanInstance mocks base method +func (m *MockStore) CleanInstance(instanceID string) error { m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "DeleteStrategy", id) + ret := m.ctrl.Call(m, "CleanInstance", instanceID) ret0, _ := ret[0].(error) return ret0 } -// DeleteStrategy indicates an expected call of DeleteStrategy. -func (mr *MockStoreMockRecorder) DeleteStrategy(id interface{}) *gomock.Call { +// CleanInstance indicates an expected call of CleanInstance +func (mr *MockStoreMockRecorder) CleanInstance(instanceID interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "DeleteStrategy", reflect.TypeOf((*MockStore)(nil).DeleteStrategy), id) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "CleanInstance", reflect.TypeOf((*MockStore)(nil).CleanInstance), instanceID) } -// DeleteTagByConfigFile mocks base method. -func (m *MockStore) DeleteTagByConfigFile(tx store.Tx, namespace, group, fileName string) error { +// BatchGetInstanceIsolate mocks base method +func (m *MockStore) BatchGetInstanceIsolate(ids map[string]bool) (map[string]bool, error) { m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "DeleteTagByConfigFile", tx, namespace, group, fileName) - ret0, _ := ret[0].(error) - return ret0 + ret := m.ctrl.Call(m, "BatchGetInstanceIsolate", ids) + ret0, _ := ret[0].(map[string]bool) + ret1, _ := ret[1].(error) + return ret0, ret1 } -// DeleteTagByConfigFile indicates an expected call of DeleteTagByConfigFile. -func (mr *MockStoreMockRecorder) DeleteTagByConfigFile(tx, namespace, group, fileName interface{}) *gomock.Call { +// BatchGetInstanceIsolate indicates an expected call of BatchGetInstanceIsolate +func (mr *MockStoreMockRecorder) BatchGetInstanceIsolate(ids interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "DeleteTagByConfigFile", reflect.TypeOf((*MockStore)(nil).DeleteTagByConfigFile), tx, namespace, group, fileName) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "BatchGetInstanceIsolate", reflect.TypeOf((*MockStore)(nil).BatchGetInstanceIsolate), ids) } -// DeleteTagCircuitBreaker mocks base method. -func (m *MockStore) DeleteTagCircuitBreaker(id, version string) error { +// GetInstancesBrief mocks base method +func (m *MockStore) GetInstancesBrief(ids map[string]bool) (map[string]*model.Instance, error) { m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "DeleteTagCircuitBreaker", id, version) - ret0, _ := ret[0].(error) - return ret0 + ret := m.ctrl.Call(m, "GetInstancesBrief", ids) + ret0, _ := ret[0].(map[string]*model.Instance) + ret1, _ := ret[1].(error) + return ret0, ret1 } -// DeleteTagCircuitBreaker indicates an expected call of DeleteTagCircuitBreaker. -func (mr *MockStoreMockRecorder) DeleteTagCircuitBreaker(id, version interface{}) *gomock.Call { +// GetInstancesBrief indicates an expected call of GetInstancesBrief +func (mr *MockStoreMockRecorder) GetInstancesBrief(ids interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "DeleteTagCircuitBreaker", reflect.TypeOf((*MockStore)(nil).DeleteTagCircuitBreaker), id, version) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetInstancesBrief", reflect.TypeOf((*MockStore)(nil).GetInstancesBrief), ids) } -// DeleteUser mocks base method. -func (m *MockStore) DeleteUser(user *model.User) error { +// GetInstance mocks base method +func (m *MockStore) GetInstance(instanceID string) (*model.Instance, error) { m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "DeleteUser", user) - ret0, _ := ret[0].(error) - return ret0 + ret := m.ctrl.Call(m, "GetInstance", instanceID) + ret0, _ := ret[0].(*model.Instance) + ret1, _ := ret[1].(error) + return ret0, ret1 } -// DeleteUser indicates an expected call of DeleteUser. -func (mr *MockStoreMockRecorder) DeleteUser(user interface{}) *gomock.Call { +// GetInstance indicates an expected call of GetInstance +func (mr *MockStoreMockRecorder) GetInstance(instanceID interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "DeleteUser", reflect.TypeOf((*MockStore)(nil).DeleteUser), user) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetInstance", reflect.TypeOf((*MockStore)(nil).GetInstance), instanceID) } -// Destroy mocks base method. -func (m *MockStore) Destroy() error { +// GetInstancesCount mocks base method +func (m *MockStore) GetInstancesCount() (uint32, error) { m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "Destroy") - ret0, _ := ret[0].(error) - return ret0 + ret := m.ctrl.Call(m, "GetInstancesCount") + ret0, _ := ret[0].(uint32) + ret1, _ := ret[1].(error) + return ret0, ret1 } -// Destroy indicates an expected call of Destroy. -func (mr *MockStoreMockRecorder) Destroy() *gomock.Call { +// GetInstancesCount indicates an expected call of GetInstancesCount +func (mr *MockStoreMockRecorder) GetInstancesCount() *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Destroy", reflect.TypeOf((*MockStore)(nil).Destroy)) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetInstancesCount", reflect.TypeOf((*MockStore)(nil).GetInstancesCount)) } -// EnableRateLimit mocks base method. -func (m *MockStore) EnableRateLimit(limit *model.RateLimit) error { +// GetInstancesMainByService mocks base method +func (m *MockStore) GetInstancesMainByService(serviceID, host string) ([]*model.Instance, error) { m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "EnableRateLimit", limit) - ret0, _ := ret[0].(error) - return ret0 + ret := m.ctrl.Call(m, "GetInstancesMainByService", serviceID, host) + ret0, _ := ret[0].([]*model.Instance) + ret1, _ := ret[1].(error) + return ret0, ret1 } -// EnableRateLimit indicates an expected call of EnableRateLimit. -func (mr *MockStoreMockRecorder) EnableRateLimit(limit interface{}) *gomock.Call { +// GetInstancesMainByService indicates an expected call of GetInstancesMainByService +func (mr *MockStoreMockRecorder) GetInstancesMainByService(serviceID, host interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "EnableRateLimit", reflect.TypeOf((*MockStore)(nil).EnableRateLimit), limit) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetInstancesMainByService", reflect.TypeOf((*MockStore)(nil).GetInstancesMainByService), serviceID, host) } -// FindConfigFileGroups mocks base method. -func (m *MockStore) FindConfigFileGroups(namespace string, names []string) ([]*model.ConfigFileGroup, error) { +// GetExpandInstances mocks base method +func (m *MockStore) GetExpandInstances(filter, metaFilter map[string]string, offset, limit uint32) (uint32, []*model.Instance, error) { m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "FindConfigFileGroups", namespace, names) - ret0, _ := ret[0].([]*model.ConfigFileGroup) - ret1, _ := ret[1].(error) - return ret0, ret1 + ret := m.ctrl.Call(m, "GetExpandInstances", filter, metaFilter, offset, limit) + ret0, _ := ret[0].(uint32) + ret1, _ := ret[1].([]*model.Instance) + ret2, _ := ret[2].(error) + return ret0, ret1, ret2 } -// FindConfigFileGroups indicates an expected call of FindConfigFileGroups. -func (mr *MockStoreMockRecorder) FindConfigFileGroups(namespace, names interface{}) *gomock.Call { +// GetExpandInstances indicates an expected call of GetExpandInstances +func (mr *MockStoreMockRecorder) GetExpandInstances(filter, metaFilter, offset, limit interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "FindConfigFileGroups", reflect.TypeOf((*MockStore)(nil).FindConfigFileGroups), namespace, names) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetExpandInstances", reflect.TypeOf((*MockStore)(nil).GetExpandInstances), filter, metaFilter, offset, limit) } -// FindConfigFileReleaseByModifyTimeAfter mocks base method. -func (m *MockStore) FindConfigFileReleaseByModifyTimeAfter(modifyTime time.Time) ([]*model.ConfigFileRelease, error) { +// GetMoreInstances mocks base method +func (m *MockStore) GetMoreInstances(mtime time.Time, firstUpdate, needMeta bool, serviceID []string) (map[string]*model.Instance, error) { m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "FindConfigFileReleaseByModifyTimeAfter", modifyTime) - ret0, _ := ret[0].([]*model.ConfigFileRelease) + ret := m.ctrl.Call(m, "GetMoreInstances", mtime, firstUpdate, needMeta, serviceID) + ret0, _ := ret[0].(map[string]*model.Instance) ret1, _ := ret[1].(error) return ret0, ret1 } -// FindConfigFileReleaseByModifyTimeAfter indicates an expected call of FindConfigFileReleaseByModifyTimeAfter. -func (mr *MockStoreMockRecorder) FindConfigFileReleaseByModifyTimeAfter(modifyTime interface{}) *gomock.Call { +// GetMoreInstances indicates an expected call of GetMoreInstances +func (mr *MockStoreMockRecorder) GetMoreInstances(mtime, firstUpdate, needMeta, serviceID interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "FindConfigFileReleaseByModifyTimeAfter", reflect.TypeOf((*MockStore)(nil).FindConfigFileReleaseByModifyTimeAfter), modifyTime) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetMoreInstances", reflect.TypeOf((*MockStore)(nil).GetMoreInstances), mtime, firstUpdate, needMeta, serviceID) } -// GenNextL5Sid mocks base method. -func (m *MockStore) GenNextL5Sid(layoutID uint32) (string, error) { +// SetInstanceHealthStatus mocks base method +func (m *MockStore) SetInstanceHealthStatus(instanceID string, flag int, revision string) error { m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "GenNextL5Sid", layoutID) - ret0, _ := ret[0].(string) - ret1, _ := ret[1].(error) - return ret0, ret1 + ret := m.ctrl.Call(m, "SetInstanceHealthStatus", instanceID, flag, revision) + ret0, _ := ret[0].(error) + return ret0 } -// GenNextL5Sid indicates an expected call of GenNextL5Sid. -func (mr *MockStoreMockRecorder) GenNextL5Sid(layoutID interface{}) *gomock.Call { +// SetInstanceHealthStatus indicates an expected call of SetInstanceHealthStatus +func (mr *MockStoreMockRecorder) SetInstanceHealthStatus(instanceID, flag, revision interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GenNextL5Sid", reflect.TypeOf((*MockStore)(nil).GenNextL5Sid), layoutID) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SetInstanceHealthStatus", reflect.TypeOf((*MockStore)(nil).SetInstanceHealthStatus), instanceID, flag, revision) } -// GetBusinessByID mocks base method. -func (m *MockStore) GetBusinessByID(id string) (*model.Business, error) { +// BatchSetInstanceHealthStatus mocks base method +func (m *MockStore) BatchSetInstanceHealthStatus(ids []interface{}, healthy int, revision string) error { m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "GetBusinessByID", id) - ret0, _ := ret[0].(*model.Business) - ret1, _ := ret[1].(error) - return ret0, ret1 + ret := m.ctrl.Call(m, "BatchSetInstanceHealthStatus", ids, healthy, revision) + ret0, _ := ret[0].(error) + return ret0 } -// GetBusinessByID indicates an expected call of GetBusinessByID. -func (mr *MockStoreMockRecorder) GetBusinessByID(id interface{}) *gomock.Call { +// BatchSetInstanceHealthStatus indicates an expected call of BatchSetInstanceHealthStatus +func (mr *MockStoreMockRecorder) BatchSetInstanceHealthStatus(ids, healthy, revision interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetBusinessByID", reflect.TypeOf((*MockStore)(nil).GetBusinessByID), id) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "BatchSetInstanceHealthStatus", reflect.TypeOf((*MockStore)(nil).BatchSetInstanceHealthStatus), ids, healthy, revision) } -// GetCircuitBreaker mocks base method. -func (m *MockStore) GetCircuitBreaker(id, version string) (*model.CircuitBreaker, error) { +// BatchSetInstanceIsolate mocks base method +func (m *MockStore) BatchSetInstanceIsolate(ids []interface{}, isolate int, revision string) error { m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "GetCircuitBreaker", id, version) - ret0, _ := ret[0].(*model.CircuitBreaker) - ret1, _ := ret[1].(error) - return ret0, ret1 + ret := m.ctrl.Call(m, "BatchSetInstanceIsolate", ids, isolate, revision) + ret0, _ := ret[0].(error) + return ret0 } -// GetCircuitBreaker indicates an expected call of GetCircuitBreaker. -func (mr *MockStoreMockRecorder) GetCircuitBreaker(id, version interface{}) *gomock.Call { +// BatchSetInstanceIsolate indicates an expected call of BatchSetInstanceIsolate +func (mr *MockStoreMockRecorder) BatchSetInstanceIsolate(ids, isolate, revision interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetCircuitBreaker", reflect.TypeOf((*MockStore)(nil).GetCircuitBreaker), id, version) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "BatchSetInstanceIsolate", reflect.TypeOf((*MockStore)(nil).BatchSetInstanceIsolate), ids, isolate, revision) } -// GetCircuitBreakerForCache mocks base method. -func (m *MockStore) GetCircuitBreakerForCache(mtime time.Time, firstUpdate bool) ([]*model.ServiceWithCircuitBreaker, error) { +// CreateRoutingConfig mocks base method +func (m *MockStore) CreateRoutingConfig(conf *model.RoutingConfig) error { m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "GetCircuitBreakerForCache", mtime, firstUpdate) - ret0, _ := ret[0].([]*model.ServiceWithCircuitBreaker) + ret := m.ctrl.Call(m, "CreateRoutingConfig", conf) + ret0, _ := ret[0].(error) + return ret0 +} + +// CreateRoutingConfig indicates an expected call of CreateRoutingConfig +func (mr *MockStoreMockRecorder) CreateRoutingConfig(conf interface{}) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "CreateRoutingConfig", reflect.TypeOf((*MockStore)(nil).CreateRoutingConfig), conf) +} + +// UpdateRoutingConfig mocks base method +func (m *MockStore) UpdateRoutingConfig(conf *model.RoutingConfig) error { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "UpdateRoutingConfig", conf) + ret0, _ := ret[0].(error) + return ret0 +} + +// UpdateRoutingConfig indicates an expected call of UpdateRoutingConfig +func (mr *MockStoreMockRecorder) UpdateRoutingConfig(conf interface{}) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "UpdateRoutingConfig", reflect.TypeOf((*MockStore)(nil).UpdateRoutingConfig), conf) +} + +// DeleteRoutingConfig mocks base method +func (m *MockStore) DeleteRoutingConfig(serviceID string) error { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "DeleteRoutingConfig", serviceID) + ret0, _ := ret[0].(error) + return ret0 +} + +// DeleteRoutingConfig indicates an expected call of DeleteRoutingConfig +func (mr *MockStoreMockRecorder) DeleteRoutingConfig(serviceID interface{}) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "DeleteRoutingConfig", reflect.TypeOf((*MockStore)(nil).DeleteRoutingConfig), serviceID) +} + +// DeleteRoutingConfigTx mocks base method +func (m *MockStore) DeleteRoutingConfigTx(tx store.Tx, serviceID string) error { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "DeleteRoutingConfigTx", tx, serviceID) + ret0, _ := ret[0].(error) + return ret0 +} + +// DeleteRoutingConfigTx indicates an expected call of DeleteRoutingConfigTx +func (mr *MockStoreMockRecorder) DeleteRoutingConfigTx(tx, serviceID interface{}) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "DeleteRoutingConfigTx", reflect.TypeOf((*MockStore)(nil).DeleteRoutingConfigTx), tx, serviceID) +} + +// GetRoutingConfigsForCache mocks base method +func (m *MockStore) GetRoutingConfigsForCache(mtime time.Time, firstUpdate bool) ([]*model.RoutingConfig, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "GetRoutingConfigsForCache", mtime, firstUpdate) + ret0, _ := ret[0].([]*model.RoutingConfig) ret1, _ := ret[1].(error) return ret0, ret1 } -// GetCircuitBreakerForCache indicates an expected call of GetCircuitBreakerForCache. -func (mr *MockStoreMockRecorder) GetCircuitBreakerForCache(mtime, firstUpdate interface{}) *gomock.Call { +// GetRoutingConfigsForCache indicates an expected call of GetRoutingConfigsForCache +func (mr *MockStoreMockRecorder) GetRoutingConfigsForCache(mtime, firstUpdate interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetCircuitBreakerForCache", reflect.TypeOf((*MockStore)(nil).GetCircuitBreakerForCache), mtime, firstUpdate) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetRoutingConfigsForCache", reflect.TypeOf((*MockStore)(nil).GetRoutingConfigsForCache), mtime, firstUpdate) } -// GetCircuitBreakerMasterRelation mocks base method. -func (m *MockStore) GetCircuitBreakerMasterRelation(ruleID string) ([]*model.CircuitBreakerRelation, error) { +// GetRoutingConfigWithService mocks base method +func (m *MockStore) GetRoutingConfigWithService(name, namespace string) (*model.RoutingConfig, error) { m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "GetCircuitBreakerMasterRelation", ruleID) - ret0, _ := ret[0].([]*model.CircuitBreakerRelation) + ret := m.ctrl.Call(m, "GetRoutingConfigWithService", name, namespace) + ret0, _ := ret[0].(*model.RoutingConfig) ret1, _ := ret[1].(error) return ret0, ret1 } -// GetCircuitBreakerMasterRelation indicates an expected call of GetCircuitBreakerMasterRelation. -func (mr *MockStoreMockRecorder) GetCircuitBreakerMasterRelation(ruleID interface{}) *gomock.Call { +// GetRoutingConfigWithService indicates an expected call of GetRoutingConfigWithService +func (mr *MockStoreMockRecorder) GetRoutingConfigWithService(name, namespace interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetCircuitBreakerMasterRelation", reflect.TypeOf((*MockStore)(nil).GetCircuitBreakerMasterRelation), ruleID) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetRoutingConfigWithService", reflect.TypeOf((*MockStore)(nil).GetRoutingConfigWithService), name, namespace) } -// GetCircuitBreakerRelation mocks base method. -func (m *MockStore) GetCircuitBreakerRelation(ruleID, ruleVersion string) ([]*model.CircuitBreakerRelation, error) { +// GetRoutingConfigWithID mocks base method +func (m *MockStore) GetRoutingConfigWithID(id string) (*model.RoutingConfig, error) { m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "GetCircuitBreakerRelation", ruleID, ruleVersion) - ret0, _ := ret[0].([]*model.CircuitBreakerRelation) + ret := m.ctrl.Call(m, "GetRoutingConfigWithID", id) + ret0, _ := ret[0].(*model.RoutingConfig) ret1, _ := ret[1].(error) return ret0, ret1 } -// GetCircuitBreakerRelation indicates an expected call of GetCircuitBreakerRelation. -func (mr *MockStoreMockRecorder) GetCircuitBreakerRelation(ruleID, ruleVersion interface{}) *gomock.Call { +// GetRoutingConfigWithID indicates an expected call of GetRoutingConfigWithID +func (mr *MockStoreMockRecorder) GetRoutingConfigWithID(id interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetCircuitBreakerRelation", reflect.TypeOf((*MockStore)(nil).GetCircuitBreakerRelation), ruleID, ruleVersion) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetRoutingConfigWithID", reflect.TypeOf((*MockStore)(nil).GetRoutingConfigWithID), id) } -// GetCircuitBreakerVersions mocks base method. -func (m *MockStore) GetCircuitBreakerVersions(id string) ([]string, error) { +// GetRoutingConfigs mocks base method +func (m *MockStore) GetRoutingConfigs(filter map[string]string, offset, limit uint32) (uint32, []*model.ExtendRoutingConfig, error) { m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "GetCircuitBreakerVersions", id) - ret0, _ := ret[0].([]string) + ret := m.ctrl.Call(m, "GetRoutingConfigs", filter, offset, limit) + ret0, _ := ret[0].(uint32) + ret1, _ := ret[1].([]*model.ExtendRoutingConfig) + ret2, _ := ret[2].(error) + return ret0, ret1, ret2 +} + +// GetRoutingConfigs indicates an expected call of GetRoutingConfigs +func (mr *MockStoreMockRecorder) GetRoutingConfigs(filter, offset, limit interface{}) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetRoutingConfigs", reflect.TypeOf((*MockStore)(nil).GetRoutingConfigs), filter, offset, limit) +} + +// GetL5Extend mocks base method +func (m *MockStore) GetL5Extend(serviceID string) (map[string]interface{}, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "GetL5Extend", serviceID) + ret0, _ := ret[0].(map[string]interface{}) ret1, _ := ret[1].(error) return ret0, ret1 } -// GetCircuitBreakerVersions indicates an expected call of GetCircuitBreakerVersions. -func (mr *MockStoreMockRecorder) GetCircuitBreakerVersions(id interface{}) *gomock.Call { +// GetL5Extend indicates an expected call of GetL5Extend +func (mr *MockStoreMockRecorder) GetL5Extend(serviceID interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetCircuitBreakerVersions", reflect.TypeOf((*MockStore)(nil).GetCircuitBreakerVersions), id) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetL5Extend", reflect.TypeOf((*MockStore)(nil).GetL5Extend), serviceID) } -// GetCircuitBreakersByService mocks base method. -func (m *MockStore) GetCircuitBreakersByService(name, namespace string) (*model.CircuitBreaker, error) { +// SetL5Extend mocks base method +func (m *MockStore) SetL5Extend(serviceID string, meta map[string]interface{}) (map[string]interface{}, error) { m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "GetCircuitBreakersByService", name, namespace) - ret0, _ := ret[0].(*model.CircuitBreaker) + ret := m.ctrl.Call(m, "SetL5Extend", serviceID, meta) + ret0, _ := ret[0].(map[string]interface{}) ret1, _ := ret[1].(error) return ret0, ret1 } -// GetCircuitBreakersByService indicates an expected call of GetCircuitBreakersByService. -func (mr *MockStoreMockRecorder) GetCircuitBreakersByService(name, namespace interface{}) *gomock.Call { +// SetL5Extend indicates an expected call of SetL5Extend +func (mr *MockStoreMockRecorder) SetL5Extend(serviceID, meta interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetCircuitBreakersByService", reflect.TypeOf((*MockStore)(nil).GetCircuitBreakersByService), name, namespace) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SetL5Extend", reflect.TypeOf((*MockStore)(nil).SetL5Extend), serviceID, meta) } -// GetConfigFile mocks base method. -func (m *MockStore) GetConfigFile(tx store.Tx, namespace, group, name string) (*model.ConfigFile, error) { +// GenNextL5Sid mocks base method +func (m *MockStore) GenNextL5Sid(layoutID uint32) (string, error) { m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "GetConfigFile", tx, namespace, group, name) - ret0, _ := ret[0].(*model.ConfigFile) + ret := m.ctrl.Call(m, "GenNextL5Sid", layoutID) + ret0, _ := ret[0].(string) ret1, _ := ret[1].(error) return ret0, ret1 } -// GetConfigFile indicates an expected call of GetConfigFile. -func (mr *MockStoreMockRecorder) GetConfigFile(tx, namespace, group, name interface{}) *gomock.Call { +// GenNextL5Sid indicates an expected call of GenNextL5Sid +func (mr *MockStoreMockRecorder) GenNextL5Sid(layoutID interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetConfigFile", reflect.TypeOf((*MockStore)(nil).GetConfigFile), tx, namespace, group, name) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GenNextL5Sid", reflect.TypeOf((*MockStore)(nil).GenNextL5Sid), layoutID) } -// GetConfigFileGroup mocks base method. -func (m *MockStore) GetConfigFileGroup(namespace, name string) (*model.ConfigFileGroup, error) { +// GetMoreL5Extend mocks base method +func (m *MockStore) GetMoreL5Extend(mtime time.Time) (map[string]map[string]interface{}, error) { m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "GetConfigFileGroup", namespace, name) - ret0, _ := ret[0].(*model.ConfigFileGroup) + ret := m.ctrl.Call(m, "GetMoreL5Extend", mtime) + ret0, _ := ret[0].(map[string]map[string]interface{}) ret1, _ := ret[1].(error) return ret0, ret1 } -// GetConfigFileGroup indicates an expected call of GetConfigFileGroup. -func (mr *MockStoreMockRecorder) GetConfigFileGroup(namespace, name interface{}) *gomock.Call { +// GetMoreL5Extend indicates an expected call of GetMoreL5Extend +func (mr *MockStoreMockRecorder) GetMoreL5Extend(mtime interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetConfigFileGroup", reflect.TypeOf((*MockStore)(nil).GetConfigFileGroup), namespace, name) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetMoreL5Extend", reflect.TypeOf((*MockStore)(nil).GetMoreL5Extend), mtime) } -// GetConfigFileRelease mocks base method. -func (m *MockStore) GetConfigFileRelease(tx store.Tx, namespace, group, fileName string) (*model.ConfigFileRelease, error) { +// GetMoreL5Routes mocks base method +func (m *MockStore) GetMoreL5Routes(flow uint32) ([]*model.Route, error) { m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "GetConfigFileRelease", tx, namespace, group, fileName) - ret0, _ := ret[0].(*model.ConfigFileRelease) + ret := m.ctrl.Call(m, "GetMoreL5Routes", flow) + ret0, _ := ret[0].([]*model.Route) ret1, _ := ret[1].(error) return ret0, ret1 } -// GetConfigFileRelease indicates an expected call of GetConfigFileRelease. -func (mr *MockStoreMockRecorder) GetConfigFileRelease(tx, namespace, group, fileName interface{}) *gomock.Call { +// GetMoreL5Routes indicates an expected call of GetMoreL5Routes +func (mr *MockStoreMockRecorder) GetMoreL5Routes(flow interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetConfigFileRelease", reflect.TypeOf((*MockStore)(nil).GetConfigFileRelease), tx, namespace, group, fileName) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetMoreL5Routes", reflect.TypeOf((*MockStore)(nil).GetMoreL5Routes), flow) } -// GetConfigFileReleaseWithAllFlag mocks base method. -func (m *MockStore) GetConfigFileReleaseWithAllFlag(tx store.Tx, namespace, group, fileName string) (*model.ConfigFileRelease, error) { +// GetMoreL5Policies mocks base method +func (m *MockStore) GetMoreL5Policies(flow uint32) ([]*model.Policy, error) { m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "GetConfigFileReleaseWithAllFlag", tx, namespace, group, fileName) - ret0, _ := ret[0].(*model.ConfigFileRelease) + ret := m.ctrl.Call(m, "GetMoreL5Policies", flow) + ret0, _ := ret[0].([]*model.Policy) ret1, _ := ret[1].(error) return ret0, ret1 } -// GetConfigFileReleaseWithAllFlag indicates an expected call of GetConfigFileReleaseWithAllFlag. -func (mr *MockStoreMockRecorder) GetConfigFileReleaseWithAllFlag(tx, namespace, group, fileName interface{}) *gomock.Call { +// GetMoreL5Policies indicates an expected call of GetMoreL5Policies +func (mr *MockStoreMockRecorder) GetMoreL5Policies(flow interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetConfigFileReleaseWithAllFlag", reflect.TypeOf((*MockStore)(nil).GetConfigFileReleaseWithAllFlag), tx, namespace, group, fileName) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetMoreL5Policies", reflect.TypeOf((*MockStore)(nil).GetMoreL5Policies), flow) } -// GetConfigFileTemplate mocks base method. -func (m *MockStore) GetConfigFileTemplate(name string) (*model.ConfigFileTemplate, error) { +// GetMoreL5Sections mocks base method +func (m *MockStore) GetMoreL5Sections(flow uint32) ([]*model.Section, error) { m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "GetConfigFileTemplate", name) - ret0, _ := ret[0].(*model.ConfigFileTemplate) + ret := m.ctrl.Call(m, "GetMoreL5Sections", flow) + ret0, _ := ret[0].([]*model.Section) ret1, _ := ret[1].(error) return ret0, ret1 } -// GetConfigFileTemplate indicates an expected call of GetConfigFileTemplate. -func (mr *MockStoreMockRecorder) GetConfigFileTemplate(name interface{}) *gomock.Call { +// GetMoreL5Sections indicates an expected call of GetMoreL5Sections +func (mr *MockStoreMockRecorder) GetMoreL5Sections(flow interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetConfigFileTemplate", reflect.TypeOf((*MockStore)(nil).GetConfigFileTemplate), name) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetMoreL5Sections", reflect.TypeOf((*MockStore)(nil).GetMoreL5Sections), flow) } -// GetDefaultStrategyDetailByPrincipal mocks base method. -func (m *MockStore) GetDefaultStrategyDetailByPrincipal(principalId string, principalType model.PrincipalType) (*model.StrategyDetail, error) { +// GetMoreL5IPConfigs mocks base method +func (m *MockStore) GetMoreL5IPConfigs(flow uint32) ([]*model.IPConfig, error) { m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "GetDefaultStrategyDetailByPrincipal", principalId, principalType) - ret0, _ := ret[0].(*model.StrategyDetail) + ret := m.ctrl.Call(m, "GetMoreL5IPConfigs", flow) + ret0, _ := ret[0].([]*model.IPConfig) ret1, _ := ret[1].(error) return ret0, ret1 } -// GetDefaultStrategyDetailByPrincipal indicates an expected call of GetDefaultStrategyDetailByPrincipal. -func (mr *MockStoreMockRecorder) GetDefaultStrategyDetailByPrincipal(principalId, principalType interface{}) *gomock.Call { +// GetMoreL5IPConfigs indicates an expected call of GetMoreL5IPConfigs +func (mr *MockStoreMockRecorder) GetMoreL5IPConfigs(flow interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetDefaultStrategyDetailByPrincipal", reflect.TypeOf((*MockStore)(nil).GetDefaultStrategyDetailByPrincipal), principalId, principalType) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetMoreL5IPConfigs", reflect.TypeOf((*MockStore)(nil).GetMoreL5IPConfigs), flow) } -// GetExpandInstances mocks base method. -func (m *MockStore) GetExpandInstances(filter, metaFilter map[string]string, offset, limit uint32) (uint32, []*model.Instance, error) { +// CreateRateLimit mocks base method +func (m *MockStore) CreateRateLimit(limiting *model.RateLimit) error { m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "GetExpandInstances", filter, metaFilter, offset, limit) - ret0, _ := ret[0].(uint32) - ret1, _ := ret[1].([]*model.Instance) - ret2, _ := ret[2].(error) - return ret0, ret1, ret2 + ret := m.ctrl.Call(m, "CreateRateLimit", limiting) + ret0, _ := ret[0].(error) + return ret0 } -// GetExpandInstances indicates an expected call of GetExpandInstances. -func (mr *MockStoreMockRecorder) GetExpandInstances(filter, metaFilter, offset, limit interface{}) *gomock.Call { +// CreateRateLimit indicates an expected call of CreateRateLimit +func (mr *MockStoreMockRecorder) CreateRateLimit(limiting interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetExpandInstances", reflect.TypeOf((*MockStore)(nil).GetExpandInstances), filter, metaFilter, offset, limit) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "CreateRateLimit", reflect.TypeOf((*MockStore)(nil).CreateRateLimit), limiting) +} + +// UpdateRateLimit mocks base method +func (m *MockStore) UpdateRateLimit(limiting *model.RateLimit) error { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "UpdateRateLimit", limiting) + ret0, _ := ret[0].(error) + return ret0 +} + +// UpdateRateLimit indicates an expected call of UpdateRateLimit +func (mr *MockStoreMockRecorder) UpdateRateLimit(limiting interface{}) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "UpdateRateLimit", reflect.TypeOf((*MockStore)(nil).UpdateRateLimit), limiting) +} + +// EnableRateLimit mocks base method +func (m *MockStore) EnableRateLimit(limit *model.RateLimit) error { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "EnableRateLimit", limit) + ret0, _ := ret[0].(error) + return ret0 +} + +// EnableRateLimit indicates an expected call of EnableRateLimit +func (mr *MockStoreMockRecorder) EnableRateLimit(limit interface{}) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "EnableRateLimit", reflect.TypeOf((*MockStore)(nil).EnableRateLimit), limit) +} + +// DeleteRateLimit mocks base method +func (m *MockStore) DeleteRateLimit(limiting *model.RateLimit) error { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "DeleteRateLimit", limiting) + ret0, _ := ret[0].(error) + return ret0 } -// GetExtendRateLimits mocks base method. +// DeleteRateLimit indicates an expected call of DeleteRateLimit +func (mr *MockStoreMockRecorder) DeleteRateLimit(limiting interface{}) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "DeleteRateLimit", reflect.TypeOf((*MockStore)(nil).DeleteRateLimit), limiting) +} + +// GetExtendRateLimits mocks base method func (m *MockStore) GetExtendRateLimits(query map[string]string, offset, limit uint32) (uint32, []*model.ExtendRateLimit, error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "GetExtendRateLimits", query, offset, limit) @@ -954,926 +1068,981 @@ func (m *MockStore) GetExtendRateLimits(query map[string]string, offset, limit u return ret0, ret1, ret2 } -// GetExtendRateLimits indicates an expected call of GetExtendRateLimits. +// GetExtendRateLimits indicates an expected call of GetExtendRateLimits func (mr *MockStoreMockRecorder) GetExtendRateLimits(query, offset, limit interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetExtendRateLimits", reflect.TypeOf((*MockStore)(nil).GetExtendRateLimits), query, offset, limit) } -// GetGroup mocks base method. -func (m *MockStore) GetGroup(id string) (*model.UserGroupDetail, error) { +// GetRateLimitWithID mocks base method +func (m *MockStore) GetRateLimitWithID(id string) (*model.RateLimit, error) { m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "GetGroup", id) - ret0, _ := ret[0].(*model.UserGroupDetail) + ret := m.ctrl.Call(m, "GetRateLimitWithID", id) + ret0, _ := ret[0].(*model.RateLimit) ret1, _ := ret[1].(error) return ret0, ret1 } -// GetGroup indicates an expected call of GetGroup. -func (mr *MockStoreMockRecorder) GetGroup(id interface{}) *gomock.Call { +// GetRateLimitWithID indicates an expected call of GetRateLimitWithID +func (mr *MockStoreMockRecorder) GetRateLimitWithID(id interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetGroup", reflect.TypeOf((*MockStore)(nil).GetGroup), id) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetRateLimitWithID", reflect.TypeOf((*MockStore)(nil).GetRateLimitWithID), id) } -// GetGroupByName mocks base method. -func (m *MockStore) GetGroupByName(name, owner string) (*model.UserGroup, error) { +// GetRateLimitsForCache mocks base method +func (m *MockStore) GetRateLimitsForCache(mtime time.Time, firstUpdate bool) ([]*model.RateLimit, []*model.RateLimitRevision, error) { m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "GetGroupByName", name, owner) - ret0, _ := ret[0].(*model.UserGroup) - ret1, _ := ret[1].(error) - return ret0, ret1 + ret := m.ctrl.Call(m, "GetRateLimitsForCache", mtime, firstUpdate) + ret0, _ := ret[0].([]*model.RateLimit) + ret1, _ := ret[1].([]*model.RateLimitRevision) + ret2, _ := ret[2].(error) + return ret0, ret1, ret2 } -// GetGroupByName indicates an expected call of GetGroupByName. -func (mr *MockStoreMockRecorder) GetGroupByName(name, owner interface{}) *gomock.Call { +// GetRateLimitsForCache indicates an expected call of GetRateLimitsForCache +func (mr *MockStoreMockRecorder) GetRateLimitsForCache(mtime, firstUpdate interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetGroupByName", reflect.TypeOf((*MockStore)(nil).GetGroupByName), name, owner) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetRateLimitsForCache", reflect.TypeOf((*MockStore)(nil).GetRateLimitsForCache), mtime, firstUpdate) } -// GetGroups mocks base method. -func (m *MockStore) GetGroups(filters map[string]string, offset, limit uint32) (uint32, []*model.UserGroup, error) { +// CreateCircuitBreaker mocks base method +func (m *MockStore) CreateCircuitBreaker(circuitBreaker *model.CircuitBreaker) error { m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "GetGroups", filters, offset, limit) - ret0, _ := ret[0].(uint32) - ret1, _ := ret[1].([]*model.UserGroup) - ret2, _ := ret[2].(error) - return ret0, ret1, ret2 + ret := m.ctrl.Call(m, "CreateCircuitBreaker", circuitBreaker) + ret0, _ := ret[0].(error) + return ret0 } -// GetGroups indicates an expected call of GetGroups. -func (mr *MockStoreMockRecorder) GetGroups(filters, offset, limit interface{}) *gomock.Call { +// CreateCircuitBreaker indicates an expected call of CreateCircuitBreaker +func (mr *MockStoreMockRecorder) CreateCircuitBreaker(circuitBreaker interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetGroups", reflect.TypeOf((*MockStore)(nil).GetGroups), filters, offset, limit) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "CreateCircuitBreaker", reflect.TypeOf((*MockStore)(nil).CreateCircuitBreaker), circuitBreaker) } -// GetGroupsForCache mocks base method. -func (m *MockStore) GetGroupsForCache(mtime time.Time, firstUpdate bool) ([]*model.UserGroupDetail, error) { +// TagCircuitBreaker mocks base method +func (m *MockStore) TagCircuitBreaker(circuitBreaker *model.CircuitBreaker) error { m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "GetGroupsForCache", mtime, firstUpdate) - ret0, _ := ret[0].([]*model.UserGroupDetail) + ret := m.ctrl.Call(m, "TagCircuitBreaker", circuitBreaker) + ret0, _ := ret[0].(error) + return ret0 +} + +// TagCircuitBreaker indicates an expected call of TagCircuitBreaker +func (mr *MockStoreMockRecorder) TagCircuitBreaker(circuitBreaker interface{}) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "TagCircuitBreaker", reflect.TypeOf((*MockStore)(nil).TagCircuitBreaker), circuitBreaker) +} + +// ReleaseCircuitBreaker mocks base method +func (m *MockStore) ReleaseCircuitBreaker(circuitBreakerRelation *model.CircuitBreakerRelation) error { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "ReleaseCircuitBreaker", circuitBreakerRelation) + ret0, _ := ret[0].(error) + return ret0 +} + +// ReleaseCircuitBreaker indicates an expected call of ReleaseCircuitBreaker +func (mr *MockStoreMockRecorder) ReleaseCircuitBreaker(circuitBreakerRelation interface{}) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ReleaseCircuitBreaker", reflect.TypeOf((*MockStore)(nil).ReleaseCircuitBreaker), circuitBreakerRelation) +} + +// UnbindCircuitBreaker mocks base method +func (m *MockStore) UnbindCircuitBreaker(serviceID, ruleID, ruleVersion string) error { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "UnbindCircuitBreaker", serviceID, ruleID, ruleVersion) + ret0, _ := ret[0].(error) + return ret0 +} + +// UnbindCircuitBreaker indicates an expected call of UnbindCircuitBreaker +func (mr *MockStoreMockRecorder) UnbindCircuitBreaker(serviceID, ruleID, ruleVersion interface{}) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "UnbindCircuitBreaker", reflect.TypeOf((*MockStore)(nil).UnbindCircuitBreaker), serviceID, ruleID, ruleVersion) +} + +// DeleteTagCircuitBreaker mocks base method +func (m *MockStore) DeleteTagCircuitBreaker(id, version string) error { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "DeleteTagCircuitBreaker", id, version) + ret0, _ := ret[0].(error) + return ret0 +} + +// DeleteTagCircuitBreaker indicates an expected call of DeleteTagCircuitBreaker +func (mr *MockStoreMockRecorder) DeleteTagCircuitBreaker(id, version interface{}) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "DeleteTagCircuitBreaker", reflect.TypeOf((*MockStore)(nil).DeleteTagCircuitBreaker), id, version) +} + +// DeleteMasterCircuitBreaker mocks base method +func (m *MockStore) DeleteMasterCircuitBreaker(id string) error { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "DeleteMasterCircuitBreaker", id) + ret0, _ := ret[0].(error) + return ret0 +} + +// DeleteMasterCircuitBreaker indicates an expected call of DeleteMasterCircuitBreaker +func (mr *MockStoreMockRecorder) DeleteMasterCircuitBreaker(id interface{}) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "DeleteMasterCircuitBreaker", reflect.TypeOf((*MockStore)(nil).DeleteMasterCircuitBreaker), id) +} + +// UpdateCircuitBreaker mocks base method +func (m *MockStore) UpdateCircuitBreaker(circuitBraker *model.CircuitBreaker) error { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "UpdateCircuitBreaker", circuitBraker) + ret0, _ := ret[0].(error) + return ret0 +} + +// UpdateCircuitBreaker indicates an expected call of UpdateCircuitBreaker +func (mr *MockStoreMockRecorder) UpdateCircuitBreaker(circuitBraker interface{}) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "UpdateCircuitBreaker", reflect.TypeOf((*MockStore)(nil).UpdateCircuitBreaker), circuitBraker) +} + +// GetCircuitBreaker mocks base method +func (m *MockStore) GetCircuitBreaker(id, version string) (*model.CircuitBreaker, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "GetCircuitBreaker", id, version) + ret0, _ := ret[0].(*model.CircuitBreaker) ret1, _ := ret[1].(error) return ret0, ret1 } -// GetGroupsForCache indicates an expected call of GetGroupsForCache. -func (mr *MockStoreMockRecorder) GetGroupsForCache(mtime, firstUpdate interface{}) *gomock.Call { +// GetCircuitBreaker indicates an expected call of GetCircuitBreaker +func (mr *MockStoreMockRecorder) GetCircuitBreaker(id, version interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetGroupsForCache", reflect.TypeOf((*MockStore)(nil).GetGroupsForCache), mtime, firstUpdate) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetCircuitBreaker", reflect.TypeOf((*MockStore)(nil).GetCircuitBreaker), id, version) } -// GetInstance mocks base method. -func (m *MockStore) GetInstance(instanceID string) (*model.Instance, error) { +// GetCircuitBreakerVersions mocks base method +func (m *MockStore) GetCircuitBreakerVersions(id string) ([]string, error) { m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "GetInstance", instanceID) - ret0, _ := ret[0].(*model.Instance) + ret := m.ctrl.Call(m, "GetCircuitBreakerVersions", id) + ret0, _ := ret[0].([]string) ret1, _ := ret[1].(error) return ret0, ret1 } -// GetInstance indicates an expected call of GetInstance. -func (mr *MockStoreMockRecorder) GetInstance(instanceID interface{}) *gomock.Call { +// GetCircuitBreakerVersions indicates an expected call of GetCircuitBreakerVersions +func (mr *MockStoreMockRecorder) GetCircuitBreakerVersions(id interface{}) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetCircuitBreakerVersions", reflect.TypeOf((*MockStore)(nil).GetCircuitBreakerVersions), id) +} + +// GetCircuitBreakerMasterRelation mocks base method +func (m *MockStore) GetCircuitBreakerMasterRelation(ruleID string) ([]*model.CircuitBreakerRelation, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "GetCircuitBreakerMasterRelation", ruleID) + ret0, _ := ret[0].([]*model.CircuitBreakerRelation) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// GetCircuitBreakerMasterRelation indicates an expected call of GetCircuitBreakerMasterRelation +func (mr *MockStoreMockRecorder) GetCircuitBreakerMasterRelation(ruleID interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetInstance", reflect.TypeOf((*MockStore)(nil).GetInstance), instanceID) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetCircuitBreakerMasterRelation", reflect.TypeOf((*MockStore)(nil).GetCircuitBreakerMasterRelation), ruleID) } -// GetInstancesBrief mocks base method. -func (m *MockStore) GetInstancesBrief(ids map[string]bool) (map[string]*model.Instance, error) { +// GetCircuitBreakerRelation mocks base method +func (m *MockStore) GetCircuitBreakerRelation(ruleID, ruleVersion string) ([]*model.CircuitBreakerRelation, error) { m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "GetInstancesBrief", ids) - ret0, _ := ret[0].(map[string]*model.Instance) + ret := m.ctrl.Call(m, "GetCircuitBreakerRelation", ruleID, ruleVersion) + ret0, _ := ret[0].([]*model.CircuitBreakerRelation) ret1, _ := ret[1].(error) return ret0, ret1 } -// GetInstancesBrief indicates an expected call of GetInstancesBrief. -func (mr *MockStoreMockRecorder) GetInstancesBrief(ids interface{}) *gomock.Call { +// GetCircuitBreakerRelation indicates an expected call of GetCircuitBreakerRelation +func (mr *MockStoreMockRecorder) GetCircuitBreakerRelation(ruleID, ruleVersion interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetInstancesBrief", reflect.TypeOf((*MockStore)(nil).GetInstancesBrief), ids) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetCircuitBreakerRelation", reflect.TypeOf((*MockStore)(nil).GetCircuitBreakerRelation), ruleID, ruleVersion) } -// GetInstancesCount mocks base method. -func (m *MockStore) GetInstancesCount() (uint32, error) { +// GetCircuitBreakerForCache mocks base method +func (m *MockStore) GetCircuitBreakerForCache(mtime time.Time, firstUpdate bool) ([]*model.ServiceWithCircuitBreaker, error) { m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "GetInstancesCount") - ret0, _ := ret[0].(uint32) + ret := m.ctrl.Call(m, "GetCircuitBreakerForCache", mtime, firstUpdate) + ret0, _ := ret[0].([]*model.ServiceWithCircuitBreaker) ret1, _ := ret[1].(error) return ret0, ret1 } -// GetInstancesCount indicates an expected call of GetInstancesCount. -func (mr *MockStoreMockRecorder) GetInstancesCount() *gomock.Call { +// GetCircuitBreakerForCache indicates an expected call of GetCircuitBreakerForCache +func (mr *MockStoreMockRecorder) GetCircuitBreakerForCache(mtime, firstUpdate interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetInstancesCount", reflect.TypeOf((*MockStore)(nil).GetInstancesCount)) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetCircuitBreakerForCache", reflect.TypeOf((*MockStore)(nil).GetCircuitBreakerForCache), mtime, firstUpdate) } -// GetInstancesMainByService mocks base method. -func (m *MockStore) GetInstancesMainByService(serviceID, host string) ([]*model.Instance, error) { +// ListMasterCircuitBreakers mocks base method +func (m *MockStore) ListMasterCircuitBreakers(filters map[string]string, offset, limit uint32) (*model.CircuitBreakerDetail, error) { m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "GetInstancesMainByService", serviceID, host) - ret0, _ := ret[0].([]*model.Instance) + ret := m.ctrl.Call(m, "ListMasterCircuitBreakers", filters, offset, limit) + ret0, _ := ret[0].(*model.CircuitBreakerDetail) ret1, _ := ret[1].(error) return ret0, ret1 } -// GetInstancesMainByService indicates an expected call of GetInstancesMainByService. -func (mr *MockStoreMockRecorder) GetInstancesMainByService(serviceID, host interface{}) *gomock.Call { +// ListMasterCircuitBreakers indicates an expected call of ListMasterCircuitBreakers +func (mr *MockStoreMockRecorder) ListMasterCircuitBreakers(filters, offset, limit interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetInstancesMainByService", reflect.TypeOf((*MockStore)(nil).GetInstancesMainByService), serviceID, host) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ListMasterCircuitBreakers", reflect.TypeOf((*MockStore)(nil).ListMasterCircuitBreakers), filters, offset, limit) } -// GetL5Extend mocks base method. -func (m *MockStore) GetL5Extend(serviceID string) (map[string]interface{}, error) { +// ListReleaseCircuitBreakers mocks base method +func (m *MockStore) ListReleaseCircuitBreakers(filters map[string]string, offset, limit uint32) (*model.CircuitBreakerDetail, error) { m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "GetL5Extend", serviceID) - ret0, _ := ret[0].(map[string]interface{}) + ret := m.ctrl.Call(m, "ListReleaseCircuitBreakers", filters, offset, limit) + ret0, _ := ret[0].(*model.CircuitBreakerDetail) ret1, _ := ret[1].(error) return ret0, ret1 } -// GetL5Extend indicates an expected call of GetL5Extend. -func (mr *MockStoreMockRecorder) GetL5Extend(serviceID interface{}) *gomock.Call { +// ListReleaseCircuitBreakers indicates an expected call of ListReleaseCircuitBreakers +func (mr *MockStoreMockRecorder) ListReleaseCircuitBreakers(filters, offset, limit interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetL5Extend", reflect.TypeOf((*MockStore)(nil).GetL5Extend), serviceID) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ListReleaseCircuitBreakers", reflect.TypeOf((*MockStore)(nil).ListReleaseCircuitBreakers), filters, offset, limit) } -// GetLatestConfigFileReleaseHistory mocks base method. -func (m *MockStore) GetLatestConfigFileReleaseHistory(namespace, group, fileName string) (*model.ConfigFileReleaseHistory, error) { +// GetCircuitBreakersByService mocks base method +func (m *MockStore) GetCircuitBreakersByService(name, namespace string) (*model.CircuitBreaker, error) { m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "GetLatestConfigFileReleaseHistory", namespace, group, fileName) - ret0, _ := ret[0].(*model.ConfigFileReleaseHistory) + ret := m.ctrl.Call(m, "GetCircuitBreakersByService", name, namespace) + ret0, _ := ret[0].(*model.CircuitBreaker) ret1, _ := ret[1].(error) return ret0, ret1 } -// GetLatestConfigFileReleaseHistory indicates an expected call of GetLatestConfigFileReleaseHistory. -func (mr *MockStoreMockRecorder) GetLatestConfigFileReleaseHistory(namespace, group, fileName interface{}) *gomock.Call { +// GetCircuitBreakersByService indicates an expected call of GetCircuitBreakersByService +func (mr *MockStoreMockRecorder) GetCircuitBreakersByService(name, namespace interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetLatestConfigFileReleaseHistory", reflect.TypeOf((*MockStore)(nil).GetLatestConfigFileReleaseHistory), namespace, group, fileName) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetCircuitBreakersByService", reflect.TypeOf((*MockStore)(nil).GetCircuitBreakersByService), name, namespace) } -// GetMoreBusiness mocks base method. -func (m *MockStore) GetMoreBusiness(mtime time.Time) ([]*model.Business, error) { +// CreatePlatform mocks base method +func (m *MockStore) CreatePlatform(platform *model.Platform) error { m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "GetMoreBusiness", mtime) - ret0, _ := ret[0].([]*model.Business) - ret1, _ := ret[1].(error) - return ret0, ret1 + ret := m.ctrl.Call(m, "CreatePlatform", platform) + ret0, _ := ret[0].(error) + return ret0 } -// GetMoreBusiness indicates an expected call of GetMoreBusiness. -func (mr *MockStoreMockRecorder) GetMoreBusiness(mtime interface{}) *gomock.Call { +// CreatePlatform indicates an expected call of CreatePlatform +func (mr *MockStoreMockRecorder) CreatePlatform(platform interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetMoreBusiness", reflect.TypeOf((*MockStore)(nil).GetMoreBusiness), mtime) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "CreatePlatform", reflect.TypeOf((*MockStore)(nil).CreatePlatform), platform) } -// GetMoreClients mocks base method. -func (m *MockStore) GetMoreClients(mtime time.Time, firstUpdate bool) (map[string]*model.Client, error) { +// UpdatePlatform mocks base method +func (m *MockStore) UpdatePlatform(platform *model.Platform) error { m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "GetMoreClients", mtime, firstUpdate) - ret0, _ := ret[0].(map[string]*model.Client) - ret1, _ := ret[1].(error) - return ret0, ret1 + ret := m.ctrl.Call(m, "UpdatePlatform", platform) + ret0, _ := ret[0].(error) + return ret0 } -// GetMoreClients indicates an expected call of GetMoreClients. -func (mr *MockStoreMockRecorder) GetMoreClients(mtime, firstUpdate interface{}) *gomock.Call { +// UpdatePlatform indicates an expected call of UpdatePlatform +func (mr *MockStoreMockRecorder) UpdatePlatform(platform interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetMoreClients", reflect.TypeOf((*MockStore)(nil).GetMoreClients), mtime, firstUpdate) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "UpdatePlatform", reflect.TypeOf((*MockStore)(nil).UpdatePlatform), platform) } -// GetMoreInstances mocks base method. -func (m *MockStore) GetMoreInstances(mtime time.Time, firstUpdate, needMeta bool, serviceID []string) (map[string]*model.Instance, error) { +// DeletePlatform mocks base method +func (m *MockStore) DeletePlatform(id string) error { m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "GetMoreInstances", mtime, firstUpdate, needMeta, serviceID) - ret0, _ := ret[0].(map[string]*model.Instance) - ret1, _ := ret[1].(error) - return ret0, ret1 + ret := m.ctrl.Call(m, "DeletePlatform", id) + ret0, _ := ret[0].(error) + return ret0 } -// GetMoreInstances indicates an expected call of GetMoreInstances. -func (mr *MockStoreMockRecorder) GetMoreInstances(mtime, firstUpdate, needMeta, serviceID interface{}) *gomock.Call { +// DeletePlatform indicates an expected call of DeletePlatform +func (mr *MockStoreMockRecorder) DeletePlatform(id interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetMoreInstances", reflect.TypeOf((*MockStore)(nil).GetMoreInstances), mtime, firstUpdate, needMeta, serviceID) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "DeletePlatform", reflect.TypeOf((*MockStore)(nil).DeletePlatform), id) } -// GetMoreL5Extend mocks base method. -func (m *MockStore) GetMoreL5Extend(mtime time.Time) (map[string]map[string]interface{}, error) { +// GetPlatformById mocks base method +func (m *MockStore) GetPlatformById(id string) (*model.Platform, error) { m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "GetMoreL5Extend", mtime) - ret0, _ := ret[0].(map[string]map[string]interface{}) + ret := m.ctrl.Call(m, "GetPlatformById", id) + ret0, _ := ret[0].(*model.Platform) ret1, _ := ret[1].(error) return ret0, ret1 } -// GetMoreL5Extend indicates an expected call of GetMoreL5Extend. -func (mr *MockStoreMockRecorder) GetMoreL5Extend(mtime interface{}) *gomock.Call { +// GetPlatformById indicates an expected call of GetPlatformById +func (mr *MockStoreMockRecorder) GetPlatformById(id interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetMoreL5Extend", reflect.TypeOf((*MockStore)(nil).GetMoreL5Extend), mtime) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetPlatformById", reflect.TypeOf((*MockStore)(nil).GetPlatformById), id) } -// GetMoreL5IPConfigs mocks base method. -func (m *MockStore) GetMoreL5IPConfigs(flow uint32) ([]*model.IPConfig, error) { +// GetPlatforms mocks base method +func (m *MockStore) GetPlatforms(query map[string]string, offset, limit uint32) (uint32, []*model.Platform, error) { m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "GetMoreL5IPConfigs", flow) - ret0, _ := ret[0].([]*model.IPConfig) - ret1, _ := ret[1].(error) - return ret0, ret1 + ret := m.ctrl.Call(m, "GetPlatforms", query, offset, limit) + ret0, _ := ret[0].(uint32) + ret1, _ := ret[1].([]*model.Platform) + ret2, _ := ret[2].(error) + return ret0, ret1, ret2 } -// GetMoreL5IPConfigs indicates an expected call of GetMoreL5IPConfigs. -func (mr *MockStoreMockRecorder) GetMoreL5IPConfigs(flow interface{}) *gomock.Call { +// GetPlatforms indicates an expected call of GetPlatforms +func (mr *MockStoreMockRecorder) GetPlatforms(query, offset, limit interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetMoreL5IPConfigs", reflect.TypeOf((*MockStore)(nil).GetMoreL5IPConfigs), flow) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetPlatforms", reflect.TypeOf((*MockStore)(nil).GetPlatforms), query, offset, limit) } -// GetMoreL5Policies mocks base method. -func (m *MockStore) GetMoreL5Policies(flow uint32) ([]*model.Policy, error) { +// GetUnixSecond mocks base method +func (m *MockStore) GetUnixSecond() (int64, error) { m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "GetMoreL5Policies", flow) - ret0, _ := ret[0].([]*model.Policy) + ret := m.ctrl.Call(m, "GetUnixSecond") + ret0, _ := ret[0].(int64) ret1, _ := ret[1].(error) return ret0, ret1 } -// GetMoreL5Policies indicates an expected call of GetMoreL5Policies. -func (mr *MockStoreMockRecorder) GetMoreL5Policies(flow interface{}) *gomock.Call { +// GetUnixSecond indicates an expected call of GetUnixSecond +func (mr *MockStoreMockRecorder) GetUnixSecond() *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetMoreL5Policies", reflect.TypeOf((*MockStore)(nil).GetMoreL5Policies), flow) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetUnixSecond", reflect.TypeOf((*MockStore)(nil).GetUnixSecond)) } -// GetMoreL5Routes mocks base method. -func (m *MockStore) GetMoreL5Routes(flow uint32) ([]*model.Route, error) { +// AddUser mocks base method +func (m *MockStore) AddUser(user *model.User) error { m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "GetMoreL5Routes", flow) - ret0, _ := ret[0].([]*model.Route) - ret1, _ := ret[1].(error) - return ret0, ret1 + ret := m.ctrl.Call(m, "AddUser", user) + ret0, _ := ret[0].(error) + return ret0 } -// GetMoreL5Routes indicates an expected call of GetMoreL5Routes. -func (mr *MockStoreMockRecorder) GetMoreL5Routes(flow interface{}) *gomock.Call { +// AddUser indicates an expected call of AddUser +func (mr *MockStoreMockRecorder) AddUser(user interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetMoreL5Routes", reflect.TypeOf((*MockStore)(nil).GetMoreL5Routes), flow) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "AddUser", reflect.TypeOf((*MockStore)(nil).AddUser), user) } -// GetMoreL5Sections mocks base method. -func (m *MockStore) GetMoreL5Sections(flow uint32) ([]*model.Section, error) { +// UpdateUser mocks base method +func (m *MockStore) UpdateUser(user *model.User) error { m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "GetMoreL5Sections", flow) - ret0, _ := ret[0].([]*model.Section) - ret1, _ := ret[1].(error) - return ret0, ret1 + ret := m.ctrl.Call(m, "UpdateUser", user) + ret0, _ := ret[0].(error) + return ret0 } -// GetMoreL5Sections indicates an expected call of GetMoreL5Sections. -func (mr *MockStoreMockRecorder) GetMoreL5Sections(flow interface{}) *gomock.Call { +// UpdateUser indicates an expected call of UpdateUser +func (mr *MockStoreMockRecorder) UpdateUser(user interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetMoreL5Sections", reflect.TypeOf((*MockStore)(nil).GetMoreL5Sections), flow) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "UpdateUser", reflect.TypeOf((*MockStore)(nil).UpdateUser), user) } -// GetMoreNamespaces mocks base method. -func (m *MockStore) GetMoreNamespaces(mtime time.Time) ([]*model.Namespace, error) { +// DeleteUser mocks base method +func (m *MockStore) DeleteUser(user *model.User) error { m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "GetMoreNamespaces", mtime) - ret0, _ := ret[0].([]*model.Namespace) - ret1, _ := ret[1].(error) - return ret0, ret1 + ret := m.ctrl.Call(m, "DeleteUser", user) + ret0, _ := ret[0].(error) + return ret0 } -// GetMoreNamespaces indicates an expected call of GetMoreNamespaces. -func (mr *MockStoreMockRecorder) GetMoreNamespaces(mtime interface{}) *gomock.Call { +// DeleteUser indicates an expected call of DeleteUser +func (mr *MockStoreMockRecorder) DeleteUser(user interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetMoreNamespaces", reflect.TypeOf((*MockStore)(nil).GetMoreNamespaces), mtime) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "DeleteUser", reflect.TypeOf((*MockStore)(nil).DeleteUser), user) } -// GetMoreServices mocks base method. -func (m *MockStore) GetMoreServices(mtime time.Time, firstUpdate, disableBusiness, needMeta bool) (map[string]*model.Service, error) { +// GetSubCount mocks base method +func (m *MockStore) GetSubCount(user *model.User) (uint32, error) { m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "GetMoreServices", mtime, firstUpdate, disableBusiness, needMeta) - ret0, _ := ret[0].(map[string]*model.Service) + ret := m.ctrl.Call(m, "GetSubCount", user) + ret0, _ := ret[0].(uint32) ret1, _ := ret[1].(error) return ret0, ret1 } -// GetMoreServices indicates an expected call of GetMoreServices. -func (mr *MockStoreMockRecorder) GetMoreServices(mtime, firstUpdate, disableBusiness, needMeta interface{}) *gomock.Call { +// GetSubCount indicates an expected call of GetSubCount +func (mr *MockStoreMockRecorder) GetSubCount(user interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetMoreServices", reflect.TypeOf((*MockStore)(nil).GetMoreServices), mtime, firstUpdate, disableBusiness, needMeta) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetSubCount", reflect.TypeOf((*MockStore)(nil).GetSubCount), user) } -// GetNamespace mocks base method. -func (m *MockStore) GetNamespace(name string) (*model.Namespace, error) { +// GetUser mocks base method +func (m *MockStore) GetUser(id string) (*model.User, error) { m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "GetNamespace", name) - ret0, _ := ret[0].(*model.Namespace) + ret := m.ctrl.Call(m, "GetUser", id) + ret0, _ := ret[0].(*model.User) ret1, _ := ret[1].(error) return ret0, ret1 } -// GetNamespace indicates an expected call of GetNamespace. -func (mr *MockStoreMockRecorder) GetNamespace(name interface{}) *gomock.Call { +// GetUser indicates an expected call of GetUser +func (mr *MockStoreMockRecorder) GetUser(id interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetNamespace", reflect.TypeOf((*MockStore)(nil).GetNamespace), name) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetUser", reflect.TypeOf((*MockStore)(nil).GetUser), id) } -// GetNamespaces mocks base method. -func (m *MockStore) GetNamespaces(filter map[string][]string, offset, limit int) ([]*model.Namespace, uint32, error) { +// GetUserByName mocks base method +func (m *MockStore) GetUserByName(name, ownerId string) (*model.User, error) { m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "GetNamespaces", filter, offset, limit) - ret0, _ := ret[0].([]*model.Namespace) - ret1, _ := ret[1].(uint32) - ret2, _ := ret[2].(error) - return ret0, ret1, ret2 + ret := m.ctrl.Call(m, "GetUserByName", name, ownerId) + ret0, _ := ret[0].(*model.User) + ret1, _ := ret[1].(error) + return ret0, ret1 } -// GetNamespaces indicates an expected call of GetNamespaces. -func (mr *MockStoreMockRecorder) GetNamespaces(filter, offset, limit interface{}) *gomock.Call { +// GetUserByName indicates an expected call of GetUserByName +func (mr *MockStoreMockRecorder) GetUserByName(name, ownerId interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetNamespaces", reflect.TypeOf((*MockStore)(nil).GetNamespaces), filter, offset, limit) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetUserByName", reflect.TypeOf((*MockStore)(nil).GetUserByName), name, ownerId) } -// GetPlatformById mocks base method. -func (m *MockStore) GetPlatformById(id string) (*model.Platform, error) { +// GetUserByIds mocks base method +func (m *MockStore) GetUserByIds(ids []string) ([]*model.User, error) { m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "GetPlatformById", id) - ret0, _ := ret[0].(*model.Platform) + ret := m.ctrl.Call(m, "GetUserByIds", ids) + ret0, _ := ret[0].([]*model.User) ret1, _ := ret[1].(error) return ret0, ret1 } -// GetPlatformById indicates an expected call of GetPlatformById. -func (mr *MockStoreMockRecorder) GetPlatformById(id interface{}) *gomock.Call { +// GetUserByIds indicates an expected call of GetUserByIds +func (mr *MockStoreMockRecorder) GetUserByIds(ids interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetPlatformById", reflect.TypeOf((*MockStore)(nil).GetPlatformById), id) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetUserByIds", reflect.TypeOf((*MockStore)(nil).GetUserByIds), ids) } -// GetPlatforms mocks base method. -func (m *MockStore) GetPlatforms(query map[string]string, offset, limit uint32) (uint32, []*model.Platform, error) { +// GetUsers mocks base method +func (m *MockStore) GetUsers(filters map[string]string, offset, limit uint32) (uint32, []*model.User, error) { m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "GetPlatforms", query, offset, limit) + ret := m.ctrl.Call(m, "GetUsers", filters, offset, limit) ret0, _ := ret[0].(uint32) - ret1, _ := ret[1].([]*model.Platform) + ret1, _ := ret[1].([]*model.User) ret2, _ := ret[2].(error) return ret0, ret1, ret2 } -// GetPlatforms indicates an expected call of GetPlatforms. -func (mr *MockStoreMockRecorder) GetPlatforms(query, offset, limit interface{}) *gomock.Call { +// GetUsers indicates an expected call of GetUsers +func (mr *MockStoreMockRecorder) GetUsers(filters, offset, limit interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetPlatforms", reflect.TypeOf((*MockStore)(nil).GetPlatforms), query, offset, limit) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetUsers", reflect.TypeOf((*MockStore)(nil).GetUsers), filters, offset, limit) } -// GetRateLimitWithID mocks base method. -func (m *MockStore) GetRateLimitWithID(id string) (*model.RateLimit, error) { +// GetUsersForCache mocks base method +func (m *MockStore) GetUsersForCache(mtime time.Time, firstUpdate bool) ([]*model.User, error) { m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "GetRateLimitWithID", id) - ret0, _ := ret[0].(*model.RateLimit) + ret := m.ctrl.Call(m, "GetUsersForCache", mtime, firstUpdate) + ret0, _ := ret[0].([]*model.User) ret1, _ := ret[1].(error) return ret0, ret1 } -// GetRateLimitWithID indicates an expected call of GetRateLimitWithID. -func (mr *MockStoreMockRecorder) GetRateLimitWithID(id interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetRateLimitWithID", reflect.TypeOf((*MockStore)(nil).GetRateLimitWithID), id) -} - -// GetRateLimitsForCache mocks base method. -func (m *MockStore) GetRateLimitsForCache(mtime time.Time, firstUpdate bool) ([]*model.RateLimit, []*model.RateLimitRevision, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "GetRateLimitsForCache", mtime, firstUpdate) - ret0, _ := ret[0].([]*model.RateLimit) - ret1, _ := ret[1].([]*model.RateLimitRevision) - ret2, _ := ret[2].(error) - return ret0, ret1, ret2 -} - -// GetRateLimitsForCache indicates an expected call of GetRateLimitsForCache. -func (mr *MockStoreMockRecorder) GetRateLimitsForCache(mtime, firstUpdate interface{}) *gomock.Call { +// GetUsersForCache indicates an expected call of GetUsersForCache +func (mr *MockStoreMockRecorder) GetUsersForCache(mtime, firstUpdate interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetRateLimitsForCache", reflect.TypeOf((*MockStore)(nil).GetRateLimitsForCache), mtime, firstUpdate) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetUsersForCache", reflect.TypeOf((*MockStore)(nil).GetUsersForCache), mtime, firstUpdate) } -// GetRoutingConfigWithID mocks base method. -func (m *MockStore) GetRoutingConfigWithID(id string) (*model.RoutingConfig, error) { +// AddGroup mocks base method +func (m *MockStore) AddGroup(group *model.UserGroupDetail) error { m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "GetRoutingConfigWithID", id) - ret0, _ := ret[0].(*model.RoutingConfig) - ret1, _ := ret[1].(error) - return ret0, ret1 + ret := m.ctrl.Call(m, "AddGroup", group) + ret0, _ := ret[0].(error) + return ret0 } -// GetRoutingConfigWithID indicates an expected call of GetRoutingConfigWithID. -func (mr *MockStoreMockRecorder) GetRoutingConfigWithID(id interface{}) *gomock.Call { +// AddGroup indicates an expected call of AddGroup +func (mr *MockStoreMockRecorder) AddGroup(group interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetRoutingConfigWithID", reflect.TypeOf((*MockStore)(nil).GetRoutingConfigWithID), id) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "AddGroup", reflect.TypeOf((*MockStore)(nil).AddGroup), group) } -// GetRoutingConfigWithService mocks base method. -func (m *MockStore) GetRoutingConfigWithService(name, namespace string) (*model.RoutingConfig, error) { +// UpdateGroup mocks base method +func (m *MockStore) UpdateGroup(group *model.ModifyUserGroup) error { m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "GetRoutingConfigWithService", name, namespace) - ret0, _ := ret[0].(*model.RoutingConfig) - ret1, _ := ret[1].(error) - return ret0, ret1 + ret := m.ctrl.Call(m, "UpdateGroup", group) + ret0, _ := ret[0].(error) + return ret0 } -// GetRoutingConfigWithService indicates an expected call of GetRoutingConfigWithService. -func (mr *MockStoreMockRecorder) GetRoutingConfigWithService(name, namespace interface{}) *gomock.Call { +// UpdateGroup indicates an expected call of UpdateGroup +func (mr *MockStoreMockRecorder) UpdateGroup(group interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetRoutingConfigWithService", reflect.TypeOf((*MockStore)(nil).GetRoutingConfigWithService), name, namespace) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "UpdateGroup", reflect.TypeOf((*MockStore)(nil).UpdateGroup), group) } -// GetRoutingConfigs mocks base method. -func (m *MockStore) GetRoutingConfigs(filter map[string]string, offset, limit uint32) (uint32, []*model.ExtendRoutingConfig, error) { +// DeleteGroup mocks base method +func (m *MockStore) DeleteGroup(group *model.UserGroupDetail) error { m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "GetRoutingConfigs", filter, offset, limit) - ret0, _ := ret[0].(uint32) - ret1, _ := ret[1].([]*model.ExtendRoutingConfig) - ret2, _ := ret[2].(error) - return ret0, ret1, ret2 + ret := m.ctrl.Call(m, "DeleteGroup", group) + ret0, _ := ret[0].(error) + return ret0 } -// GetRoutingConfigs indicates an expected call of GetRoutingConfigs. -func (mr *MockStoreMockRecorder) GetRoutingConfigs(filter, offset, limit interface{}) *gomock.Call { +// DeleteGroup indicates an expected call of DeleteGroup +func (mr *MockStoreMockRecorder) DeleteGroup(group interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetRoutingConfigs", reflect.TypeOf((*MockStore)(nil).GetRoutingConfigs), filter, offset, limit) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "DeleteGroup", reflect.TypeOf((*MockStore)(nil).DeleteGroup), group) } -// GetRoutingConfigsForCache mocks base method. -func (m *MockStore) GetRoutingConfigsForCache(mtime time.Time, firstUpdate bool) ([]*model.RoutingConfig, error) { +// GetGroup mocks base method +func (m *MockStore) GetGroup(id string) (*model.UserGroupDetail, error) { m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "GetRoutingConfigsForCache", mtime, firstUpdate) - ret0, _ := ret[0].([]*model.RoutingConfig) + ret := m.ctrl.Call(m, "GetGroup", id) + ret0, _ := ret[0].(*model.UserGroupDetail) ret1, _ := ret[1].(error) return ret0, ret1 } -// GetRoutingConfigsForCache indicates an expected call of GetRoutingConfigsForCache. -func (mr *MockStoreMockRecorder) GetRoutingConfigsForCache(mtime, firstUpdate interface{}) *gomock.Call { +// GetGroup indicates an expected call of GetGroup +func (mr *MockStoreMockRecorder) GetGroup(id interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetRoutingConfigsForCache", reflect.TypeOf((*MockStore)(nil).GetRoutingConfigsForCache), mtime, firstUpdate) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetGroup", reflect.TypeOf((*MockStore)(nil).GetGroup), id) } -// GetService mocks base method. -func (m *MockStore) GetService(name, namespace string) (*model.Service, error) { +// GetGroupByName mocks base method +func (m *MockStore) GetGroupByName(name, owner string) (*model.UserGroup, error) { m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "GetService", name, namespace) - ret0, _ := ret[0].(*model.Service) + ret := m.ctrl.Call(m, "GetGroupByName", name, owner) + ret0, _ := ret[0].(*model.UserGroup) ret1, _ := ret[1].(error) return ret0, ret1 } -// GetService indicates an expected call of GetService. -func (mr *MockStoreMockRecorder) GetService(name, namespace interface{}) *gomock.Call { +// GetGroupByName indicates an expected call of GetGroupByName +func (mr *MockStoreMockRecorder) GetGroupByName(name, owner interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetService", reflect.TypeOf((*MockStore)(nil).GetService), name, namespace) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetGroupByName", reflect.TypeOf((*MockStore)(nil).GetGroupByName), name, owner) } -// GetServiceAliases mocks base method. -func (m *MockStore) GetServiceAliases(filter map[string]string, offset, limit uint32) (uint32, []*model.ServiceAlias, error) { +// GetGroups mocks base method +func (m *MockStore) GetGroups(filters map[string]string, offset, limit uint32) (uint32, []*model.UserGroup, error) { m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "GetServiceAliases", filter, offset, limit) + ret := m.ctrl.Call(m, "GetGroups", filters, offset, limit) ret0, _ := ret[0].(uint32) - ret1, _ := ret[1].([]*model.ServiceAlias) + ret1, _ := ret[1].([]*model.UserGroup) ret2, _ := ret[2].(error) return ret0, ret1, ret2 } -// GetServiceAliases indicates an expected call of GetServiceAliases. -func (mr *MockStoreMockRecorder) GetServiceAliases(filter, offset, limit interface{}) *gomock.Call { +// GetGroups indicates an expected call of GetGroups +func (mr *MockStoreMockRecorder) GetGroups(filters, offset, limit interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetServiceAliases", reflect.TypeOf((*MockStore)(nil).GetServiceAliases), filter, offset, limit) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetGroups", reflect.TypeOf((*MockStore)(nil).GetGroups), filters, offset, limit) } -// GetServiceByID mocks base method. -func (m *MockStore) GetServiceByID(id string) (*model.Service, error) { +// GetGroupsForCache mocks base method +func (m *MockStore) GetGroupsForCache(mtime time.Time, firstUpdate bool) ([]*model.UserGroupDetail, error) { m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "GetServiceByID", id) - ret0, _ := ret[0].(*model.Service) + ret := m.ctrl.Call(m, "GetGroupsForCache", mtime, firstUpdate) + ret0, _ := ret[0].([]*model.UserGroupDetail) ret1, _ := ret[1].(error) return ret0, ret1 } -// GetServiceByID indicates an expected call of GetServiceByID. -func (mr *MockStoreMockRecorder) GetServiceByID(id interface{}) *gomock.Call { +// GetGroupsForCache indicates an expected call of GetGroupsForCache +func (mr *MockStoreMockRecorder) GetGroupsForCache(mtime, firstUpdate interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetServiceByID", reflect.TypeOf((*MockStore)(nil).GetServiceByID), id) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetGroupsForCache", reflect.TypeOf((*MockStore)(nil).GetGroupsForCache), mtime, firstUpdate) } -// GetServices mocks base method. -func (m *MockStore) GetServices(serviceFilters, serviceMetas map[string]string, instanceFilters *store.InstanceArgs, offset, limit uint32) (uint32, []*model.Service, error) { +// AddStrategy mocks base method +func (m *MockStore) AddStrategy(strategy *model.StrategyDetail) error { m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "GetServices", serviceFilters, serviceMetas, instanceFilters, offset, limit) - ret0, _ := ret[0].(uint32) - ret1, _ := ret[1].([]*model.Service) - ret2, _ := ret[2].(error) - return ret0, ret1, ret2 + ret := m.ctrl.Call(m, "AddStrategy", strategy) + ret0, _ := ret[0].(error) + return ret0 } -// GetServices indicates an expected call of GetServices. -func (mr *MockStoreMockRecorder) GetServices(serviceFilters, serviceMetas, instanceFilters, offset, limit interface{}) *gomock.Call { +// AddStrategy indicates an expected call of AddStrategy +func (mr *MockStoreMockRecorder) AddStrategy(strategy interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetServices", reflect.TypeOf((*MockStore)(nil).GetServices), serviceFilters, serviceMetas, instanceFilters, offset, limit) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "AddStrategy", reflect.TypeOf((*MockStore)(nil).AddStrategy), strategy) } -// GetServicesBatch mocks base method. -func (m *MockStore) GetServicesBatch(services []*model.Service) ([]*model.Service, error) { +// UpdateStrategy mocks base method +func (m *MockStore) UpdateStrategy(strategy *model.ModifyStrategyDetail) error { m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "GetServicesBatch", services) - ret0, _ := ret[0].([]*model.Service) - ret1, _ := ret[1].(error) - return ret0, ret1 + ret := m.ctrl.Call(m, "UpdateStrategy", strategy) + ret0, _ := ret[0].(error) + return ret0 } -// GetServicesBatch indicates an expected call of GetServicesBatch. -func (mr *MockStoreMockRecorder) GetServicesBatch(services interface{}) *gomock.Call { +// UpdateStrategy indicates an expected call of UpdateStrategy +func (mr *MockStoreMockRecorder) UpdateStrategy(strategy interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetServicesBatch", reflect.TypeOf((*MockStore)(nil).GetServicesBatch), services) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "UpdateStrategy", reflect.TypeOf((*MockStore)(nil).UpdateStrategy), strategy) } -// GetServicesCount mocks base method. -func (m *MockStore) GetServicesCount() (uint32, error) { +// DeleteStrategy mocks base method +func (m *MockStore) DeleteStrategy(id string) error { m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "GetServicesCount") - ret0, _ := ret[0].(uint32) - ret1, _ := ret[1].(error) - return ret0, ret1 + ret := m.ctrl.Call(m, "DeleteStrategy", id) + ret0, _ := ret[0].(error) + return ret0 } -// GetServicesCount indicates an expected call of GetServicesCount. -func (mr *MockStoreMockRecorder) GetServicesCount() *gomock.Call { +// DeleteStrategy indicates an expected call of DeleteStrategy +func (mr *MockStoreMockRecorder) DeleteStrategy(id interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetServicesCount", reflect.TypeOf((*MockStore)(nil).GetServicesCount)) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "DeleteStrategy", reflect.TypeOf((*MockStore)(nil).DeleteStrategy), id) } -// GetSourceServiceToken mocks base method. -func (m *MockStore) GetSourceServiceToken(name, namespace string) (*model.Service, error) { +// LooseAddStrategyResources mocks base method +func (m *MockStore) LooseAddStrategyResources(resources []model.StrategyResource) error { m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "GetSourceServiceToken", name, namespace) - ret0, _ := ret[0].(*model.Service) - ret1, _ := ret[1].(error) - return ret0, ret1 + ret := m.ctrl.Call(m, "LooseAddStrategyResources", resources) + ret0, _ := ret[0].(error) + return ret0 } -// GetSourceServiceToken indicates an expected call of GetSourceServiceToken. -func (mr *MockStoreMockRecorder) GetSourceServiceToken(name, namespace interface{}) *gomock.Call { +// LooseAddStrategyResources indicates an expected call of LooseAddStrategyResources +func (mr *MockStoreMockRecorder) LooseAddStrategyResources(resources interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetSourceServiceToken", reflect.TypeOf((*MockStore)(nil).GetSourceServiceToken), name, namespace) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "LooseAddStrategyResources", reflect.TypeOf((*MockStore)(nil).LooseAddStrategyResources), resources) } -// GetStrategies mocks base method. -func (m *MockStore) GetStrategies(filters map[string]string, offset, limit uint32) (uint32, []*model.StrategyDetail, error) { +// RemoveStrategyResources mocks base method +func (m *MockStore) RemoveStrategyResources(resources []model.StrategyResource) error { m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "GetStrategies", filters, offset, limit) - ret0, _ := ret[0].(uint32) - ret1, _ := ret[1].([]*model.StrategyDetail) - ret2, _ := ret[2].(error) - return ret0, ret1, ret2 + ret := m.ctrl.Call(m, "RemoveStrategyResources", resources) + ret0, _ := ret[0].(error) + return ret0 } -// GetStrategies indicates an expected call of GetStrategies. -func (mr *MockStoreMockRecorder) GetStrategies(filters, offset, limit interface{}) *gomock.Call { +// RemoveStrategyResources indicates an expected call of RemoveStrategyResources +func (mr *MockStoreMockRecorder) RemoveStrategyResources(resources interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetStrategies", reflect.TypeOf((*MockStore)(nil).GetStrategies), filters, offset, limit) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "RemoveStrategyResources", reflect.TypeOf((*MockStore)(nil).RemoveStrategyResources), resources) } -// GetStrategyDetail mocks base method. -func (m *MockStore) GetStrategyDetail(id string) (*model.StrategyDetail, error) { +// GetStrategyResources mocks base method +func (m *MockStore) GetStrategyResources(principalId string, principalRole model.PrincipalType) ([]model.StrategyResource, error) { m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "GetStrategyDetail", id) - ret0, _ := ret[0].(*model.StrategyDetail) + ret := m.ctrl.Call(m, "GetStrategyResources", principalId, principalRole) + ret0, _ := ret[0].([]model.StrategyResource) ret1, _ := ret[1].(error) return ret0, ret1 } -// GetStrategyDetail indicates an expected call of GetStrategyDetail. -func (mr *MockStoreMockRecorder) GetStrategyDetail(id interface{}) *gomock.Call { +// GetStrategyResources indicates an expected call of GetStrategyResources +func (mr *MockStoreMockRecorder) GetStrategyResources(principalId, principalRole interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetStrategyDetail", reflect.TypeOf((*MockStore)(nil).GetStrategyDetail), id) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetStrategyResources", reflect.TypeOf((*MockStore)(nil).GetStrategyResources), principalId, principalRole) } -// GetStrategyDetailsForCache mocks base method. -func (m *MockStore) GetStrategyDetailsForCache(mtime time.Time, firstUpdate bool) ([]*model.StrategyDetail, error) { +// GetDefaultStrategyDetailByPrincipal mocks base method +func (m *MockStore) GetDefaultStrategyDetailByPrincipal(principalId string, principalType model.PrincipalType) (*model.StrategyDetail, error) { m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "GetStrategyDetailsForCache", mtime, firstUpdate) - ret0, _ := ret[0].([]*model.StrategyDetail) + ret := m.ctrl.Call(m, "GetDefaultStrategyDetailByPrincipal", principalId, principalType) + ret0, _ := ret[0].(*model.StrategyDetail) ret1, _ := ret[1].(error) return ret0, ret1 } -// GetStrategyDetailsForCache indicates an expected call of GetStrategyDetailsForCache. -func (mr *MockStoreMockRecorder) GetStrategyDetailsForCache(mtime, firstUpdate interface{}) *gomock.Call { +// GetDefaultStrategyDetailByPrincipal indicates an expected call of GetDefaultStrategyDetailByPrincipal +func (mr *MockStoreMockRecorder) GetDefaultStrategyDetailByPrincipal(principalId, principalType interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetStrategyDetailsForCache", reflect.TypeOf((*MockStore)(nil).GetStrategyDetailsForCache), mtime, firstUpdate) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetDefaultStrategyDetailByPrincipal", reflect.TypeOf((*MockStore)(nil).GetDefaultStrategyDetailByPrincipal), principalId, principalType) } -// GetStrategyResources mocks base method. -func (m *MockStore) GetStrategyResources(principalId string, principalRole model.PrincipalType) ([]model.StrategyResource, error) { +// GetStrategyDetail mocks base method +func (m *MockStore) GetStrategyDetail(id string) (*model.StrategyDetail, error) { m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "GetStrategyResources", principalId, principalRole) - ret0, _ := ret[0].([]model.StrategyResource) + ret := m.ctrl.Call(m, "GetStrategyDetail", id) + ret0, _ := ret[0].(*model.StrategyDetail) ret1, _ := ret[1].(error) return ret0, ret1 } -// GetStrategyResources indicates an expected call of GetStrategyResources. -func (mr *MockStoreMockRecorder) GetStrategyResources(principalId, principalRole interface{}) *gomock.Call { +// GetStrategyDetail indicates an expected call of GetStrategyDetail +func (mr *MockStoreMockRecorder) GetStrategyDetail(id interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetStrategyResources", reflect.TypeOf((*MockStore)(nil).GetStrategyResources), principalId, principalRole) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetStrategyDetail", reflect.TypeOf((*MockStore)(nil).GetStrategyDetail), id) } -// GetSubCount mocks base method. -func (m *MockStore) GetSubCount(user *model.User) (uint32, error) { +// GetStrategies mocks base method +func (m *MockStore) GetStrategies(filters map[string]string, offset, limit uint32) (uint32, []*model.StrategyDetail, error) { m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "GetSubCount", user) + ret := m.ctrl.Call(m, "GetStrategies", filters, offset, limit) ret0, _ := ret[0].(uint32) - ret1, _ := ret[1].(error) - return ret0, ret1 + ret1, _ := ret[1].([]*model.StrategyDetail) + ret2, _ := ret[2].(error) + return ret0, ret1, ret2 } -// GetSubCount indicates an expected call of GetSubCount. -func (mr *MockStoreMockRecorder) GetSubCount(user interface{}) *gomock.Call { +// GetStrategies indicates an expected call of GetStrategies +func (mr *MockStoreMockRecorder) GetStrategies(filters, offset, limit interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetSubCount", reflect.TypeOf((*MockStore)(nil).GetSubCount), user) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetStrategies", reflect.TypeOf((*MockStore)(nil).GetStrategies), filters, offset, limit) } -// GetSystemServices mocks base method. -func (m *MockStore) GetSystemServices() ([]*model.Service, error) { +// GetStrategyDetailsForCache mocks base method +func (m *MockStore) GetStrategyDetailsForCache(mtime time.Time, firstUpdate bool) ([]*model.StrategyDetail, error) { m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "GetSystemServices") - ret0, _ := ret[0].([]*model.Service) + ret := m.ctrl.Call(m, "GetStrategyDetailsForCache", mtime, firstUpdate) + ret0, _ := ret[0].([]*model.StrategyDetail) ret1, _ := ret[1].(error) return ret0, ret1 } -// GetSystemServices indicates an expected call of GetSystemServices. -func (mr *MockStoreMockRecorder) GetSystemServices() *gomock.Call { +// GetStrategyDetailsForCache indicates an expected call of GetStrategyDetailsForCache +func (mr *MockStoreMockRecorder) GetStrategyDetailsForCache(mtime, firstUpdate interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetSystemServices", reflect.TypeOf((*MockStore)(nil).GetSystemServices)) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetStrategyDetailsForCache", reflect.TypeOf((*MockStore)(nil).GetStrategyDetailsForCache), mtime, firstUpdate) } -// GetUnixSecond mocks base method. -func (m *MockStore) GetUnixSecond() (int64, error) { +// EnableRouting mocks base method +func (m *MockStore) EnableRouting(conf *v2.RoutingConfig) error { m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "GetUnixSecond") - ret0, _ := ret[0].(int64) - ret1, _ := ret[1].(error) - return ret0, ret1 + ret := m.ctrl.Call(m, "EnableRouting", conf) + ret0, _ := ret[0].(error) + return ret0 } -// GetUnixSecond indicates an expected call of GetUnixSecond. -func (mr *MockStoreMockRecorder) GetUnixSecond() *gomock.Call { +// EnableRouting indicates an expected call of EnableRouting +func (mr *MockStoreMockRecorder) EnableRouting(conf interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetUnixSecond", reflect.TypeOf((*MockStore)(nil).GetUnixSecond)) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "EnableRouting", reflect.TypeOf((*MockStore)(nil).EnableRouting), conf) } -// GetUser mocks base method. -func (m *MockStore) GetUser(id string) (*model.User, error) { +// CreateRoutingConfigV2 mocks base method +func (m *MockStore) CreateRoutingConfigV2(conf *v2.RoutingConfig) error { m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "GetUser", id) - ret0, _ := ret[0].(*model.User) - ret1, _ := ret[1].(error) - return ret0, ret1 + ret := m.ctrl.Call(m, "CreateRoutingConfigV2", conf) + ret0, _ := ret[0].(error) + return ret0 } -// GetUser indicates an expected call of GetUser. -func (mr *MockStoreMockRecorder) GetUser(id interface{}) *gomock.Call { +// CreateRoutingConfigV2 indicates an expected call of CreateRoutingConfigV2 +func (mr *MockStoreMockRecorder) CreateRoutingConfigV2(conf interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetUser", reflect.TypeOf((*MockStore)(nil).GetUser), id) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "CreateRoutingConfigV2", reflect.TypeOf((*MockStore)(nil).CreateRoutingConfigV2), conf) } -// GetUserByIds mocks base method. -func (m *MockStore) GetUserByIds(ids []string) ([]*model.User, error) { +// CreateRoutingConfigV2Tx mocks base method +func (m *MockStore) CreateRoutingConfigV2Tx(tx store.Tx, conf *v2.RoutingConfig) error { m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "GetUserByIds", ids) - ret0, _ := ret[0].([]*model.User) - ret1, _ := ret[1].(error) - return ret0, ret1 + ret := m.ctrl.Call(m, "CreateRoutingConfigV2Tx", tx, conf) + ret0, _ := ret[0].(error) + return ret0 } -// GetUserByIds indicates an expected call of GetUserByIds. -func (mr *MockStoreMockRecorder) GetUserByIds(ids interface{}) *gomock.Call { +// CreateRoutingConfigV2Tx indicates an expected call of CreateRoutingConfigV2Tx +func (mr *MockStoreMockRecorder) CreateRoutingConfigV2Tx(tx, conf interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetUserByIds", reflect.TypeOf((*MockStore)(nil).GetUserByIds), ids) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "CreateRoutingConfigV2Tx", reflect.TypeOf((*MockStore)(nil).CreateRoutingConfigV2Tx), tx, conf) } -// GetUserByName mocks base method. -func (m *MockStore) GetUserByName(name, ownerId string) (*model.User, error) { +// UpdateRoutingConfigV2 mocks base method +func (m *MockStore) UpdateRoutingConfigV2(conf *v2.RoutingConfig) error { m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "GetUserByName", name, ownerId) - ret0, _ := ret[0].(*model.User) - ret1, _ := ret[1].(error) - return ret0, ret1 + ret := m.ctrl.Call(m, "UpdateRoutingConfigV2", conf) + ret0, _ := ret[0].(error) + return ret0 } -// GetUserByName indicates an expected call of GetUserByName. -func (mr *MockStoreMockRecorder) GetUserByName(name, ownerId interface{}) *gomock.Call { +// UpdateRoutingConfigV2 indicates an expected call of UpdateRoutingConfigV2 +func (mr *MockStoreMockRecorder) UpdateRoutingConfigV2(conf interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetUserByName", reflect.TypeOf((*MockStore)(nil).GetUserByName), name, ownerId) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "UpdateRoutingConfigV2", reflect.TypeOf((*MockStore)(nil).UpdateRoutingConfigV2), conf) } -// GetUsers mocks base method. -func (m *MockStore) GetUsers(filters map[string]string, offset, limit uint32) (uint32, []*model.User, error) { +// UpdateRoutingConfigV2Tx mocks base method +func (m *MockStore) UpdateRoutingConfigV2Tx(tx store.Tx, conf *v2.RoutingConfig) error { m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "GetUsers", filters, offset, limit) - ret0, _ := ret[0].(uint32) - ret1, _ := ret[1].([]*model.User) - ret2, _ := ret[2].(error) - return ret0, ret1, ret2 + ret := m.ctrl.Call(m, "UpdateRoutingConfigV2Tx", tx, conf) + ret0, _ := ret[0].(error) + return ret0 } -// GetUsers indicates an expected call of GetUsers. -func (mr *MockStoreMockRecorder) GetUsers(filters, offset, limit interface{}) *gomock.Call { +// UpdateRoutingConfigV2Tx indicates an expected call of UpdateRoutingConfigV2Tx +func (mr *MockStoreMockRecorder) UpdateRoutingConfigV2Tx(tx, conf interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetUsers", reflect.TypeOf((*MockStore)(nil).GetUsers), filters, offset, limit) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "UpdateRoutingConfigV2Tx", reflect.TypeOf((*MockStore)(nil).UpdateRoutingConfigV2Tx), tx, conf) } -// GetUsersForCache mocks base method. -func (m *MockStore) GetUsersForCache(mtime time.Time, firstUpdate bool) ([]*model.User, error) { +// DeleteRoutingConfigV2 mocks base method +func (m *MockStore) DeleteRoutingConfigV2(serviceID string) error { m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "GetUsersForCache", mtime, firstUpdate) - ret0, _ := ret[0].([]*model.User) - ret1, _ := ret[1].(error) - return ret0, ret1 + ret := m.ctrl.Call(m, "DeleteRoutingConfigV2", serviceID) + ret0, _ := ret[0].(error) + return ret0 } -// GetUsersForCache indicates an expected call of GetUsersForCache. -func (mr *MockStoreMockRecorder) GetUsersForCache(mtime, firstUpdate interface{}) *gomock.Call { +// DeleteRoutingConfigV2 indicates an expected call of DeleteRoutingConfigV2 +func (mr *MockStoreMockRecorder) DeleteRoutingConfigV2(serviceID interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetUsersForCache", reflect.TypeOf((*MockStore)(nil).GetUsersForCache), mtime, firstUpdate) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "DeleteRoutingConfigV2", reflect.TypeOf((*MockStore)(nil).DeleteRoutingConfigV2), serviceID) } -// Initialize mocks base method. -func (m *MockStore) Initialize(c *store.Config) error { +// GetRoutingConfigsV2ForCache mocks base method +func (m *MockStore) GetRoutingConfigsV2ForCache(mtime time.Time, firstUpdate bool) ([]*v2.RoutingConfig, error) { m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "Initialize", c) - ret0, _ := ret[0].(error) - return ret0 + ret := m.ctrl.Call(m, "GetRoutingConfigsV2ForCache", mtime, firstUpdate) + ret0, _ := ret[0].([]*v2.RoutingConfig) + ret1, _ := ret[1].(error) + return ret0, ret1 } -// Initialize indicates an expected call of Initialize. -func (mr *MockStoreMockRecorder) Initialize(c interface{}) *gomock.Call { +// GetRoutingConfigsV2ForCache indicates an expected call of GetRoutingConfigsV2ForCache +func (mr *MockStoreMockRecorder) GetRoutingConfigsV2ForCache(mtime, firstUpdate interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Initialize", reflect.TypeOf((*MockStore)(nil).Initialize), c) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetRoutingConfigsV2ForCache", reflect.TypeOf((*MockStore)(nil).GetRoutingConfigsV2ForCache), mtime, firstUpdate) } -// ListBusiness mocks base method. -func (m *MockStore) ListBusiness(owner string) ([]*model.Business, error) { +// GetRoutingConfigV2WithID mocks base method +func (m *MockStore) GetRoutingConfigV2WithID(id string) (*v2.RoutingConfig, error) { m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "ListBusiness", owner) - ret0, _ := ret[0].([]*model.Business) + ret := m.ctrl.Call(m, "GetRoutingConfigV2WithID", id) + ret0, _ := ret[0].(*v2.RoutingConfig) ret1, _ := ret[1].(error) return ret0, ret1 } -// ListBusiness indicates an expected call of ListBusiness. -func (mr *MockStoreMockRecorder) ListBusiness(owner interface{}) *gomock.Call { +// GetRoutingConfigV2WithID indicates an expected call of GetRoutingConfigV2WithID +func (mr *MockStoreMockRecorder) GetRoutingConfigV2WithID(id interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ListBusiness", reflect.TypeOf((*MockStore)(nil).ListBusiness), owner) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetRoutingConfigV2WithID", reflect.TypeOf((*MockStore)(nil).GetRoutingConfigV2WithID), id) } -// ListMasterCircuitBreakers mocks base method. -func (m *MockStore) ListMasterCircuitBreakers(filters map[string]string, offset, limit uint32) (*model.CircuitBreakerDetail, error) { +// GetRoutingConfigV2WithIDTx mocks base method +func (m *MockStore) GetRoutingConfigV2WithIDTx(tx store.Tx, id string) (*v2.RoutingConfig, error) { m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "ListMasterCircuitBreakers", filters, offset, limit) - ret0, _ := ret[0].(*model.CircuitBreakerDetail) + ret := m.ctrl.Call(m, "GetRoutingConfigV2WithIDTx", tx, id) + ret0, _ := ret[0].(*v2.RoutingConfig) ret1, _ := ret[1].(error) return ret0, ret1 } -// ListMasterCircuitBreakers indicates an expected call of ListMasterCircuitBreakers. -func (mr *MockStoreMockRecorder) ListMasterCircuitBreakers(filters, offset, limit interface{}) *gomock.Call { +// GetRoutingConfigV2WithIDTx indicates an expected call of GetRoutingConfigV2WithIDTx +func (mr *MockStoreMockRecorder) GetRoutingConfigV2WithIDTx(tx, id interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ListMasterCircuitBreakers", reflect.TypeOf((*MockStore)(nil).ListMasterCircuitBreakers), filters, offset, limit) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetRoutingConfigV2WithIDTx", reflect.TypeOf((*MockStore)(nil).GetRoutingConfigV2WithIDTx), tx, id) } -// ListNamespaces mocks base method. -func (m *MockStore) ListNamespaces(owner string) ([]*model.Namespace, error) { +// CreateConfigFileGroup mocks base method +func (m *MockStore) CreateConfigFileGroup(fileGroup *model.ConfigFileGroup) (*model.ConfigFileGroup, error) { m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "ListNamespaces", owner) - ret0, _ := ret[0].([]*model.Namespace) + ret := m.ctrl.Call(m, "CreateConfigFileGroup", fileGroup) + ret0, _ := ret[0].(*model.ConfigFileGroup) ret1, _ := ret[1].(error) return ret0, ret1 } -// ListNamespaces indicates an expected call of ListNamespaces. -func (mr *MockStoreMockRecorder) ListNamespaces(owner interface{}) *gomock.Call { +// CreateConfigFileGroup indicates an expected call of CreateConfigFileGroup +func (mr *MockStoreMockRecorder) CreateConfigFileGroup(fileGroup interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ListNamespaces", reflect.TypeOf((*MockStore)(nil).ListNamespaces), owner) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "CreateConfigFileGroup", reflect.TypeOf((*MockStore)(nil).CreateConfigFileGroup), fileGroup) } -// ListReleaseCircuitBreakers mocks base method. -func (m *MockStore) ListReleaseCircuitBreakers(filters map[string]string, offset, limit uint32) (*model.CircuitBreakerDetail, error) { +// GetConfigFileGroup mocks base method +func (m *MockStore) GetConfigFileGroup(namespace, name string) (*model.ConfigFileGroup, error) { m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "ListReleaseCircuitBreakers", filters, offset, limit) - ret0, _ := ret[0].(*model.CircuitBreakerDetail) + ret := m.ctrl.Call(m, "GetConfigFileGroup", namespace, name) + ret0, _ := ret[0].(*model.ConfigFileGroup) ret1, _ := ret[1].(error) return ret0, ret1 } -// ListReleaseCircuitBreakers indicates an expected call of ListReleaseCircuitBreakers. -func (mr *MockStoreMockRecorder) ListReleaseCircuitBreakers(filters, offset, limit interface{}) *gomock.Call { +// GetConfigFileGroup indicates an expected call of GetConfigFileGroup +func (mr *MockStoreMockRecorder) GetConfigFileGroup(namespace, name interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ListReleaseCircuitBreakers", reflect.TypeOf((*MockStore)(nil).ListReleaseCircuitBreakers), filters, offset, limit) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetConfigFileGroup", reflect.TypeOf((*MockStore)(nil).GetConfigFileGroup), namespace, name) } -// LooseAddStrategyResources mocks base method. -func (m *MockStore) LooseAddStrategyResources(resources []model.StrategyResource) error { +// QueryConfigFileGroups mocks base method +func (m *MockStore) QueryConfigFileGroups(namespace, name string, offset, limit uint32) (uint32, []*model.ConfigFileGroup, error) { m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "LooseAddStrategyResources", resources) - ret0, _ := ret[0].(error) - return ret0 + ret := m.ctrl.Call(m, "QueryConfigFileGroups", namespace, name, offset, limit) + ret0, _ := ret[0].(uint32) + ret1, _ := ret[1].([]*model.ConfigFileGroup) + ret2, _ := ret[2].(error) + return ret0, ret1, ret2 } -// LooseAddStrategyResources indicates an expected call of LooseAddStrategyResources. -func (mr *MockStoreMockRecorder) LooseAddStrategyResources(resources interface{}) *gomock.Call { +// QueryConfigFileGroups indicates an expected call of QueryConfigFileGroups +func (mr *MockStoreMockRecorder) QueryConfigFileGroups(namespace, name, offset, limit interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "LooseAddStrategyResources", reflect.TypeOf((*MockStore)(nil).LooseAddStrategyResources), resources) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "QueryConfigFileGroups", reflect.TypeOf((*MockStore)(nil).QueryConfigFileGroups), namespace, name, offset, limit) } -// Name mocks base method. -func (m *MockStore) Name() string { +// DeleteConfigFileGroup mocks base method +func (m *MockStore) DeleteConfigFileGroup(namespace, name string) error { m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "Name") - ret0, _ := ret[0].(string) + ret := m.ctrl.Call(m, "DeleteConfigFileGroup", namespace, name) + ret0, _ := ret[0].(error) return ret0 } -// Name indicates an expected call of Name. -func (mr *MockStoreMockRecorder) Name() *gomock.Call { +// DeleteConfigFileGroup indicates an expected call of DeleteConfigFileGroup +func (mr *MockStoreMockRecorder) DeleteConfigFileGroup(namespace, name interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Name", reflect.TypeOf((*MockStore)(nil).Name)) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "DeleteConfigFileGroup", reflect.TypeOf((*MockStore)(nil).DeleteConfigFileGroup), namespace, name) } -// QueryAllConfigFileTemplates mocks base method. -func (m *MockStore) QueryAllConfigFileTemplates() ([]*model.ConfigFileTemplate, error) { +// UpdateConfigFileGroup mocks base method +func (m *MockStore) UpdateConfigFileGroup(fileGroup *model.ConfigFileGroup) (*model.ConfigFileGroup, error) { m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "QueryAllConfigFileTemplates") - ret0, _ := ret[0].([]*model.ConfigFileTemplate) + ret := m.ctrl.Call(m, "UpdateConfigFileGroup", fileGroup) + ret0, _ := ret[0].(*model.ConfigFileGroup) ret1, _ := ret[1].(error) return ret0, ret1 } -// QueryAllConfigFileTemplates indicates an expected call of QueryAllConfigFileTemplates. -func (mr *MockStoreMockRecorder) QueryAllConfigFileTemplates() *gomock.Call { +// UpdateConfigFileGroup indicates an expected call of UpdateConfigFileGroup +func (mr *MockStoreMockRecorder) UpdateConfigFileGroup(fileGroup interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "QueryAllConfigFileTemplates", reflect.TypeOf((*MockStore)(nil).QueryAllConfigFileTemplates)) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "UpdateConfigFileGroup", reflect.TypeOf((*MockStore)(nil).UpdateConfigFileGroup), fileGroup) } -// QueryConfigFileByTag mocks base method. -func (m *MockStore) QueryConfigFileByTag(namespace, group, fileName string, tags ...string) ([]*model.ConfigFileTag, error) { +// FindConfigFileGroups mocks base method +func (m *MockStore) FindConfigFileGroups(namespace string, names []string) ([]*model.ConfigFileGroup, error) { m.ctrl.T.Helper() - varargs := []interface{}{namespace, group, fileName} - for _, a := range tags { - varargs = append(varargs, a) - } - ret := m.ctrl.Call(m, "QueryConfigFileByTag", varargs...) - ret0, _ := ret[0].([]*model.ConfigFileTag) + ret := m.ctrl.Call(m, "FindConfigFileGroups", namespace, names) + ret0, _ := ret[0].([]*model.ConfigFileGroup) ret1, _ := ret[1].(error) return ret0, ret1 } -// QueryConfigFileByTag indicates an expected call of QueryConfigFileByTag. -func (mr *MockStoreMockRecorder) QueryConfigFileByTag(namespace, group, fileName interface{}, tags ...interface{}) *gomock.Call { +// FindConfigFileGroups indicates an expected call of FindConfigFileGroups +func (mr *MockStoreMockRecorder) FindConfigFileGroups(namespace, names interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() - varargs := append([]interface{}{namespace, group, fileName}, tags...) - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "QueryConfigFileByTag", reflect.TypeOf((*MockStore)(nil).QueryConfigFileByTag), varargs...) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "FindConfigFileGroups", reflect.TypeOf((*MockStore)(nil).FindConfigFileGroups), namespace, names) } -// QueryConfigFileGroups mocks base method. -func (m *MockStore) QueryConfigFileGroups(namespace, name string, offset, limit uint32) (uint32, []*model.ConfigFileGroup, error) { +// CreateConfigFile mocks base method +func (m *MockStore) CreateConfigFile(tx store.Tx, file *model.ConfigFile) (*model.ConfigFile, error) { m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "QueryConfigFileGroups", namespace, name, offset, limit) - ret0, _ := ret[0].(uint32) - ret1, _ := ret[1].([]*model.ConfigFileGroup) - ret2, _ := ret[2].(error) - return ret0, ret1, ret2 + ret := m.ctrl.Call(m, "CreateConfigFile", tx, file) + ret0, _ := ret[0].(*model.ConfigFile) + ret1, _ := ret[1].(error) + return ret0, ret1 } -// QueryConfigFileGroups indicates an expected call of QueryConfigFileGroups. -func (mr *MockStoreMockRecorder) QueryConfigFileGroups(namespace, name, offset, limit interface{}) *gomock.Call { +// CreateConfigFile indicates an expected call of CreateConfigFile +func (mr *MockStoreMockRecorder) CreateConfigFile(tx, file interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "QueryConfigFileGroups", reflect.TypeOf((*MockStore)(nil).QueryConfigFileGroups), namespace, name, offset, limit) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "CreateConfigFile", reflect.TypeOf((*MockStore)(nil).CreateConfigFile), tx, file) } -// QueryConfigFileReleaseHistories mocks base method. -func (m *MockStore) QueryConfigFileReleaseHistories(namespace, group, fileName string, offset, limit uint32, endId uint64) (uint32, []*model.ConfigFileReleaseHistory, error) { +// GetConfigFile mocks base method +func (m *MockStore) GetConfigFile(tx store.Tx, namespace, group, name string) (*model.ConfigFile, error) { m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "QueryConfigFileReleaseHistories", namespace, group, fileName, offset, limit, endId) - ret0, _ := ret[0].(uint32) - ret1, _ := ret[1].([]*model.ConfigFileReleaseHistory) - ret2, _ := ret[2].(error) - return ret0, ret1, ret2 + ret := m.ctrl.Call(m, "GetConfigFile", tx, namespace, group, name) + ret0, _ := ret[0].(*model.ConfigFile) + ret1, _ := ret[1].(error) + return ret0, ret1 } -// QueryConfigFileReleaseHistories indicates an expected call of QueryConfigFileReleaseHistories. -func (mr *MockStoreMockRecorder) QueryConfigFileReleaseHistories(namespace, group, fileName, offset, limit, endId interface{}) *gomock.Call { +// GetConfigFile indicates an expected call of GetConfigFile +func (mr *MockStoreMockRecorder) GetConfigFile(tx, namespace, group, name interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "QueryConfigFileReleaseHistories", reflect.TypeOf((*MockStore)(nil).QueryConfigFileReleaseHistories), namespace, group, fileName, offset, limit, endId) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetConfigFile", reflect.TypeOf((*MockStore)(nil).GetConfigFile), tx, namespace, group, name) } -// QueryConfigFiles mocks base method. +// QueryConfigFiles mocks base method func (m *MockStore) QueryConfigFiles(namespace, group, name string, offset, limit uint32) (uint32, []*model.ConfigFile, error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "QueryConfigFiles", namespace, group, name, offset, limit) @@ -1883,13 +2052,13 @@ func (m *MockStore) QueryConfigFiles(namespace, group, name string, offset, limi return ret0, ret1, ret2 } -// QueryConfigFiles indicates an expected call of QueryConfigFiles. +// QueryConfigFiles indicates an expected call of QueryConfigFiles func (mr *MockStoreMockRecorder) QueryConfigFiles(namespace, group, name, offset, limit interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "QueryConfigFiles", reflect.TypeOf((*MockStore)(nil).QueryConfigFiles), namespace, group, name, offset, limit) } -// QueryConfigFilesByGroup mocks base method. +// QueryConfigFilesByGroup mocks base method func (m *MockStore) QueryConfigFilesByGroup(namespace, group string, offset, limit uint32) (uint32, []*model.ConfigFile, error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "QueryConfigFilesByGroup", namespace, group, offset, limit) @@ -1899,406 +2068,379 @@ func (m *MockStore) QueryConfigFilesByGroup(namespace, group string, offset, lim return ret0, ret1, ret2 } -// QueryConfigFilesByGroup indicates an expected call of QueryConfigFilesByGroup. +// QueryConfigFilesByGroup indicates an expected call of QueryConfigFilesByGroup func (mr *MockStoreMockRecorder) QueryConfigFilesByGroup(namespace, group, offset, limit interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "QueryConfigFilesByGroup", reflect.TypeOf((*MockStore)(nil).QueryConfigFilesByGroup), namespace, group, offset, limit) } -// QueryTagByConfigFile mocks base method. -func (m *MockStore) QueryTagByConfigFile(namespace, group, fileName string) ([]*model.ConfigFileTag, error) { +// UpdateConfigFile mocks base method +func (m *MockStore) UpdateConfigFile(tx store.Tx, file *model.ConfigFile) (*model.ConfigFile, error) { m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "QueryTagByConfigFile", namespace, group, fileName) - ret0, _ := ret[0].([]*model.ConfigFileTag) + ret := m.ctrl.Call(m, "UpdateConfigFile", tx, file) + ret0, _ := ret[0].(*model.ConfigFile) ret1, _ := ret[1].(error) return ret0, ret1 } -// QueryTagByConfigFile indicates an expected call of QueryTagByConfigFile. -func (mr *MockStoreMockRecorder) QueryTagByConfigFile(namespace, group, fileName interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "QueryTagByConfigFile", reflect.TypeOf((*MockStore)(nil).QueryTagByConfigFile), namespace, group, fileName) -} - -// ReleaseCircuitBreaker mocks base method. -func (m *MockStore) ReleaseCircuitBreaker(circuitBreakerRelation *model.CircuitBreakerRelation) error { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "ReleaseCircuitBreaker", circuitBreakerRelation) - ret0, _ := ret[0].(error) - return ret0 -} - -// ReleaseCircuitBreaker indicates an expected call of ReleaseCircuitBreaker. -func (mr *MockStoreMockRecorder) ReleaseCircuitBreaker(circuitBreakerRelation interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ReleaseCircuitBreaker", reflect.TypeOf((*MockStore)(nil).ReleaseCircuitBreaker), circuitBreakerRelation) -} - -// RemoveStrategyResources mocks base method. -func (m *MockStore) RemoveStrategyResources(resources []model.StrategyResource) error { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "RemoveStrategyResources", resources) - ret0, _ := ret[0].(error) - return ret0 -} - -// RemoveStrategyResources indicates an expected call of RemoveStrategyResources. -func (mr *MockStoreMockRecorder) RemoveStrategyResources(resources interface{}) *gomock.Call { +// UpdateConfigFile indicates an expected call of UpdateConfigFile +func (mr *MockStoreMockRecorder) UpdateConfigFile(tx, file interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "RemoveStrategyResources", reflect.TypeOf((*MockStore)(nil).RemoveStrategyResources), resources) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "UpdateConfigFile", reflect.TypeOf((*MockStore)(nil).UpdateConfigFile), tx, file) } -// SetInstanceHealthStatus mocks base method. -func (m *MockStore) SetInstanceHealthStatus(instanceID string, flag int, revision string) error { +// DeleteConfigFile mocks base method +func (m *MockStore) DeleteConfigFile(tx store.Tx, namespace, group, name string) error { m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "SetInstanceHealthStatus", instanceID, flag, revision) + ret := m.ctrl.Call(m, "DeleteConfigFile", tx, namespace, group, name) ret0, _ := ret[0].(error) return ret0 } -// SetInstanceHealthStatus indicates an expected call of SetInstanceHealthStatus. -func (mr *MockStoreMockRecorder) SetInstanceHealthStatus(instanceID, flag, revision interface{}) *gomock.Call { +// DeleteConfigFile indicates an expected call of DeleteConfigFile +func (mr *MockStoreMockRecorder) DeleteConfigFile(tx, namespace, group, name interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SetInstanceHealthStatus", reflect.TypeOf((*MockStore)(nil).SetInstanceHealthStatus), instanceID, flag, revision) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "DeleteConfigFile", reflect.TypeOf((*MockStore)(nil).DeleteConfigFile), tx, namespace, group, name) } -// SetL5Extend mocks base method. -func (m *MockStore) SetL5Extend(serviceID string, meta map[string]interface{}) (map[string]interface{}, error) { +// CountByConfigFileGroup mocks base method +func (m *MockStore) CountByConfigFileGroup(namespace, group string) (uint64, error) { m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "SetL5Extend", serviceID, meta) - ret0, _ := ret[0].(map[string]interface{}) + ret := m.ctrl.Call(m, "CountByConfigFileGroup", namespace, group) + ret0, _ := ret[0].(uint64) ret1, _ := ret[1].(error) return ret0, ret1 } -// SetL5Extend indicates an expected call of SetL5Extend. -func (mr *MockStoreMockRecorder) SetL5Extend(serviceID, meta interface{}) *gomock.Call { +// CountByConfigFileGroup indicates an expected call of CountByConfigFileGroup +func (mr *MockStoreMockRecorder) CountByConfigFileGroup(namespace, group interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SetL5Extend", reflect.TypeOf((*MockStore)(nil).SetL5Extend), serviceID, meta) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "CountByConfigFileGroup", reflect.TypeOf((*MockStore)(nil).CountByConfigFileGroup), namespace, group) } -// StartTx mocks base method. -func (m *MockStore) StartTx() (store.Tx, error) { +// CreateConfigFileRelease mocks base method +func (m *MockStore) CreateConfigFileRelease(tx store.Tx, fileRelease *model.ConfigFileRelease) (*model.ConfigFileRelease, error) { m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "StartTx") - ret0, _ := ret[0].(store.Tx) + ret := m.ctrl.Call(m, "CreateConfigFileRelease", tx, fileRelease) + ret0, _ := ret[0].(*model.ConfigFileRelease) ret1, _ := ret[1].(error) return ret0, ret1 } -// StartTx indicates an expected call of StartTx. -func (mr *MockStoreMockRecorder) StartTx() *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "StartTx", reflect.TypeOf((*MockStore)(nil).StartTx)) -} - -// TagCircuitBreaker mocks base method. -func (m *MockStore) TagCircuitBreaker(circuitBreaker *model.CircuitBreaker) error { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "TagCircuitBreaker", circuitBreaker) - ret0, _ := ret[0].(error) - return ret0 -} - -// TagCircuitBreaker indicates an expected call of TagCircuitBreaker. -func (mr *MockStoreMockRecorder) TagCircuitBreaker(circuitBreaker interface{}) *gomock.Call { +// CreateConfigFileRelease indicates an expected call of CreateConfigFileRelease +func (mr *MockStoreMockRecorder) CreateConfigFileRelease(tx, fileRelease interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "TagCircuitBreaker", reflect.TypeOf((*MockStore)(nil).TagCircuitBreaker), circuitBreaker) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "CreateConfigFileRelease", reflect.TypeOf((*MockStore)(nil).CreateConfigFileRelease), tx, fileRelease) } -// UnbindCircuitBreaker mocks base method. -func (m *MockStore) UnbindCircuitBreaker(serviceID, ruleID, ruleVersion string) error { +// UpdateConfigFileRelease mocks base method +func (m *MockStore) UpdateConfigFileRelease(tx store.Tx, fileRelease *model.ConfigFileRelease) (*model.ConfigFileRelease, error) { m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "UnbindCircuitBreaker", serviceID, ruleID, ruleVersion) - ret0, _ := ret[0].(error) - return ret0 + ret := m.ctrl.Call(m, "UpdateConfigFileRelease", tx, fileRelease) + ret0, _ := ret[0].(*model.ConfigFileRelease) + ret1, _ := ret[1].(error) + return ret0, ret1 } -// UnbindCircuitBreaker indicates an expected call of UnbindCircuitBreaker. -func (mr *MockStoreMockRecorder) UnbindCircuitBreaker(serviceID, ruleID, ruleVersion interface{}) *gomock.Call { +// UpdateConfigFileRelease indicates an expected call of UpdateConfigFileRelease +func (mr *MockStoreMockRecorder) UpdateConfigFileRelease(tx, fileRelease interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "UnbindCircuitBreaker", reflect.TypeOf((*MockStore)(nil).UnbindCircuitBreaker), serviceID, ruleID, ruleVersion) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "UpdateConfigFileRelease", reflect.TypeOf((*MockStore)(nil).UpdateConfigFileRelease), tx, fileRelease) } -// UpdateBusiness mocks base method. -func (m *MockStore) UpdateBusiness(business *model.Business) error { +// GetConfigFileRelease mocks base method +func (m *MockStore) GetConfigFileRelease(tx store.Tx, namespace, group, fileName string) (*model.ConfigFileRelease, error) { m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "UpdateBusiness", business) - ret0, _ := ret[0].(error) - return ret0 + ret := m.ctrl.Call(m, "GetConfigFileRelease", tx, namespace, group, fileName) + ret0, _ := ret[0].(*model.ConfigFileRelease) + ret1, _ := ret[1].(error) + return ret0, ret1 } -// UpdateBusiness indicates an expected call of UpdateBusiness. -func (mr *MockStoreMockRecorder) UpdateBusiness(business interface{}) *gomock.Call { +// GetConfigFileRelease indicates an expected call of GetConfigFileRelease +func (mr *MockStoreMockRecorder) GetConfigFileRelease(tx, namespace, group, fileName interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "UpdateBusiness", reflect.TypeOf((*MockStore)(nil).UpdateBusiness), business) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetConfigFileRelease", reflect.TypeOf((*MockStore)(nil).GetConfigFileRelease), tx, namespace, group, fileName) } -// UpdateBusinessToken mocks base method. -func (m *MockStore) UpdateBusinessToken(bid, token string) error { +// GetConfigFileReleaseWithAllFlag mocks base method +func (m *MockStore) GetConfigFileReleaseWithAllFlag(tx store.Tx, namespace, group, fileName string) (*model.ConfigFileRelease, error) { m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "UpdateBusinessToken", bid, token) - ret0, _ := ret[0].(error) - return ret0 + ret := m.ctrl.Call(m, "GetConfigFileReleaseWithAllFlag", tx, namespace, group, fileName) + ret0, _ := ret[0].(*model.ConfigFileRelease) + ret1, _ := ret[1].(error) + return ret0, ret1 } -// UpdateBusinessToken indicates an expected call of UpdateBusinessToken. -func (mr *MockStoreMockRecorder) UpdateBusinessToken(bid, token interface{}) *gomock.Call { +// GetConfigFileReleaseWithAllFlag indicates an expected call of GetConfigFileReleaseWithAllFlag +func (mr *MockStoreMockRecorder) GetConfigFileReleaseWithAllFlag(tx, namespace, group, fileName interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "UpdateBusinessToken", reflect.TypeOf((*MockStore)(nil).UpdateBusinessToken), bid, token) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetConfigFileReleaseWithAllFlag", reflect.TypeOf((*MockStore)(nil).GetConfigFileReleaseWithAllFlag), tx, namespace, group, fileName) } -// UpdateCircuitBreaker mocks base method. -func (m *MockStore) UpdateCircuitBreaker(circuitBraker *model.CircuitBreaker) error { +// DeleteConfigFileRelease mocks base method +func (m *MockStore) DeleteConfigFileRelease(tx store.Tx, namespace, group, fileName, deleteBy string) error { m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "UpdateCircuitBreaker", circuitBraker) + ret := m.ctrl.Call(m, "DeleteConfigFileRelease", tx, namespace, group, fileName, deleteBy) ret0, _ := ret[0].(error) return ret0 } -// UpdateCircuitBreaker indicates an expected call of UpdateCircuitBreaker. -func (mr *MockStoreMockRecorder) UpdateCircuitBreaker(circuitBraker interface{}) *gomock.Call { +// DeleteConfigFileRelease indicates an expected call of DeleteConfigFileRelease +func (mr *MockStoreMockRecorder) DeleteConfigFileRelease(tx, namespace, group, fileName, deleteBy interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "UpdateCircuitBreaker", reflect.TypeOf((*MockStore)(nil).UpdateCircuitBreaker), circuitBraker) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "DeleteConfigFileRelease", reflect.TypeOf((*MockStore)(nil).DeleteConfigFileRelease), tx, namespace, group, fileName, deleteBy) } -// UpdateConfigFile mocks base method. -func (m *MockStore) UpdateConfigFile(tx store.Tx, file *model.ConfigFile) (*model.ConfigFile, error) { +// FindConfigFileReleaseByModifyTimeAfter mocks base method +func (m *MockStore) FindConfigFileReleaseByModifyTimeAfter(modifyTime time.Time) ([]*model.ConfigFileRelease, error) { m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "UpdateConfigFile", tx, file) - ret0, _ := ret[0].(*model.ConfigFile) + ret := m.ctrl.Call(m, "FindConfigFileReleaseByModifyTimeAfter", modifyTime) + ret0, _ := ret[0].([]*model.ConfigFileRelease) ret1, _ := ret[1].(error) return ret0, ret1 } -// UpdateConfigFile indicates an expected call of UpdateConfigFile. -func (mr *MockStoreMockRecorder) UpdateConfigFile(tx, file interface{}) *gomock.Call { +// FindConfigFileReleaseByModifyTimeAfter indicates an expected call of FindConfigFileReleaseByModifyTimeAfter +func (mr *MockStoreMockRecorder) FindConfigFileReleaseByModifyTimeAfter(modifyTime interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "UpdateConfigFile", reflect.TypeOf((*MockStore)(nil).UpdateConfigFile), tx, file) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "FindConfigFileReleaseByModifyTimeAfter", reflect.TypeOf((*MockStore)(nil).FindConfigFileReleaseByModifyTimeAfter), modifyTime) } -// UpdateConfigFileGroup mocks base method. -func (m *MockStore) UpdateConfigFileGroup(fileGroup *model.ConfigFileGroup) (*model.ConfigFileGroup, error) { +// CreateConfigFileReleaseHistory mocks base method +func (m *MockStore) CreateConfigFileReleaseHistory(tx store.Tx, fileReleaseHistory *model.ConfigFileReleaseHistory) error { m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "UpdateConfigFileGroup", fileGroup) - ret0, _ := ret[0].(*model.ConfigFileGroup) - ret1, _ := ret[1].(error) - return ret0, ret1 + ret := m.ctrl.Call(m, "CreateConfigFileReleaseHistory", tx, fileReleaseHistory) + ret0, _ := ret[0].(error) + return ret0 } -// UpdateConfigFileGroup indicates an expected call of UpdateConfigFileGroup. -func (mr *MockStoreMockRecorder) UpdateConfigFileGroup(fileGroup interface{}) *gomock.Call { +// CreateConfigFileReleaseHistory indicates an expected call of CreateConfigFileReleaseHistory +func (mr *MockStoreMockRecorder) CreateConfigFileReleaseHistory(tx, fileReleaseHistory interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "UpdateConfigFileGroup", reflect.TypeOf((*MockStore)(nil).UpdateConfigFileGroup), fileGroup) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "CreateConfigFileReleaseHistory", reflect.TypeOf((*MockStore)(nil).CreateConfigFileReleaseHistory), tx, fileReleaseHistory) } - -// UpdateConfigFileRelease mocks base method. -func (m *MockStore) UpdateConfigFileRelease(tx store.Tx, fileRelease *model.ConfigFileRelease) (*model.ConfigFileRelease, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "UpdateConfigFileRelease", tx, fileRelease) - ret0, _ := ret[0].(*model.ConfigFileRelease) - ret1, _ := ret[1].(error) - return ret0, ret1 + +// QueryConfigFileReleaseHistories mocks base method +func (m *MockStore) QueryConfigFileReleaseHistories(namespace, group, fileName string, offset, limit uint32, endId uint64) (uint32, []*model.ConfigFileReleaseHistory, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "QueryConfigFileReleaseHistories", namespace, group, fileName, offset, limit, endId) + ret0, _ := ret[0].(uint32) + ret1, _ := ret[1].([]*model.ConfigFileReleaseHistory) + ret2, _ := ret[2].(error) + return ret0, ret1, ret2 } -// UpdateConfigFileRelease indicates an expected call of UpdateConfigFileRelease. -func (mr *MockStoreMockRecorder) UpdateConfigFileRelease(tx, fileRelease interface{}) *gomock.Call { +// QueryConfigFileReleaseHistories indicates an expected call of QueryConfigFileReleaseHistories +func (mr *MockStoreMockRecorder) QueryConfigFileReleaseHistories(namespace, group, fileName, offset, limit, endId interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "UpdateConfigFileRelease", reflect.TypeOf((*MockStore)(nil).UpdateConfigFileRelease), tx, fileRelease) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "QueryConfigFileReleaseHistories", reflect.TypeOf((*MockStore)(nil).QueryConfigFileReleaseHistories), namespace, group, fileName, offset, limit, endId) } -// UpdateGroup mocks base method. -func (m *MockStore) UpdateGroup(group *model.ModifyUserGroup) error { +// GetLatestConfigFileReleaseHistory mocks base method +func (m *MockStore) GetLatestConfigFileReleaseHistory(namespace, group, fileName string) (*model.ConfigFileReleaseHistory, error) { m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "UpdateGroup", group) - ret0, _ := ret[0].(error) - return ret0 + ret := m.ctrl.Call(m, "GetLatestConfigFileReleaseHistory", namespace, group, fileName) + ret0, _ := ret[0].(*model.ConfigFileReleaseHistory) + ret1, _ := ret[1].(error) + return ret0, ret1 } -// UpdateGroup indicates an expected call of UpdateGroup. -func (mr *MockStoreMockRecorder) UpdateGroup(group interface{}) *gomock.Call { +// GetLatestConfigFileReleaseHistory indicates an expected call of GetLatestConfigFileReleaseHistory +func (mr *MockStoreMockRecorder) GetLatestConfigFileReleaseHistory(namespace, group, fileName interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "UpdateGroup", reflect.TypeOf((*MockStore)(nil).UpdateGroup), group) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetLatestConfigFileReleaseHistory", reflect.TypeOf((*MockStore)(nil).GetLatestConfigFileReleaseHistory), namespace, group, fileName) } -// UpdateInstance mocks base method. -func (m *MockStore) UpdateInstance(instance *model.Instance) error { +// CreateConfigFileTag mocks base method +func (m *MockStore) CreateConfigFileTag(tx store.Tx, fileTag *model.ConfigFileTag) error { m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "UpdateInstance", instance) + ret := m.ctrl.Call(m, "CreateConfigFileTag", tx, fileTag) ret0, _ := ret[0].(error) return ret0 } -// UpdateInstance indicates an expected call of UpdateInstance. -func (mr *MockStoreMockRecorder) UpdateInstance(instance interface{}) *gomock.Call { +// CreateConfigFileTag indicates an expected call of CreateConfigFileTag +func (mr *MockStoreMockRecorder) CreateConfigFileTag(tx, fileTag interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "UpdateInstance", reflect.TypeOf((*MockStore)(nil).UpdateInstance), instance) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "CreateConfigFileTag", reflect.TypeOf((*MockStore)(nil).CreateConfigFileTag), tx, fileTag) } -// UpdateNamespace mocks base method. -func (m *MockStore) UpdateNamespace(namespace *model.Namespace) error { +// QueryConfigFileByTag mocks base method +func (m *MockStore) QueryConfigFileByTag(namespace, group, fileName string, tags ...string) ([]*model.ConfigFileTag, error) { m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "UpdateNamespace", namespace) - ret0, _ := ret[0].(error) - return ret0 + varargs := []interface{}{namespace, group, fileName} + for _, a := range tags { + varargs = append(varargs, a) + } + ret := m.ctrl.Call(m, "QueryConfigFileByTag", varargs...) + ret0, _ := ret[0].([]*model.ConfigFileTag) + ret1, _ := ret[1].(error) + return ret0, ret1 } -// UpdateNamespace indicates an expected call of UpdateNamespace. -func (mr *MockStoreMockRecorder) UpdateNamespace(namespace interface{}) *gomock.Call { +// QueryConfigFileByTag indicates an expected call of QueryConfigFileByTag +func (mr *MockStoreMockRecorder) QueryConfigFileByTag(namespace, group, fileName interface{}, tags ...interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "UpdateNamespace", reflect.TypeOf((*MockStore)(nil).UpdateNamespace), namespace) + varargs := append([]interface{}{namespace, group, fileName}, tags...) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "QueryConfigFileByTag", reflect.TypeOf((*MockStore)(nil).QueryConfigFileByTag), varargs...) } -// UpdateNamespaceToken mocks base method. -func (m *MockStore) UpdateNamespaceToken(name, token string) error { +// QueryTagByConfigFile mocks base method +func (m *MockStore) QueryTagByConfigFile(namespace, group, fileName string) ([]*model.ConfigFileTag, error) { m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "UpdateNamespaceToken", name, token) - ret0, _ := ret[0].(error) - return ret0 + ret := m.ctrl.Call(m, "QueryTagByConfigFile", namespace, group, fileName) + ret0, _ := ret[0].([]*model.ConfigFileTag) + ret1, _ := ret[1].(error) + return ret0, ret1 } -// UpdateNamespaceToken indicates an expected call of UpdateNamespaceToken. -func (mr *MockStoreMockRecorder) UpdateNamespaceToken(name, token interface{}) *gomock.Call { +// QueryTagByConfigFile indicates an expected call of QueryTagByConfigFile +func (mr *MockStoreMockRecorder) QueryTagByConfigFile(namespace, group, fileName interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "UpdateNamespaceToken", reflect.TypeOf((*MockStore)(nil).UpdateNamespaceToken), name, token) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "QueryTagByConfigFile", reflect.TypeOf((*MockStore)(nil).QueryTagByConfigFile), namespace, group, fileName) } -// UpdatePlatform mocks base method. -func (m *MockStore) UpdatePlatform(platform *model.Platform) error { +// DeleteConfigFileTag mocks base method +func (m *MockStore) DeleteConfigFileTag(tx store.Tx, namespace, group, fileName, key, value string) error { m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "UpdatePlatform", platform) + ret := m.ctrl.Call(m, "DeleteConfigFileTag", tx, namespace, group, fileName, key, value) ret0, _ := ret[0].(error) return ret0 } -// UpdatePlatform indicates an expected call of UpdatePlatform. -func (mr *MockStoreMockRecorder) UpdatePlatform(platform interface{}) *gomock.Call { +// DeleteConfigFileTag indicates an expected call of DeleteConfigFileTag +func (mr *MockStoreMockRecorder) DeleteConfigFileTag(tx, namespace, group, fileName, key, value interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "UpdatePlatform", reflect.TypeOf((*MockStore)(nil).UpdatePlatform), platform) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "DeleteConfigFileTag", reflect.TypeOf((*MockStore)(nil).DeleteConfigFileTag), tx, namespace, group, fileName, key, value) } -// UpdateRateLimit mocks base method. -func (m *MockStore) UpdateRateLimit(limiting *model.RateLimit) error { +// DeleteTagByConfigFile mocks base method +func (m *MockStore) DeleteTagByConfigFile(tx store.Tx, namespace, group, fileName string) error { m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "UpdateRateLimit", limiting) + ret := m.ctrl.Call(m, "DeleteTagByConfigFile", tx, namespace, group, fileName) ret0, _ := ret[0].(error) return ret0 } -// UpdateRateLimit indicates an expected call of UpdateRateLimit. -func (mr *MockStoreMockRecorder) UpdateRateLimit(limiting interface{}) *gomock.Call { +// DeleteTagByConfigFile indicates an expected call of DeleteTagByConfigFile +func (mr *MockStoreMockRecorder) DeleteTagByConfigFile(tx, namespace, group, fileName interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "UpdateRateLimit", reflect.TypeOf((*MockStore)(nil).UpdateRateLimit), limiting) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "DeleteTagByConfigFile", reflect.TypeOf((*MockStore)(nil).DeleteTagByConfigFile), tx, namespace, group, fileName) } -// UpdateRoutingConfig mocks base method. -func (m *MockStore) UpdateRoutingConfig(conf *model.RoutingConfig) error { +// QueryAllConfigFileTemplates mocks base method +func (m *MockStore) QueryAllConfigFileTemplates() ([]*model.ConfigFileTemplate, error) { m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "UpdateRoutingConfig", conf) - ret0, _ := ret[0].(error) - return ret0 + ret := m.ctrl.Call(m, "QueryAllConfigFileTemplates") + ret0, _ := ret[0].([]*model.ConfigFileTemplate) + ret1, _ := ret[1].(error) + return ret0, ret1 } -// UpdateRoutingConfig indicates an expected call of UpdateRoutingConfig. -func (mr *MockStoreMockRecorder) UpdateRoutingConfig(conf interface{}) *gomock.Call { +// QueryAllConfigFileTemplates indicates an expected call of QueryAllConfigFileTemplates +func (mr *MockStoreMockRecorder) QueryAllConfigFileTemplates() *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "UpdateRoutingConfig", reflect.TypeOf((*MockStore)(nil).UpdateRoutingConfig), conf) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "QueryAllConfigFileTemplates", reflect.TypeOf((*MockStore)(nil).QueryAllConfigFileTemplates)) } -// UpdateService mocks base method. -func (m *MockStore) UpdateService(service *model.Service, needUpdateOwner bool) error { +// CreateConfigFileTemplate mocks base method +func (m *MockStore) CreateConfigFileTemplate(template *model.ConfigFileTemplate) (*model.ConfigFileTemplate, error) { m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "UpdateService", service, needUpdateOwner) - ret0, _ := ret[0].(error) - return ret0 + ret := m.ctrl.Call(m, "CreateConfigFileTemplate", template) + ret0, _ := ret[0].(*model.ConfigFileTemplate) + ret1, _ := ret[1].(error) + return ret0, ret1 } -// UpdateService indicates an expected call of UpdateService. -func (mr *MockStoreMockRecorder) UpdateService(service, needUpdateOwner interface{}) *gomock.Call { +// CreateConfigFileTemplate indicates an expected call of CreateConfigFileTemplate +func (mr *MockStoreMockRecorder) CreateConfigFileTemplate(template interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "UpdateService", reflect.TypeOf((*MockStore)(nil).UpdateService), service, needUpdateOwner) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "CreateConfigFileTemplate", reflect.TypeOf((*MockStore)(nil).CreateConfigFileTemplate), template) } -// UpdateServiceAlias mocks base method. -func (m *MockStore) UpdateServiceAlias(alias *model.Service, needUpdateOwner bool) error { +// GetConfigFileTemplate mocks base method +func (m *MockStore) GetConfigFileTemplate(name string) (*model.ConfigFileTemplate, error) { m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "UpdateServiceAlias", alias, needUpdateOwner) - ret0, _ := ret[0].(error) - return ret0 + ret := m.ctrl.Call(m, "GetConfigFileTemplate", name) + ret0, _ := ret[0].(*model.ConfigFileTemplate) + ret1, _ := ret[1].(error) + return ret0, ret1 } -// UpdateServiceAlias indicates an expected call of UpdateServiceAlias. -func (mr *MockStoreMockRecorder) UpdateServiceAlias(alias, needUpdateOwner interface{}) *gomock.Call { +// GetConfigFileTemplate indicates an expected call of GetConfigFileTemplate +func (mr *MockStoreMockRecorder) GetConfigFileTemplate(name interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "UpdateServiceAlias", reflect.TypeOf((*MockStore)(nil).UpdateServiceAlias), alias, needUpdateOwner) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetConfigFileTemplate", reflect.TypeOf((*MockStore)(nil).GetConfigFileTemplate), name) } -// UpdateServiceToken mocks base method. -func (m *MockStore) UpdateServiceToken(serviceID, token, revision string) error { +// BatchAddClients mocks base method +func (m *MockStore) BatchAddClients(clients []*model.Client) error { m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "UpdateServiceToken", serviceID, token, revision) + ret := m.ctrl.Call(m, "BatchAddClients", clients) ret0, _ := ret[0].(error) return ret0 } -// UpdateServiceToken indicates an expected call of UpdateServiceToken. -func (mr *MockStoreMockRecorder) UpdateServiceToken(serviceID, token, revision interface{}) *gomock.Call { +// BatchAddClients indicates an expected call of BatchAddClients +func (mr *MockStoreMockRecorder) BatchAddClients(clients interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "UpdateServiceToken", reflect.TypeOf((*MockStore)(nil).UpdateServiceToken), serviceID, token, revision) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "BatchAddClients", reflect.TypeOf((*MockStore)(nil).BatchAddClients), clients) } -// UpdateStrategy mocks base method. -func (m *MockStore) UpdateStrategy(strategy *model.ModifyStrategyDetail) error { +// BatchDeleteClients mocks base method +func (m *MockStore) BatchDeleteClients(ids []string) error { m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "UpdateStrategy", strategy) + ret := m.ctrl.Call(m, "BatchDeleteClients", ids) ret0, _ := ret[0].(error) return ret0 } -// UpdateStrategy indicates an expected call of UpdateStrategy. -func (mr *MockStoreMockRecorder) UpdateStrategy(strategy interface{}) *gomock.Call { +// BatchDeleteClients indicates an expected call of BatchDeleteClients +func (mr *MockStoreMockRecorder) BatchDeleteClients(ids interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "UpdateStrategy", reflect.TypeOf((*MockStore)(nil).UpdateStrategy), strategy) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "BatchDeleteClients", reflect.TypeOf((*MockStore)(nil).BatchDeleteClients), ids) } -// UpdateUser mocks base method. -func (m *MockStore) UpdateUser(user *model.User) error { +// GetMoreClients mocks base method +func (m *MockStore) GetMoreClients(mtime time.Time, firstUpdate bool) (map[string]*model.Client, error) { m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "UpdateUser", user) - ret0, _ := ret[0].(error) - return ret0 + ret := m.ctrl.Call(m, "GetMoreClients", mtime, firstUpdate) + ret0, _ := ret[0].(map[string]*model.Client) + ret1, _ := ret[1].(error) + return ret0, ret1 } -// UpdateUser indicates an expected call of UpdateUser. -func (mr *MockStoreMockRecorder) UpdateUser(user interface{}) *gomock.Call { +// GetMoreClients indicates an expected call of GetMoreClients +func (mr *MockStoreMockRecorder) GetMoreClients(mtime, firstUpdate interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "UpdateUser", reflect.TypeOf((*MockStore)(nil).UpdateUser), user) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetMoreClients", reflect.TypeOf((*MockStore)(nil).GetMoreClients), mtime, firstUpdate) } -// MockNamespaceStore is a mock of NamespaceStore interface. +// MockNamespaceStore is a mock of NamespaceStore interface type MockNamespaceStore struct { ctrl *gomock.Controller recorder *MockNamespaceStoreMockRecorder } -// MockNamespaceStoreMockRecorder is the mock recorder for MockNamespaceStore. +// MockNamespaceStoreMockRecorder is the mock recorder for MockNamespaceStore type MockNamespaceStoreMockRecorder struct { mock *MockNamespaceStore } -// NewMockNamespaceStore creates a new mock instance. +// NewMockNamespaceStore creates a new mock instance func NewMockNamespaceStore(ctrl *gomock.Controller) *MockNamespaceStore { mock := &MockNamespaceStore{ctrl: ctrl} mock.recorder = &MockNamespaceStoreMockRecorder{mock} return mock } -// EXPECT returns an object that allows the caller to indicate expected use. +// EXPECT returns an object that allows the caller to indicate expected use func (m *MockNamespaceStore) EXPECT() *MockNamespaceStoreMockRecorder { return m.recorder } -// AddNamespace mocks base method. +// AddNamespace mocks base method func (m *MockNamespaceStore) AddNamespace(namespace *model.Namespace) error { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "AddNamespace", namespace) @@ -2306,28 +2448,56 @@ func (m *MockNamespaceStore) AddNamespace(namespace *model.Namespace) error { return ret0 } -// AddNamespace indicates an expected call of AddNamespace. +// AddNamespace indicates an expected call of AddNamespace func (mr *MockNamespaceStoreMockRecorder) AddNamespace(namespace interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "AddNamespace", reflect.TypeOf((*MockNamespaceStore)(nil).AddNamespace), namespace) } -// GetMoreNamespaces mocks base method. -func (m *MockNamespaceStore) GetMoreNamespaces(mtime time.Time) ([]*model.Namespace, error) { +// UpdateNamespace mocks base method +func (m *MockNamespaceStore) UpdateNamespace(namespace *model.Namespace) error { m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "GetMoreNamespaces", mtime) + ret := m.ctrl.Call(m, "UpdateNamespace", namespace) + ret0, _ := ret[0].(error) + return ret0 +} + +// UpdateNamespace indicates an expected call of UpdateNamespace +func (mr *MockNamespaceStoreMockRecorder) UpdateNamespace(namespace interface{}) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "UpdateNamespace", reflect.TypeOf((*MockNamespaceStore)(nil).UpdateNamespace), namespace) +} + +// UpdateNamespaceToken mocks base method +func (m *MockNamespaceStore) UpdateNamespaceToken(name, token string) error { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "UpdateNamespaceToken", name, token) + ret0, _ := ret[0].(error) + return ret0 +} + +// UpdateNamespaceToken indicates an expected call of UpdateNamespaceToken +func (mr *MockNamespaceStoreMockRecorder) UpdateNamespaceToken(name, token interface{}) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "UpdateNamespaceToken", reflect.TypeOf((*MockNamespaceStore)(nil).UpdateNamespaceToken), name, token) +} + +// ListNamespaces mocks base method +func (m *MockNamespaceStore) ListNamespaces(owner string) ([]*model.Namespace, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "ListNamespaces", owner) ret0, _ := ret[0].([]*model.Namespace) ret1, _ := ret[1].(error) return ret0, ret1 } -// GetMoreNamespaces indicates an expected call of GetMoreNamespaces. -func (mr *MockNamespaceStoreMockRecorder) GetMoreNamespaces(mtime interface{}) *gomock.Call { +// ListNamespaces indicates an expected call of ListNamespaces +func (mr *MockNamespaceStoreMockRecorder) ListNamespaces(owner interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetMoreNamespaces", reflect.TypeOf((*MockNamespaceStore)(nil).GetMoreNamespaces), mtime) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ListNamespaces", reflect.TypeOf((*MockNamespaceStore)(nil).ListNamespaces), owner) } -// GetNamespace mocks base method. +// GetNamespace mocks base method func (m *MockNamespaceStore) GetNamespace(name string) (*model.Namespace, error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "GetNamespace", name) @@ -2336,13 +2506,13 @@ func (m *MockNamespaceStore) GetNamespace(name string) (*model.Namespace, error) return ret0, ret1 } -// GetNamespace indicates an expected call of GetNamespace. +// GetNamespace indicates an expected call of GetNamespace func (mr *MockNamespaceStoreMockRecorder) GetNamespace(name interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetNamespace", reflect.TypeOf((*MockNamespaceStore)(nil).GetNamespace), name) } -// GetNamespaces mocks base method. +// GetNamespaces mocks base method func (m *MockNamespaceStore) GetNamespaces(filter map[string][]string, offset, limit int) ([]*model.Namespace, uint32, error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "GetNamespaces", filter, offset, limit) @@ -2352,79 +2522,51 @@ func (m *MockNamespaceStore) GetNamespaces(filter map[string][]string, offset, l return ret0, ret1, ret2 } -// GetNamespaces indicates an expected call of GetNamespaces. +// GetNamespaces indicates an expected call of GetNamespaces func (mr *MockNamespaceStoreMockRecorder) GetNamespaces(filter, offset, limit interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetNamespaces", reflect.TypeOf((*MockNamespaceStore)(nil).GetNamespaces), filter, offset, limit) } -// ListNamespaces mocks base method. -func (m *MockNamespaceStore) ListNamespaces(owner string) ([]*model.Namespace, error) { +// GetMoreNamespaces mocks base method +func (m *MockNamespaceStore) GetMoreNamespaces(mtime time.Time) ([]*model.Namespace, error) { m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "ListNamespaces", owner) + ret := m.ctrl.Call(m, "GetMoreNamespaces", mtime) ret0, _ := ret[0].([]*model.Namespace) ret1, _ := ret[1].(error) return ret0, ret1 } -// ListNamespaces indicates an expected call of ListNamespaces. -func (mr *MockNamespaceStoreMockRecorder) ListNamespaces(owner interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ListNamespaces", reflect.TypeOf((*MockNamespaceStore)(nil).ListNamespaces), owner) -} - -// UpdateNamespace mocks base method. -func (m *MockNamespaceStore) UpdateNamespace(namespace *model.Namespace) error { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "UpdateNamespace", namespace) - ret0, _ := ret[0].(error) - return ret0 -} - -// UpdateNamespace indicates an expected call of UpdateNamespace. -func (mr *MockNamespaceStoreMockRecorder) UpdateNamespace(namespace interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "UpdateNamespace", reflect.TypeOf((*MockNamespaceStore)(nil).UpdateNamespace), namespace) -} - -// UpdateNamespaceToken mocks base method. -func (m *MockNamespaceStore) UpdateNamespaceToken(name, token string) error { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "UpdateNamespaceToken", name, token) - ret0, _ := ret[0].(error) - return ret0 -} - -// UpdateNamespaceToken indicates an expected call of UpdateNamespaceToken. -func (mr *MockNamespaceStoreMockRecorder) UpdateNamespaceToken(name, token interface{}) *gomock.Call { +// GetMoreNamespaces indicates an expected call of GetMoreNamespaces +func (mr *MockNamespaceStoreMockRecorder) GetMoreNamespaces(mtime interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "UpdateNamespaceToken", reflect.TypeOf((*MockNamespaceStore)(nil).UpdateNamespaceToken), name, token) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetMoreNamespaces", reflect.TypeOf((*MockNamespaceStore)(nil).GetMoreNamespaces), mtime) } -// MockTransaction is a mock of Transaction interface. +// MockTransaction is a mock of Transaction interface type MockTransaction struct { ctrl *gomock.Controller recorder *MockTransactionMockRecorder } -// MockTransactionMockRecorder is the mock recorder for MockTransaction. +// MockTransactionMockRecorder is the mock recorder for MockTransaction type MockTransactionMockRecorder struct { mock *MockTransaction } -// NewMockTransaction creates a new mock instance. +// NewMockTransaction creates a new mock instance func NewMockTransaction(ctrl *gomock.Controller) *MockTransaction { mock := &MockTransaction{ctrl: ctrl} mock.recorder = &MockTransactionMockRecorder{mock} return mock } -// EXPECT returns an object that allows the caller to indicate expected use. +// EXPECT returns an object that allows the caller to indicate expected use func (m *MockTransaction) EXPECT() *MockTransactionMockRecorder { return m.recorder } -// Commit mocks base method. +// Commit mocks base method func (m *MockTransaction) Commit() error { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Commit") @@ -2432,27 +2574,13 @@ func (m *MockTransaction) Commit() error { return ret0 } -// Commit indicates an expected call of Commit. +// Commit indicates an expected call of Commit func (mr *MockTransactionMockRecorder) Commit() *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Commit", reflect.TypeOf((*MockTransaction)(nil).Commit)) } -// DeleteNamespace mocks base method. -func (m *MockTransaction) DeleteNamespace(name string) error { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "DeleteNamespace", name) - ret0, _ := ret[0].(error) - return ret0 -} - -// DeleteNamespace indicates an expected call of DeleteNamespace. -func (mr *MockTransactionMockRecorder) DeleteNamespace(name interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "DeleteNamespace", reflect.TypeOf((*MockTransaction)(nil).DeleteNamespace), name) -} - -// LockBootstrap mocks base method. +// LockBootstrap mocks base method func (m *MockTransaction) LockBootstrap(key, server string) error { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "LockBootstrap", key, server) @@ -2460,13 +2588,13 @@ func (m *MockTransaction) LockBootstrap(key, server string) error { return ret0 } -// LockBootstrap indicates an expected call of LockBootstrap. +// LockBootstrap indicates an expected call of LockBootstrap func (mr *MockTransactionMockRecorder) LockBootstrap(key, server interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "LockBootstrap", reflect.TypeOf((*MockTransaction)(nil).LockBootstrap), key, server) } -// LockNamespace mocks base method. +// LockNamespace mocks base method func (m *MockTransaction) LockNamespace(name string) (*model.Namespace, error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "LockNamespace", name) @@ -2475,13 +2603,27 @@ func (m *MockTransaction) LockNamespace(name string) (*model.Namespace, error) { return ret0, ret1 } -// LockNamespace indicates an expected call of LockNamespace. +// LockNamespace indicates an expected call of LockNamespace func (mr *MockTransactionMockRecorder) LockNamespace(name interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "LockNamespace", reflect.TypeOf((*MockTransaction)(nil).LockNamespace), name) } -// LockService mocks base method. +// DeleteNamespace mocks base method +func (m *MockTransaction) DeleteNamespace(name string) error { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "DeleteNamespace", name) + ret0, _ := ret[0].(error) + return ret0 +} + +// DeleteNamespace indicates an expected call of DeleteNamespace +func (mr *MockTransactionMockRecorder) DeleteNamespace(name interface{}) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "DeleteNamespace", reflect.TypeOf((*MockTransaction)(nil).DeleteNamespace), name) +} + +// LockService mocks base method func (m *MockTransaction) LockService(name, namespace string) (*model.Service, error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "LockService", name, namespace) @@ -2490,13 +2632,13 @@ func (m *MockTransaction) LockService(name, namespace string) (*model.Service, e return ret0, ret1 } -// LockService indicates an expected call of LockService. +// LockService indicates an expected call of LockService func (mr *MockTransactionMockRecorder) LockService(name, namespace interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "LockService", reflect.TypeOf((*MockTransaction)(nil).LockService), name, namespace) } -// RLockService mocks base method. +// RLockService mocks base method func (m *MockTransaction) RLockService(name, namespace string) (*model.Service, error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "RLockService", name, namespace) @@ -2505,36 +2647,36 @@ func (m *MockTransaction) RLockService(name, namespace string) (*model.Service, return ret0, ret1 } -// RLockService indicates an expected call of RLockService. +// RLockService indicates an expected call of RLockService func (mr *MockTransactionMockRecorder) RLockService(name, namespace interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "RLockService", reflect.TypeOf((*MockTransaction)(nil).RLockService), name, namespace) } -// MockTx is a mock of Tx interface. +// MockTx is a mock of Tx interface type MockTx struct { ctrl *gomock.Controller recorder *MockTxMockRecorder } -// MockTxMockRecorder is the mock recorder for MockTx. +// MockTxMockRecorder is the mock recorder for MockTx type MockTxMockRecorder struct { mock *MockTx } -// NewMockTx creates a new mock instance. +// NewMockTx creates a new mock instance func NewMockTx(ctrl *gomock.Controller) *MockTx { mock := &MockTx{ctrl: ctrl} mock.recorder = &MockTxMockRecorder{mock} return mock } -// EXPECT returns an object that allows the caller to indicate expected use. +// EXPECT returns an object that allows the caller to indicate expected use func (m *MockTx) EXPECT() *MockTxMockRecorder { return m.recorder } -// Commit mocks base method. +// Commit mocks base method func (m *MockTx) Commit() error { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Commit") @@ -2542,64 +2684,64 @@ func (m *MockTx) Commit() error { return ret0 } -// Commit indicates an expected call of Commit. +// Commit indicates an expected call of Commit func (mr *MockTxMockRecorder) Commit() *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Commit", reflect.TypeOf((*MockTx)(nil).Commit)) } -// GetDelegateTx mocks base method. -func (m *MockTx) GetDelegateTx() interface{} { +// Rollback mocks base method +func (m *MockTx) Rollback() error { m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "GetDelegateTx") - ret0, _ := ret[0].(interface{}) + ret := m.ctrl.Call(m, "Rollback") + ret0, _ := ret[0].(error) return ret0 } -// GetDelegateTx indicates an expected call of GetDelegateTx. -func (mr *MockTxMockRecorder) GetDelegateTx() *gomock.Call { +// Rollback indicates an expected call of Rollback +func (mr *MockTxMockRecorder) Rollback() *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetDelegateTx", reflect.TypeOf((*MockTx)(nil).GetDelegateTx)) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Rollback", reflect.TypeOf((*MockTx)(nil).Rollback)) } -// Rollback mocks base method. -func (m *MockTx) Rollback() error { +// GetDelegateTx mocks base method +func (m *MockTx) GetDelegateTx() interface{} { m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "Rollback") - ret0, _ := ret[0].(error) + ret := m.ctrl.Call(m, "GetDelegateTx") + ret0, _ := ret[0].(interface{}) return ret0 } -// Rollback indicates an expected call of Rollback. -func (mr *MockTxMockRecorder) Rollback() *gomock.Call { +// GetDelegateTx indicates an expected call of GetDelegateTx +func (mr *MockTxMockRecorder) GetDelegateTx() *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Rollback", reflect.TypeOf((*MockTx)(nil).Rollback)) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetDelegateTx", reflect.TypeOf((*MockTx)(nil).GetDelegateTx)) } -// MockToolStore is a mock of ToolStore interface. +// MockToolStore is a mock of ToolStore interface type MockToolStore struct { ctrl *gomock.Controller recorder *MockToolStoreMockRecorder } -// MockToolStoreMockRecorder is the mock recorder for MockToolStore. +// MockToolStoreMockRecorder is the mock recorder for MockToolStore type MockToolStoreMockRecorder struct { mock *MockToolStore } -// NewMockToolStore creates a new mock instance. +// NewMockToolStore creates a new mock instance func NewMockToolStore(ctrl *gomock.Controller) *MockToolStore { mock := &MockToolStore{ctrl: ctrl} mock.recorder = &MockToolStoreMockRecorder{mock} return mock } -// EXPECT returns an object that allows the caller to indicate expected use. +// EXPECT returns an object that allows the caller to indicate expected use func (m *MockToolStore) EXPECT() *MockToolStoreMockRecorder { return m.recorder } -// GetUnixSecond mocks base method. +// GetUnixSecond mocks base method func (m *MockToolStore) GetUnixSecond() (int64, error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "GetUnixSecond") @@ -2608,7 +2750,7 @@ func (m *MockToolStore) GetUnixSecond() (int64, error) { return ret0, ret1 } -// GetUnixSecond indicates an expected call of GetUnixSecond. +// GetUnixSecond indicates an expected call of GetUnixSecond func (mr *MockToolStoreMockRecorder) GetUnixSecond() *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetUnixSecond", reflect.TypeOf((*MockToolStore)(nil).GetUnixSecond)) diff --git a/store/sqldb/default.go b/store/sqldb/default.go index f16498bd1..89f17ffe3 100644 --- a/store/sqldb/default.go +++ b/store/sqldb/default.go @@ -66,6 +66,9 @@ type stableStore struct { //client info stores *clientStore + // v2 存储 + *routingConfigStoreV2 + // 主数据库,可以进行读写 master *BaseDB // 对主数据库的事务操作,可读写 @@ -272,4 +275,6 @@ func (s *stableStore) newStore() { s.configFileTemplateStore = &configFileTemplateStore{db: s.master} s.clientStore = &clientStore{master: s.master, slave: s.slave} + + s.routingConfigStoreV2 = &routingConfigStoreV2{master: s.master, slave: s.slave} } diff --git a/store/sqldb/routing_config.go b/store/sqldb/routing_config.go index 928ec9ade..0d9f8cbc8 100644 --- a/store/sqldb/routing_config.go +++ b/store/sqldb/routing_config.go @@ -19,6 +19,7 @@ package sqldb import ( "database/sql" + "errors" "fmt" "time" @@ -95,6 +96,27 @@ func (rs *routingConfigStore) DeleteRoutingConfig(serviceID string) error { return nil } +// DeleteRoutingConfigTx 删除 +func (rs *routingConfigStore) DeleteRoutingConfigTx(tx store.Tx, serviceID string) error { + if tx == nil { + return errors.New("transaction is nil") + } + + if serviceID == "" { + log.Errorf("[Store][database] delete routing config missing service id") + return store.NewStatusError(store.EmptyParamsErr, "missing service id") + } + + dbTx := tx.GetDelegateTx().(*BaseTx) + + str := `update routing_config set flag = 1, mtime = sysdate() where id = ?` + if _, err := dbTx.Exec(str, serviceID); err != nil { + log.Errorf("[Store][database] delete routing config(%s) err: %s", serviceID, err.Error()) + return store.Error(err) + } + return nil +} + // GetRoutingConfigsForCache 缓存增量拉取 func (rs *routingConfigStore) GetRoutingConfigsForCache( mtime time.Time, firstUpdate bool) ([]*model.RoutingConfig, error) { diff --git a/store/sqldb/routing_config_v2.go b/store/sqldb/routing_config_v2.go new file mode 100644 index 000000000..48bf7a9e1 --- /dev/null +++ b/store/sqldb/routing_config_v2.go @@ -0,0 +1,307 @@ +/** + * Tencent is pleased to support the open source community by making Polaris available. + * + * Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved. + * + * Licensed under the BSD 3-Clause License (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://opensource.org/licenses/BSD-3-Clause + * + * 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 sqldb + +import ( + "database/sql" + "errors" + "fmt" + "time" + + v2 "github.com/polarismesh/polaris-server/common/model/v2" + "github.com/polarismesh/polaris-server/store" + "go.uber.org/zap" +) + +// RoutingConfigStoreV2 的实现 +type routingConfigStoreV2 struct { + master *BaseDB + slave *BaseDB +} + +// CreateRoutingConfigV2 新增一个路由配置 +func (r *routingConfigStoreV2) CreateRoutingConfigV2(conf *v2.RoutingConfig) error { + if conf.ID == "" || conf.Revision == "" { + log.Errorf("[Store][boltdb] create routing config v2 missing id or revision") + return store.NewStatusError(store.EmptyParamsErr, "missing id or revision") + } + if conf.Policy == "" || conf.Config == "" { + log.Errorf("[Store][boltdb] create routing config v2 missing params") + return store.NewStatusError(store.EmptyParamsErr, "missing some params") + } + + err := RetryTransaction("CreateRoutingConfigV2", func() error { + tx, err := r.master.Begin() + if err != nil { + return err + } + + defer tx.Rollback() + if err := r.createRoutingConfigV2Tx(tx, conf); err != nil { + return err + } + + if err := tx.Commit(); err != nil { + log.Errorf("[Store][database] create routing config v2(%+v) commit: %s", conf, err.Error()) + return store.Error(err) + } + + return nil + }) + + return store.Error(err) +} + +func (r *routingConfigStoreV2) CreateRoutingConfigV2Tx(tx store.Tx, conf *v2.RoutingConfig) error { + if tx == nil { + return errors.New("tx is nil") + } + + dbTx := tx.GetDelegateTx().(*BaseTx) + return r.createRoutingConfigV2Tx(dbTx, conf) +} + +func (r *routingConfigStoreV2) createRoutingConfigV2Tx(tx *BaseTx, conf *v2.RoutingConfig) error { + + insertSQL := "INSERT INTO routing_config_v2(id, namespace, name, policy, config, enable, " + + " priority, revision, description, ctime, mtime, etime) VALUES (?,?,?,?,?,?,?,?,?,sysdate(),sysdate(),%s)" + + var enable int + if conf.Enable { + enable = 1 + insertSQL = fmt.Sprintf(insertSQL, "sysdate()") + } else { + enable = 0 + insertSQL = fmt.Sprintf(insertSQL, emptyEnableTime) + } + + log.Debug("[Store][database] create routing v2", zap.String("sql", insertSQL)) + + if _, err := tx.Exec(insertSQL, conf.ID, conf.Namespace, conf.Name, conf.Policy, + conf.Config, enable, conf.Priority, conf.Revision, conf.Description); err != nil { + log.Errorf("[Store][database] create routing v2(%+v) err: %s", conf, err.Error()) + return store.Error(err) + } + return nil +} + +// UpdateRoutingConfigV2 更新一个路由配置 +func (r *routingConfigStoreV2) UpdateRoutingConfigV2(conf *v2.RoutingConfig) error { + + tx, err := r.master.Begin() + if err != nil { + return err + } + + defer tx.Rollback() + + if err := r.updateRoutingConfigV2Tx(tx, conf); err != nil { + return err + } + + if err := tx.Commit(); err != nil { + log.Errorf("[Store][database] update routing config v2(%+v) commit: %s", conf, err.Error()) + return store.Error(err) + } + + return nil +} + +func (r *routingConfigStoreV2) UpdateRoutingConfigV2Tx(tx store.Tx, conf *v2.RoutingConfig) error { + if tx == nil { + return errors.New("tx is nil") + } + + dbTx := tx.GetDelegateTx().(*BaseTx) + return r.updateRoutingConfigV2Tx(dbTx, conf) +} + +func (r *routingConfigStoreV2) updateRoutingConfigV2Tx(tx *BaseTx, conf *v2.RoutingConfig) error { + if conf.ID == "" || conf.Revision == "" { + log.Errorf("[Store][database] update routing config v2 missing id or revision") + return store.NewStatusError(store.EmptyParamsErr, "missing id or revision") + } + if conf.Policy == "" || conf.Config == "" { + log.Errorf("[Store][boltdb] create routing config v2 missing params") + return store.NewStatusError(store.EmptyParamsErr, "missing some params") + } + + str := "update routing_config_v2 set name = ?, policy = ?, config = ?, revision = ?, priority = ?, " + + " description = ?, mtime = sysdate() where id = ? and namespace = ?" + if _, err := tx.Exec(str, conf.Name, conf.Policy, conf.Config, conf.Revision, conf.Priority, conf.Description, + conf.ID, conf.Namespace); err != nil { + log.Errorf("[Store][database] update routing config v2(%+v) exec err: %s", conf, err.Error()) + return store.Error(err) + } + return nil +} + +// EnableRateLimit 启用限流规则 +func (r *routingConfigStoreV2) EnableRouting(conf *v2.RoutingConfig) error { + if conf.ID == "" || conf.Revision == "" { + return errors.New("[Store][database] enable routing config v2 missing some params") + } + + err := RetryTransaction("EnableRouting", func() error { + var ( + enable int + etimeStr string + ) + if conf.Enable { + enable = 1 + etimeStr = "sysdate()" + } else { + enable = 0 + etimeStr = emptyEnableTime + } + str := fmt.Sprintf( + `update routing_config_v2 set enable = ?, revision = ?, mtime = sysdate(), etime=%s where id = ?`, etimeStr) + if _, err := r.master.Exec(str, enable, conf.Revision, conf.ID); err != nil { + log.Errorf("[Store][database] update outing config v2(%+v), sql %s, err: %s", conf, str, err) + return err + } + + return nil + }) + + return store.Error(err) +} + +// DeleteRoutingConfigV2 删除一个路由配置 +func (r *routingConfigStoreV2) DeleteRoutingConfigV2(ruleID string) error { + + if ruleID == "" { + log.Errorf("[Store][database] delete routing config v2 missing service id") + return store.NewStatusError(store.EmptyParamsErr, "missing service id") + } + + str := `update routing_config_v2 set flag = 1, mtime = sysdate() where id = ?` + if _, err := r.master.Exec(str, ruleID); err != nil { + log.Errorf("[Store][database] delete routing config v2(%s) err: %s", ruleID, err.Error()) + return store.Error(err) + } + + return nil +} + +// GetRoutingConfigsV2ForCache 通过mtime拉取增量的路由配置信息 +// 此方法用于 cache 增量更新,需要注意 mtime 应为数据库时间戳 +func (r *routingConfigStoreV2) GetRoutingConfigsV2ForCache(mtime time.Time, firstUpdate bool) ([]*v2.RoutingConfig, error) { + str := `select id, name, policy, config, enable, revision, flag, priority, description, + unix_timestamp(ctime), unix_timestamp(mtime), unix_timestamp(etime) + from routing_config_v2 where mtime > FROM_UNIXTIME(?) ` + + if firstUpdate { + str += " and flag != 1" // nolint + } + rows, err := r.slave.Query(str, timeToTimestamp(mtime)) + if err != nil { + log.Errorf("[Store][database] query routing configs v2 with mtime err: %s", err.Error()) + return nil, err + } + out, err := fetchRoutingConfigV2Rows(rows) + if err != nil { + return nil, err + } + + return out, nil +} + +// GetRoutingConfigV2WithID 根据服务ID拉取路由配置 +func (r *routingConfigStoreV2) GetRoutingConfigV2WithID(ruleID string) (*v2.RoutingConfig, error) { + + tx, err := r.master.Begin() + if err != nil { + return nil, err + } + + defer tx.Rollback() + return r.getRoutingConfigV2WithIDTx(tx, ruleID) +} + +// GetRoutingConfigV2WithIDTx +func (r *routingConfigStoreV2) GetRoutingConfigV2WithIDTx(tx store.Tx, ruleID string) (*v2.RoutingConfig, error) { + + if tx == nil { + return nil, errors.New("transaction is nil") + } + + dbTx := tx.GetDelegateTx().(*BaseTx) + return r.getRoutingConfigV2WithIDTx(dbTx, ruleID) +} + +func (r *routingConfigStoreV2) getRoutingConfigV2WithIDTx(tx *BaseTx, ruleID string) (*v2.RoutingConfig, error) { + + str := `select id, name, policy, config, enable, revision, flag, priority, description, + unix_timestamp(ctime), unix_timestamp(mtime), unix_timestamp(etime) + from routing_config_v2 + where id = ? and flag = 0` + rows, err := tx.Query(str, ruleID) + if err != nil { + log.Errorf("[Store][database] query routing v2 with id(%s) err: %s", ruleID, err.Error()) + return nil, err + } + + out, err := fetchRoutingConfigV2Rows(rows) + if err != nil { + return nil, err + } + + if len(out) == 0 { + return nil, nil + } + + return out[0], nil +} + +// fetchRoutingConfigRows 读取数据库的数据,并且释放rows +func fetchRoutingConfigV2Rows(rows *sql.Rows) ([]*v2.RoutingConfig, error) { + defer rows.Close() + var out []*v2.RoutingConfig + for rows.Next() { + var ( + entry v2.RoutingConfig + flag, enable int + ctime, mtime, etime int64 + ) + + err := rows.Scan(&entry.ID, &entry.Name, &entry.Policy, &entry.Config, &enable, &entry.Revision, + &flag, &entry.Priority, &entry.Description, &ctime, &mtime, &etime) + if err != nil { + log.Errorf("[database][store] fetch routing config v2 scan err: %s", err.Error()) + return nil, err + } + + entry.CreateTime = time.Unix(ctime, 0) + entry.ModifyTime = time.Unix(mtime, 0) + entry.EnableTime = time.Unix(etime, 0) + entry.Valid = true + if flag == 1 { + entry.Valid = false + } + entry.Enable = enable == 1 + + out = append(out, &entry) + } + if err := rows.Err(); err != nil { + log.Errorf("[database][store] fetch routing config v2 next err: %s", err.Error()) + return nil, err + } + + return out, nil +} diff --git a/store/sqldb/scripts/delta/v1_11_0-v1_12_0.sql b/store/sqldb/scripts/delta/v1_11_0-v1_12_0.sql new file mode 100644 index 000000000..af6bfa3bb --- /dev/null +++ b/store/sqldb/scripts/delta/v1_11_0-v1_12_0.sql @@ -0,0 +1,41 @@ +/* + * Tencent is pleased to support the open source community by making Polaris available. + * + * Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved. + * + * Licensed under the BSD 3-Clause License (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://opensource.org/licenses/BSD-3-Clause + * + * 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. + */ +-- +-- Database: `polaris_server` +-- +USE `polaris_server`; + +CREATE TABLE `routing_config_v2` +( + `id` VARCHAR(128) NOT NULL, + `name` VARCHAR(64) NOT NULL default '', + `namespace` VARCHAR(64) NOT NULL default '', + `policy` VARCHAR(64) NOT NULL, + `config` TEXT, + `enable` INT NOT NULL DEFAULT 0, + `revision` VARCHAR(40) NOT NULL, + `description` VARCHAR(500) NOT NULL DEFAULT '', + `priority` smallint(6) NOT NULL DEFAULT '0' comment 'routing rule priority', + `flag` TINYINT(4) NOT NULL DEFAULT '0', + `ctime` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, + `mtime` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, + `etime` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, + `extend_info` VARCHAR(1024) DEFAULT '', + PRIMARY KEY (`id`), + KEY `mtime` (`mtime`) +) engine = innodb; + diff --git a/store/sqldb/scripts/delta/v160-v170.sql b/store/sqldb/scripts/delta/v1_6_0-v1_7_0.sql similarity index 100% rename from store/sqldb/scripts/delta/v160-v170.sql rename to store/sqldb/scripts/delta/v1_6_0-v1_7_0.sql diff --git a/store/sqldb/scripts/delta/v170-v180.sql b/store/sqldb/scripts/delta/v1_7_0-v1_8_0.sql similarity index 100% rename from store/sqldb/scripts/delta/v170-v180.sql rename to store/sqldb/scripts/delta/v1_7_0-v1_8_0.sql diff --git a/store/sqldb/scripts/delta/v180-v190.sql b/store/sqldb/scripts/delta/v1_8_0-v1_11_0.sql similarity index 62% rename from store/sqldb/scripts/delta/v180-v190.sql rename to store/sqldb/scripts/delta/v1_8_0-v1_11_0.sql index f1aa136ff..d0192c8db 100644 --- a/store/sqldb/scripts/delta/v180-v190.sql +++ b/store/sqldb/scripts/delta/v1_8_0-v1_11_0.sql @@ -1,31 +1,45 @@ -/* - * Tencent is pleased to support the open source community by making Polaris available. - * - * Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved. - * - * Licensed under the BSD 3-Clause License (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://opensource.org/licenses/BSD-3-Clause - * - * 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. - */ - -CREATE TABLE `config_file_template` ( - `id` bigint(10) unsigned NOT NULL AUTO_INCREMENT COMMENT '主键', - `name` varchar(128) COLLATE utf8_bin NOT NULL COMMENT '配置文件模板名称', - `content` longtext COLLATE utf8_bin NOT NULL COMMENT '配置文件模板内容', - `format` varchar(16) COLLATE utf8_bin DEFAULT 'text' COMMENT '模板文件格式', - `comment` varchar(512) COLLATE utf8_bin DEFAULT NULL COMMENT '模板描述信息', - `flag` tinyint(4) NOT NULL DEFAULT '0' COMMENT '软删除标记位', - `create_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', - `create_by` varchar(32) COLLATE utf8_bin DEFAULT NULL COMMENT '创建人', - `modify_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '最后更新时间', - `modify_by` varchar(32) COLLATE utf8_bin DEFAULT NULL COMMENT '最后更新人', - PRIMARY KEY (`id`), - UNIQUE KEY `uk_name` (`name`) -) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8 COLLATE=utf8_bin COMMENT='配置文件模板表'; +/* + * Tencent is pleased to support the open source community by making Polaris available. + * + * Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved. + * + * Licensed under the BSD 3-Clause License (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://opensource.org/licenses/BSD-3-Clause + * + * 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. + */ +-- +-- Database: `polaris_server` +-- + +USE `polaris_server`; + +ALTER TABLE `ratelimit_config` ADD COLUMN `name` varchar(64) NOT NULL; +ALTER TABLE `ratelimit_config` ADD COLUMN `disable` tinyint(4) NOT NULL DEFAULT '0'; +ALTER TABLE `ratelimit_config` ADD COLUMN `etime` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP; +ALTER TABLE `ratelimit_config` ADD COLUMN `method` varchar(512) NOT NULL; + + +CREATE TABLE `config_file_template` ( + `id` bigint(10) unsigned NOT NULL AUTO_INCREMENT COMMENT '主键', + `name` varchar(128) COLLATE utf8_bin NOT NULL COMMENT '配置文件模板名称', + `content` longtext COLLATE utf8_bin NOT NULL COMMENT '配置文件模板内容', + `format` varchar(16) COLLATE utf8_bin DEFAULT 'text' COMMENT '模板文件格式', + `comment` varchar(512) COLLATE utf8_bin DEFAULT NULL COMMENT '模板描述信息', + `flag` tinyint(4) NOT NULL DEFAULT '0' COMMENT '软删除标记位', + `create_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', + `create_by` varchar(32) COLLATE utf8_bin DEFAULT NULL COMMENT '创建人', + `modify_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '最后更新时间', + `modify_by` varchar(32) COLLATE utf8_bin DEFAULT NULL COMMENT '最后更新人', + PRIMARY KEY (`id`), + UNIQUE KEY `uk_name` (`name`) +) ENGINE=InnoDB COMMENT='配置文件模板表'; + +INSERT INTO `config_file_template` (`id`,`name`,`content`,`format`,`comment`,`create_time`,`create_by`,`modify_time`,`modify_by`) VALUES (2,'spring-cloud-gateway-braining','{\n \"rules\":[\n {\n \"conditions\":[\n {\n \"key\":\"${http.query.uid}\",\n \"values\":[\n \"10000\"\n ],\n \"operation\":\"EQUALS\"\n }\n ],\n \"labels\":[\n {\n \"key\":\"env\",\n \"value\":\"green\"\n }\n ]\n }\n ]\n}','json','Spring Cloud Gateway 染色规则','2022-08-18 10:54:46','polaris','2022-08-18 10:55:22','polaris'); + diff --git a/store/sqldb/scripts/polaris_server.sql b/store/sqldb/scripts/polaris_server.sql index 07d4eefa9..aed7704b4 100644 --- a/store/sqldb/scripts/polaris_server.sql +++ b/store/sqldb/scripts/polaris_server.sql @@ -254,51 +254,7 @@ VALUES ('fbca9bfa04ae4ead86e1ecf5811e32a9', 'polaris', 0, '2021-09-06 07:55:07', - '2021-09-06 07:55:09'), - ('bbfdda174ea64e11ac862adf14593c03', - 'polaris.monitor', - 'Polaris', - 'polaris monitor service', - 'polaris', - '50b4e7d8affa4634b52523d398d1a369', - '3649b17283d94d7baee5fb5d8160a225', - 'polaris', - 0, - '2021-09-06 07:55:07', - '2021-09-06 07:55:11'), - ('e6542db1a2cc846c1866010b40b7f51f', - 'polaris.config', - 'Polaris', - 'polaris config service', - 'polaris', - 'c874d9a0a4b45c82c93e6bf285518c7b', - '769ec01f58875088faf2cb9e44a4b2d2', - 'polaris', - 0, - '2021-09-06 07:55:07', - '2021-09-06 07:55:11'), - ('1866010b40be6542db1a2cc846c7f51f', - 'polaris.discover', - 'Polaris', - 'polaris discover service', - 'polaris', - '2a54df30a6fd4910bdb601dd40b6d58e', - '5060b13df17240d8-84001e5ae0216c48', - 'polaris', - 0, - '2021-09-06 07:55:07', - '2021-09-06 07:55:11'), - ('846c1866010b40b7f51fe6542db1a2cc', - 'polaris.healthcheck', - 'Polaris', - 'polaris health check service', - 'polaris', - '254b202a965541a5966b725ae18a6613', - 'aaa44f501ebb4884b0f5c005666ecca1', - 'polaris', - 0, - '2021-09-06 07:55:07', - '2021-09-06 07:55:11'); + '2021-09-06 07:55:09'); -- -------------------------------------------------------- -- @@ -832,6 +788,8 @@ INSERT INTO `user` (`id`, `token_enable`, `user_type`, `comment`, + `mobile`, + `email`, `owner`) VALUES ('65e4789a6d5b49669adf1e9e8387549c', 'polaris', @@ -841,6 +799,8 @@ VALUES ('65e4789a6d5b49669adf1e9e8387549c', 1, 20, 'default polaris admin account', + '12345678910', + '12345678910', ''); -- Permissions policy inserted into Polaris-Admin @@ -935,3 +895,48 @@ CREATE TABLE `config_file_template` ( PRIMARY KEY (`id`), UNIQUE KEY `uk_name` (`name`) ) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8 COLLATE=utf8_bin COMMENT='配置文件模板表'; + +INSERT INTO `config_file_template` (`name`, `content`, `format`, `comment`, `create_time` + , `create_by`, `modify_time`, `modify_by`) +VALUES ("spring-cloud-gateway-braining", '{ + "rules":[ + { + "conditions":[ + { + "key":"${http.query.uid}", + "values":["10000"], + "operation":"EQUALS" + } + ], + "labels":[ + { + "key":"env", + "value":"green" + } + ] + } + ] +}', "json", "Spring Cloud Gateway 染色规则", NOW() + , "polaris", NOW(), "polaris"); + +-- v1.12.0 +CREATE TABLE `routing_config_v2` +( + `id` VARCHAR(128) NOT NULL, + `name` VARCHAR(64) NOT NULL default '', + `namespace` VARCHAR(64) NOT NULL default '', + `policy` VARCHAR(64) NOT NULL, + `config` TEXT, + `enable` INT NOT NULL DEFAULT 0, + `revision` VARCHAR(40) NOT NULL, + `description` VARCHAR(500) NOT NULL DEFAULT '', + `priority` smallint(6) NOT NULL DEFAULT '0' comment 'routing rule priority', + `flag` TINYINT(4) NOT NULL DEFAULT '0', + `ctime` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, + `mtime` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, + `etime` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, + `extend_info` VARCHAR(1024) DEFAULT '', + PRIMARY KEY (`id`), + KEY `mtime` (`mtime`) +) engine = innodb; + diff --git a/store/sqldb/tool.go b/store/sqldb/tool.go index 1bb312f07..423e40f68 100644 --- a/store/sqldb/tool.go +++ b/store/sqldb/tool.go @@ -31,7 +31,7 @@ const ( maxQueryInterval = time.Second ) -// GetNow 获取当前时间,单位秒 +// GetUnixSecond 获取当前时间,单位秒 func (t *toolStore) GetUnixSecond() (int64, error) { startTime := time.Now() rows, err := t.db.Query(nowSql) diff --git a/test/client_grpc_test.go b/test/client_grpc_test.go index f59672c9c..6a07571b9 100644 --- a/test/client_grpc_test.go +++ b/test/client_grpc_test.go @@ -128,7 +128,7 @@ func TestClientGRPC_DiscoverInstance(t *testing.T) { testMeta["version"] = instances[0].Version.GetValue() testMeta["protocol"] = instances[0].Protocol.GetValue() - assert.Equalf(t, testMeta, resp.Instances[0].Metadata, "instance metadata actual : %v", instances[0].Metadata) + assert.True(t, resp.Instances[0].Metadata["internal-mock-label"] == "polaris-auto-mock-test", "instance metadata actual : %v", instances[0].Metadata) }) if err != nil { t.Fatalf("discover instance fail") diff --git a/test/grpc/register.go b/test/grpc/register.go index adc522f21..6533462c5 100644 --- a/test/grpc/register.go +++ b/test/grpc/register.go @@ -56,7 +56,7 @@ func (c *Client) DeregisterInstance(instance *api.Instance) error { md := metadata.Pairs("request-id", utils.NewUUID()) ctx := metadata.NewOutgoingContext(context.Background(), md) - ctx, cancel := context.WithTimeout(ctx, time.Second) + ctx, cancel := context.WithTimeout(ctx, 10*time.Second) defer cancel() rsp, err := c.Worker.DeregisterInstance(ctx, instance) diff --git a/test/http/circuitbreaker_config.go b/test/http/circuitbreaker_config.go index 76fe8feaf..79b224776 100644 --- a/test/http/circuitbreaker_config.go +++ b/test/http/circuitbreaker_config.go @@ -92,7 +92,7 @@ func (c *Client) CreateCircuitBreakers(circuitBreakers []*api.CircuitBreaker) (* ret, err := GetBatchWriteResponse(response) if err != nil { fmt.Printf("%v\n", err) - return nil, err + return ret, err } return checkCreateCircuitBreakersResponse(ret, circuitBreakers) @@ -118,7 +118,7 @@ func (c *Client) CreateCircuitBreakerVersions(circuitBreakers []*api.CircuitBrea ret, err := GetBatchWriteResponse(response) if err != nil { fmt.Printf("%v\n", err) - return nil, err + return ret, err } return checkCreateCircuitBreakersResponse(ret, circuitBreakers) diff --git a/test/http/client.go b/test/http/client.go index 9b797244d..2086929ce 100644 --- a/test/http/client.go +++ b/test/http/client.go @@ -105,11 +105,12 @@ func GetBatchWriteResponse(response *http.Response) (*api.BatchWriteResponse, er fmt.Printf("%+v\n", ret) } else { fmt.Printf("%v\n", checkErr) + ret = nil } // 检查回复 if response.StatusCode != 200 { - return nil, errors.New("invalid http code") + return ret, fmt.Errorf("invalid http code : %d, ret code : %d", response.StatusCode, ret.GetCode().GetValue()) } if checkErr == nil { diff --git a/test/http/config_center.go b/test/http/config_center.go index 777696c7c..cfe4bfbe9 100644 --- a/test/http/config_center.go +++ b/test/http/config_center.go @@ -281,7 +281,7 @@ func checkCreateConfigResponse(ret *api.ConfigResponse) ( switch { case ret.GetCode().GetValue() != api.ExecuteSuccess: - return nil, errors.New("invalid batch code") + return nil, errors.New(ret.GetInfo().GetValue()) } return ret, nil @@ -292,7 +292,7 @@ func checkQueryConfigResponse(ret *api.ConfigBatchQueryResponse) ( switch { case ret.GetCode().GetValue() != api.ExecuteSuccess: - return nil, errors.New("invalid batch code") + return nil, errors.New(ret.GetInfo().GetValue()) } return ret, nil diff --git a/test/http/instance.go b/test/http/instance.go index 31cedcdd2..7293323c2 100644 --- a/test/http/instance.go +++ b/test/http/instance.go @@ -75,7 +75,7 @@ func (c *Client) CreateInstances(instances []*api.Instance) (*api.BatchWriteResp ret, err := GetBatchWriteResponse(response) if err != nil { fmt.Printf("%v\n", err) - return nil, err + return ret, err } return checkCreateInstancesResponse(ret, instances) diff --git a/test/http/namespace.go b/test/http/namespace.go index e3f3b0415..39776fda1 100644 --- a/test/http/namespace.go +++ b/test/http/namespace.go @@ -71,7 +71,7 @@ func (c *Client) CreateNamespaces(namespaces []*api.Namespace) (*api.BatchWriteR ret, err := GetBatchWriteResponse(response) if err != nil { fmt.Printf("%v\n", err) - return nil, err + return ret, err } return checkCreateNamespacesResponse(ret, namespaces) @@ -108,6 +108,33 @@ func (c *Client) DeleteNamespaces(namespaces []*api.Namespace) error { return nil } +// DeleteNamespaces 删除命名空间 +func (c *Client) DeleteNamespacesGetResp(namespaces []*api.Namespace) (*api.BatchWriteResponse, error) { + fmt.Printf("\ndelete namespaces\n") + + url := fmt.Sprintf("http://%v/naming/%v/namespaces/delete", c.Address, c.Version) + + body, err := JSONFromNamespaces(namespaces) + if err != nil { + fmt.Printf("%v\n", err) + return nil, err + } + + response, err := c.SendRequest("POST", url, body) + if err != nil { + fmt.Printf("%v\n", err) + return nil, err + } + + resp, err := GetBatchWriteResponse(response) + if err != nil { + fmt.Printf("%v\n", err) + return resp, err + } + + return resp, nil +} + // UpdateNamesapces 更新命名空间 func (c *Client) UpdateNamesapces(namespaces []*api.Namespace) error { fmt.Printf("\nupdate namespaces\n") diff --git a/test/http/platform.go b/test/http/platform.go deleted file mode 100644 index 9561b287e..000000000 --- a/test/http/platform.go +++ /dev/null @@ -1,267 +0,0 @@ -/** - * Tencent is pleased to support the open source community by making Polaris available. - * - * Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved. - * - * Licensed under the BSD 3-Clause License (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://opensource.org/licenses/BSD-3-Clause - * - * 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 http - -import ( - "bytes" - "errors" - "fmt" - "io" - - "github.com/golang/protobuf/jsonpb" - - api "github.com/polarismesh/polaris-server/common/api/v1" -) - -/** - * @brief 平台数据转JSON - */ -func JSONFromPlatforms(platforms []*api.Platform) (*bytes.Buffer, error) { - m := jsonpb.Marshaler{Indent: " "} - - buffer := bytes.NewBuffer([]byte{}) - - buffer.Write([]byte("[")) - for index, service := range platforms { - if index > 0 { - buffer.Write([]byte(",\n")) - } - err := m.Marshal(buffer, service) - if err != nil { - return nil, err - } - } - - buffer.Write([]byte("]")) - return buffer, nil -} - -/** - * @brief 创建平台 - */ -func (c *Client) CreatePlatforms(platforms []*api.Platform) (*api.BatchWriteResponse, error) { - fmt.Printf("\ncreate platforms\n") - - url := fmt.Sprintf("http://%v/naming/%v/platforms", c.Address, c.Version) - - body, err := JSONFromPlatforms(platforms) - if err != nil { - fmt.Printf("%v\n", err) - return nil, err - } - - response, err := c.SendRequest("POST", url, body) - if err != nil { - fmt.Printf("%v\n", err) - return nil, err - } - - ret, err := GetBatchWriteResponse(response) - if err != nil { - fmt.Printf("%v\n", err) - return nil, err - } - - return checkCreatePlatformsResponse(ret, platforms) -} - -/** - * @brief 删除平台 - */ -func (c *Client) DeletePlatforms(platforms []*api.Platform) error { - fmt.Printf("\ndelete platforms\n") - - url := fmt.Sprintf("http://%v/naming/%v/platforms/delete", c.Address, c.Version) - - body, err := JSONFromPlatforms(platforms) - if err != nil { - fmt.Printf("%v\n", err) - return err - } - - response, err := c.SendRequest("POST", url, body) - if err != nil { - fmt.Printf("%v\n", err) - return err - } - - _, err = GetBatchWriteResponse(response) - if err != nil { - if err == io.EOF { - return nil - } - - fmt.Printf("%v\n", err) - return err - } - return nil -} - -/** - * @brief 更新平台 - */ -func (c *Client) UpdatePlatforms(platforms []*api.Platform) error { - fmt.Printf("\nupdate platforms\n") - - url := fmt.Sprintf("http://%v/naming/%v/platforms", c.Address, c.Version) - - body, err := JSONFromPlatforms(platforms) - if err != nil { - fmt.Printf("%v\n", err) - return err - } - - response, err := c.SendRequest("PUT", url, body) - if err != nil { - fmt.Printf("%v\n", err) - return err - } - - _, err = GetBatchWriteResponse(response) - if err != nil { - if err == io.EOF { - return nil - } - - fmt.Printf("%v\n", err) - return err - } - return nil -} - -/** - * @brief 查询平台 - */ -func (c *Client) GetPlatforms(platforms []*api.Platform) error { - fmt.Printf("\nget platforms\n") - - url := fmt.Sprintf("http://%v/naming/%v/platforms", c.Address, c.Version) - - params := map[string][]interface{}{ - "name": {platforms[0].GetName().GetValue()}, - } - - url = c.CompleteURL(url, params) - response, err := c.SendRequest("GET", url, nil) - if err != nil { - return err - } - - ret, err := GetBatchQueryResponse(response) - if err != nil { - fmt.Printf("%v\n", err) - return err - } - - if ret.GetCode() == nil || ret.GetCode().GetValue() != api.ExecuteSuccess { - return fmt.Errorf("invalid batch code: %v", ret.GetCode().GetValue()) - } - - platformsSize := len(platforms) - - if ret.GetAmount() == nil || ret.GetAmount().GetValue() != uint32(platformsSize) { - return fmt.Errorf("invalid batch amount: %d, expect amount is %d", - ret.GetAmount().GetValue(), platformsSize) - } - - if ret.GetSize() == nil || ret.GetSize().GetValue() != uint32(platformsSize) { - return fmt.Errorf("invalid batch size: %d, expect size is %d", - ret.GetSize().GetValue(), platformsSize) - } - - collection := make(map[string]*api.Platform) - for _, platform := range platforms { - collection[platform.GetId().GetValue()] = platform - } - - items := ret.GetPlatforms() - if items == nil || len(items) != platformsSize { - return errors.New("invalid batch platforms") - } - - for _, item := range items { - if correctItem, ok := collection[item.GetId().GetValue()]; ok { - if result, err := comparePlatform(correctItem, item); !result { - return fmt.Errorf("invalid platform. id is %s, err is %s", item.GetId().GetValue(), err.Error()) - } - } else { - return fmt.Errorf("platform not found. id is %s", item.GetId().GetValue()) - } - } - return nil -} - -/** - * @brief 检查创建平台的回复 - */ -func checkCreatePlatformsResponse(ret *api.BatchWriteResponse, platforms []*api.Platform) ( - *api.BatchWriteResponse, error) { - if ret.GetCode() == nil || ret.GetCode().GetValue() != api.ExecuteSuccess { - return nil, fmt.Errorf("invalid batch code: %v", ret.GetCode().GetValue()) - } - - platformsSize := len(platforms) - if ret.GetSize() == nil || ret.GetSize().GetValue() != uint32(platformsSize) { - return nil, fmt.Errorf("invalid batch size, expect size is %d, actual size is %d", - platformsSize, ret.GetSize().GetValue()) - } - - items := ret.GetResponses() - if items == nil || len(items) != platformsSize { - return nil, errors.New("invalid batch response") - } - - for index, item := range items { - if item.GetCode() == nil || item.GetCode().GetValue() != api.ExecuteSuccess { - return nil, fmt.Errorf("invalid code: %v", item.GetCode().GetValue()) - } - - platform := item.GetPlatform() - if platform == nil { - return nil, errors.New("empty platform") - } - if _, err := comparePlatform(platforms[index], platform); err != nil { - return nil, fmt.Errorf("invalid platform. id is %s, err is %s", - platform.GetId().GetValue(), err.Error()) - } - } - return ret, nil -} - -/** - * @brief 比较平台信息是否相等 - */ -func comparePlatform(correctItem *api.Platform, item *api.Platform) (bool, error) { - switch { - case correctItem.GetId().GetValue() != item.GetId().GetValue(): - return false, errors.New("error id") - case correctItem.GetName().GetValue() != item.GetName().GetValue(): - return false, errors.New("error name") - case correctItem.GetDomain().GetValue() != item.GetDomain().GetValue(): - return false, errors.New("error domain") - case correctItem.GetQps().GetValue() != item.GetQps().GetValue(): - return false, errors.New("error qps") - case correctItem.GetOwner().GetValue() != item.GetOwner().GetValue(): - return false, errors.New("error owner") - case correctItem.GetDepartment().GetValue() != item.GetDepartment().GetValue(): - return false, errors.New("error department") - case correctItem.GetComment().GetValue() != item.GetComment().GetValue(): - return false, errors.New("error comment") - } - return true, nil -} diff --git a/test/http/ratelimit_config.go b/test/http/ratelimit_config.go index 10811e143..65bd8d2cb 100644 --- a/test/http/ratelimit_config.go +++ b/test/http/ratelimit_config.go @@ -76,7 +76,7 @@ func (c *Client) CreateRateLimits(rateLimits []*api.Rule) (*api.BatchWriteRespon ret, err := GetBatchWriteResponse(response) if err != nil { fmt.Printf("%v\n", err) - return nil, err + return ret, err } return checkCreateRateLimitsResponse(ret, rateLimits) diff --git a/test/http/service.go b/test/http/service.go index 8303f88ed..9bca91eb2 100644 --- a/test/http/service.go +++ b/test/http/service.go @@ -76,7 +76,7 @@ func (c *Client) CreateServices(services []*api.Service) (*api.BatchWriteRespons ret, err := GetBatchWriteResponse(response) if err != nil { fmt.Printf("%v\n", err) - return nil, err + return ret, err } return checkCreateServicesResponse(ret, services) diff --git a/test/i18n_test.go b/test/i18n_test.go index fcbb42bc5..f3462673d 100644 --- a/test/i18n_test.go +++ b/test/i18n_test.go @@ -38,8 +38,8 @@ func TestI18n(t *testing.T) { want string } tests := []args{ - {lang: "zh", want: "执行异常"}, - {lang: "en", want: "execute exception"}, + {lang: "zh", want: "命名空间名称非法"}, + {lang: "en", want: "invalid namespace name"}, } for _, item := range tests { ret, err := reqCreateIllegalNamespace(item.lang) diff --git a/test/namespace_test.go b/test/namespace_test.go index e8c773eff..28d20fc29 100644 --- a/test/namespace_test.go +++ b/test/namespace_test.go @@ -124,7 +124,96 @@ func TestCountNamespaceService(t *testing.T) { t.Logf("TestNamespaceServiceCnt success") // 开始清理所有的数据 +} + +// TestDeleteNamespaceWhenHaveService 当命名空间下还有服务时进行删除命名空间的操作 +func TestDeleteNamespaceWhenHaveService(t *testing.T) { + t.Log("test namepsace delete when has service") + client := http.NewClient(httpserverAddress, httpserverVersion) + + namespaces := resource.CreateNamespaces() + + // 创建命名空间 + _, err := client.CreateNamespaces(namespaces) + if err != nil { + t.Fatalf("create namespaces fail: %s", err.Error()) + } + t.Log("create namepsaces success") + + services := resource.CreateServices(namespaces[0]) + if _, err = client.CreateServices(services); err != nil { + t.Fatal(err) + } + + resp, err := client.DeleteNamespacesGetResp(namespaces) + if resp != nil { + if resp.GetCode().GetValue() != v1.NamespaceExistedServices { + t.Fatalf("delete namespace need return code:NamespaceExistedServices, actual : %d, %s", int(resp.GetCode().GetValue()), resp.GetInfo().GetValue()) + } + } + if err != nil && resp == nil { + t.Fatalf("delete namespaces fail: %s", err.Error()) + } + + // 删除 service + if err := client.DeleteServices(services); err != nil { + t.Fatalf("delete service fail: %+v", err) + } + + resp, err = client.DeleteNamespacesGetResp(namespaces) + if resp != nil { + if resp.GetCode().GetValue() != v1.ExecuteSuccess { + t.Fatalf("delete namespace need return code:ExecuteSuccess, actual : %d, %s", int(resp.GetCode().GetValue()), resp.GetInfo().GetValue()) + } + } + if err != nil && resp == nil { + t.Fatalf("delete namespaces fail: %s", err.Error()) + } +} + +// TestDeleteNamespaceWhenHaveConfigGroup 当命名空间下还有配置时进行删除命名空间的操作 +func TestDeleteNamespaceWhenHaveConfigGroup(t *testing.T) { + t.Log("test namepsace interface") + client := http.NewClient(httpserverAddress, httpserverVersion) + + namespaces := resource.CreateNamespaces() + + // 创建命名空间 + _, err := client.CreateNamespaces(namespaces) + if err != nil { + t.Fatalf("create namespaces fail: %s", err.Error()) + } + t.Log("create namepsaces success") + + groups := resource.MockConfigGroups(namespaces[0]) + if _, err = client.CreateConfigGroup(groups[0]); err != nil { + t.Fatal(err) + } + + resp, err := client.DeleteNamespacesGetResp(namespaces) + if resp != nil { + if resp.GetCode().GetValue() != v1.NamespaceExistedConfigGroups { + t.Fatalf("delete namespace need return code:NamespaceExistedConfigGroups, actual : %d, %s", int(resp.GetCode().GetValue()), resp.GetInfo().GetValue()) + } + } + if err != nil && resp == nil { + t.Fatalf("delete namespaces fail: %s", err.Error()) + } + // 删除配置分组 + if _, err := client.DeleteConfigGroup(groups[0]); err != nil { + t.Fatalf("delete service fail: %+v", err) + } + + resp, err = client.DeleteNamespacesGetResp(namespaces) + if resp != nil { + if resp.GetCode().GetValue() != v1.ExecuteSuccess { + t.Fatalf("delete namespace need return code:ExecuteSuccess, actual : %d, %s", int(resp.GetCode().GetValue()), resp.GetInfo().GetValue()) + } + } + if err != nil && resp == nil { + t.Fatalf("delete namespaces fail: %s", err.Error()) + } } func createServiceAndInstance(t *testing.T, expectRes *map[string]model.NamespaceServiceCount, client *http.Client, namespace *v1.Namespace) ([]*v1.Service, []*v1.Instance) { diff --git a/test/platform_test.go b/test/platform_test.go deleted file mode 100644 index 3a4006fe4..000000000 --- a/test/platform_test.go +++ /dev/null @@ -1,79 +0,0 @@ -//go:build integration -// +build integration - -/** - * Tencent is pleased to support the open source community by making Polaris available. - * - * Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved. - * - * Licensed under the BSD 3-Clause License (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://opensource.org/licenses/BSD-3-Clause - * - * 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 test - -import ( - "testing" - - "github.com/polarismesh/polaris-server/test/http" - "github.com/polarismesh/polaris-server/test/resource" -) - -/** - * @brief 测试增删改查平台 - */ -func TestPlatform(t *testing.T) { - t.Log("test platform interface") - - client := http.NewClient(httpserverAddress, httpserverVersion) - - platforms := resource.CreatePlatforms() - - // 创建平台 - ret, err := client.CreatePlatforms(platforms) - if err != nil { - t.Fatalf("create platforms fail: %s", err.Error()) - } - for index, item := range ret.GetResponses() { - platforms[index].Token = item.GetPlatform().GetToken() - } - t.Log("create platforms success") - - // 查询平台 - err = client.GetPlatforms(platforms) - if err != nil { - t.Fatalf("get platforms fail: %s", err.Error()) - } - t.Log("get platforms success") - - // 更新平台 - resource.UpdatePlatforms(platforms) - - err = client.UpdatePlatforms(platforms) - if err != nil { - t.Fatalf("update platforms fail: %s", err.Error()) - } - t.Log("update platforms success") - - // 查询平台 - err = client.GetPlatforms(platforms) - if err != nil { - t.Fatalf("get platforms fail: %s", err.Error()) - } - t.Log("get platforms success") - - // 删除平台 - err = client.DeletePlatforms(platforms) - if err != nil { - t.Fatalf("delete platforms fail: %s", err.Error()) - } - t.Log("delete platforms success") -} diff --git a/test/resource/platform.go b/test/resource/platform.go deleted file mode 100644 index 071f0e194..000000000 --- a/test/resource/platform.go +++ /dev/null @@ -1,62 +0,0 @@ -/** - * Tencent is pleased to support the open source community by making Polaris available. - * - * Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved. - * - * Licensed under the BSD 3-Clause License (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://opensource.org/licenses/BSD-3-Clause - * - * 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 resource - -import ( - "fmt" - "time" - - api "github.com/polarismesh/polaris-server/common/api/v1" - "github.com/polarismesh/polaris-server/common/utils" -) - -/** - * @brief 创建测试平台 - */ -func CreatePlatforms() []*api.Platform { - nowStr := time.Now().Format("2006-01-02T15-04-05") - var platforms []*api.Platform - for index := 1; index <= 2; index++ { - platform := &api.Platform{ - Id: utils.NewStringValue(fmt.Sprintf("id-%v-%v", index, nowStr)), - Name: utils.NewStringValue(fmt.Sprintf("name-%v", nowStr)), - Domain: utils.NewStringValue(fmt.Sprintf("domain-%v-%v", index, nowStr)), - Qps: utils.NewUInt32Value(uint32(index)), - Owner: utils.NewStringValue(fmt.Sprintf("owner-%v-%v", index, nowStr)), - Department: utils.NewStringValue(fmt.Sprintf("department-%v-%v", index, nowStr)), - Comment: utils.NewStringValue(fmt.Sprintf("comment-%v-%v", index, nowStr)), - } - platforms = append(platforms, platform) - } - - return platforms -} - -/** - * @brief 更新测试平台 - */ -func UpdatePlatforms(platforms []*api.Platform) { - for _, platform := range platforms { - platform.Name = utils.NewStringValue("update-name") - platform.Domain = utils.NewStringValue("update-domain") - platform.Qps = utils.NewUInt32Value(platform.GetQps().GetValue() + 1) - platform.Owner = utils.NewStringValue("update-owner") - platform.Department = utils.NewStringValue("update-department") - platform.Comment = utils.NewStringValue("update-comment") - } -} diff --git a/testdata/config_test.yaml b/testdata/config_test.yaml new file mode 100644 index 000000000..4eec945f7 --- /dev/null +++ b/testdata/config_test.yaml @@ -0,0 +1,131 @@ +# server启动引导配置 +bootstrap: + # 全局日志 + logger: + config: + rotateOutputPath: log/polaris-config.log + errorRotateOutputPath: log/polaris-config-error.log + rotationMaxSize: 100 + rotationMaxBackups: 10 + rotationMaxAge: 7 + outputLevel: info + # outputPaths: + # - stdout + # errorOutputPaths: + # - stderr + auth: + rotateOutputPath: log/polaris-auth.log + errorRotateOutputPath: log/polaris-auth-error.log + rotationMaxSize: 100 + rotationMaxBackups: 10 + rotationMaxAge: 7 + outputLevel: info + # outputPaths: + # - stdout + # errorOutputPaths: + # - stderr + store: + rotateOutputPath: log/polaris-store.log + errorRotateOutputPath: log/polaris-store-error.log + rotationMaxSize: 100 + rotationMaxBackups: 10 + rotationMaxAge: 7 + outputLevel: info + # outputPaths: + # - stdout + # errorOutputPaths: + # - stderr + cache: + rotateOutputPath: log/polaris-cache.log + errorRotateOutputPath: log/polaris-cache-error.log + rotationMaxSize: 100 + rotationMaxBackups: 10 + rotationMaxAge: 7 + outputLevel: info + # outputPaths: + # - stdout + # errorOutputPaths: + # - stderr + naming: + rotateOutputPath: log/polaris-naming.log + errorRotateOutputPath: log/polaris-naming-error.log + rotationMaxSize: 100 + rotationMaxBackups: 10 + rotationMaxAge: 7 + outputLevel: info + # outputPaths: + # - stdout + # errorOutputPaths: + # - stderr + default: + rotateOutputPath: log/polaris-default.log + errorRotateOutputPath: log/polaris-default-error.log + rotationMaxSize: 100 + rotationMaxBackups: 10 + rotationMaxAge: 7 + outputLevel: info + outputPaths: + - stdout + errorOutputPaths: + - stderr +namespace: + # 是否允许自动创建命名空间 + autoCreate: true +# 配置中心模块启动配置 +config: + # 是否启动配置模块 + open: true + cache: + #配置文件缓存过期时间,单位s + expireTimeAfterWrite: 3600 +# 存储配置 +store: + name: boltdbStore + option: + path: ./config_center_test.bolt +auth: + # 鉴权插件 + name: defaultAuth + option: + # token 加密的 salt,鉴权解析 token 时需要依靠这个 salt 去解密 token 的信息 + # salt 的长度需要满足以下任意一个:len(salt) in [16, 24, 32] + salt: polarismesh@2021 + # 控制台鉴权能力开关,默认开启 + consoleOpen: true + # 客户端鉴权能力开关, 默认关闭 + clientOpen: false + # name: defaultStore + # option: + # master: + # dbType: mysql + # dbName: polaris_server + # dbUser: # 数据库账号 + # dbPwd: # 数据库密码 + # dbAddr: 127.0.0.1:3306 + # maxOpenConns: -1 + # maxIdleConns: -1 + # connMaxLifetime: 300 # 单位秒 + # txIsolationLevel: 2 #LevelReadCommitted +# 缓存配置 +cache: + open: true + resources: + - name: service # 加载服务数据 + option: + disableBusiness: false # 不加载业务服务 + needMeta: true # 加载服务元数据 + - name: instance # 加载实例数据 + option: + disableBusiness: false # 不加载业务服务实例 + needMeta: true # 加载实例元数据 + - name: routingConfig # 加载路由数据 + - name: rateLimitConfig # 加载限流数据 + - name: circuitBreakerConfig # 加载熔断数据 + - name: users # 加载用户、用户组数据 + - name: strategyRule # 加载鉴权规则数据 + - name: namespace # 加载命名空间数据 + - name: client # 加载 SDK 数据 +# - name: l5 # 加载l5数据 +plugin: + auth: + name: defaultAuth \ No newline at end of file diff --git a/testdata/config_test_sqldb.yaml b/testdata/config_test_sqldb.yaml new file mode 100644 index 000000000..97fcd6ad5 --- /dev/null +++ b/testdata/config_test_sqldb.yaml @@ -0,0 +1,128 @@ +# server启动引导配置 +bootstrap: + # 全局日志 + logger: + config: + rotateOutputPath: log/polaris-config.log + errorRotateOutputPath: log/polaris-config-error.log + rotationMaxSize: 100 + rotationMaxBackups: 10 + rotationMaxAge: 7 + outputLevel: info + # outputPaths: + # - stdout + # errorOutputPaths: + # - stderr + auth: + rotateOutputPath: log/polaris-auth.log + errorRotateOutputPath: log/polaris-auth-error.log + rotationMaxSize: 100 + rotationMaxBackups: 10 + rotationMaxAge: 7 + outputLevel: info + # outputPaths: + # - stdout + # errorOutputPaths: + # - stderr + store: + rotateOutputPath: log/polaris-store.log + errorRotateOutputPath: log/polaris-store-error.log + rotationMaxSize: 100 + rotationMaxBackups: 10 + rotationMaxAge: 7 + outputLevel: info + # outputPaths: + # - stdout + # errorOutputPaths: + # - stderr + cache: + rotateOutputPath: log/polaris-cache.log + errorRotateOutputPath: log/polaris-cache-error.log + rotationMaxSize: 100 + rotationMaxBackups: 10 + rotationMaxAge: 7 + outputLevel: info + # outputPaths: + # - stdout + # errorOutputPaths: + # - stderr + naming: + rotateOutputPath: log/polaris-naming.log + errorRotateOutputPath: log/polaris-naming-error.log + rotationMaxSize: 100 + rotationMaxBackups: 10 + rotationMaxAge: 7 + outputLevel: info + # outputPaths: + # - stdout + # errorOutputPaths: + # - stderr + default: + rotateOutputPath: log/polaris-default.log + errorRotateOutputPath: log/polaris-default-error.log + rotationMaxSize: 100 + rotationMaxBackups: 10 + rotationMaxAge: 7 + outputLevel: info + outputPaths: + - stdout + errorOutputPaths: + - stderr +namespace: + # 是否允许自动创建命名空间 + autoCreate: true +# 配置中心模块启动配置 +config: + # 是否启动配置模块 + open: true + cache: + #配置文件缓存过期时间,单位s + expireTimeAfterWrite: 3600 +# 存储配置 +store: + name: defaultStore + option: + master: + dbType: mysql + dbName: polaris_server + dbUser: root + dbPwd: polaris + dbAddr: 127.0.0.1:3306 + maxOpenConns: -1 + maxIdleConns: -1 + connMaxLifetime: 300 # 单位秒 + txIsolationLevel: 2 #LevelReadCommitted +auth: + # 鉴权插件 + name: defaultAuth + option: + # token 加密的 salt,鉴权解析 token 时需要依靠这个 salt 去解密 token 的信息 + # salt 的长度需要满足以下任意一个:len(salt) in [16, 24, 32] + salt: polarismesh@2021 + # 控制台鉴权能力开关,默认开启 + consoleOpen: true + # 客户端鉴权能力开关, 默认关闭 + clientOpen: false +# 缓存配置 +cache: + open: true + resources: + - name: service # 加载服务数据 + option: + disableBusiness: false # 不加载业务服务 + needMeta: true # 加载服务元数据 + - name: instance # 加载实例数据 + option: + disableBusiness: false # 不加载业务服务实例 + needMeta: true # 加载实例元数据 + - name: routingConfig # 加载路由数据 + - name: rateLimitConfig # 加载限流数据 + - name: circuitBreakerConfig # 加载熔断数据 + - name: users # 加载用户、用户组数据 + - name: strategyRule # 加载鉴权规则数据 + - name: namespace # 加载命名空间数据 + - name: client # 加载 SDK 数据 +# - name: l5 # 加载l5数据 +plugin: + auth: + name: defaultAuth diff --git a/testdata/eureka_apiserver_test.yaml b/testdata/eureka_apiserver_test.yaml new file mode 100644 index 000000000..9015c353b --- /dev/null +++ b/testdata/eureka_apiserver_test.yaml @@ -0,0 +1,244 @@ +# server启动引导配置 +bootstrap: + # 全局日志 + logger: + config: + rotateOutputPath: log/polaris-config.log + errorRotateOutputPath: log/polaris-config-error.log + rotationMaxSize: 100 + rotationMaxBackups: 10 + rotationMaxAge: 7 + outputLevel: info + outputPaths: + - stdout + errorOutputPaths: + - stderr + auth: + rotateOutputPath: log/polaris-auth.log + errorRotateOutputPath: log/polaris-auth-error.log + rotationMaxSize: 100 + rotationMaxBackups: 10 + rotationMaxAge: 7 + outputLevel: info + outputPaths: + - stdout + errorOutputPaths: + - stderr + store: + rotateOutputPath: log/polaris-store.log + errorRotateOutputPath: log/polaris-store-error.log + rotationMaxSize: 100 + rotationMaxBackups: 10 + rotationMaxAge: 7 + outputLevel: info + outputPaths: + - stdout + errorOutputPaths: + - stderr + cache: + rotateOutputPath: log/polaris-cache.log + errorRotateOutputPath: log/polaris-cache-error.log + rotationMaxSize: 100 + rotationMaxBackups: 10 + rotationMaxAge: 7 + outputLevel: info + outputPaths: + - stdout + errorOutputPaths: + - stderr + naming: + rotateOutputPath: log/polaris-naming.log + errorRotateOutputPath: log/polaris-naming-error.log + rotationMaxSize: 100 + rotationMaxBackups: 10 + rotationMaxAge: 7 + outputLevel: info + outputPaths: + - stdout + errorOutputPaths: + - stderr + default: + rotateOutputPath: log/polaris-default.log + errorRotateOutputPath: log/polaris-default-error.log + rotationMaxSize: 100 + rotationMaxBackups: 10 + rotationMaxAge: 7 + outputLevel: info + outputPaths: + - stdout + errorOutputPaths: + - stderr +# - name: l5pbserver +# option: +# listenIP: 0.0.0.0 +# listenPort: 7779 +# clusterName: cl5.discover +# 核心逻辑的配置 +auth: + # 鉴权插件 + name: defaultAuth + option: + # token 加密的 salt,鉴权解析 token 时需要依靠这个 salt 去解密 token 的信息 + # salt 的长度需要满足以下任意一个:len(salt) in [16, 24, 32] + salt: polarismesh@2021 + # 控制台鉴权能力开关,默认开启 + consoleOpen: true + # 客户端鉴权能力开关, 默认关闭 + clientOpen: false +namespace: + # 是否允许自动创建命名空间 + autoCreate: true +naming: + auth: + open: false + # 批量控制器 + batch: + register: + open: true + queueSize: 10240 + waitTime: 32ms + maxBatchCount: 32 + concurrency: 16 + deregister: + open: true + queueSize: 10240 + waitTime: 32ms + maxBatchCount: 32 + concurrency: 16 +# 配置中心模块启动配置 +config: + # 是否启动配置模块 + open: true + cache: + #配置文件缓存过期时间,单位s + expireTimeAfterWrite: 3600 +# 健康检查的配置 +healthcheck: + open: true + service: polaris.checker + slotNum: 30 + minCheckInterval: 1s + maxCheckInterval: 30s + batch: + heartbeat: + open: true + queueSize: 10240 + waitTime: 32ms + maxBatchCount: 32 + concurrency: 8 + checkers: + - name: heartbeatMemory +# - name: heartbeatRedis +# option: +# kvAddr: ##REDIS_ADDR## +# kvUser: ##REDIS_USER# +# kvPasswd: ##REDIS_PWD## +# poolSize: 200 +# minIdleConns: 30 +# idleTimeout: 120s +# connectTimeout: 200ms +# msgTimeout: 200ms +# concurrency: 200 +# withTLS: false +# 缓存配置 +cache: + open: true + resources: + - name: service # 加载服务数据 + option: + disableBusiness: false # 不加载业务服务 + needMeta: true # 加载服务元数据 + - name: instance # 加载实例数据 + option: + disableBusiness: false # 不加载业务服务实例 + needMeta: true # 加载实例元数据 +# - name: l5 # 加载l5数据 +# 存储配置 +store: + # 单机文件存储插件 + name: boltdbStore + option: + path: ./polaris.bolt + ## 数据库存储插件 + # name: defaultStore + # option: + # master: + # dbType: mysql + # dbName: polaris_server + # dbUser: root ##DB_USER## + # dbPwd: polaris ##DB_PWD## + # dbAddr: "127.0.0.1:3306" ##DB_ADDR## + # maxOpenConns: -1 + # maxIdleConns: -1 + # connMaxLifetime: 300 # 单位秒 + # txIsolationLevel: 2 #LevelReadCommitted +# 插件配置 +plugin: + history: + name: HistoryLogger + discoverEvent: + name: discoverEventLocal + # option: + # queueSize: 1024 + # outputPath: ./discover-event + # rotationMaxSize: 500 + # rotationMaxAge: 8 + # rotationMaxBackups: 100 + discoverStatis: + name: discoverLocal + option: + interval: 60 # 统计间隔,单位为秒 + outputPath: ./discover-statis + statis: + name: local + option: + interval: 60 # 统计间隔,单位为秒 + outputPath: ./statis + # api 调用指标数据计算上报到 prometheus + # name: prometheus + # option: + # interval: 60 # 统计间隔,单位为秒 + auth: + name: defaultAuth + ratelimit: + name: token-bucket + option: + remote-conf: false # 是否使用远程配置 + ip-limit: # ip级限流,全局 + open: true # 系统是否开启ip级限流 + global: + open: true + bucket: 300 # 最高峰值 + rate: 200 # 平均一个IP每秒的请求数 + resource-cache-amount: 1024 # 最大缓存的IP个数 + white-list: [127.0.0.1] + instance-limit: + open: true + global: + bucket: 200 + rate: 100 + resource-cache-amount: 1024 + api-limit: # 接口级限流 + open: false # 是否开启接口限流,全局开关,只有为true,才代表系统的限流开启。默认关闭 + rules: + - name: store-read + limit: + open: true # 接口的全局配置,如果在api子项中,不配置,则该接口依据global来做限制 + bucket: 2000 # 令牌桶最大值 + rate: 1000 # 每秒产生的令牌数 + - name: store-write + limit: + open: true + bucket: 1000 + rate: 500 + apis: + - name: "POST:/v1/naming/services" + rule: store-write + - name: "PUT:/v1/naming/services" + rule: store-write + - name: "POST:/v1/naming/services/delete" + rule: store-write + - name: "GET:/v1/naming/services" + rule: store-read + - name: "GET:/v1/naming/services/count" + rule: store-read diff --git a/service/mesh/invalid-virtualService.yaml b/testdata/mesh/invalid-virtualService.yaml similarity index 91% rename from service/mesh/invalid-virtualService.yaml rename to testdata/mesh/invalid-virtualService.yaml index 27859a71a..587b621e0 100644 --- a/service/mesh/invalid-virtualService.yaml +++ b/testdata/mesh/invalid-virtualService.yaml @@ -2,8 +2,9 @@ apiVersion: networking.istio.io/v1alpha3 kind: VirtualService metadata: name: reviews-route -spec: hosts: -- reviews.prod.svc.cluster.local +spec: + hosts: + - reviews.prod.svc.cluster.local http: - name: "reviews-v2-routes" match: diff --git a/service/mesh/normal-gateway.yaml b/testdata/mesh/normal-gateway.yaml similarity index 100% rename from service/mesh/normal-gateway.yaml rename to testdata/mesh/normal-gateway.yaml diff --git a/service/mesh/normal-virtualService-nometa.yaml b/testdata/mesh/normal-virtualService-nometa.yaml similarity index 100% rename from service/mesh/normal-virtualService-nometa.yaml rename to testdata/mesh/normal-virtualService-nometa.yaml diff --git a/service/mesh/normal-virtualService.yaml b/testdata/mesh/normal-virtualService.yaml similarity index 100% rename from service/mesh/normal-virtualService.yaml rename to testdata/mesh/normal-virtualService.yaml diff --git a/service/mesh/update-virtualService.yaml b/testdata/mesh/update-virtualService.yaml similarity index 100% rename from service/mesh/update-virtualService.yaml rename to testdata/mesh/update-virtualService.yaml diff --git a/testdata/polaris-server.yaml b/testdata/polaris-server.yaml new file mode 100644 index 000000000..fdb4102a8 --- /dev/null +++ b/testdata/polaris-server.yaml @@ -0,0 +1,387 @@ +# server启动引导配置 +bootstrap: + # 全局日志 + logger: + config: + rotateOutputPath: log/polaris-config.log + errorRotateOutputPath: log/polaris-config-error.log + rotationMaxSize: 100 + rotationMaxBackups: 10 + rotationMaxAge: 7 + outputLevel: info + # outputPaths: + # - stdout + # errorOutputPaths: + # - stderr + auth: + rotateOutputPath: log/polaris-auth.log + errorRotateOutputPath: log/polaris-auth-error.log + rotationMaxSize: 100 + rotationMaxBackups: 10 + rotationMaxAge: 7 + outputLevel: info + # outputPaths: + # - stdout + # errorOutputPaths: + # - stderr + store: + rotateOutputPath: log/polaris-store.log + errorRotateOutputPath: log/polaris-store-error.log + rotationMaxSize: 100 + rotationMaxBackups: 10 + rotationMaxAge: 7 + outputLevel: info + # outputPaths: + # - stdout + # errorOutputPaths: + # - stderr + cache: + rotateOutputPath: log/polaris-cache.log + errorRotateOutputPath: log/polaris-cache-error.log + rotationMaxSize: 100 + rotationMaxBackups: 10 + rotationMaxAge: 7 + outputLevel: info + # outputPaths: + # - stdout + # errorOutputPaths: + # - stderr + naming: + rotateOutputPath: log/polaris-naming.log + errorRotateOutputPath: log/polaris-naming-error.log + rotationMaxSize: 100 + rotationMaxBackups: 10 + rotationMaxAge: 7 + outputLevel: info + # outputPaths: + # - stdout + # errorOutputPaths: + # - stderr + healthcheck: + rotateOutputPath: log/polaris-healthcheck.log + errorRotateOutputPath: log/polaris-healthcheck-error.log + rotationMaxSize: 100 + rotationMaxBackups: 10 + rotationMaxAge: 7 + outputLevel: info + # outputPaths: + # - stdout + # errorOutputPaths: + # - stderr + xdsv3: + rotateOutputPath: log/polaris-xdsv3.log + errorRotateOutputPath: log/polaris-xdsv3-error.log + rotationMaxSize: 100 + rotationMaxBackups: 10 + rotationMaxAge: 7 + outputLevel: info + # outputPaths: + # - stdout + # errorOutputPaths: + # - stderr + default: + rotateOutputPath: log/polaris-default.log + errorRotateOutputPath: log/polaris-default-error.log + rotationMaxSize: 100 + rotationMaxBackups: 10 + rotationMaxAge: 7 + outputLevel: info + outputPaths: + - stdout + errorOutputPaths: + - stderr + # 按顺序启动server + startInOrder: + open: true # 是否开启,默认是关闭 + key: sz # 全局锁 + # 注册为北极星服务 + polaris_service: + # probe_address: ##DB_ADDR## + enable_register: true + isolated: false + services: + - name: polaris.checker + protocols: + - service-grpc +# apiserver配置 +apiservers: + - name: service-eureka + option: + listenIP: "0.0.0.0" + listenPort: 8761 + namespace: default + owner: polaris + refreshInterval: 10 + deltaExpireInterval: 60 + unhealthyExpireInterval: 180 + connLimit: + openConnLimit: false + maxConnPerHost: 1024 + maxConnLimit: 10240 + whiteList: 127.0.0.1 + purgeCounterInterval: 10s + purgeCounterExpired: 5s + - name: api-http # 协议名,全局唯一 + option: + listenIP: "0.0.0.0" + listenPort: 8090 + enablePprof: true # debug pprof + enableSwagger: true + connLimit: + openConnLimit: false + maxConnPerHost: 128 + maxConnLimit: 5120 + whiteList: 127.0.0.1 + purgeCounterInterval: 10s + purgeCounterExpired: 5s + api: + admin: + enable: true + console: + enable: true + include: [default] + client: + enable: true + include: [discover, register, healthcheck] + config: + enable: true + include: [default] + - name: service-grpc + option: + listenIP: "0.0.0.0" + listenPort: 8091 + connLimit: + openConnLimit: false + maxConnPerHost: 128 + maxConnLimit: 5120 + enableCacheProto: true + sizeCacheProto: 128 + tls: + certFile: "" + keyFile: "" + trustedCAFile: "" + api: + client: + enable: true + include: [discover, register, healthcheck] + - name: config-grpc + option: + listenIP: "0.0.0.0" + listenPort: 8093 + connLimit: + openConnLimit: false + maxConnPerHost: 128 + maxConnLimit: 5120 + api: + client: + enable: true + - name: xds-v3 + option: + listenIP: "0.0.0.0" + listenPort: 15010 + connLimit: + openConnLimit: false + maxConnPerHost: 128 + maxConnLimit: 10240 + - name: prometheus-sd + option: + listenIP: "0.0.0.0" + listenPort: 9000 + connLimit: + openConnLimit: false + maxConnPerHost: 128 + maxConnLimit: 10240 + # - name: service-l5 + # option: + # listenIP: 0.0.0.0 + # listenPort: 7779 + # clusterName: cl5.discover +# 核心逻辑的配置 +auth: + # 鉴权插件 + name: defaultAuth + option: + # token 加密的 salt,鉴权解析 token 时需要依靠这个 salt 去解密 token 的信息 + # salt 的长度需要满足以下任意一个:len(salt) in [16, 24, 32] + salt: polarismesh@2021 + # 控制台鉴权能力开关,默认开启 + consoleOpen: true + # 客户端鉴权能力开关, 默认关闭 + clientOpen: false +namespace: + # 是否允许自动创建命名空间 + autoCreate: true +naming: + auth: + open: false + # 批量控制器 + batch: + register: + open: true + queueSize: 10240 + waitTime: 32ms + maxBatchCount: 128 + concurrency: 128 + dropExpireTask: true + taskLife: 30s + deregister: + open: true + queueSize: 10240 + waitTime: 32ms + maxBatchCount: 128 + concurrency: 128 + clientRegister: + open: true + queueSize: 10240 + waitTime: 32s + maxBatchCount: 1024 + concurrency: 64 + clientDeregister: + open: true + queueSize: 10240 + waitTime: 32ms + maxBatchCount: 32 + concurrency: 64 +# 健康检查的配置 +healthcheck: + open: true + service: polaris.checker + slotNum: 30 + minCheckInterval: 1s + maxCheckInterval: 30s + clientReportInterval: 120s + batch: + heartbeat: + open: true + queueSize: 10240 + waitTime: 32ms + maxBatchCount: 32 + concurrency: 64 + checkers: + # - name: heartbeatMemory + - name: heartbeatRedis + option: + kvAddr: + 127.0.0.1:6379 ##REDIS_ADDR## + # ACL user from redis v6.0, remove it if ACL is not available + kvUser: ##REDIS_USER# + kvPasswd: ##REDIS_PWD## + poolSize: 200 + minIdleConns: 30 + idleTimeout: 120s + connectTimeout: 200ms + msgTimeout: 200ms + concurrency: 200 + withTLS: false +# 配置中心模块启动配置 +config: + # 是否启动配置模块 + open: true + cache: + #配置文件缓存过期时间,单位s + expireTimeAfterWrite: 3600 +# 缓存配置 +cache: + open: true + resources: + - name: service # 加载服务数据 + option: + disableBusiness: false # 不加载业务服务 + needMeta: true # 加载服务元数据 + - name: instance # 加载实例数据 + option: + disableBusiness: false # 不加载业务服务实例 + needMeta: true # 加载实例元数据 + - name: routingConfig # 加载路由数据 + - name: rateLimitConfig # 加载限流数据 + - name: circuitBreakerConfig # 加载熔断数据 + - name: users # 加载用户、用户组数据 + - name: strategyRule # 加载鉴权规则数据 + - name: namespace # 加载命名空间数据 + - name: client # 加载 SDK 数据 +# - name: l5 # 加载l5数据 +# 存储配置 +store: + # 单机文件存储插件 + # name: boltdbStore + # option: + # path: ./polaris.bolt + ## 数据库存储插件 + name: defaultStore + option: + master: + dbType: mysql + dbName: polaris_server + dbUser: root ##DB_USER## + dbPwd: polaris ##DB_PWD## + dbAddr: "127.0.0.1:3306" ##DB_ADDR## + maxOpenConns: -1 + maxIdleConns: -1 + connMaxLifetime: 300 # 单位秒 + txIsolationLevel: 2 #LevelReadCommitted +# 插件配置 +plugin: + history: + name: HistoryLogger + discoverEvent: + name: discoverEventLocal + # option: + # queueSize: 1024 + # outputPath: ./discover-event + # rotationMaxSize: 500 + # rotationMaxAge: 8 + # rotationMaxBackups: 100 + discoverStatis: + name: discoverLocal + option: + interval: 60 # 统计间隔,单位为秒 + outputPath: ./discover-statis + statis: + name: local + option: + interval: 60 # 统计间隔,单位为秒 + outputPath: ./statis + auth: + name: defaultAuth + ratelimit: + name: token-bucket + option: + remote-conf: false # 是否使用远程配置 + ip-limit: # ip级限流,全局 + open: true # 系统是否开启ip级限流 + global: + open: true + bucket: 300 # 最高峰值 + rate: 200 # 平均一个IP每秒的请求数 + resource-cache-amount: 1024 # 最大缓存的IP个数 + white-list: [127.0.0.1] + instance-limit: + open: true + global: + bucket: 200 + rate: 100 + resource-cache-amount: 1024 + api-limit: # 接口级限流 + open: false # 是否开启接口限流,全局开关,只有为true,才代表系统的限流开启。默认关闭 + rules: + - name: store-read + limit: + open: true # 接口的全局配置,如果在api子项中,不配置,则该接口依据global来做限制 + bucket: 2000 # 令牌桶最大值 + rate: 1000 # 每秒产生的令牌数 + - name: store-write + limit: + open: true + bucket: 1000 + rate: 500 + apis: + - name: "POST:/v1/naming/services" + rule: store-write + - name: "PUT:/v1/naming/services" + rule: store-write + - name: "POST:/v1/naming/services/delete" + rule: store-write + - name: "GET:/v1/naming/services" + rule: store-read + - name: "GET:/v1/naming/services/count" + rule: store-read diff --git a/service/test.yaml b/testdata/service_test.yaml similarity index 100% rename from service/test.yaml rename to testdata/service_test.yaml diff --git a/service/test_sqldb.yaml b/testdata/service_test_sqldb.yaml similarity index 94% rename from service/test_sqldb.yaml rename to testdata/service_test_sqldb.yaml index 803ec4730..438825804 100644 --- a/service/test_sqldb.yaml +++ b/testdata/service_test_sqldb.yaml @@ -98,13 +98,13 @@ naming: queueSize: 10240 waitTime: 32ms maxBatchCount: 32 - concurrency: 64 + concurrency: 8 deregister: open: true queueSize: 10240 waitTime: 32ms maxBatchCount: 32 - concurrency: 64 + concurrency: 8 # 配置中心模块启动配置 config: # 是否启动配置模块 @@ -125,7 +125,7 @@ healthcheck: queueSize: 10240 waitTime: 32ms maxBatchCount: 32 - concurrency: 64 + concurrency: 16 checkers: # - name: heartbeatMemory - name: heartbeatRedis @@ -133,12 +133,12 @@ healthcheck: kvAddr: 127.0.0.1:6379 ##REDIS_ADDR## kvUser: ##REDIS_USER# kvPasswd: ##REDIS_PWD## - poolSize: 200 + poolSize: 8 minIdleConns: 30 idleTimeout: 120s connectTimeout: 200ms msgTimeout: 200ms - concurrency: 200 + concurrency: 10 withTLS: false # 缓存配置 cache: diff --git a/testdata/testdata.go b/testdata/testdata.go new file mode 100644 index 000000000..b76c8c87d --- /dev/null +++ b/testdata/testdata.go @@ -0,0 +1,38 @@ +/** + * Tencent is pleased to support the open source community by making Polaris available. + * + * Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved. + * + * Licensed under the BSD 3-Clause License (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://opensource.org/licenses/BSD-3-Clause + * + * 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 testdata + +import ( + "path/filepath" + "runtime" +) + +var basepath string + +func init() { + _, currentFile, _, _ := runtime.Caller(0) + basepath = filepath.Dir(currentFile) +} + +// Path gets the absolute path. +func Path(rel string) string { + if filepath.IsAbs(rel) { + return rel + } + return filepath.Join(basepath, rel) +}