diff --git a/.github/workflows/codeql.yml b/.github/workflows/codeql.yml new file mode 100644 index 0000000..376ed21 --- /dev/null +++ b/.github/workflows/codeql.yml @@ -0,0 +1,77 @@ +# For most projects, this workflow file will not need changing; you simply need +# to commit it to your repository. +# +# You may wish to alter this file to override the set of languages analyzed, +# or to provide custom queries or build logic. +# +# ******** NOTE ******** +# We have attempted to detect the languages in your repository. Please check +# the `language` matrix defined below to confirm you have the correct set of +# supported CodeQL languages. +# +name: "CodeQL" + +on: + push: + branches: [ "main" ] + pull_request: + # The branches below must be a subset of the branches above + branches: [ "main" ] + schedule: + - cron: '45 5 * * 0' + +jobs: + analyze: + name: Analyze + runs-on: ${{ (matrix.language == 'swift' && 'macos-latest') || 'ubuntu-latest' }} + timeout-minutes: ${{ (matrix.language == 'swift' && 120) || 360 }} + permissions: + actions: read + contents: read + security-events: write + + strategy: + fail-fast: false + matrix: + language: [ 'go' ] + # CodeQL supports [ 'cpp', 'csharp', 'go', 'java', 'javascript', 'python', 'ruby', 'swift' ] + # Use only 'java' to analyze code written in Java, Kotlin or both + # Use only 'javascript' to analyze code written in JavaScript, TypeScript or both + # Learn more about CodeQL language support at https://aka.ms/codeql-docs/language-support + + steps: + - name: Checkout repository + uses: actions/checkout@v3 + + # Initializes the CodeQL tools for scanning. + - name: Initialize CodeQL + uses: github/codeql-action/init@v2 + with: + languages: ${{ matrix.language }} + # If you wish to specify custom queries, you can do so here or in a config file. + # By default, queries listed here will override any specified in a config file. + # Prefix the list here with "+" to use these queries and those in the config file. + + # For more details on CodeQL's query packs, refer to: https://docs.github.com/en/code-security/code-scanning/automatically-scanning-your-code-for-vulnerabilities-and-errors/configuring-code-scanning#using-queries-in-ql-packs + # queries: security-extended,security-and-quality + + + # Autobuild attempts to build any compiled languages (C/C++, C#, Go, Java, or Swift). + # If this step fails, then you should remove it and run the build manually (see below) + - name: Autobuild + uses: github/codeql-action/autobuild@v2 + + # ℹ️ Command-line programs to run using the OS shell. + # 📚 See https://docs.github.com/en/actions/using-workflows/workflow-syntax-for-github-actions#jobsjob_idstepsrun + + # If the Autobuild fails above, remove it and uncomment the following three lines. + # modify them (or add more) to build your code if your project, please refer to the EXAMPLE below for guidance. + + # - run: | + # echo "Run, Build Application using script" + # ./location_of_script_within_repo/buildscript.sh + + - name: Perform CodeQL Analysis + uses: github/codeql-action/analyze@v2 + with: + category: "/language:${{matrix.language}}" diff --git a/.github/workflows/golang-ci.yml b/.github/workflows/golang-ci.yml new file mode 100644 index 0000000..394cb4d --- /dev/null +++ b/.github/workflows/golang-ci.yml @@ -0,0 +1,43 @@ +# 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. + +name: golangci-lint +on: + push: + branches: + - main + - release* + pull_request: + branches: + - main + - release* + - feature/** + +jobs: + golangci: + strategy: + matrix: + go-version: [ "1.21.5" ] + name: golangci-lint + runs-on: ubuntu-latest + steps: + - uses: actions/setup-go@v3 + - uses: actions/checkout@v3 + - name: golangci-lint + uses: golangci/golangci-lint-action@v3.6.0 + with: + # Required: the version of golangci-lint is required and must be specified without patch version: we always use the latest patch version. + version: latest + args: --timeout=30m diff --git a/.github/workflows/license.yml b/.github/workflows/license.yml new file mode 100644 index 0000000..32c49fd --- /dev/null +++ b/.github/workflows/license.yml @@ -0,0 +1,40 @@ +# 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. + +name: License checker + +on: + push: + branches: + - main + - release* + pull_request: + branches: + - main + - release* + +jobs: + check-license: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v2 + + - name: Check License Header + uses: apache/skywalking-eyes@main + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + with: + log: info + config: .licenserc.yaml diff --git a/.golangci.yml b/.golangci.yml new file mode 100644 index 0000000..e7a2858 --- /dev/null +++ b/.golangci.yml @@ -0,0 +1,421 @@ +# 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. + +## This file contains all available configuration options +## with their default values. + +# See https://github.com/golangci/golangci-lint#config-file +# See https://golangci-lint.run/usage/configuration/ + +# Options for analysis running. +run: + # Exit code when at least one issue was found. + # Default: 1 + issues-exit-code: 2 + + # Include test files or not. + # Default: true + tests: false + + # Which dirs to skip: issues from them won't be reported. + # Can use regexp here: `generated.*`, regexp is applied on full path. + # Default value is empty list, + # but default dirs are skipped independently of this option's value (see skip-dirs-use-default). + # "/" will be replaced by current OS file path separator to properly work on Windows. + skip-dirs: + - pkg/model/pb + - .*~ + - test + + # Which files to skip: they will be analyzed, but issues from them won't be reported. + # Default value is empty list, + # but there is no need to include all autogenerated files, + # we confidently recognize autogenerated files. + # If it's not please let us know. + # "/" will be replaced by current OS file path separator to properly work on Windows. + skip-files: + - ".*\\.my\\.go$" + - ".*\\.pb\\.go$" + - ".*_test\\.go$" + - ".*\\.yaml$" + - ".*\\.yml$" + +# Main linters configurations. +# See https://golangci-lint.run/usage/linters +linters: + # Disable all default enabled linters. + disable-all: true + # Custom enable linters we want to use. + enable: + - errcheck # Errcheck is a program for checking for unchecked errors in go programs. + - errchkjson # Checks types passed to the json encoding functions. Reports unsupported types and optionally reports occasions, where the check for the returned error can be omitted. + - funlen # Tool for detection of long functions + - gci # Gci controls golang package import order and makes it always deterministic. + - goconst # Finds repeated strings that could be replaced by a constant + - gocritic # Provides diagnostics that check for bugs, performance and style issues. + - gofmt # Gofmt checks whether code was gofmt-ed. By default this tool runs with -s option to check for code simplification + - gosimple # Linter for Go source code that specializes in simplifying code + - govet # Vet examines Go source code and reports suspicious constructs, such as Printf calls whose arguments do not align with the format string + - misspell # Finds commonly misspelled English words in comments + - nolintlint # Reports ill-formed or insufficient nolint directives + - revive # Fast, configurable, extensible, flexible, and beautiful linter for Go. Drop-in replacement of golint. + - staticcheck # It's a set of rules from staticcheck. It's not the same thing as the staticcheck binary. + - typecheck # Like the front-end of a Go compiler, parses and type-checks Go code + - usestdlibvars # A linter that detect the possibility to use variables/constants from the Go standard library. + - lll + #- whitespace # Tool for detection of leading and trailing whitespace + +issues: + max-issues-per-linter: 0 + max-same-issues: 0 + exclude-rules: + # helpers in tests often (rightfully) pass a *testing.T as their first argument + - path: _test\.go + text: "context.Context should be the first parameter of a function" + linters: + - revive + # Yes, they are, but it's okay in a test + - path: _test\.go + text: "exported func.*returns unexported type.*which can be annoying to use" + linters: + - revive + # https://github.com/go-critic/go-critic/issues/926 + - linters: + - gocritic + text: "unnecessaryDefer:" + +# https://golangci-lint.run/usage/linters +linters-settings: + # https://golangci-lint.run/usage/linters/#misspell + misspell: + locale: US + ignore-words: + - cancelled + + # https://golangci-lint.run/usage/linters/#revive + revive: + ignore-generated-header: true + severity: error + rules: + - name: atomic + - name: line-length-limit + severity: error + arguments: [480] + - name: unhandled-error + severity: warning + disabled: true + arguments: ["fmt.Printf", "myFunction"] + - name: var-naming + severity: warning + disabled: true + arguments: + - [ + "ID", + "URL", + "IP", + "HTTP", + "JSON", + "API", + "UID", + "Id", + "Api", + "Uid", + "Http", + "Json", + "Ip", + "Url", + ] # AllowList + - ["VM"] # DenyList + - name: string-format + severity: warning + disabled: false + arguments: + - - "core.WriteError[1].Message" + - "/^([^A-Z]|$)/" + - must not start with a capital letter + - - "fmt.Errorf[0]" + - '/(^|[^\.!?])$/' + - must not end in punctuation + - - panic + - '/^[^\n]*$/' + - must not contain line breaks + - name: function-result-limit + severity: warning + disabled: false + arguments: [5] + - name: import-shadowing + severity: warning + disabled: false + arguments: ["github.com/polarismesh/polaris-plugin-api", "namespace"] + - name: waitgroup-by-value + severity: warning + disabled: false + - name: max-public-structs + severity: warning + disabled: false + arguments: [35] + - name: indent-error-flow + severity: warning + disabled: false + - name: function-length + severity: warning + disabled: false + arguments: [80, 0] + - name: file-header + arguments: + [ + "Tencent is pleased to support the open source community by making Polaris available.", + ] + - name: exported + severity: warning + disabled: true + - name: errorf + severity: warning + disabled: false + - name: error-naming + severity: warning + disabled: false + + # https://golangci-lint.run/usage/linters/#funlen + funlen: + # Checks the number of lines in a function. + # If lower than 0, disable the check. + # Default: 60 + lines: 230 + # Checks the number of statements in a function. + # If lower than 0, disable the check. + # Default: 40 + statements: -1 + + # https://golangci-lint.run/usage/linters/#lll + lll: + # Max line length, lines longer will be reported. + # '\t' is counted as 1 character by default, and can be changed with the tab-width option. + # Default: 120. + line-length: 140 + # Tab width in spaces. + # Default: 1 + tab-width: 1 + + # https://golangci-lint.run/usage/linters/#goconst + goconst: + # Minimal length of string constant. + # Default: 3 + min-len: 2 + # Minimum occurrences of constant string count to trigger issue. + # Default: 3 + # For subsequent optimization, the value is reduced. + min-occurrences: 60 + # Ignore test files. + # Default: false + ignore-tests: true + # Look for existing constants matching the values. + # Default: true + match-constant: false + # Search also for duplicated numbers. + # Default: false + numbers: true + # Minimum value, only works with goconst.numbers + # Default: 3 + min: 5 + # Maximum value, only works with goconst.numbers + # Default: 3 + max: 20 + # Ignore when constant is not used as function argument. + # Default: true + ignore-calls: false + + # https://golangci-lint.run/usage/linters/#gocritic + gocritic: + disabled-checks: + - ifElseChain + - assignOp + - appendAssign + - singleCaseSwitch + - regexpMust + - typeSwitchVar + - elseif + - badCall + + # https://golangci-lint.run/usage/linters/#gosimple + gosimple: + # Select the Go version to target. + # Default: 1.13 + # Deprecated: use the global `run.go` instead. + go: "1.15" + # Sxxxx checks in https://staticcheck.io/docs/configuration/options/#checks + # Default: ["*"] + checks: + [ + "all", + "-S1000", + "-S1001", + "-S1002", + "-S1008", + "-S1009", + "-S1016", + "-S1023", + "-S1025", + "-S1029", + "-S1034", + "-S1040", + "-S1019", + ] + + # https://golangci-lint.run/usage/linters/#govet + govet: + # Report about shadowed variables. + # Default: false + check-shadowing: true + # Settings per analyzer. + settings: + # Analyzer name, run `go tool vet help` to see all analyzers. + printf: + # Comma-separated list of print function names to check (in addition to default, see `go tool vet help printf`). + # Default: [] + funcs: + - (github.com/golangci/golangci-lint/pkg/logutils.Log).Infof + - (github.com/golangci/golangci-lint/pkg/logutils.Log).Warnf + - (github.com/golangci/golangci-lint/pkg/logutils.Log).Errorf + - (github.com/golangci/golangci-lint/pkg/logutils.Log).Fatalf + # shadow: + # Whether to be strict about shadowing; can be noisy. + # Default: false + # strict: false + unusedresult: + # Comma-separated list of functions whose results must be used + # (in addition to defaults context.WithCancel,context.WithDeadline,context.WithTimeout,context.WithValue, + # errors.New,fmt.Errorf,fmt.Sprint,fmt.Sprintf,sort.Reverse) + # Default [] + funcs: + - pkg.MyFunc + - context.WithCancel + - context.WithDeadline + - context.WithTimeout + - context.WithValue + - sort.Reverse + # Comma-separated list of names of methods of type func() string whose results must be used + # (in addition to default Error,String) + # Default [] + stringmethods: + - MyMethod + # Enable all analyzers. + # Default: false + enable-all: true + # Disable analyzers by name. + # Run `go tool vet help` to see all analyzers. + # Default: [] + disable: + - asmdecl + - assign + - atomic + - atomicalign + - bools + - buildtag + - cgocall + - composites + - copylocks + - deepequalerrors + - errorsas + - fieldalignment + - findcall + - framepointer + - httpresponse + - ifaceassert + - loopclosure + - lostcancel + - nilfunc + - nilness + - reflectvaluecompare + - shift + - shadow + - sigchanyzer + - sortslice + - stdmethods + - stringintconv + - structtag + - testinggoroutine + - tests + - unmarshal + - unreachable + - unsafeptr + - unusedwrite + + # https://golangci-lint.run/usage/linters/#staticcheck + staticcheck: + # Select the Go version to target. + # Default: "1.13" + # Deprecated: use the global `run.go` instead. + go: "1.15" + # SAxxxx checks in https://staticcheck.io/docs/configuration/options/#checks + # Default: ["*"] + checks: + [ + "all", + "-SA1019", + "-SA4015", + "-SA1029", + "-SA1016", + "-SA9003", + "-SA4006", + "-SA6003", + "-SA1004", + "-SA4009", + "-SA6002", + "-SA4017", + "-SA4021", + "-SA1006", + "-SA4010", + ] + + # https://golangci-lint.run/usage/linters/#gofmt + gofmt: + # Simplify code: gofmt with `-s` option. + # Default: true + simplify: true + # Apply the rewrite rules to the source before reformatting. + # https://pkg.go.dev/cmd/gofmt + # Default: [] + rewrite-rules: [] + + # https://golangci-lint.run/usage/linters/#gci + gci: + # Section configuration to compare against. + # Section names are case-insensitive and may contain parameters in (). + # The default order of sections is `standard > default > custom > blank > dot`, + # If `custom-order` is `true`, it follows the order of `sections` option. + # Default: ["standard", "default"] + sections: + - standard # Standard section: captures all standard packages. + - default # Default section: contains all imports that could not be matched to another section type. + - prefix(github.com/polarismesh/polaris-plugin-api) # Custom section: groups all imports with the specified Prefix. + #- blank # Blank section: contains all blank imports. This section is not present unless explicitly enabled. + #- dot # Dot section: contains all dot imports. This section is not present unless explicitly enabled. + # Skip generated files. + # Default: true + skip-generated: true + # Enable custom order of sections. + # If `true`, make the section order the same as the order of `sections`. + # Default: false + custom-order: true + + # https://golangci-lint.run/usage/linters/#whitespace + whitespace: + # Enforces newlines (or comments) after every multi-line if statement. + # Default: false + multi-if: false + # Enforces newlines (or comments) after every multi-line function signature. + # Default: false + multi-func: false diff --git a/.licenserc.yaml b/.licenserc.yaml new file mode 100644 index 0000000..39729ba --- /dev/null +++ b/.licenserc.yaml @@ -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. + +header: # `header` section is configurations for source codes license header. + license: + spdx-id: BSD-3-Clause # the spdx id of the license, it's convenient when your license is standard SPDX license. + copyright-owner: Tencent # the copyright owner to replace the [owner] in the `spdx-id` template. + content: + | # `license` will be used as the content when `fix` command needs to insert a license header. + 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. + # `pattern` is optional regexp if all the file headers are the same as `license` or the license of `spdx-id` and `copyright-owner`. + pattern: | + 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. + paths: # `paths` are the path list that will be checked (and fixed) by license-eye, default is ['**']. + - "**" + + paths-ignore: # `paths-ignore` are the path list that will be ignored by license-eye. + # folder + - "common/api/protoc" + - "deploy" + - "release" + - "test/data/xds" + - "apiserver/nacosserver/v2/pb" + - "apiserver/xdsserverv3/cache" + + # single file + - "LICENSE" + - ".gitignore" + - "Makefile" + - "Dockerfile" + - "version" + - ".golangci.yml" + - ".github" + - "logo.svg" + - "**/*.pb.go" + - "**/*_mock.go" + - "**/*.proto" + - "**/*.md" + - "**/go.mod" + - "**/go.sum" + - "apiserver/xdsserverv3/cache/linear.go" + comment: on-failure # on what condition license-eye will comment on the pull request, `on-failure`, `always`, `never`. + + # license-location-threshold specifies the index threshold where the license header can be located, + # after all, a "header" cannot be TOO far from the file start. + license-location-threshold: 80 + language: + Go: + extensions: + - ".go" + comment_style_id: SlashAsterisk + +dependency: + files: + - go.mod diff --git a/README.md b/README.md index a90d277..027897d 100644 --- a/README.md +++ b/README.md @@ -1,2 +1 @@ # polaris-plugin-api -# polaris-plugin-api diff --git a/access_control/auth/api.go b/access_control/auth/api.go new file mode 100644 index 0000000..59ccc2d --- /dev/null +++ b/access_control/auth/api.go @@ -0,0 +1,217 @@ +/** + * 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" + "errors" + "fmt" + "sync" + + apisecurity "github.com/polarismesh/specification/source/go/api/v1/security" + apiservice "github.com/polarismesh/specification/source/go/api/v1/service_manage" +) + +// AuthChecker 权限管理通用接口定义 +type AuthChecker interface { + // Initialize 执行初始化动作 + Initialize(options *Config) error + // VerifyCredential 验证令牌 + VerifyCredential(preCtx *AcquireContext) error + // CheckClientPermission 执行检查客户端动作判断是否有权限,并且对 RequestContext 注入操作者数据 + CheckClientPermission(preCtx *AcquireContext) (bool, error) + // CheckConsolePermission 执行检查控制台动作判断是否有权限,并且对 RequestContext 注入操作者数据 + CheckConsolePermission(preCtx *AcquireContext) (bool, error) + // IsOpenConsoleAuth 返回是否开启了操作鉴权,可以用于前端查询 + IsOpenConsoleAuth() bool + // IsOpenClientAuth + IsOpenClientAuth() bool +} + +// UserServer 用户数据管理 server +type UserServer interface { + // Initialize 初始化 + Initialize(authOpt *Config) error + // Name 用户数据管理server名称 + Name() string + // CreateUsers 批量创建用户 + CreateUsers(ctx context.Context, users []*apisecurity.User) *apiservice.BatchWriteResponse + // UpdateUser 更新用户信息 + UpdateUser(ctx context.Context, user *apisecurity.User) *apiservice.Response + // UpdateUserPassword 更新用户密码 + UpdateUserPassword(ctx context.Context, req *apisecurity.ModifyUserPassword) *apiservice.Response + // DeleteUsers 批量删除用户 + DeleteUsers(ctx context.Context, users []*apisecurity.User) *apiservice.BatchWriteResponse + // GetUsers 查询用户列表 + GetUsers(ctx context.Context, query map[string]string) *apiservice.BatchQueryResponse + // GetUserToken 获取用户的 token + GetUserToken(ctx context.Context, user *apisecurity.User) *apiservice.Response + // UpdateUserToken 禁止用户的token使用 + UpdateUserToken(ctx context.Context, user *apisecurity.User) *apiservice.Response + // ResetUserToken 重置用户的token + ResetUserToken(ctx context.Context, user *apisecurity.User) *apiservice.Response + // Login 登录动作 + Login(req *apisecurity.LoginRequest) *apiservice.Response + GroupOperator +} + +// GroupOperator 用户组相关操作 +type GroupOperator interface { + // CreateGroup 创建用户组 + CreateGroup(ctx context.Context, group *apisecurity.UserGroup) *apiservice.Response + // UpdateGroups 更新用户组 + UpdateGroups(ctx context.Context, groups []*apisecurity.ModifyUserGroup) *apiservice.BatchWriteResponse + // DeleteGroups 批量删除用户组 + DeleteGroups(ctx context.Context, group []*apisecurity.UserGroup) *apiservice.BatchWriteResponse + // GetGroups 查询用户组列表(不带用户详细信息) + GetGroups(ctx context.Context, query map[string]string) *apiservice.BatchQueryResponse + // GetGroup 根据用户组信息,查询该用户组下的用户相信 + GetGroup(ctx context.Context, req *apisecurity.UserGroup) *apiservice.Response + // GetGroupToken 获取用户组的 token + GetGroupToken(ctx context.Context, group *apisecurity.UserGroup) *apiservice.Response + // UpdateGroupToken 取消用户组的 token 使用 + UpdateGroupToken(ctx context.Context, group *apisecurity.UserGroup) *apiservice.Response + // ResetGroupToken 重置用户组的 token + ResetGroupToken(ctx context.Context, group *apisecurity.UserGroup) *apiservice.Response +} + +// StrategyServer 策略相关操作 +type StrategyServer interface { + // Initialize 初始化 + Initialize(authOpt *Config) error + // Name 策略管理server名称 + Name() string + // CreateStrategy 创建策略 + CreateStrategy(ctx context.Context, strategy *apisecurity.AuthStrategy) *apiservice.Response + // UpdateStrategies 批量更新策略 + UpdateStrategies(ctx context.Context, reqs []*apisecurity.ModifyAuthStrategy) *apiservice.BatchWriteResponse + // DeleteStrategies 删除策略 + DeleteStrategies(ctx context.Context, reqs []*apisecurity.AuthStrategy) *apiservice.BatchWriteResponse + // GetStrategies 获取资源列表 + // support 1. 支持按照 principal-id + principal-role 进行查询 + // support 2. 支持普通的鉴权策略查询 + GetStrategies(ctx context.Context, query map[string]string) *apiservice.BatchQueryResponse + // GetStrategy 获取策略详细 + GetStrategy(ctx context.Context, strategy *apisecurity.AuthStrategy) *apiservice.Response + // GetPrincipalResources 获取某个 principal 的所有可操作资源列表 + GetPrincipalResources(ctx context.Context, query map[string]string) *apiservice.Response + // GetAuthChecker 获取鉴权检查器 + GetAuthChecker() AuthChecker + // AfterResourceOperation 操作完资源的后置处理逻辑 + AfterResourceOperation(afterCtx *AcquireContext) error +} + +const ( + // DefaultUserMgnPluginName default user server name + DefaultUserMgnPluginName = "defaultUser" + // DefaultStrategyMgnPluginName default strategy server name + DefaultStrategyMgnPluginName = "defaultStrategy" +) + +// Config 鉴权能力的相关配置参数 +type Config struct { + // Name 原AuthServer名称,已废弃 + Name string + // Option 原AuthServer的option,已废弃 + // Deprecated + Option map[string]interface{} + // User UserOperator的相关配置 + User *UserConfig `yaml:"user"` + // Strategy StrategyOperator的相关配置 + Strategy *StrategyConfig `yaml:"strategy"` +} + +func (c *Config) SetDefault() { + if c.User == nil { + c.User = &UserConfig{ + Name: DefaultUserMgnPluginName, + Option: map[string]interface{}{}, + } + } + if c.Strategy == nil { + c.Strategy = &StrategyConfig{ + Name: DefaultStrategyMgnPluginName, + Option: map[string]interface{}{}, + } + } +} + +// UserConfig UserOperator的相关配置 +type UserConfig struct { + // Name UserOperator的名称 + Name string `yaml:"name"` + // Option UserOperator的option + Option map[string]interface{} `yaml:"option"` +} + +// StrategyConfig StrategyOperator的相关配置 +type StrategyConfig struct { + // Name StrategyOperator的名称 + Name string `yaml:"name"` + // Option StrategyOperator的option + Option map[string]interface{} `yaml:"option"` +} + +var ( + // userMgnSlots 保存用户管理manager slot + userMgnSlots = map[string]UserServer{} + // strategyMgnSlots 保存策略管理manager slot + strategyMgnSlots = map[string]StrategyServer{} + once sync.Once + userMgn UserServer + strategyMgn StrategyServer + finishInit bool +) + +// RegisterUserServer 注册一个新的 UserServer +func RegisterUserServer(s UserServer) error { + name := s.Name() + if _, ok := userMgnSlots[name]; ok { + return fmt.Errorf("UserServer=[%s] exist", name) + } + + userMgnSlots[name] = s + return nil +} + +// GetUserServer 获取一个 UserServer +func GetUserServer() (UserServer, error) { + if !finishInit { + return nil, errors.New("UserServer has not done Initialize") + } + return userMgn, nil +} + +// RegisterStrategyServer 注册一个新的 StrategyServer +func RegisterStrategyServer(s StrategyServer) error { + name := s.Name() + if _, ok := strategyMgnSlots[name]; ok { + return fmt.Errorf("StrategyServer=[%s] exist", name) + } + + strategyMgnSlots[name] = s + return nil +} + +// GetStrategyServer 获取一个 StrategyServer +func GetStrategyServer() (StrategyServer, error) { + if !finishInit { + return nil, errors.New("StrategyServer has not done Initialize") + } + return strategyMgn, nil +} diff --git a/access_control/auth/context.go b/access_control/auth/context.go new file mode 100644 index 0000000..feef89c --- /dev/null +++ b/access_control/auth/context.go @@ -0,0 +1,285 @@ +/** + * 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" + + apisecurity "github.com/polarismesh/specification/source/go/api/v1/security" +) + +// ResourceEntry 资源最简单信息 +type ResourceEntry struct { + ResourceID string + Operator string +} + +// ResourceOperation 资源操作 +type ResourceOperation int16 + +const ( + // Read 只读动作 + Read ResourceOperation = 10 + // Create 创建动作 + Create ResourceOperation = 20 + // Modify 修改动作 + Modify ResourceOperation = 30 + // Delete 删除动作 + Delete ResourceOperation = 40 +) + +// BzModule 模块标识 +type BzModule int16 + +const ( + // UnknowModule 未知模块 + UnknowModule BzModule = iota + // CoreModule 核心模块 + CoreModule + // DiscoverModule 服务模块 + DiscoverModule + // ConfigModule 配置模块 + ConfigModule + // AuthModule 鉴权模块 + AuthModule + // MaintainModule 运维操作模块 + MaintainModule + // BootstrapModule 初始化模块 + BootstrapModule +) + +// AcquireContext 每次鉴权请求上下文信息 +type AcquireContext struct { + // RequestContext 请求上下文 + requestContext context.Context + // Module 来自那个业务层(服务注册与服务治理、配置模块) + module BzModule + // Method 操作函数 + method string + // Operation 本次操作涉及的动作 + operation ResourceOperation + // Resources 本次 + accessResources map[apisecurity.ResourceType][]ResourceEntry + // Attachment 携带信息,用于操作完权限检查和资源操作的后置处理逻辑,解决信息需要二次查询问题 + attachment map[string]interface{} + // fromClient 是否来自客户端的请求 + fromClient bool +} + +type acquireContextOption func(authCtx *AcquireContext) + +var ( + _defaultAuthContextOptions []acquireContextOption = []acquireContextOption{ + WithFromConsole(), + } +) + +// NewAcquireContext 创建一个请求响应 +// +// @param options +// @return *AcquireContext +func NewAcquireContext(options ...acquireContextOption) *AcquireContext { + authCtx := &AcquireContext{ + attachment: make(map[string]interface{}), + accessResources: make(map[apisecurity.ResourceType][]ResourceEntry), + module: UnknowModule, + } + + for index := range _defaultAuthContextOptions { + opt := _defaultAuthContextOptions[index] + opt(authCtx) + } + + for index := range options { + opt := options[index] + opt(authCtx) + } + + return authCtx +} + +// WithRequestContext 设置请求上下文 +// +// @param ctx +// @return acquireContextOption +func WithRequestContext(ctx context.Context) acquireContextOption { + return func(authCtx *AcquireContext) { + authCtx.requestContext = ctx + } +} + +// WithModule 设置本次请求的模块 +// +// @param module +// @return acquireContextOption +func WithModule(module BzModule) acquireContextOption { + return func(authCtx *AcquireContext) { + authCtx.module = module + } +} + +// WithMethod 本次操作函数名称 +func WithMethod(method string) acquireContextOption { + return func(authCtx *AcquireContext) { + authCtx.method = method + } +} + +// WithOperation 设置本次的操作类型 +// +// @param operation +// @return acquireContextOption +func WithOperation(operation ResourceOperation) acquireContextOption { + return func(authCtx *AcquireContext) { + authCtx.operation = operation + } +} + +// WithAccessResources 设置本次访问的资源 +// +// @param accessResources +// @return acquireContextOption +func WithAccessResources(accessResources map[apisecurity.ResourceType][]ResourceEntry) acquireContextOption { + return func(authCtx *AcquireContext) { + authCtx.accessResources = accessResources + } +} + +// WithAttachment 设置本次请求的额外携带信息 +// +// @param attachment +// @return acquireContextOption +func WithAttachment(attachment map[string]interface{}) acquireContextOption { + return func(authCtx *AcquireContext) { + for k, v := range attachment { + authCtx.attachment[k] = v + } + } +} + +// WithFromConsole 设置本次请求来自控制台 +func WithFromConsole() acquireContextOption { + return func(authCtx *AcquireContext) { + authCtx.fromClient = false + } +} + +// WithFromClient 设置本次请求来自客户端 +func WithFromClient() acquireContextOption { + return func(authCtx *AcquireContext) { + authCtx.fromClient = true + } +} + +// GetRequestContext 获取 context.Context +// +// @receiver authCtx +// @return context.Context +func (authCtx *AcquireContext) GetRequestContext() context.Context { + return authCtx.requestContext +} + +// SetRequestContext 重新设置 context.Context +// +// @receiver authCtx +// @param requestContext +func (authCtx *AcquireContext) SetRequestContext(requestContext context.Context) { + authCtx.requestContext = requestContext +} + +// GetModule 获取请求的模块 +// +// @receiver authCtx +// @return BzModule +func (authCtx *AcquireContext) GetModule() BzModule { + return authCtx.module +} + +// GetOperation 获取本次操作的类型 +// +// @receiver authCtx +// @return ResourceOperation +func (authCtx *AcquireContext) GetOperation() ResourceOperation { + return authCtx.operation +} + +// GetAccessResources 获取本次请求的资源 +// +// @receiver authCtx +// @return map +func (authCtx *AcquireContext) GetAccessResources() map[apisecurity.ResourceType][]ResourceEntry { + return authCtx.accessResources +} + +// SetAccessResources 设置本次请求的资源 +// +// @receiver authCtx +// @param accessRes +func (authCtx *AcquireContext) SetAccessResources(accessRes map[apisecurity.ResourceType][]ResourceEntry) { + authCtx.accessResources = accessRes +} + +// GetAttachments 获取本次请求的额外携带信息 +func (authCtx *AcquireContext) GetAttachments() map[string]interface{} { + return authCtx.attachment +} + +// GetAttachment 按照 key 获取某一个附件信息 +func (authCtx *AcquireContext) GetAttachment(key string) (interface{}, bool) { + val, ok := authCtx.attachment[key] + return val, ok +} + +// SetAttachment 设置附件 +func (authCtx *AcquireContext) SetAttachment(key string, val interface{}) { + authCtx.attachment[key] = val +} + +// GetMethod 获取本次请求涉及的操作函数 +func (authCtx *AcquireContext) GetMethod() string { + return authCtx.method +} + +// SetFromClient 本次请求来自客户端 +func (authCtx *AcquireContext) SetFromClient() { + authCtx.fromClient = true +} + +// SetFromConsole 本次请求来自OpenAPI +func (authCtx *AcquireContext) SetFromConsole() { + authCtx.fromClient = false +} + +// IsFromClient 本次请求是否来自客户端 +func (authCtx *AcquireContext) IsFromClient() bool { + return authCtx.fromClient +} + +// IsFromConsole 本次请求是否来自OpenAPI +func (authCtx *AcquireContext) IsFromConsole() bool { + return !authCtx.IsFromClient() +} + +// IsAccessResourceEmpty 判断当前待访问的资源,是否为空 +func (authCtx *AcquireContext) IsAccessResourceEmpty() bool { + nsEmpty := len(authCtx.accessResources[apisecurity.ResourceType_Namespaces]) == 0 + svcEmpty := len(authCtx.accessResources[apisecurity.ResourceType_Services]) == 0 + cfgEmpty := len(authCtx.accessResources[apisecurity.ResourceType_ConfigGroups]) == 0 + + return nsEmpty && svcEmpty && cfgEmpty +} diff --git a/access_control/ratelimit/api.go b/access_control/ratelimit/api.go new file mode 100644 index 0000000..680dffd --- /dev/null +++ b/access_control/ratelimit/api.go @@ -0,0 +1,64 @@ +/** + * 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 ratelimit + +// RatelimitType rate limit type +type RatelimitType int + +const ( + // IPRatelimit Based on IP flow control + IPRatelimit RatelimitType = iota + 1 + + // APIRatelimit Based on interface-level flow control + APIRatelimit + + // ServiceRatelimit Based on Service flow control + ServiceRatelimit + + // InstanceRatelimit Based on Instance flow control + InstanceRatelimit +) + +// RatelimitStr rate limit string map +var RatelimitStr = map[RatelimitType]string{ + IPRatelimit: "ip-limit", + APIRatelimit: "api-limit", + ServiceRatelimit: "service-limit", + InstanceRatelimit: "instance-limit", +} + +// ConfigEntry 单个插件配置 +type ConfigEntry struct { + Name string `yaml:"name"` + Option map[string]interface{} `yaml:"option"` +} + +// Ratelimit Ratelimit plugin interface +type Ratelimit interface { + // Name . + Name() string + // Initialize . + Initialize(c *ConfigEntry) error + // Destroy . + Destroy() error + // Allow Whether to allow access, true: allow, FALSE: not allowing Todo + // - Parameter ratingype is the type of current limits, and the ID is the key that limits the current + // - If RateType is Ratelimitip, the ID is IP, RateType is Ratelimitservice, and the ID is + // IP_NAMESPACE_SERVICE or IP_SERVICEID + Allow(typ RatelimitType, resource string) bool +} diff --git a/access_control/whitelist/api.go b/access_control/whitelist/api.go new file mode 100644 index 0000000..72ea649 --- /dev/null +++ b/access_control/whitelist/api.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 whitelist + +// ConfigEntry 单个插件配置 +type ConfigEntry struct { + Name string `yaml:"name"` + Option map[string]interface{} `yaml:"option"` +} + +// Whitelist White list interface +type Whitelist interface { + // Name . + Name() string + // Initialize . + Initialize(c *ConfigEntry) error + // Destroy . + Destroy() error + // Contain . + Contain(entry string) bool +} diff --git a/apiserver/api.go b/apiserver/api.go new file mode 100644 index 0000000..9d29bbe --- /dev/null +++ b/apiserver/api.go @@ -0,0 +1,67 @@ +/** + * 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 apiserver + +import ( + "context" + "fmt" +) + +// Config API服务器配置 +type Config struct { + Name string + Option map[string]interface{} + API map[string]APIConfig +} + +// APIConfig API配置 +type APIConfig struct { + Enable bool + Include []string +} + +// Apiserver API服务器接口 +type Apiserver interface { + // GetProtocol API协议名 + GetProtocol() string + // GetPort API的监听端口 + GetPort() uint32 + // Initialize API初始化逻辑 + Initialize(ctx context.Context, option map[string]interface{}, api map[string]APIConfig) error + // Run API服务的主逻辑循环 + Run(errCh chan error) + // Stop 停止API端口监听 + Stop() + // Restart 重启API + Restart(option map[string]interface{}, api map[string]APIConfig, errCh chan error) error +} + +var ( + Slots = make(map[string]Apiserver) +) + +// Register 注册API服务器 +func Register(name string, server Apiserver) error { + if _, exist := Slots[name]; exist { + return fmt.Errorf("apiserver name:%s exist", name) + } + + Slots[name] = server + + return nil +} diff --git a/cmdb/api.go b/cmdb/api.go new file mode 100644 index 0000000..6aced15 --- /dev/null +++ b/cmdb/api.go @@ -0,0 +1,58 @@ +/** + * 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 plugin + +import ( + apimodel "github.com/polarismesh/specification/source/go/api/v1/model" +) + +// Location cmdb信息,对应内存结构体 +type Location struct { + Proto *apimodel.Location + RegionID uint32 + ZoneID uint32 + CampusID uint32 + Valid bool +} + +// ConfigEntry 单个插件配置 +type ConfigEntry struct { + Name string `yaml:"name"` + Option map[string]interface{} `yaml:"option"` +} + +// CMDB CMDB插件接口 +type CMDB interface { + // Name . + Name() string + // Initialize . + Initialize(c *ConfigEntry) error + // Destroy . + Destroy() error + // GetLocation 在CMDB中没有找到Host,返回error为nil,location为nil + // 插件内部出现错误,返回error不为nil,忽略location + GetLocation(host string) (*Location, error) + // Range 提供一个Range接口,遍历所有的数据 + // 遍历失败,通过Range返回值error可以额捕获 + // 参数为一个回调函数 + // 返回值:bool,是否继续遍历 + // 返回值:error,回调函数处理结果,error不为nil,则停止遍历过程,并且通过Range返回error + Range(handler func(host string, location *Location) (bool, error)) error + // Size 获取当前CMDB存储的entry个数 + Size() int32 +} diff --git a/crypto/api.go b/crypto/api.go new file mode 100644 index 0000000..400d37b --- /dev/null +++ b/crypto/api.go @@ -0,0 +1,52 @@ +/** + * 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 crypto + +// ConfigEntry 单个插件配置 +type ConfigEntry struct { + Name string `yaml:"name"` + Option map[string]interface{} `yaml:"option"` +} + +// Crypto Crypto interface +type Crypto interface { + // Name . + Name() string + // Initialize . + Initialize(c *ConfigEntry) error + // Destroy . + Destroy() error + // GenerateKey . + GenerateKey() ([]byte, error) + // Encrypt . + Encrypt(plaintext string, key []byte) (cryptotext string, err error) + // Decrypt . + Decrypt(cryptotext string, key []byte) (string, error) +} + +// ParsePassword Password plug -in +type ParsePassword interface { + // Name . + Name() string + // Initialize . + Initialize(c *ConfigEntry) error + // Destroy . + Destroy() error + // ParsePassword . + ParsePassword(cipher string) (string, error) +} diff --git a/format.sh b/format.sh new file mode 100644 index 0000000..7afb77f --- /dev/null +++ b/format.sh @@ -0,0 +1,51 @@ +#!/bin/bash +# 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. + +# 格式化 go.mod +go mod tidy -compat=1.17 + +docker run -t --rm -v $(pwd):/app -w /app golangci/golangci-lint:v1.55.2 golangci-lint run -v + +# 处理 go imports 的格式化 +rm -rf style_tool +rm -rf goimports-reviser + +mkdir -p style_tool + +cd style_tool + +is_arm=$(/usr/bin/uname -m | grep -E "arm|aarch64" | wc -l) +goimports_target_file="goimports-reviser_3.3.1_linux_amd64.tar.gz" + +if [ "$(uname)" == "Darwin" ]; then + if [ "${is_arm}" == "1" ]; then + goimports_target_file="goimports-reviser_3.3.1_darwin_arm64.tar.gz" + else + goimports_target_file="goimports-reviser_3.3.1_darwin_amd64.tar.gz" + fi +fi + +wget "https://github.com/incu6us/goimports-reviser/releases/download/v3.3.1/${goimports_target_file}" +tar -zxvf ${goimports_target_file} +mv goimports-reviser ../ + +cd ../ + +# 处理 go 代码格式化 +go fmt ./... + +find . -name "*.go" -type f | grep -v .pb.go | grep -v test/tools/tools.go | grep -v ./plugin.go | + xargs -I {} ./goimports-reviser -rm-unused -format {} -project-name github.com/polarismesh/polaris-plugin-api diff --git a/go.mod b/go.mod new file mode 100644 index 0000000..825fc94 --- /dev/null +++ b/go.mod @@ -0,0 +1,15 @@ +module github.com/polarismesh/polaris-plugin-api + +go 1.21 + +require github.com/polarismesh/specification v1.4.2 + +require ( + github.com/golang/protobuf v1.5.2 // indirect + golang.org/x/net v0.2.0 // indirect + golang.org/x/sys v0.2.0 // indirect + golang.org/x/text v0.4.0 // indirect + google.golang.org/genproto v0.0.0-20200526211855-cb27e3aa2013 // indirect + google.golang.org/grpc v1.51.0 // indirect + google.golang.org/protobuf v1.28.1 // indirect +) diff --git a/go.sum b/go.sum new file mode 100644 index 0000000..8c0767a --- /dev/null +++ b/go.sum @@ -0,0 +1,78 @@ +cloud.google.com/go v0.26.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMTw= +github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU= +github.com/census-instrumentation/opencensus-proto v0.2.1/go.mod h1:f6KPmirojxKA12rnyqOA5BBL4O983OfeGPqjHWSTneU= +github.com/client9/misspell v0.3.4/go.mod h1:qj6jICC3Q7zFZvVWo7KLAzC3yx5G7kyvSDkc90ppPyw= +github.com/envoyproxy/go-control-plane v0.9.1-0.20191026205805-5f8ba28d4473/go.mod h1:YTl/9mNaCwkRvm6d1a2C3ymFceY/DCBVvsKhRF0iEA4= +github.com/envoyproxy/protoc-gen-validate v0.1.0/go.mod h1:iSmxcyjqTsJpI2R4NaDN7+kN2VEUnK/pcBlmesArF7c= +github.com/golang/glog v0.0.0-20160126235308-23def4e6c14b/go.mod h1:SBH7ygxi8pfUlaOkMMuAQtPIUF8ecWP5IEl/CR7VP2Q= +github.com/golang/mock v1.1.1/go.mod h1:oTYuIxOrZwtPieC+H1uAHpcLFnEyAGVDL/k47Jfbm0A= +github.com/golang/protobuf v1.2.0/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= +github.com/golang/protobuf v1.3.2/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= +github.com/golang/protobuf v1.4.0-rc.1/go.mod h1:ceaxUfeHdC40wWswd/P6IGgMaK3YpKi5j83Wpe3EHw8= +github.com/golang/protobuf v1.4.0-rc.1.0.20200221234624-67d41d38c208/go.mod h1:xKAWHe0F5eneWXFV3EuXVDTCmh+JuBKY0li0aMyXATA= +github.com/golang/protobuf v1.4.0-rc.2/go.mod h1:LlEzMj4AhA7rCAGe4KMBDvJI+AwstrUpVNzEA03Pprs= +github.com/golang/protobuf v1.4.0-rc.4.0.20200313231945-b860323f09d0/go.mod h1:WU3c8KckQ9AFe+yFwt9sWVRKCVIyN9cPHBJSNnbL67w= +github.com/golang/protobuf v1.4.0/go.mod h1:jodUvKwWbYaEsadDk5Fwe5c77LiNKVO9IDvqG2KuDX0= +github.com/golang/protobuf v1.4.1/go.mod h1:U8fpvMrcmy5pZrNK1lt4xCsGvpyWQ/VVv6QDs8UjoX8= +github.com/golang/protobuf v1.5.0/go.mod h1:FsONVRAS9T7sI+LIUmWTfcYkHO4aIWwzhcaSAoJOfIk= +github.com/golang/protobuf v1.5.2 h1:ROPKBNFfQgOUMifHyP+KYbvpjbdoFNs+aK7DXlji0Tw= +github.com/golang/protobuf v1.5.2/go.mod h1:XVQd3VNwM+JqD3oG2Ue2ip4fOMUkwXdXDdiuN0vRsmY= +github.com/google/go-cmp v0.2.0/go.mod h1:oXzfMopK8JAjlY9xF4vHSVASa0yLyX7SntLO5aqRK0M= +github.com/google/go-cmp v0.3.0/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU= +github.com/google/go-cmp v0.3.1/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU= +github.com/google/go-cmp v0.4.0/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= +github.com/google/go-cmp v0.5.5/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= +github.com/polarismesh/specification v1.4.2 h1:Y54jc86sdggM5DAbvxDNeEJxjN1uc8R6g5mV+i74e0E= +github.com/polarismesh/specification v1.4.2/go.mod h1:rDvMMtl5qebPmqiBLNa5Ps0XtwkP31ZLirbH4kXA0YU= +github.com/prometheus/client_model v0.0.0-20190812154241-14fe0d1b01d4/go.mod h1:xMI15A0UPsDsEKsMN9yxemIoYk6Tm2C1GtYGdfGttqA= +golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= +golang.org/x/exp v0.0.0-20190121172915-509febef88a4/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA= +golang.org/x/lint v0.0.0-20181026193005-c67002cb31c3/go.mod h1:UVdnD1Gm6xHRNCYTkRU2/jEulfH38KcIWyp/GAMgvoE= +golang.org/x/lint v0.0.0-20190227174305-5b3e6a55c961/go.mod h1:wehouNa3lNwaWXcvxsM5YxQ5yQlVC4a0KAMCusXpPoU= +golang.org/x/lint v0.0.0-20190313153728-d0100b6bd8b3/go.mod h1:6SW0HCj/g11FgYtHlgUYUwCkIfeOF89ocIRzGO/8vkc= +golang.org/x/net v0.0.0-20180724234803-3673e40ba225/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= +golang.org/x/net v0.0.0-20180826012351-8a410e7b638d/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= +golang.org/x/net v0.0.0-20190213061140-3a22650c66bd/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= +golang.org/x/net v0.0.0-20190311183353-d8887717615a/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= +golang.org/x/net v0.2.0 h1:sZfSu1wtKLGlWI4ZZayP0ck9Y73K1ynO6gqzTdBVdPU= +golang.org/x/net v0.2.0/go.mod h1:KqCZLdyyvdV855qA2rE3GC2aiw5xGR5TEjj8smXukLY= +golang.org/x/oauth2 v0.0.0-20180821212333-d2e6202438be/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U= +golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20181108010431-42b317875d0f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sys v0.0.0-20180830151530-49385e6e1522/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +golang.org/x/sys v0.2.0 h1:ljd4t30dBnAvMZaQCevtY0xLLD0A+bRZXbgLMLU1F/A= +golang.org/x/sys v0.2.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= +golang.org/x/text v0.4.0 h1:BrVqGRd7+k1DiOgtnFvAkoQEWQvBc25ouMJM6429SFg= +golang.org/x/text v0.4.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8= +golang.org/x/tools v0.0.0-20190114222345-bf090417da8b/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= +golang.org/x/tools v0.0.0-20190226205152-f727befe758c/go.mod h1:9Yl7xja0Znq3iFh3HoIrodX9oNMXvdceNzlUR8zjMvY= +golang.org/x/tools v0.0.0-20190311212946-11955173bddd/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs= +golang.org/x/tools v0.0.0-20190524140312-2c0ae7006135/go.mod h1:RgjU9mgBXZiqYHBnxXauZ1Gv1EHHAz9KjViQ78xBX0Q= +golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= +google.golang.org/appengine v1.1.0/go.mod h1:EbEs0AVv82hx2wNQdGPgUI5lhzA/G0D9YwlJXL52JkM= +google.golang.org/appengine v1.4.0/go.mod h1:xpcJRLb0r/rnEns0DIKYYv+WjYCduHsrkT7/EB5XEv4= +google.golang.org/genproto v0.0.0-20180817151627-c66870c02cf8/go.mod h1:JiN7NxoALGmiZfu7CAH4rXhgtRTLTxftemlI0sWmxmc= +google.golang.org/genproto v0.0.0-20190819201941-24fa4b261c55/go.mod h1:DMBHOl98Agz4BDEuKkezgsaosCRResVns1a3J2ZsMNc= +google.golang.org/genproto v0.0.0-20200526211855-cb27e3aa2013 h1:+kGHl1aib/qcwaRi1CbqBZ1rk19r85MNUf8HaBghugY= +google.golang.org/genproto v0.0.0-20200526211855-cb27e3aa2013/go.mod h1:NbSheEEYHJ7i3ixzK3sjbqSGDJWnxyFXZblF3eUsNvo= +google.golang.org/grpc v1.19.0/go.mod h1:mqu4LbDTu4XGKhr4mRzUsmM4RtVoemTSY81AxZiDr8c= +google.golang.org/grpc v1.23.0/go.mod h1:Y5yQAOtifL1yxbo5wqy6BxZv8vAUGQwXBOALyacEbxg= +google.golang.org/grpc v1.27.0/go.mod h1:qbnxyOmOxrQa7FizSgH+ReBfzJrCY1pSN7KXBS8abTk= +google.golang.org/grpc v1.51.0 h1:E1eGv1FTqoLIdnBCZufiSHgKjlqG6fKFf6pPWtMTh8U= +google.golang.org/grpc v1.51.0/go.mod h1:wgNDFcnuBGmxLKI/qn4T+m5BtEBYXJPvibbUPsAIPww= +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= +google.golang.org/protobuf v1.20.1-0.20200309200217-e05f789c0967/go.mod h1:A+miEFZTKqfCUM6K7xSMQL9OKL/b6hQv+e19PK+JZNE= +google.golang.org/protobuf v1.21.0/go.mod h1:47Nbq4nVaFHyn7ilMalzfO3qCViNmqZ2kzikPIcrTAo= +google.golang.org/protobuf v1.22.0/go.mod h1:EGpADcykh3NcUnDUJcl1+ZksZNG86OlYog2l/sGQquU= +google.golang.org/protobuf v1.23.1-0.20200526195155-81db48ad09cc/go.mod h1:EGpADcykh3NcUnDUJcl1+ZksZNG86OlYog2l/sGQquU= +google.golang.org/protobuf v1.26.0-rc.1/go.mod h1:jlhhOSvTdKEhbULTjvd4ARK9grFBp09yW+WbY/TyQbw= +google.golang.org/protobuf v1.26.0/go.mod h1:9q0QmTI4eRPtz6boOQmLYwt+qCgq0jsYwAQnmE0givc= +google.golang.org/protobuf v1.28.1 h1:d0NfwRgPtno5B1Wa6L2DAG+KivqkdutMf1UhdNx175w= +google.golang.org/protobuf v1.28.1/go.mod h1:HV8QOd/L58Z+nl8r43ehVNZIU/HEI6OcFqwMG9pJV4I= +honnef.co/go/tools v0.0.0-20190102054323-c2f93a96b099/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4= +honnef.co/go/tools v0.0.0-20190523083050-ea95bdfd59fc/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4= diff --git a/observability/discoverevent/api.go b/observability/discoverevent/api.go new file mode 100644 index 0000000..9fafcbd --- /dev/null +++ b/observability/discoverevent/api.go @@ -0,0 +1,63 @@ +package discoverevent + +import ( + "time" + + apiservice "github.com/polarismesh/specification/source/go/api/v1/service_manage" +) + +// ConfigEntry 单个插件配置 +type ConfigEntry struct { + Name string `yaml:"name"` + Option map[string]interface{} `yaml:"option"` +} + +// InstanceEventType 探测事件类型 +type InstanceEventType string + +const ( + // EventDiscoverNone empty discover event + EventDiscoverNone InstanceEventType = "EventDiscoverNone" + // EventInstanceOnline instance becoming online + EventInstanceOnline InstanceEventType = "InstanceOnline" + // EventInstanceTurnUnHealth Instance becomes unhealthy + EventInstanceTurnUnHealth InstanceEventType = "InstanceTurnUnHealth" + // EventInstanceTurnHealth Instance becomes healthy + EventInstanceTurnHealth InstanceEventType = "InstanceTurnHealth" + // EventInstanceOpenIsolate Instance is in isolation + EventInstanceOpenIsolate InstanceEventType = "InstanceOpenIsolate" + // EventInstanceCloseIsolate Instance shutdown isolation state + EventInstanceCloseIsolate InstanceEventType = "InstanceCloseIsolate" + // EventInstanceOffline Instance offline + EventInstanceOffline InstanceEventType = "InstanceOffline" + // EventInstanceSendHeartbeat Instance send heartbeat package to server + EventInstanceSendHeartbeat InstanceEventType = "InstanceSendHeartbeat" + // EventInstanceUpdate Instance metadata and info update event + EventInstanceUpdate InstanceEventType = "InstanceUpdate" + // EventClientOffline . + EventClientOffline InstanceEventType = "ClientOffline" +) + +// InstanceEvent 服务实例事件 +type InstanceEvent struct { + Id string + SvcId string + Namespace string + Service string + Instance *apiservice.Instance + EType InstanceEventType + CreateTime time.Time + MetaData map[string]string +} + +// DiscoverChannel is used to receive discover events from the agent +type DiscoverChannel interface { + // Name . + Name() string + // Initialize . + Initialize(c *ConfigEntry) error + // Destroy . + Destroy() error + // PublishEvent Release a service event + PublishEvent(event *InstanceEvent) +} diff --git a/observability/history/api.go b/observability/history/api.go new file mode 100644 index 0000000..c892a0c --- /dev/null +++ b/observability/history/api.go @@ -0,0 +1,72 @@ +/** + * 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 history + +import ( + "fmt" + "time" +) + +// ConfigEntry 单个插件配置 +type ConfigEntry struct { + Name string `yaml:"name"` + Option map[string]interface{} `yaml:"option"` +} + +// History 历史记录插件 +type History interface { + // Name . + Name() string + // Initialize . + Initialize(c *ConfigEntry) error + // Destroy . + Destroy() error + // Record . + Record(entry *RecordEntry) +} + +// OperationType Operating type +type OperationType string + +// Resource Operating resources +type Resource string + +// RecordEntry Operation records +type RecordEntry struct { + ResourceType Resource + ResourceName string + Namespace string + Operator string + OperationType OperationType + Detail string + Server string + HappenTime time.Time +} + +func (r *RecordEntry) String(format func(time.Time) string) string { + return fmt.Sprintf("%s|%s|%s|%s|%s|%s|%s|%s", + format(r.HappenTime), + r.ResourceType, + r.ResourceName, + r.Namespace, + r.OperationType, + r.Operator, + r.Detail, + r.Server, + ) +} diff --git a/observability/statis/api.go b/observability/statis/api.go new file mode 100644 index 0000000..14d3322 --- /dev/null +++ b/observability/statis/api.go @@ -0,0 +1,141 @@ +/** + * 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 statis + +import ( + "fmt" + "strconv" + "time" +) + +// ConfigEntry 单个插件配置 +type ConfigEntry struct { + Name string `yaml:"name"` + Option map[string]interface{} `yaml:"option"` +} + +// Statis Statistical plugin interface +type Statis interface { + // Name . + Name() string + // Initialize . + Initialize(c *ConfigEntry) error + // Destroy . + Destroy() error + // ReportCallMetrics report call metrics info + ReportCallMetrics(metric CallMetric) + // ReportDiscoveryMetrics report discovery metrics + ReportDiscoveryMetrics(metric ...DiscoveryMetric) + // ReportConfigMetrics report config_center metrics + ReportConfigMetrics(metric ...ConfigMetrics) + // ReportDiscoverCall report discover service times + ReportDiscoverCall(metric ClientDiscoverMetric) +} + +type TrafficDirection string + +const ( + // TrafficDirectionInBound . + TrafficDirectionInBound TrafficDirection = "INBOUND" + // TrafficDirectionOutBound . + TrafficDirectionOutBound TrafficDirection = "OUTBOUND" +) + +const ( + LabelApi = "api" + LabelProtocol = "protocol" + LabelErrCode = "err_code" +) + +// CallMetricType . +type CallMetricType string + +type CallMetric struct { + Type CallMetricType + API string + Protocol string + Code int + Times int + Success bool + Duration time.Duration + Labels map[string]string + TrafficDirection TrafficDirection +} + +func (m CallMetric) GetLabels() map[string]string { + if len(m.Labels) == 0 { + m.Labels = map[string]string{} + } + m.Labels[LabelApi] = m.API + m.Labels[LabelProtocol] = m.Protocol + m.Labels[LabelErrCode] = strconv.FormatInt(int64(m.Code), 10) + return m.Labels +} + +type DiscoveryMetricType string + +const ( + ClientMetrics DiscoveryMetricType = "client" + ServiceMetrics DiscoveryMetricType = "service" + InstanceMetrics DiscoveryMetricType = "instance" +) + +type DiscoveryMetric struct { + Type DiscoveryMetricType + Total int64 + Abnormal int64 + Offline int64 + Online int64 + Isolate int64 + Labels map[string]string +} + +type ClientDiscoverMetric struct { + ClientIP string + Action string + Namespace string + Resource string + Revision string + Timestamp int64 + CostTime int64 + Success bool +} + +func (c ClientDiscoverMetric) String() string { + revision := c.Revision + if revision == "" { + revision = "-" + } + return fmt.Sprintf("%s|%s|%s|%s|%s|%s|%dms|%+v", c.ClientIP, c.Action, c.Namespace, c.Resource, + revision, time.Unix(c.Timestamp/1000, 0).Format(time.DateTime), c.CostTime, c.Success) +} + +type ConfigMetricType string + +const ( + ConfigGroupMetric ConfigMetricType = "config_group" + FileMetric ConfigMetricType = "file" + ReleaseFileMetric ConfigMetricType = "release_file" +) + +type ConfigMetrics struct { + Type ConfigMetricType + Total int64 + Release int64 + Labels map[string]string +} diff --git a/service/healthcheck/api.go b/service/healthcheck/api.go new file mode 100644 index 0000000..6c369e1 --- /dev/null +++ b/service/healthcheck/api.go @@ -0,0 +1,116 @@ +/** + * 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 healthcheck + +import ( + "context" +) + +// ReportRequest report heartbeat request +type ReportRequest struct { + QueryRequest + LocalHost string + CurTimeSec int64 + Count int64 +} + +// CheckRequest check heartbeat request +type CheckRequest struct { + QueryRequest + ExpireDurationSec uint32 + CurTimeSec func() int64 +} + +// CheckResponse check heartbeat response +type CheckResponse struct { + Healthy bool + LastHeartbeatTimeSec int64 + StayUnchanged bool + Regular bool +} + +// QueryRequest query heartbeat request +type QueryRequest struct { + InstanceId string + Host string + Port uint32 + Healthy bool +} + +// BatchQueryRequest batch query heartbeat request +type BatchQueryRequest struct { + Requests []*QueryRequest +} + +// QueryResponse query heartbeat response +type QueryResponse struct { + Server string + Exists bool + LastHeartbeatSec int64 + Count int64 +} + +// BatchQueryResponse batch query heartbeat response +type BatchQueryResponse struct { + Responses []*QueryResponse +} + +// AddCheckRequest add check request +type AddCheckRequest struct { + Instances []string + LocalHost string +} + +// HealthCheckType health check type +type HealthCheckType int32 + +const ( + HealthCheckerHeartbeat HealthCheckType = iota + 1 +) + +// ConfigEntry 单个插件配置 +type ConfigEntry struct { + Name string `yaml:"name"` + Option map[string]interface{} `yaml:"option"` +} + +// HealthChecker health checker plugin interface +type HealthChecker interface { + // Name . + Name() string + // Initialize . + Initialize(c *ConfigEntry) error + // Destroy . + Destroy() error + // Type for health check plugin, only one same type plugin is allowed + Type() HealthCheckType + // Report process heartbeat info report + Report(ctx context.Context, request *ReportRequest) error + // Check process the instance check + Check(request *CheckRequest) (*CheckResponse, error) + // Query queries the heartbeat time + Query(ctx context.Context, request *QueryRequest) (*QueryResponse, error) + // BatchQuery batch queries the heartbeat time + BatchQuery(ctx context.Context, request *BatchQueryRequest) (*BatchQueryResponse, error) + // Suspend health checker for entire expired duration manually + Suspend() + // SuspendTimeSec get the suspend time in seconds + SuspendTimeSec() int64 + // Delete delete the id + Delete(ctx context.Context, id string) error +} diff --git a/store/admin_api.go b/store/admin_api.go new file mode 100644 index 0000000..b637e96 --- /dev/null +++ b/store/admin_api.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 store + +import ( + "time" + + "github.com/polarismesh/polaris-plugin-api/store/model" +) + +type AdminStore interface { + // StartLeaderElection start leader election + StartLeaderElection(key string) error + + // IsLeader whether it is leader node + IsLeader(key string) bool + + // ListLeaderElections list all leaderelection + ListLeaderElections() ([]*model.LeaderElection, error) + + // ReleaseLeaderElection force release leader status + ReleaseLeaderElection(key string) error + + // BatchCleanDeletedInstances batch clean soft deleted instances + BatchCleanDeletedInstances(timeout time.Duration, batchSize uint32) (uint32, error) + + // GetUnHealthyInstances get unhealthy instances which mtime time out + GetUnHealthyInstances(timeout time.Duration, limit uint32) ([]string, error) + + // BatchCleanDeletedClients batch clean soft deleted clients + BatchCleanDeletedClients(timeout time.Duration, batchSize uint32) (uint32, error) +} + +// LeaderChangeEvent +type LeaderChangeEvent struct { + Key string + Leader bool + LeaderHost string +} diff --git a/store/api.go b/store/api.go new file mode 100644 index 0000000..de089f7 --- /dev/null +++ b/store/api.go @@ -0,0 +1,141 @@ +/** + * 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 store + +import ( + "errors" + "sync" + "time" + + "github.com/polarismesh/polaris-plugin-api/store/model" +) + +var ( + // StoreSlots store slots + StoreSlots = make(map[string]Store) + + once = &sync.Once{} + config = &Config{} +) + +// RegisterStore 注册一个新的Store +func RegisterStore(s Store) error { + name := s.Name() + if _, ok := StoreSlots[name]; ok { + return errors.New("store name already existed") + } + + StoreSlots[name] = s + return nil +} + +// Config Store的通用配置 +type Config struct { + Name string + Option map[string]interface{} +} + +// Store 通用存储接口 +type Store interface { + // Name 存储层的名字 + Name() string + // Initialize 存储的初始化函数 + Initialize(c *Config) error + // Destroy 存储的析构函数 + Destroy() error + // CreateTransaction 创建事务对象 + CreateTransaction() (Transaction, error) + // StartTx 开启一个原子事务 + StartTx() (Tx, error) + // StartReadTx 开启一个原子事务 + StartReadTx() (Tx, error) + // NamespaceStore Service namespace interface + NamespaceStore + // NamingModuleStore Service Registration Discovery Module Storage Interface + NamingModuleStore + // ConfigFileModuleStore Configure the central module storage interface + ConfigFileModuleStore + // ClientStore Client the central module storage interface + ClientStore + // AdminStore Maintain inteface + AdminStore + // GrayStore mgr gray resource + GrayStore +} + +// NamespaceStore Namespace storage interface +type NamespaceStore interface { + // AddNamespace Save a namespace + AddNamespace(namespace *model.Namespace) error + // UpdateNamespace Update namespace + UpdateNamespace(namespace *model.Namespace) error + // UpdateNamespaceToken Update namespace token + UpdateNamespaceToken(name string, token string) error + // GetNamespace Get the details of the namespace according to Name + GetNamespace(name string) (*model.Namespace, error) + // GetNamespaces Query Namespace from the database + GetNamespaces(filter map[string][]string, offset, limit int) ([]*model.Namespace, uint32, error) + // GetMoreNamespaces Get incremental data + // 此方法用于 cache 增量更新,需要注意 mtime 应为数据库时间戳 + GetMoreNamespaces(mtime time.Time) ([]*model.Namespace, error) +} + +// GrayStore Gray storage interface +type GrayStore interface { + // CleanGrayResource . + CleanGrayResource(tx Tx, data *model.GrayResource) error + // CreateGrayResourceTx . + CreateGrayResourceTx(tx Tx, data *model.GrayResource) error + // GetMoreGrayResouces . + GetMoreGrayResouces(firstUpdate bool, mtime time.Time) ([]*model.GrayResource, error) +} + +// Transaction Transaction interface, does not support multi-level concurrency operation, +// currently only support a single price serial operation +type Transaction interface { + // Commit Transaction + Commit() error + // LockBootstrap Start the lock, limit the concurrent number of Server boot + LockBootstrap(key string, server string) error + // LockNamespace Row it locks Namespace + LockNamespace(name string) (*model.Namespace, error) + // DeleteNamespace Delete Namespace + DeleteNamespace(name string) error + // LockService Row it locks service + LockService(name string, namespace string) (*model.Service, error) + // RLockService Shared lock service + RLockService(name string, namespace string) (*model.Service, error) +} + +// Tx Atomic matters without any business attributes.Abstraction of different storage type transactions +type Tx interface { + // Commit Transaction + Commit() error + // Rollback transaction + Rollback() error + // GetDelegateTx Get the original proxy transaction object.Different storage types have no business implementation + GetDelegateTx() interface{} + // CreateReadView create a snapshot read view + CreateReadView() error +} + +// ToolStore Storage related functions and tool interfaces +type ToolStore interface { + // GetUnixSecond Get the current time + GetUnixSecond(maxWait time.Duration) (int64, error) +} diff --git a/store/code.go b/store/code.go new file mode 100644 index 0000000..7b9e445 --- /dev/null +++ b/store/code.go @@ -0,0 +1,134 @@ +/** + * 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 store + +import ( + "strings" +) + +// StatusCode 存储层的状态码 +type StatusCode uint32 + +// 状态码定义 +const ( + Ok StatusCode = iota + // 参数不合法 + EmptyParamsErr + // 数据不合法,比如越级了,超过了字段大小 + OutOfRangeErr + // 数据冲突,在并发更新metadata的时候可能会出现 + DataConflictErr + // 找不到namespace,service插入依赖namespace是否存在 + NotFoundNamespace + // 找不到service,在instance等资源插入的时候依赖service是否存在 + NotFoundService + // 在标记规则前,需要保证规则的master版本存在 + NotFoundMasterConfig + // 在发布规则前,需要保证规则已标记且服务存在 + NotFoundTagConfigOrService + // 在删除规则时,发现存在已经发布的版本 + ExistReleasedConfig + // 操作的行数与预期不符合 + AffectedRowsNotMatch + // 主键重复,一般是资源已存在了,提醒用户资源存在 + DuplicateEntryErr + // 外键错误,一般是操作不当导致的 + ForeignKeyErr + // 数据库死锁 + DeadlockErr + // 网格订阅服务的时候,网格或者服务不存在 + NotFoundMeshOrService + // 更新订阅服务的时候,订阅服务不存在 + NotFoundMeshService + // Failed to find target CircuitBreaker + NotFoundCircuitBreaker + // Failed to find fuse breaker information associated with service + NotFoundReleaseCircuitBreaker + Unknown + // 用户不存在 + NotFoundUser + // 用户组不存在 + NotFoundUserGroup + // 非法的用户ID列表 + InvalidUserIDSlice + NotFoundResource +) + +// Error 普通error转StatusError +func Error(err error) error { + if err == nil { + return nil + } + + // 已经是StatusError了,不再转换 + if _, ok := err.(*StatusError); ok { + return err + } + + s := &StatusError{message: err.Error()} + if strings.Contains(s.message, "Data too long") { + s.code = OutOfRangeErr + } else if strings.Contains(s.message, "Duplicate entry") { + s.code = DuplicateEntryErr + } else if strings.Contains(s.message, "a foreign key constraint fails") { + s.code = ForeignKeyErr + } else if strings.Contains(s.message, "Deadlock") { + s.code = DeadlockErr + } else { + s.code = Unknown + } + + return s +} + +// NewStatusError 根据code和message创建StatusError +func NewStatusError(code StatusCode, message string) error { + return &StatusError{ + code: code, + message: message, + } +} + +// Code 根据error接口,获取状态码 +func Code(err error) StatusCode { + if err == nil { + return Ok + } + + se, ok := err.(*StatusError) + if ok { + return se.code + } + + return Unknown +} + +// StatusError 包括了状态码的error接口 +type StatusError struct { + code StatusCode + message string +} + +// Error 实现error接口 +func (s *StatusError) Error() string { + if s == nil { + return "" + } + + return s.message +} diff --git a/store/config_api.go b/store/config_api.go new file mode 100644 index 0000000..e092441 --- /dev/null +++ b/store/config_api.go @@ -0,0 +1,119 @@ +/* + * 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 store + +import ( + "time" + + "github.com/polarismesh/polaris-plugin-api/store/model" +) + +// ConfigFileModuleStore 配置中心模块存储接口 +type ConfigFileModuleStore interface { + ConfigFileGroupStore + ConfigFileStore + ConfigFileReleaseStore + ConfigFileReleaseHistoryStore + ConfigFileTemplateStore +} + +// ConfigFileGroupStore 配置文件组存储接口 +type ConfigFileGroupStore interface { + // CreateConfigFileGroup 创建配置文件组 + CreateConfigFileGroup(fileGroup *model.ConfigFileGroup) (*model.ConfigFileGroup, error) + // UpdateConfigFileGroup 更新配置文件组 + UpdateConfigFileGroup(fileGroup *model.ConfigFileGroup) error + // GetConfigFileGroup 获取单个配置文件组 + GetConfigFileGroup(namespace, name string) (*model.ConfigFileGroup, error) + // DeleteConfigFileGroup 删除配置文件组 + DeleteConfigFileGroup(namespace, name string) error + // GetMoreConfigGroup 获取配置分组 + GetMoreConfigGroup(firstUpdate bool, mtime time.Time) ([]*model.ConfigFileGroup, error) + // CountConfigGroups 获取一个命名空间下的配置分组数量 + CountConfigGroups(namespace string) (uint64, error) +} + +// ConfigFileStore 配置文件存储接口 +type ConfigFileStore interface { + // LockConfigFile 加锁配置文件 + LockConfigFile(tx Tx, file *model.ConfigFileKey) (*model.ConfigFile, error) + // CreateConfigFileTx 创建配置文件 + CreateConfigFileTx(tx Tx, file *model.ConfigFile) error + // GetConfigFile 获取配置文件 + GetConfigFile(namespace, group, name string) (*model.ConfigFile, error) + // GetConfigFileTx 获取配置文件 + GetConfigFileTx(tx Tx, namespace, group, name string) (*model.ConfigFile, error) + // QueryConfigFiles 翻页查询配置文件,group、name可为模糊匹配 + QueryConfigFiles(filter map[string]string, offset uint32, limit uint32) (uint32, []*model.ConfigFile, error) + // UpdateConfigFileTx 更新配置文件 + UpdateConfigFileTx(tx Tx, file *model.ConfigFile) error + // DeleteConfigFileTx 删除配置文件 + DeleteConfigFileTx(tx Tx, namespace, group, name string) error + // CountConfigFiles 获取一个配置文件组下的文件数量 + CountConfigFiles(namespace, group string) (uint64, error) + // CountConfigFileEachGroup 统计 namespace.group 下的配置文件数量 + CountConfigFileEachGroup() (map[string]map[string]int64, error) +} + +// ConfigFileReleaseStore 配置文件发布存储接口 +type ConfigFileReleaseStore interface { + // GetConfigFileActiveRelease 获取配置文件处于 Active 的配置发布记录 + GetConfigFileActiveRelease(file *model.ConfigFileKey) (*model.ConfigFileRelease, error) + // GetConfigFileActiveReleaseTx 获取配置文件处于 Active 的配置发布记录 + GetConfigFileActiveReleaseTx(tx Tx, file *model.ConfigFileKey) (*model.ConfigFileRelease, error) + // CreateConfigFileReleaseTx 创建配置文件发布 + CreateConfigFileReleaseTx(tx Tx, fileRelease *model.ConfigFileRelease) error + // GetConfigFileRelease 获取配置文件发布内容,只获取 flag=0 的记录 + GetConfigFileRelease(req *model.ConfigFileReleaseKey) (*model.ConfigFileRelease, error) + // GetConfigFileReleaseTx 在已开启的事务中获取配置文件发布内容,只获取 flag=0 的记录 + GetConfigFileReleaseTx(tx Tx, req *model.ConfigFileReleaseKey) (*model.ConfigFileRelease, error) + // DeleteConfigFileReleaseTx 删除配置文件发布内容 + DeleteConfigFileReleaseTx(tx Tx, data *model.ConfigFileReleaseKey) error + // ActiveConfigFileReleaseTx 指定激活发布的配置文件(激活具有排他性,同一个配置文件的所有 release 中只能有一个处于 active == true 状态) + ActiveConfigFileReleaseTx(tx Tx, release *model.ConfigFileRelease) error + // InactiveConfigFileReleaseTx 指定失效发布的配置文件(失效具有排他性,同一个配置文件的所有 release 中能有多个处于 active == false 状态) + InactiveConfigFileReleaseTx(tx Tx, release *model.ConfigFileRelease) error + // CleanConfigFileReleasesTx 清空配置文件发布 + CleanConfigFileReleasesTx(tx Tx, namespace, group, fileName string) error + // GetMoreReleaseFile 获取最近更新的配置文件发布, 此方法用于 cache 增量更新,需要注意 modifyTime 应为数据库时间戳 + GetMoreReleaseFile(firstUpdate bool, modifyTime time.Time) ([]*model.ConfigFileRelease, error) + // CountConfigReleases 获取一个配置文件组下的文件数量 + CountConfigReleases(namespace, group string, onlyActive bool) (uint64, error) + // GetConfigFileBetaReleaseTx 获取灰度发布的配置文件信息 + GetConfigFileBetaReleaseTx(tx Tx, file *model.ConfigFileKey) (*model.ConfigFileRelease, error) +} + +// ConfigFileReleaseHistoryStore 配置文件发布历史存储接口 +type ConfigFileReleaseHistoryStore interface { + // CreateConfigFileReleaseHistory 创建配置文件发布历史记录 + CreateConfigFileReleaseHistory(history *model.ConfigFileReleaseHistory) error + // QueryConfigFileReleaseHistories 获取配置文件的发布历史记录 + QueryConfigFileReleaseHistories(filter map[string]string, offset, limit uint32) (uint32, []*model.ConfigFileReleaseHistory, error) + // CleanConfigFileReleaseHistory 清理配置发布历史 + CleanConfigFileReleaseHistory(endTime time.Time, limit uint64) error +} + +// ConfigFileTemplateStore config file template store +type ConfigFileTemplateStore interface { + // QueryAllConfigFileTemplates query all config file templates + QueryAllConfigFileTemplates() ([]*model.ConfigFileTemplate, error) + // CreateConfigFileTemplate create config file template + CreateConfigFileTemplate(template *model.ConfigFileTemplate) (*model.ConfigFileTemplate, error) + // GetConfigFileTemplate get config file template by name + GetConfigFileTemplate(name string) (*model.ConfigFileTemplate, error) +} diff --git a/store/discover_api.go b/store/discover_api.go new file mode 100644 index 0000000..59d4fe1 --- /dev/null +++ b/store/discover_api.go @@ -0,0 +1,282 @@ +/** + * 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 store + +import ( + "time" + + "github.com/polarismesh/polaris-plugin-api/store/model" +) + +// NamingModuleStore Service discovery, governance center module storage interface +type NamingModuleStore interface { + // ServiceStore 服务接口 + ServiceStore + // InstanceStore 实例接口 + InstanceStore + // RoutingConfigStore 路由配置接口 + RoutingConfigStore + // L5Store L5扩展接口 + L5Store + // RateLimitStore 限流规则接口 + RateLimitStore + // CircuitBreakerStore 熔断规则接口 + CircuitBreakerStore + // RoutingConfigStoreV2 路由策略 v2 接口 + RoutingConfigStoreV2 + // FaultDetectRuleStore fault detect rule interface + FaultDetectRuleStore + // ServiceContractStore 服务契约操作接口 + ServiceContractStore +} + +// ServiceStore 服务存储接口 +type ServiceStore interface { + // AddService 保存一个服务 + AddService(service *model.Service) error + // DeleteService 删除服务 + DeleteService(id, serviceName, namespaceName string) error + // DeleteServiceAlias 删除服务别名 + DeleteServiceAlias(name string, namespace string) error + // UpdateServiceAlias 修改服务别名 + UpdateServiceAlias(alias *model.Service, needUpdateOwner bool) error + // UpdateService 更新服务 + UpdateService(service *model.Service, needUpdateOwner bool) error + // UpdateServiceToken 更新服务token + UpdateServiceToken(serviceID string, token string, revision string) error + // GetSourceServiceToken 获取源服务的token信息 + GetSourceServiceToken(name string, namespace string) (*model.Service, error) + // GetService 根据服务名和命名空间获取服务的详情 + GetService(name string, namespace string) (*model.Service, error) + // GetServiceByID 根据服务ID查询服务详情 + GetServiceByID(id string) (*model.Service, error) + // GetServices 根据相关条件查询对应服务及数目 + GetServices(serviceFilters, serviceMetas map[string]string, instanceFilters *model.InstanceArgs, offset, limit uint32) ( + uint32, []*model.Service, error) + // GetServicesCount 获取所有服务总数 + GetServicesCount() (uint32, error) + // GetMoreServices 获取增量services + // 此方法用于 cache 增量更新,需要注意 mtime 应为数据库时间戳 + GetMoreServices(mtime time.Time, firstUpdate, disableBusiness, needMeta bool) (map[string]*model.Service, error) + // GetServiceAliases 获取服务别名列表 + GetServiceAliases(filter map[string]string, offset uint32, limit uint32) (uint32, []*model.ServiceAlias, error) + // GetSystemServices 获取系统服务 + GetSystemServices() ([]*model.Service, error) + // GetServicesBatch 批量获取服务id、负责人等信息 + GetServicesBatch(services []*model.Service) ([]*model.Service, error) +} + +// InstanceStore 实例存储接口 +type InstanceStore interface { + // AddInstance 增加一个实例 + AddInstance(instance *model.Instance) error + // BatchAddInstances 增加多个实例 + BatchAddInstances(instances []*model.Instance) error + // UpdateInstance 更新实例 + UpdateInstance(instance *model.Instance) error + // DeleteInstance 删除一个实例,实际是把valid置为false + DeleteInstance(instanceID string) error + // BatchDeleteInstances 批量删除实例,flag=1 + BatchDeleteInstances(ids []interface{}) error + // CleanInstance 清空一个实例,真正删除 + CleanInstance(instanceID string) error + // BatchGetInstanceIsolate 检查ID是否存在,并且返回存在的ID,以及ID的隔离状态 + BatchGetInstanceIsolate(ids map[string]bool) (map[string]bool, error) + // GetInstancesBrief 获取实例关联的token + GetInstancesBrief(ids map[string]bool) (map[string]*model.Instance, error) + // GetInstance 查询一个实例的详情,只返回有效的数据 + GetInstance(instanceID string) (*model.Instance, error) + // GetInstancesCount 获取有效的实例总数 + GetInstancesCount() (uint32, error) + // GetInstancesCountTx 获取有效的实例总数 + GetInstancesCountTx(tx Tx) (uint32, error) + // GetInstancesMainByService 根据服务和Host获取实例(不包括metadata) + GetInstancesMainByService(serviceID, host string) ([]*model.Instance, error) + // GetExpandInstances 根据过滤条件查看实例详情及对应数目 + GetExpandInstances( + filter, metaFilter map[string]string, offset uint32, limit uint32) (uint32, []*model.Instance, error) + // GetMoreInstances 根据mtime获取增量instances,返回所有store的变更信息 + // 此方法用于 cache 增量更新,需要注意 mtime 应为数据库时间戳 + GetMoreInstances(tx Tx, mtime time.Time, firstUpdate, needMeta bool, serviceID []string) (map[string]*model.Instance, error) + // SetInstanceHealthStatus 设置实例的健康状态 + SetInstanceHealthStatus(instanceID string, flag int, revision string) error + // BatchSetInstanceHealthStatus 批量设置实例的健康状态 + BatchSetInstanceHealthStatus(ids []interface{}, healthy int, revision string) error + // BatchSetInstanceIsolate 批量修改实例的隔离状态 + BatchSetInstanceIsolate(ids []interface{}, isolate int, revision string) error + // AppendInstanceMetadata 追加实例 metadata + BatchAppendInstanceMetadata(requests []*model.InstanceMetadataRequest) error + // RemoveInstanceMetadata 删除实例指定的 metadata + BatchRemoveInstanceMetadata(requests []*model.InstanceMetadataRequest) error +} + +// L5Store L5扩展存储接口 +type L5Store interface { + // GetL5Extend 获取扩展数据 + GetL5Extend(serviceID string) (map[string]interface{}, error) + // SetL5Extend 设置meta里保存的扩展数据,并返回剩余的meta + SetL5Extend(serviceID string, meta map[string]interface{}) (map[string]interface{}, error) + // GenNextL5Sid 获取module + GenNextL5Sid(layoutID uint32) (string, error) + // GetMoreL5Extend 获取增量数据 + GetMoreL5Extend(mtime time.Time) (map[string]map[string]interface{}, error) + // GetMoreL5Routes 获取Route增量数据 + GetMoreL5Routes(flow uint32) ([]*model.Route, error) + // GetMoreL5Policies 获取Policy增量数据 + GetMoreL5Policies(flow uint32) ([]*model.Policy, error) + // GetMoreL5Sections 获取Section增量数据 + GetMoreL5Sections(flow uint32) ([]*model.Section, error) + // GetMoreL5IPConfigs 获取IP Config增量数据 + GetMoreL5IPConfigs(flow uint32) ([]*model.IPConfig, error) +} + +// RoutingConfigStore 路由配置表的存储接口 +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.RoutingConfig, error) +} + +// RateLimitStore 限流规则的存储接口 +type RateLimitStore interface { + // CreateRateLimit 新增限流规则 + CreateRateLimit(limiting *model.RateLimit) error + // UpdateRateLimit 更新限流规则 + UpdateRateLimit(limiting *model.RateLimit) error + // EnableRateLimit 启用限流规则 + EnableRateLimit(limit *model.RateLimit) error + // DeleteRateLimit 删除限流规则 + DeleteRateLimit(limiting *model.RateLimit) error + // GetExtendRateLimits 根据过滤条件拉取限流规则 + GetExtendRateLimits(query map[string]string, offset uint32, limit uint32) (uint32, []*model.RateLimit, error) + // GetRateLimitWithID 根据限流ID拉取限流规则 + GetRateLimitWithID(id string) (*model.RateLimit, error) + // GetRateLimitsForCache 根据修改时间拉取增量限流规则及最新版本号 + // 此方法用于 cache 增量更新,需要注意 mtime 应为数据库时间戳 + GetRateLimitsForCache(mtime time.Time, firstUpdate bool) ([]*model.RateLimit, error) +} + +// CircuitBreakerStore 熔断规则的存储接口 +type CircuitBreakerStore interface { + // CreateCircuitBreakerRule create general circuitbreaker rule + CreateCircuitBreakerRule(cbRule *model.CircuitBreakerRule) error + // UpdateCircuitBreakerRule update general circuitbreaker rule + UpdateCircuitBreakerRule(cbRule *model.CircuitBreakerRule) error + // DeleteCircuitBreakerRule delete general circuitbreaker rule + DeleteCircuitBreakerRule(id string) error + // HasCircuitBreakerRule check circuitbreaker rule exists + HasCircuitBreakerRule(id string) (bool, error) + // HasCircuitBreakerRuleByName check circuitbreaker rule exists for name + HasCircuitBreakerRuleByName(name string, namespace string) (bool, error) + // HasCircuitBreakerRuleByNameExcludeId check circuitbreaker rule exists for name not this id + HasCircuitBreakerRuleByNameExcludeId(name string, namespace string, id string) (bool, error) + // GetCircuitBreakerRules get all circuitbreaker rules by query and limit + GetCircuitBreakerRules( + filter map[string]string, offset uint32, limit uint32) (uint32, []*model.CircuitBreakerRule, error) + // GetCircuitBreakerRulesForCache get increment circuitbreaker rules + GetCircuitBreakerRulesForCache(mtime time.Time, firstUpdate bool) ([]*model.CircuitBreakerRule, error) + // EnableCircuitBreakerRule enable specific circuitbreaker rule + EnableCircuitBreakerRule(cbRule *model.CircuitBreakerRule) error +} + +// 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 *model.RouterConfig) error + // CreateRoutingConfigV2 新增一个路由配置 + CreateRoutingConfigV2(conf *model.RouterConfig) error + // CreateRoutingConfigV2Tx 新增一个路由配置 + CreateRoutingConfigV2Tx(tx Tx, conf *model.RouterConfig) error + // UpdateRoutingConfigV2 更新一个路由配置 + UpdateRoutingConfigV2(conf *model.RouterConfig) error + // UpdateRoutingConfigV2Tx 更新一个路由配置 + UpdateRoutingConfigV2Tx(tx Tx, conf *model.RouterConfig) error + // DeleteRoutingConfigV2 删除一个路由配置 + DeleteRoutingConfigV2(serviceID string) error + // GetRoutingConfigsV2ForCache 通过mtime拉取增量的路由配置信息 + // 此方法用于 cache 增量更新,需要注意 mtime 应为数据库时间戳 + GetRoutingConfigsV2ForCache(mtime time.Time, firstUpdate bool) ([]*model.RouterConfig, error) + // GetRoutingConfigV2WithID 根据服务ID拉取路由配置 + GetRoutingConfigV2WithID(id string) (*model.RouterConfig, error) + // GetRoutingConfigV2WithIDTx 根据服务ID拉取路由配置 + GetRoutingConfigV2WithIDTx(tx Tx, id string) (*model.RouterConfig, error) +} + +// FaultDetectRuleStore store api for the fault detector config +type FaultDetectRuleStore interface { + // CreateFaultDetectRule create fault detect rule + CreateFaultDetectRule(conf *model.FaultDetectRule) error + // UpdateFaultDetectRule update fault detect rule + UpdateFaultDetectRule(conf *model.FaultDetectRule) error + // DeleteFaultDetectRule delete fault detect rule + DeleteFaultDetectRule(id string) error + // HasFaultDetectRule check fault detect rule exists + HasFaultDetectRule(id string) (bool, error) + // HasFaultDetectRuleByName check fault detect rule exists by name + HasFaultDetectRuleByName(name string, namespace string) (bool, error) + // HasFaultDetectRuleByNameExcludeId check fault detect rule exists by name not this id + HasFaultDetectRuleByNameExcludeId(name string, namespace string, id string) (bool, error) + // GetFaultDetectRules get all fault detect rules by query and limit + GetFaultDetectRules(filter map[string]string, offset uint32, limit uint32) (uint32, []*model.FaultDetectRule, error) + // GetFaultDetectRulesForCache get increment fault detect rules + GetFaultDetectRulesForCache(mtime time.Time, firstUpdate bool) ([]*model.FaultDetectRule, error) +} + +type ServiceContractStore interface { + // CreateServiceContract 创建服务契约 + CreateServiceContract(contract *model.ServiceContract) error + // UpdateServiceContract 更新服务契约 + UpdateServiceContract(contract *model.ServiceContract) error + // DeleteServiceContract 删除服务契约 + DeleteServiceContract(contract *model.ServiceContract) error + // GetMoreServiceContracts 用于缓存加载数据 + GetMoreServiceContracts(firstUpdate bool, mtime time.Time) ([]*model.ServiceContract, error) + // GetServiceContract 查询服务契约数据 + GetServiceContract(id string) (data *model.ServiceContract, err error) + // AddServiceContractInterfaces 创建服务契约API接口 + AddServiceContractInterfaces(contract *model.ServiceContract) error + // AppendServiceContractInterfaces 追加服务契约API接口 + AppendServiceContractInterfaces(contract *model.ServiceContract) error + // DeleteServiceContractInterfaces 批量删除服务契约API接口 + DeleteServiceContractInterfaces(contract *model.ServiceContract) error +} diff --git a/store/model/admin.go b/store/model/admin.go new file mode 100644 index 0000000..df44779 --- /dev/null +++ b/store/model/admin.go @@ -0,0 +1,31 @@ +/** + * 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 model + +import "time" + +// LeaderElection leader election info +type LeaderElection struct { + ElectKey string + Host string + Ctime int64 + CreateTime time.Time + Mtime int64 + ModifyTime time.Time + Valid bool +} diff --git a/store/model/auth.go b/store/model/auth.go new file mode 100644 index 0000000..708153b --- /dev/null +++ b/store/model/auth.go @@ -0,0 +1,79 @@ +package model + +import "time" + +// User 用户 +type User struct { + ID string + Name string + Password string + Owner string + Source string + Mobile string + Email string + Type string + Token string + TokenEnable bool + Valid bool + Comment string + CreateTime time.Time + ModifyTime time.Time +} + +// UserGroup 用户组 +type UserGroup struct { + ID string + Name string + Owner string + Token string + TokenEnable bool + Valid bool + Comment string + UserIds []string + CreateTime time.Time + ModifyTime time.Time +} + +// StrategyDetail 鉴权策略详细 +type StrategyDetail struct { + ID string + Name string + Action string + Comment string + Principals []Principal + Default bool + Owner string + Resources []StrategyResource + Valid bool + Revision string + CreateTime time.Time + ModifyTime time.Time +} + +// Strategy 策略main信息 +type Strategy struct { + ID string + Name string + Principal string + Action string + Comment string + Owner string + Default bool + Valid bool + CreateTime time.Time + ModifyTime time.Time +} + +// StrategyResource 策略资源 +type StrategyResource struct { + StrategyID string + ResType int32 + ResID string +} + +// Principal 策略相关人 +type Principal struct { + StrategyID string + PrincipalID string + PrincipalRole string +} diff --git a/store/model/client.go b/store/model/client.go new file mode 100644 index 0000000..6be6410 --- /dev/null +++ b/store/model/client.go @@ -0,0 +1,32 @@ +/** + * 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 model + +import ( + "time" + + apiservice "github.com/polarismesh/specification/source/go/api/v1/service_manage" +) + +// Client 客户端上报信息表 +type Client struct { + Proto *apiservice.Client + Valid bool + CreateTime time.Time + ModifyTime time.Time +} diff --git a/store/model/config.go b/store/model/config.go new file mode 100644 index 0000000..1939aa9 --- /dev/null +++ b/store/model/config.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 model + +import ( + "time" + + apimodel "github.com/polarismesh/specification/source/go/api/v1/model" +) + +type ReleaseType string + +const ( + // ReleaseTypeFull 全量类型 + ReleaseTypeFull = "" + // ReleaseTypeGray 灰度类型 + ReleaseTypeGray = "gray" +) + +/** ----------- DataObject ------------- */ + +// ConfigFileGroup 配置文件组数据持久化对象 +type ConfigFileGroup struct { + Id uint64 + Name string + Namespace string + Comment string + Owner string + Business string + Department string + Metadata map[string]string + CreateTime time.Time + ModifyTime time.Time + CreateBy string + ModifyBy string + Valid bool + Revision string +} + +type ConfigFileKey struct { + Name string + Namespace string + Group string +} + +func (c ConfigFileKey) String() string { + return c.Namespace + "@" + c.Group + "@" + c.Name +} + +// ConfigFile 配置文件数据持久化对象 +type ConfigFile struct { + Id uint64 + Name string + Namespace string + Group string + // OriginContent 最原始的配置文件内容数据 + OriginContent string + Content string + Comment string + Format string + Flag int + Valid bool + Metadata map[string]string + Encrypt bool + EncryptAlgo string + Status string + CreateBy string + ModifyBy string + ReleaseBy string + CreateTime time.Time + ModifyTime time.Time + ReleaseTime time.Time +} + +func NewConfigFileRelease() *ConfigFileRelease { + return &ConfigFileRelease{ + SimpleConfigFileRelease: &SimpleConfigFileRelease{ + ConfigFileReleaseKey: &ConfigFileReleaseKey{}, + }, + } +} + +// ConfigFileRelease 配置文件发布数据持久化对象 +type ConfigFileRelease struct { + *SimpleConfigFileRelease + Content string +} + +type ConfigFileReleaseKey struct { + Id uint64 + Name string + Namespace string + Group string + FileName string + ReleaseType ReleaseType +} + +// SimpleConfigFileRelease 配置文件发布数据持久化对象 +type SimpleConfigFileRelease struct { + *ConfigFileReleaseKey + Version uint64 + Comment string + Md5 string + Flag int + Active bool + Valid bool + Format string + Metadata map[string]string + CreateTime time.Time + CreateBy string + ModifyTime time.Time + ModifyBy string + ReleaseDescription string + BetaLabels []*apimodel.ClientLabel +} + +// ConfigFileReleaseHistory 配置文件发布历史记录数据持久化对象 +type ConfigFileReleaseHistory struct { + Id uint64 + Name string + Namespace string + Group string + FileName string + Format string + Metadata map[string]string + Content string + Comment string + Version uint64 + Md5 string + Type string + Status string + CreateTime time.Time + CreateBy string + ModifyTime time.Time + ModifyBy string + Valid bool + Reason string + ReleaseDescription string +} + +// ConfigFileTag 配置文件标签数据持久化对象 +type ConfigFileTag struct { + Id uint64 + Key string + Value string + Namespace string + Group string + FileName string + CreateTime time.Time + CreateBy string + ModifyTime time.Time + ModifyBy string + Valid bool +} + +// ConfigFileTemplate config file template data object +type ConfigFileTemplate struct { + Id uint64 + Name string + Content string + Comment string + Format string + CreateTime time.Time + CreateBy string + ModifyTime time.Time + ModifyBy string +} diff --git a/store/model/l5.go b/store/model/l5.go new file mode 100644 index 0000000..ff1deab --- /dev/null +++ b/store/model/l5.go @@ -0,0 +1,85 @@ +/** + * 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 model + +// Route 访问关系 +type Route struct { + IP uint32 + ModID uint32 + CmdID uint32 + SetID string + Valid bool + Flow uint32 +} + +// Policy 有状态规则路由策略信息 +type Policy struct { + ModID uint32 + Div uint32 + Mod uint32 + Valid bool + Flow uint32 +} + +// Section 有状态规则路由分段信息 +type Section struct { + ModID uint32 + From uint32 + To uint32 + Xid uint32 + Valid bool + Flow uint32 +} + +// IPConfig IP的区域信息 +type IPConfig struct { + IP uint32 + AreaID uint32 + CityID uint32 + IdcID uint32 + Valid bool + Flow uint32 +} + +// Sid sid信息 +type Sid struct { + ModID uint32 + CmdID uint32 +} + +// Callee 被调信息,对应t_server+t_ip_config +type Callee struct { + ModID uint32 + CmdID uint32 + SetID string + IP uint32 + Port uint32 + Weight uint32 + Location *Location + // AreaID uint32 + // CityID uint32 + // IdcID uint32 +} + +// SidConfig sid信息,对应t_sid表 +type SidConfig struct { + ModID uint32 + CmdID uint32 + Name string + Policy uint32 +} diff --git a/store/model/namespace.go b/store/model/namespace.go new file mode 100644 index 0000000..cd238f4 --- /dev/null +++ b/store/model/namespace.go @@ -0,0 +1,33 @@ +/** + * 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 model + +import "time" + +// Namespace 命名空间结构体 +type Namespace struct { + Name string + Comment string + Token string + Owner string + Valid bool + CreateTime time.Time + ModifyTime time.Time + // ServiceExportTo 服务可见性设置 + ServiceExportTo map[string]struct{} +} diff --git a/store/model/rule.go b/store/model/rule.go new file mode 100644 index 0000000..8ca3aca --- /dev/null +++ b/store/model/rule.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 model + +import ( + "time" + + apifault "github.com/polarismesh/specification/source/go/api/v1/fault_tolerance" + apiservice "github.com/polarismesh/specification/source/go/api/v1/service_manage" + apitraffic "github.com/polarismesh/specification/source/go/api/v1/traffic_manage" +) + +// CircuitBreaker 熔断规则 +type CircuitBreaker struct { + ID string + Version string + Name string + Namespace string + Business string + Department string + Comment string + Inbounds string + Outbounds string + Token string + Owner string + Revision string + Valid bool + CreateTime time.Time + ModifyTime time.Time +} + +// CircuitBreakerRelation 熔断规则绑定关系 +type CircuitBreakerRelation struct { + ServiceID string + RuleID string + RuleVersion string + Valid bool + CreateTime time.Time + ModifyTime time.Time +} + +// CircuitBreakerRule 熔断规则 +type CircuitBreakerRule struct { + Proto *apifault.CircuitBreakerRule + ID string + Name string + Namespace string + Description string + Level int + SrcService string + SrcNamespace string + DstService string + DstNamespace string + DstMethod string + Rule string + Revision string + Enable bool + Valid bool + CreateTime time.Time + ModifyTime time.Time + EnableTime time.Time +} + +// FaultDetectRule 故障探测规则 +type FaultDetectRule struct { + Proto *apifault.FaultDetectRule + ID string + Name string + Namespace string + Description string + DstService string + DstNamespace string + DstMethod string + Rule string + Revision string + Valid bool + CreateTime time.Time + ModifyTime time.Time +} + +type RoutingConfig struct { + ID string + ServiceName string + NamespaceName string + InBounds string + OutBounds string + Revision string + Valid bool + CreateTime time.Time + ModifyTime time.Time +} + +// RouterConfig Routing rules +type RouterConfig struct { + // ID The unique id of the rules + ID string `json:"id"` + // namespace router config owner namespace + Namespace string `json:"namespace"` + // name router config name + Name string `json:"name"` + // policy Rules + Policy string `json:"policy"` + // config Specific routing rules content + Config string `json:"config"` + // enable Whether the routing rules are enabled + Enable bool `json:"enable"` + // priority Rules priority + Priority uint32 `json:"priority"` + // revision Edition information of routing rules + Revision string `json:"revision"` + // Description Simple description of rules + Description string `json:"description"` + // valid Whether the routing rules are valid and have not been deleted by logic + Valid bool `json:"flag"` + // createtime Rules creation time + CreateTime time.Time `json:"ctime"` + // modifytime Rules modify time + ModifyTime time.Time `json:"mtime"` + // enabletime The last time the rules enabled + EnableTime time.Time `json:"etime"` +} + +// RateLimit 限流规则 +type RateLimit struct { + Proto *apitraffic.Rule + ID string + ServiceID string + ServiceName string + NamespaceName string + Name string + Method string + // Labels for old compatible, will be removed later + Labels string + Priority uint32 + Rule string + Revision string + Disable bool + Valid bool + CreateTime time.Time + ModifyTime time.Time + EnableTime time.Time +} + +type ServiceContract struct { + ID string + // 所属命名空间 + Namespace string + // 所属服务名称 + Service string + // 契约名称 + Name string + // 协议,http/grpc/dubbo/thrift + Protocol string + // 契约版本 + Version string + // 信息摘要 + Revision string + // 额外描述 + Content string + // 创建时间 + CreateTime time.Time + // 更新时间 + ModifyTime time.Time + // 是否有效 + Valid bool + // ClientInterfaces 客户端主动上报的接口定义 + ClientInterfaces map[string]*InterfaceDescriptor + // ManualInterfaces 通过 OpenAPI 上报的接口定义 + ManualInterfaces map[string]*InterfaceDescriptor +} + +type InterfaceDescriptor struct { + // ID + ID string + // Name 接口名称 + Name string + // ContractID + ContractID string + // 方法名称,对应 http method/ dubbo interface func/grpc service func + Method string + // 接口名称,http path/dubbo interface/grpc service + Path string + // 接口描述信息 + Content string + // 接口信息摘要 + Revision string + // 创建来源 + Source apiservice.InterfaceDescriptor_Source + // 创建时间 + CreateTime time.Time + // 更新时间 + ModifyTime time.Time + // Valid + Valid bool +} + +// GrayRule 灰度资源 +type GrayResource struct { + Name string + MatchRule string + CreateTime time.Time + ModifyTime time.Time + CreateBy string + ModifyBy string + Valid bool +} diff --git a/store/model/service.go b/store/model/service.go new file mode 100644 index 0000000..cfb2fec --- /dev/null +++ b/store/model/service.go @@ -0,0 +1,121 @@ +/** + * 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 model + +import ( + "time" + + apimodel "github.com/polarismesh/specification/source/go/api/v1/model" + apiservice "github.com/polarismesh/specification/source/go/api/v1/service_manage" +) + +// Location cmdb信息,对应内存结构体 +type Location struct { + Proto *apimodel.Location + RegionID uint32 + ZoneID uint32 + CampusID uint32 + Valid bool +} + +type ServicePort struct { + Port uint32 + Protocol string +} + +// Service 服务数据 +type Service struct { + ID string + Name string + Namespace string + Business string + Ports string + Meta map[string]string + Comment string + Department string + CmdbMod1 string + CmdbMod2 string + CmdbMod3 string + Token string + Owner string + Revision string + Reference string + ReferFilter string + PlatformID string + Valid bool + CreateTime time.Time + ModifyTime time.Time + Mtime int64 + Ctime int64 + ServicePorts []*ServicePort + // ExportTo 服务可见性暴露设置 + ExportTo map[string]struct{} +} + +// ServiceAlias 服务别名结构体 +type ServiceAlias struct { + ID string + Alias string + AliasNamespace string + ServiceID string + Service string + Namespace string + Owner string + Comment string + CreateTime time.Time + ModifyTime time.Time + ExportTo map[string]struct{} +} + +// LocationStore 地域信息,对应数据库字段 +type LocationStore struct { + IP string + Region string + Zone string + Campus string + RegionID uint32 + ZoneID uint32 + CampusID uint32 + Flag int + ModifyTime int64 +} + +// Instance 组合了api的Instance对象 +type Instance struct { + Proto *apiservice.Instance + ServiceID string + ServicePlatformID string + // Valid Whether it is deleted by logic + Valid bool + // ModifyTime Update time of instance + ModifyTime time.Time +} + +// InstanceArgs 用于通过服务实例查询服务的参数 +type InstanceArgs struct { + Hosts []string + Ports []uint32 + Meta map[string]string +} + +type InstanceMetadataRequest struct { + InstanceID string + Revision string + Keys []string + Metadata map[string]string +}