diff --git a/api/provider_impl.go b/api/provider_impl.go index 9c96546d..957ea500 100644 --- a/api/provider_impl.go +++ b/api/provider_impl.go @@ -38,6 +38,7 @@ func (c *providerAPI) RegisterInstance(instance *InstanceRegisterRequest) (*mode if err := instance.Validate(); err != nil { return nil, err } + instance.AutoHeartbeat = true return c.context.GetEngine().SyncRegister(&instance.InstanceRegisterRequest) } diff --git a/examples/extensions/zeroprotect/main.go b/examples/extensions/zeroprotect/main.go deleted file mode 100644 index 0bde4edc..00000000 --- a/examples/extensions/zeroprotect/main.go +++ /dev/null @@ -1,223 +0,0 @@ -/** - * Tencent is pleased to support the open source community by making polaris-go 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 main - -import ( - "encoding/json" - "flag" - "log" - "strconv" - "sync" - "time" - - "github.com/polarismesh/polaris-go" - "github.com/polarismesh/polaris-go/pkg/config" - "github.com/polarismesh/polaris-go/plugin/servicerouter/zeroprotect" -) - -var ( - namespace string - service string - token string - insCount int64 - basePort = 8080 -) - -func initArgs() { - flag.StringVar(&namespace, "namespace", "default", "namespace") - flag.StringVar(&service, "service", "DiscoverEchoServer", "service") - // 当北极星开启鉴权时,需要配置此参数完成相关的权限检查 - flag.StringVar(&token, "token", "", "token") - flag.Int64Var(&insCount, "ins_count", 10, "ins_count") -} - -func main() { - initArgs() - - sdkCtx, err := polaris.NewSDKContext() - if err != nil { - log.Fatal(err) - } - provider := polaris.NewProviderAPIByContext(sdkCtx) - consumer := polaris.NewConsumerAPIByContext(sdkCtx) - router := polaris.NewRouterAPIByContext(sdkCtx) - - wait, _ := createInstances(provider) - // 等待 - wait.Wait() - // 等待 SDK 和 服务端的数据同步,等待两个周期确保一定可以获取到最新的数据 - time.Sleep(5 * time.Second) - - zeroprotectIns := map[string]struct{}{} - allReq := &polaris.GetAllInstancesRequest{} - allReq.Service = service - allReq.Namespace = namespace - resp, err := consumer.GetAllInstances(allReq) - if err != nil { - log.Fatal(err) - } - lastHeartbeatTime := int64(0) - // 实例全部不健康 - for i := range resp.GetInstances() { - ins := resp.GetInstances()[i] - if ins.IsHealthy() { - log.Fatalf("ins: %s still health", ins.GetId()) - } - beatTime := ins.GetMetadata()[zeroprotect.MetadataInstanceLastHeartbeatTime] - sec, _ := strconv.ParseInt(beatTime, 10, 64) - if lastHeartbeatTime <= sec { - lastHeartbeatTime = sec - } - } - for i := range resp.GetInstances() { - ins := resp.GetInstances()[i] - beatTime := ins.GetMetadata()[zeroprotect.MetadataInstanceLastHeartbeatTime] - sec, _ := strconv.ParseInt(beatTime, 10, 64) - if zeroprotect.NeedZeroProtect(lastHeartbeatTime, sec, 2) { - zeroprotectIns[ins.GetId()] = struct{}{} - } - } - - log.Printf("====== expect zero protect ======\n%s\n====== expect zero protect ======", zeroprotectIns) - - useConsumerAPI(consumer, zeroprotectIns) - useRouterAPI(consumer, router, zeroprotectIns) -} - -func useConsumerAPI(consumer polaris.ConsumerAPI, zeroprotectIns map[string]struct{}) { - insReq := &polaris.GetInstancesRequest{} - insReq.Service = service - insReq.Namespace = namespace - - // 由于 polaris.yaml afterChain 配置的为 zeroProtectRouter,因此这里不会在走原先默认的全死全活路由策略 - resp, err := consumer.GetInstances(insReq) - if err != nil { - log.Fatal(err) - } - - insJson, _ := json.Marshal(resp.GetInstances()) - log.Printf("====== useConsumerAPI zero protect ======\n%s\n====== useConsumerAPI zero protect ======", string(insJson)) - - if len(resp.GetInstances()) == int(insCount) { - log.Fatal("zero protect fail") - } - - if len(zeroprotectIns) != len(resp.GetInstances()) { - log.Fatalf("zero protect recover instance count:%d not expect:%d", len(resp.GetInstances()), len(zeroprotectIns)) - } -} - -func useRouterAPI(consumer polaris.ConsumerAPI, router polaris.RouterAPI, zeroprotectIns map[string]struct{}) { - allReq := &polaris.GetAllInstancesRequest{} - allReq.Service = service - allReq.Namespace = namespace - resp, err := consumer.GetAllInstances(allReq) - if err != nil { - log.Fatal(err) - } - // 实例全部不健康 - for i := range resp.GetInstances() { - ins := resp.GetInstances()[i] - if ins.IsHealthy() { - log.Fatalf("ins: %s still health", ins.GetId()) - } - } - - routeReq := &polaris.ProcessRoutersRequest{} - routeReq.DstInstances = resp - // 默认配置文件走 zeroProtectRouter - routeReq.Routers = []string{} - routeResp, err := router.ProcessRouters(routeReq) - if err != nil { - log.Fatal(err) - } - - insJson, _ := json.Marshal(routeResp.GetInstances()) - log.Printf("====== useRouterAPI zero protect ======\n%s\n====== useRouterAPI zero protect ======", string(insJson)) - - if len(routeResp.GetInstances()) == int(insCount) { - log.Fatal("zero protect fail") - } - - if len(zeroprotectIns) != len(routeResp.GetInstances()) { - log.Fatalf("zero protect recover instance count:%d not expect:%d", len(routeResp.GetInstances()), len(zeroprotectIns)) - } - routeReq = &polaris.ProcessRoutersRequest{} - routeReq.DstInstances = resp - // 显示设置走全死全活路由 - routeReq.Routers = []string{config.DefaultServiceRouterFilterOnly} - routeResp, err = router.ProcessRouters(routeReq) - if err != nil { - log.Fatal(err) - } - - insJson, _ = json.Marshal(routeResp.GetInstances()) - log.Printf("====== useRouterAPI not zero protect ======\n%s\n====== useRouterAPI not zero protect ======", string(insJson)) - if len(routeResp.GetInstances()) != int(insCount) { - log.Fatal("filterOnly fail") - } - - if len(zeroprotectIns) == len(routeResp.GetInstances()) { - log.Fatal("can't use zero protect recover instance") - } -} - -func createInstances(provider polaris.ProviderAPI) (*sync.WaitGroup, *sync.Map) { - wait := &sync.WaitGroup{} - wait.Add(int(insCount)) - - beatTime := &sync.Map{} - for i := 0; i < int(insCount); i++ { - registerRequest := &polaris.InstanceRegisterRequest{} - registerRequest.Service = service - registerRequest.Namespace = namespace - registerRequest.Host = "127.0.0.1" - registerRequest.Port = basePort + i - registerRequest.ServiceToken = token - registerRequest.SetTTL(2) - resp, err := provider.Register(registerRequest) - if err != nil { - log.Fatal(err) - } - // 维持三次心跳 - go func(id string, port, a int) { - defer wait.Done() - for tick := 0; tick < 2*a; tick++ { - beatRequest := &polaris.InstanceHeartbeatRequest{} - beatRequest.InstanceID = id - beatRequest.Service = service - beatRequest.Namespace = namespace - beatRequest.Host = "127.0.0.1" - beatRequest.Port = port - - if err := provider.Heartbeat(beatRequest); err != nil { - log.Printf("%s heartbeat fail : %+v", beatRequest, err) - } - - beatTime.Store(id, time.Now().Unix()) - time.Sleep(2 * time.Second) - } - // 等待实例转为不健康 - for tick := 0; tick < 3; tick++ { - time.Sleep(3 * time.Second) - } - }(resp.InstanceID, basePort+i, i) - } - - return wait, beatTime -} diff --git a/examples/extensions/zeroprotect/polaris.yaml b/examples/extensions/zeroprotect/polaris.yaml deleted file mode 100644 index f5921f75..00000000 --- a/examples/extensions/zeroprotect/polaris.yaml +++ /dev/null @@ -1,27 +0,0 @@ -global: - serverConnector: - addresses: - - 127.0.0.1:8091 - statReporter: - enable: true - chain: - - prometheus - # - pushgateway - plugin: - prometheus: - type: pull - metricPort: 0 -consumer: - #描述:服务路由相关配置 - serviceRouter: - # 服务路由链 - chain: - # 基于主调和被调服务规则的路由策略(默认的路由策略) - - ruleBasedRouter - # 就近路由策略 - - nearbyBasedRouter - afterChain: - # 兜底路由,默认存在 - # - filterOnlyRouter - # 开启零实例保护路由,和 filterOnlyRouter 互斥 - - zeroProtectRouter \ No newline at end of file diff --git a/examples/mock/Dockerfile b/examples/mock/Dockerfile new file mode 100644 index 00000000..29c9af4e --- /dev/null +++ b/examples/mock/Dockerfile @@ -0,0 +1,19 @@ +FROM alpine:3.13.6 + +RUN sed -i 's!http://dl-cdn.alpinelinux.org/!https://mirrors.tencent.com/!g' /etc/apk/repositories + +RUN set -eux && \ + apk add tcpdump && \ + apk add tzdata && \ + apk add busybox-extras && \ + apk add curl && \ + apk add bash && \ + cp /usr/share/zoneinfo/Asia/Shanghai /etc/localtime && \ + echo "Asia/Shanghai" > /etc/timezone && \ + date + +COPY provider /root/provider + +WORKDIR /root + +CMD ["/root/provider", "-port", "28080"] \ No newline at end of file diff --git a/examples/extensions/zeroprotect/go.mod b/examples/mock/go.mod similarity index 71% rename from examples/extensions/zeroprotect/go.mod rename to examples/mock/go.mod index e89d46a4..c7ed0059 100644 --- a/examples/extensions/zeroprotect/go.mod +++ b/examples/mock/go.mod @@ -1,10 +1,8 @@ -module github.com/polarismesh/polaris-go-zeroprotect +module github.com/polarismesh/polaris-go-quickstart-provider go 1.17 -replace github.com/polarismesh/polaris-go => ../../../ - -require github.com/polarismesh/polaris-go v0.0.0-00010101000000-000000000000 +require github.com/polarismesh/polaris-go v1.4.2 require ( github.com/beorn7/perks v1.0.1 // indirect @@ -12,21 +10,21 @@ require ( github.com/dlclark/regexp2 v1.7.0 // indirect github.com/golang/protobuf v1.5.2 // indirect github.com/google/uuid v1.3.0 // indirect - github.com/hashicorp/errwrap v1.0.0 // indirect + github.com/hashicorp/errwrap v1.1.0 // indirect github.com/hashicorp/go-multierror v1.1.1 // indirect - github.com/matttproud/golang_protobuf_extensions v1.0.1 // indirect + github.com/matttproud/golang_protobuf_extensions v1.0.2-0.20181231171920-c182affec369 // indirect github.com/mitchellh/go-homedir v1.1.0 // indirect github.com/modern-go/reflect2 v1.0.2 // indirect github.com/natefinch/lumberjack v2.0.0+incompatible // indirect github.com/pkg/errors v0.9.1 // indirect - github.com/polarismesh/specification v1.3.2-alpha.2 // indirect + github.com/polarismesh/specification v1.4.1 // indirect github.com/prometheus/client_golang v1.12.2 // indirect github.com/prometheus/client_model v0.2.0 // indirect github.com/prometheus/common v0.32.1 // indirect github.com/prometheus/procfs v0.7.3 // indirect github.com/spaolacci/murmur3 v1.1.0 // indirect - go.uber.org/atomic v1.7.0 // indirect - go.uber.org/multierr v1.6.0 // indirect + go.uber.org/atomic v1.10.0 // indirect + go.uber.org/multierr v1.8.0 // indirect go.uber.org/zap v1.21.0 // indirect golang.org/x/net v0.2.0 // indirect golang.org/x/sys v0.2.0 // indirect @@ -36,3 +34,5 @@ require ( google.golang.org/protobuf v1.28.1 // indirect gopkg.in/yaml.v2 v2.4.0 // indirect ) + +replace github.com/polarismesh/polaris-go => ../../ diff --git a/examples/extensions/zeroprotect/go.sum b/examples/mock/go.sum similarity index 98% rename from examples/extensions/zeroprotect/go.sum rename to examples/mock/go.sum index 8f345102..d93306f5 100644 --- a/examples/extensions/zeroprotect/go.sum +++ b/examples/mock/go.sum @@ -171,7 +171,6 @@ github.com/BurntSushi/toml v0.3.1 h1:WXkYYl6Yr3qBf1K79EBnL4mak0OimBfB0XUf9Vl28OQ github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU= github.com/BurntSushi/xgb v0.0.0-20160522181843-27f122750802/go.mod h1:IVnqGOEym/WlBOVXweHU+Q+/VP0lqqI8lqeDx9IjBqo= github.com/OneOfOne/xxhash v1.2.2/go.mod h1:HSdplMjZKSmBqAxg5vPj2TmRDmfkzw+cTzAElWljhcU= -github.com/agiledragon/gomonkey v2.0.2+incompatible h1:eXKi9/piiC3cjJD1658mEE2o3NjkJ5vDLgYjCQu0Xlw= github.com/agiledragon/gomonkey v2.0.2+incompatible/go.mod h1:2NGfXu1a80LLr2cmWXGBDaHEjb1idR6+FVlX5T3D9hw= github.com/alecthomas/template v0.0.0-20160405071501-a0175ee3bccc/go.mod h1:LOuyumcjzFXgccqObfd/Ljyb9UuFJ6TxHnclSeseNhc= github.com/alecthomas/template v0.0.0-20190718012654-fb15b899a751/go.mod h1:LOuyumcjzFXgccqObfd/Ljyb9UuFJ6TxHnclSeseNhc= @@ -321,11 +320,11 @@ github.com/googleapis/gax-go/v2 v2.3.0/go.mod h1:b8LNqSzNabLiUpXKkY7HAR5jr6bIT99 github.com/googleapis/gax-go/v2 v2.4.0/go.mod h1:XOTVJ59hdnfJLIP/dh8n5CGryZR2LxK9wbMD5+iXC6c= github.com/googleapis/gax-go/v2 v2.5.1/go.mod h1:h6B0KMMFNtI2ddbGJn3T3ZbwkeT6yqEF02fYlzkUCyo= github.com/googleapis/go-type-adapters v1.0.0/go.mod h1:zHW75FOG2aur7gAO2B+MLby+cLsWGBF62rFAi7WjWO4= -github.com/gopherjs/gopherjs v0.0.0-20181017120253-0766667cb4d1 h1:EGx4pi6eqNxGaHF6qqu48+N2wcFQ5qg5FXgOdqsJ5d8= github.com/gopherjs/gopherjs v0.0.0-20181017120253-0766667cb4d1/go.mod h1:wJfORRmW1u3UXTncJ5qlYoELFm8eSnnEO6hX4iZ3EWY= github.com/grpc-ecosystem/grpc-gateway v1.16.0/go.mod h1:BDjrQk3hbvj6Nolgz8mAMFbcEtjT1g+wF4CSlocrBnw= -github.com/hashicorp/errwrap v1.0.0 h1:hLrqtEDnRye3+sgx6z4qVLNuviH3MR5aQ0ykNJa/UYA= github.com/hashicorp/errwrap v1.0.0/go.mod h1:YH+1FKiLXxHSkmPseP+kNlulaMuP3n2brvKWEqk/Jc4= +github.com/hashicorp/errwrap v1.1.0 h1:OxrOeh75EUXMY8TBjag2fzXGZ40LB6IKw45YeGUDY2I= +github.com/hashicorp/errwrap v1.1.0/go.mod h1:YH+1FKiLXxHSkmPseP+kNlulaMuP3n2brvKWEqk/Jc4= github.com/hashicorp/go-multierror v1.1.1 h1:H5DkEtf6CXdFp0N0Em5UCwQpXMWke8IA0+lD48awMYo= github.com/hashicorp/go-multierror v1.1.1/go.mod h1:iw975J/qwKPdAO1clOe2L8331t/9/fmwbPZ6JB6eMoM= github.com/hashicorp/golang-lru v0.5.0/go.mod h1:/m3WP610KZHVQ1SGc6re/UDhFvYD7pJ4Ao+sR/qLZy8= @@ -339,7 +338,6 @@ github.com/json-iterator/go v1.1.11/go.mod h1:KdQUCv79m/52Kvf8AW2vK1V8akMuk1QjK/ github.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo= github.com/jstemmer/go-junit-report v0.0.0-20190106144839-af01ea7f8024/go.mod h1:6v2b51hI/fHJwM22ozAgKL4VKDeJcHhJFhtBdhmNjmU= github.com/jstemmer/go-junit-report v0.9.1/go.mod h1:Brl9GWCQeLvo8nXZwPNNblvFj/XSXhF0NWZEnDohbsk= -github.com/jtolds/gls v4.20.0+incompatible h1:xdiiI2gbIgH/gLH7ADydsJ1uDOEzR8yvV7C0MuV77Wo= github.com/jtolds/gls v4.20.0+incompatible/go.mod h1:QJZ7F/aHp+rZTRtaJ1ow/lLfFfVYBRgL+9YlvaHOwJU= github.com/julienschmidt/httprouter v1.2.0/go.mod h1:SYymIcj16QtmaHHD7aYtjjsJG7VTCxuUUipMqKk8s4w= github.com/julienschmidt/httprouter v1.3.0/go.mod h1:JR6WtHb+2LUe8TCKY3cZOxFyyO8IZAc4RVcycCCAKdM= @@ -353,8 +351,9 @@ github.com/kr/pretty v0.2.1/go.mod h1:ipq/a2n7PKx3OHsz4KJII5eveXtPO4qwEXGdVfWzfn github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ= github.com/kr/text v0.1.0 h1:45sCR5RtlFHMR4UwH9sdQ5TC8v0qDQCHnXt+kaKSTVE= github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI= -github.com/matttproud/golang_protobuf_extensions v1.0.1 h1:4hp9jkHxhMHkqkrB3Ix0jegS5sx/RkqARlsWZ6pIwiU= github.com/matttproud/golang_protobuf_extensions v1.0.1/go.mod h1:D8He9yQNgCq6Z5Ld7szi9bcBfOoFv/3dc6xSMkL2PC0= +github.com/matttproud/golang_protobuf_extensions v1.0.2-0.20181231171920-c182affec369 h1:I0XW9+e1XWDxdcEniV4rQAIOPUGDq67JSCiRCgGCZLI= +github.com/matttproud/golang_protobuf_extensions v1.0.2-0.20181231171920-c182affec369/go.mod h1:BSXmuO+STAnVfrANrmjBb36TMTDstsz7MSK+HVaYKv4= github.com/mitchellh/go-homedir v1.1.0 h1:lukF9ziXFxDFPkA1vsr5zpc1XuPDn/wFntq5mG+4E0Y= github.com/mitchellh/go-homedir v1.1.0/go.mod h1:SfyaCUpYCn1Vlf4IUYiD9fPX4A5wJrkLzIz1N1q0pr0= github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= @@ -373,8 +372,8 @@ github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4= github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= -github.com/polarismesh/specification v1.3.2-alpha.2 h1:cMghyvCnRVM5ca2kYCGHOgIIxVnokiMvw0720q8a8RA= -github.com/polarismesh/specification v1.3.2-alpha.2/go.mod h1:rDvMMtl5qebPmqiBLNa5Ps0XtwkP31ZLirbH4kXA0YU= +github.com/polarismesh/specification v1.4.1 h1:lTZqeyUhhWuKyr6NDKBwmUrNfcUDvKLxWT/uOq71T5A= +github.com/polarismesh/specification v1.4.1/go.mod h1:rDvMMtl5qebPmqiBLNa5Ps0XtwkP31ZLirbH4kXA0YU= github.com/prometheus/client_golang v0.9.1/go.mod h1:7SWBe2y4D6OKWSNQJUaRYU/AaXPKyh/dDVn+NZz0KFw= github.com/prometheus/client_golang v1.0.0/go.mod h1:db9x61etRT2tGnBNRi70OPL5FsnadC4Ky3P0J6CfImo= github.com/prometheus/client_golang v1.7.1/go.mod h1:PY5Wy2awLA44sXw4AOSfFBetzPP4j5+D6mVACh+pe2M= @@ -402,9 +401,7 @@ github.com/rogpeppe/go-internal v1.3.0/go.mod h1:M8bDsm7K2OlrFYOpmOWEs/qY81heoFR github.com/sirupsen/logrus v1.2.0/go.mod h1:LxeOpSwHxABJmUn/MG1IvRgCAasNZTLOkJPxbbu5VWo= github.com/sirupsen/logrus v1.4.2/go.mod h1:tLMulIdttU9McNUspp0xgXVQah82FyeX6MwdIuYE2rE= github.com/sirupsen/logrus v1.6.0/go.mod h1:7uNnSEd1DgxDLC74fIahvMZmmYsHGZGEOFrfsX/uA88= -github.com/smartystreets/assertions v1.2.0 h1:42S6lae5dvLc7BrLu/0ugRtcFVjoJNMC/N3yZFZkDFs= github.com/smartystreets/assertions v1.2.0/go.mod h1:tcbTF8ujkAEcZ8TElKY+i30BzYlVhC/LOxJk7iOWnoo= -github.com/smartystreets/goconvey v1.7.2 h1:9RBaZCeXEQ3UselpuwUQHltGVXvdwm6cv1hgR6gDIPg= github.com/smartystreets/goconvey v1.7.2/go.mod h1:Vw0tHAZW6lzCRk3xgdin6fKYcG+G3Pg9vgXWeJpQFMM= github.com/spaolacci/murmur3 v0.0.0-20180118202830-f09979ecbc72/go.mod h1:JwIasOWyU6f++ZhiEuf87xNszmSA2myDM2Kzu9HwQUA= github.com/spaolacci/murmur3 v1.1.0 h1:7c1g84S4BPRrfL5Xrdp6fOJ206sU9y293DDHaoy0bLI= @@ -437,12 +434,14 @@ go.opencensus.io v0.22.4/go.mod h1:yxeiOL68Rb0Xd1ddK5vPZ/oVn4vY4Ynel7k9FzqtOIw= go.opencensus.io v0.22.5/go.mod h1:5pWMHQbX5EPX2/62yrJeAkowc+lfs/XD7Uxpq3pI6kk= go.opencensus.io v0.23.0/go.mod h1:XItmlyltB5F7CS4xOC1DcqMoFqwtC6OG2xF7mCv7P7E= go.opentelemetry.io/proto/otlp v0.7.0/go.mod h1:PqfVotwruBrMGOCsRd/89rSnXhoiJIqeYNgFYFoEGnI= -go.uber.org/atomic v1.7.0 h1:ADUqmZGgLDDfbSL9ZmPxKTybcoEYHgpYfELNoN+7hsw= go.uber.org/atomic v1.7.0/go.mod h1:fEN4uk6kAWBTFdckzkM89CLk9XfWZrxpCo0nPH17wJc= +go.uber.org/atomic v1.10.0 h1:9qC72Qh0+3MqyJbAn8YU5xVq1frD8bn3JtD2oXtafVQ= +go.uber.org/atomic v1.10.0/go.mod h1:LUxbIzbOniOlMKjJjyPfpl4v+PKK2cNJn91OQbhoJI0= go.uber.org/goleak v1.1.11 h1:wy28qYRKZgnJTxGxvye5/wgWr1EKjmUDGYox5mGlRlI= go.uber.org/goleak v1.1.11/go.mod h1:cwTWslyiVhfpKIDGSZEM2HlOvcqm+tG4zioyIeLoqMQ= -go.uber.org/multierr v1.6.0 h1:y6IPFStTAIT5Ytl7/XYmHvzXQ7S3g/IeZW9hyZ5thw4= go.uber.org/multierr v1.6.0/go.mod h1:cdWPpRnG4AhwMwsgIHip0KRBQjJy5kYEpYjJxpXp9iU= +go.uber.org/multierr v1.8.0 h1:dg6GjLku4EH+249NNmoIciG9N/jURbDG+pFlTkhzIC8= +go.uber.org/multierr v1.8.0/go.mod h1:7EAYxJLBy9rStEaz58O2t4Uvip6FSURkq8/ppBp95ak= go.uber.org/zap v1.21.0 h1:WefMeulhovoZ2sYXz7st6K0sLj7bBhpiFaud4r4zST8= go.uber.org/zap v1.21.0/go.mod h1:wjWOCqI0f2ZZrJF/UufIOkiC8ii6tm1iqIsLo76RfJw= golang.org/x/crypto v0.0.0-20180904163835-0709b304e793/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4= diff --git a/examples/mock/main.go b/examples/mock/main.go new file mode 100644 index 00000000..839473dc --- /dev/null +++ b/examples/mock/main.go @@ -0,0 +1,166 @@ +/** + * Tencent is pleased to support the open source community by making polaris-go 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 main + +import ( + "context" + "flag" + "log" + "os" + "os/signal" + "syscall" + + "github.com/polarismesh/polaris-go" + "github.com/polarismesh/polaris-go/pkg/model" +) + +var ( + namespace string + service string +) + +func initArgs() { + flag.StringVar(&namespace, "namespace", "default", "namespace") + flag.StringVar(&service, "service", "DiscoverEchoServer", "service") +} + +// PolarisProvider is an example of provider +type PolarisProvider struct { + provider polaris.ProviderAPI + namespace string + service string + cancel context.CancelFunc +} + +// Run starts the provider +func (svr *PolarisProvider) Run() { + ctx, cancel := context.WithCancel(context.Background()) + svr.registerService() + go svr.watchInstances(ctx) + svr.cancel = cancel +} + +func (svr *PolarisProvider) watchInstances(ctx context.Context) { + consumer := polaris.NewConsumerAPIByContext(svr.provider.SDKContext()) + rsp, err := consumer.WatchService(&polaris.WatchServiceRequest{ + WatchServiceRequest: model.WatchServiceRequest{ + Key: model.ServiceKey{ + Namespace: namespace, + Service: service, + }, + }, + }) + if err != nil { + panic(err)0 + } + + for { + select { + case <-ctx.Done(): + return + case <-rsp.EventChannel: + healthCnt := 0 + insRsp, err := consumer.GetAllInstances(&polaris.GetAllInstancesRequest{ + GetAllInstancesRequest: model.GetAllInstancesRequest{ + Namespace: namespace, + Service: service, + }, + }) + if err != nil { + log.Println(err.Error()) + continue + } + + for i := range insRsp.Instances { + if insRsp.Instances[i].IsHealthy() { + healthCnt++ + } + } + log.Printf("health count: %d, total count: %d", healthCnt, len(insRsp.Instances)) + } + } +} + +func (svr *PolarisProvider) registerService() { + log.Printf("start to invoke register operation") + registerRequest := &polaris.InstanceRegisterRequest{} + registerRequest.Service = service + registerRequest.Namespace = namespace + registerRequest.Host = os.Getenv("INSTANCE_IP") + registerRequest.Port = 8080 + registerRequest.SetTTL(5) + resp, err := svr.provider.RegisterInstance(registerRequest) + if err != nil { + log.Fatalf("fail to register instance, err is %v", err) + } + log.Printf("register response: instanceId %s", resp.InstanceID) +} + +func (svr *PolarisProvider) deregisterService() { + log.Printf("start to invoke deregister operation") + deregisterRequest := &polaris.InstanceDeRegisterRequest{} + deregisterRequest.Service = service + deregisterRequest.Namespace = namespace + deregisterRequest.Host = os.Getenv("INSTANCE_IP") + deregisterRequest.Port = 8080 + if err := svr.provider.Deregister(deregisterRequest); err != nil { + log.Fatalf("fail to deregister instance, err is %v", err) + } + log.Printf("deregister successfully.") +} + +func (svr *PolarisProvider) runMainLoop() { + ch := make(chan os.Signal, 1) + signal.Notify(ch, []os.Signal{ + syscall.SIGINT, syscall.SIGTERM, + syscall.SIGSEGV, + }...) + + for s := range ch { + log.Printf("catch signal(%+v), stop servers", s) + svr.deregisterService() + svr.cancel() + return + } +} + +func main() { + initArgs() + flag.Parse() + if len(namespace) == 0 || len(service) == 0 { + log.Print("namespace and service are required") + return + } + // provider, err := polaris.NewProviderAPI() + // 或者使用以下方法,则不需要创建配置文件 + provider, err := polaris.NewProviderAPIByAddress(os.Getenv("POLARIS_ADDRESS")) + + if err != nil { + log.Fatalf("fail to create providerAPI, err is %v", err) + } + defer provider.Destroy() + + svr := &PolarisProvider{ + provider: provider, + namespace: namespace, + service: service, + } + + svr.Run() + svr.runMainLoop() +} diff --git a/examples/mock/provider b/examples/mock/provider new file mode 100755 index 00000000..a3ea34a7 Binary files /dev/null and b/examples/mock/provider differ diff --git a/examples/quickstart/provider/isolate.sh b/examples/quickstart/provider/isolate.sh index 0e9df827..fd77fe68 100644 --- a/examples/quickstart/provider/isolate.sh +++ b/examples/quickstart/provider/isolate.sh @@ -1,5 +1,5 @@ #!/bin/bash -data="[{\"service\":\"${INSTANCE_SERVICE}\",\"namespace\":\"${INSTANCE_NAMESPACE}\",\"host\":\"${INSTANCE_IP}\",\"port\":\"${INSTANCE_PORT}\",\"isolate\":true}]" +data="[{\"service\":\"${INSTANCE_SERVICE}\",\"namespace\":\"${INSTANCE_NAMESPACE}\",\"host\":\"${INSTANCE_IP}\",\"port\":\"${INSTANCE_PORT}\",\"weight\":0}]" echo "${data}" curl -H "X-Polaris-Token; ${POLARIS_TOKEN}" -H 'Content-Type: application/json' -X PUT -d "${data}" "http://${POLARIS_OPEN_API}/naming/v1/instances"