|
| 1 | +// Copyright 2022 Linkall Inc. |
| 2 | +// |
| 3 | +// Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | +// you may not use this file except in compliance with the License. |
| 5 | +// You may obtain a copy of the License at |
| 6 | +// |
| 7 | +// http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | +// |
| 9 | +// Unless required by applicable law or agreed to in writing, software |
| 10 | +// distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | +// See the License for the specific language governing permissions and |
| 13 | +// limitations under the License. |
| 14 | + |
| 15 | +package gateway |
| 16 | + |
| 17 | +import ( |
| 18 | + "context" |
| 19 | + "fmt" |
| 20 | + ctrlpb "github.com/linkall-labs/vanus/proto/pkg/controller" |
| 21 | + "google.golang.org/grpc/credentials/insecure" |
| 22 | + "google.golang.org/protobuf/types/known/emptypb" |
| 23 | + "net" |
| 24 | + "sync" |
| 25 | + "time" |
| 26 | + |
| 27 | + "github.com/linkall-labs/vanus/observability/log" |
| 28 | + "github.com/mwitkow/grpc-proxy/proxy" |
| 29 | + "google.golang.org/grpc" |
| 30 | + "google.golang.org/grpc/codes" |
| 31 | + "google.golang.org/grpc/metadata" |
| 32 | + "google.golang.org/grpc/status" |
| 33 | +) |
| 34 | + |
| 35 | +func newCtrlProxy(port int, allowProxyMethod map[string]string, ctrlList []string) *ctrlProxy { |
| 36 | + return &ctrlProxy{ |
| 37 | + ctrlLists: ctrlList, |
| 38 | + port: port, |
| 39 | + allowProxyMethod: allowProxyMethod, |
| 40 | + ticker: time.NewTicker(time.Second), |
| 41 | + } |
| 42 | +} |
| 43 | + |
| 44 | +type ctrlProxy struct { |
| 45 | + ctrlLists []string |
| 46 | + rwMutex sync.RWMutex |
| 47 | + leaderConn *grpc.ClientConn |
| 48 | + allowProxyMethod map[string]string |
| 49 | + ticker *time.Ticker |
| 50 | + port int |
| 51 | +} |
| 52 | + |
| 53 | +func (cp *ctrlProxy) start(ctx context.Context) error { |
| 54 | + grpcServer := grpc.NewServer( |
| 55 | + grpc.UnknownServiceHandler(proxy.TransparentHandler(cp.director)), |
| 56 | + ) |
| 57 | + listen, err := net.Listen("tcp", fmt.Sprintf(":%d", cp.port)) |
| 58 | + if err != nil { |
| 59 | + return err |
| 60 | + } |
| 61 | + |
| 62 | + go cp.updateLeader(ctx) |
| 63 | + go func() { |
| 64 | + if err := grpcServer.Serve(listen); err != nil { |
| 65 | + panic("start grpc server failed: " + err.Error()) |
| 66 | + } |
| 67 | + log.Info(ctx, "the grpc server shutdown", nil) |
| 68 | + }() |
| 69 | + |
| 70 | + go func() { |
| 71 | + for { |
| 72 | + select { |
| 73 | + case <-ctx.Done(): |
| 74 | + grpcServer.GracefulStop() |
| 75 | + } |
| 76 | + } |
| 77 | + }() |
| 78 | + go cp.updateLeader(ctx) |
| 79 | + return nil |
| 80 | +} |
| 81 | + |
| 82 | +func (cp *ctrlProxy) director(ctx context.Context, fullMethodName string) (context.Context, *grpc.ClientConn, error) { |
| 83 | + md, _ := metadata.FromIncomingContext(ctx) |
| 84 | + outCtx := metadata.NewOutgoingContext(ctx, md.Copy()) |
| 85 | + |
| 86 | + if cp.leaderConn == nil { |
| 87 | + return outCtx, nil, status.Errorf(codes.Internal, "No leader founded") |
| 88 | + } |
| 89 | + |
| 90 | + _, exist := cp.allowProxyMethod[fullMethodName] |
| 91 | + if !exist { |
| 92 | + log.Warning(nil, "invalid access", map[string]interface{}{ |
| 93 | + "method": fullMethodName, |
| 94 | + }) |
| 95 | + return outCtx, nil, status.Errorf(codes.Unimplemented, "Unknown method") |
| 96 | + } |
| 97 | + |
| 98 | + cp.rwMutex.RLock() |
| 99 | + defer cp.rwMutex.RUnlock() |
| 100 | + return outCtx, cp.leaderConn, nil |
| 101 | +} |
| 102 | + |
| 103 | +func (cp *ctrlProxy) updateLeader(ctx context.Context) { |
| 104 | + defer cp.ticker.Stop() |
| 105 | + for { |
| 106 | + select { |
| 107 | + case <-ctx.Done(): |
| 108 | + return |
| 109 | + case <-cp.ticker.C: |
| 110 | + cp.rwMutex.Lock() |
| 111 | + if cp.leaderConn == nil { |
| 112 | + cp.leaderConn = getLeaderControllerGRPCConn(ctx, cp.ctrlLists...) |
| 113 | + } else { |
| 114 | + pingClient := ctrlpb.NewPingServerClient(cp.leaderConn) |
| 115 | + res, err := pingClient.Ping(ctx, &emptypb.Empty{}) |
| 116 | + if err != nil { |
| 117 | + cp.leaderConn = getLeaderControllerGRPCConn(ctx, cp.ctrlLists...) |
| 118 | + } else if res.LeaderAddr != cp.leaderConn.Target() { |
| 119 | + cp.leaderConn = getLeaderControllerGRPCConn(ctx, res.LeaderAddr) |
| 120 | + } |
| 121 | + } |
| 122 | + if cp.leaderConn == nil { |
| 123 | + log.Error(ctx, "connect to leader failed", nil) |
| 124 | + } |
| 125 | + cp.rwMutex.Unlock() |
| 126 | + } |
| 127 | + } |
| 128 | +} |
| 129 | + |
| 130 | +func getLeaderControllerGRPCConn(ctx context.Context, endpoints ...string) *grpc.ClientConn { |
| 131 | + var leaderAddr string |
| 132 | + var leaderConn *grpc.ClientConn |
| 133 | + tryConnectLeaderOnce := false |
| 134 | + for idx := range endpoints { |
| 135 | + conn := createGRPCConn(ctx, endpoints[idx]) |
| 136 | + if conn == nil { |
| 137 | + continue |
| 138 | + } |
| 139 | + pingClient := ctrlpb.NewPingServerClient(conn) |
| 140 | + res, err := pingClient.Ping(ctx, &emptypb.Empty{}) |
| 141 | + if err != nil { |
| 142 | + log.Warning(ctx, "ping controller failed", map[string]interface{}{ |
| 143 | + "endpoint": endpoints[idx], |
| 144 | + }) |
| 145 | + continue |
| 146 | + } |
| 147 | + leaderAddr = res.LeaderAddr |
| 148 | + if leaderAddr == endpoints[idx] { |
| 149 | + leaderConn = conn |
| 150 | + tryConnectLeaderOnce = false |
| 151 | + } else { |
| 152 | + _ = conn.Close() |
| 153 | + } |
| 154 | + break |
| 155 | + } |
| 156 | + |
| 157 | + if leaderAddr == "" { |
| 158 | + return nil |
| 159 | + } |
| 160 | + |
| 161 | + if leaderConn != nil { |
| 162 | + return leaderConn |
| 163 | + } else if !tryConnectLeaderOnce { |
| 164 | + leaderConn = createGRPCConn(ctx, leaderAddr) |
| 165 | + } |
| 166 | + |
| 167 | + if leaderConn == nil { |
| 168 | + log.Error(ctx, "ping controller failed", nil) |
| 169 | + return nil |
| 170 | + } |
| 171 | + return leaderConn |
| 172 | +} |
| 173 | + |
| 174 | +func createGRPCConn(ctx context.Context, addr string) *grpc.ClientConn { |
| 175 | + if addr == "" { |
| 176 | + return nil |
| 177 | + } |
| 178 | + var err error |
| 179 | + var opts []grpc.DialOption |
| 180 | + opts = append(opts, grpc.WithTransportCredentials(insecure.NewCredentials())) |
| 181 | + opts = append(opts, grpc.WithBlock()) |
| 182 | + ctx, cancel := context.WithCancel(ctx) |
| 183 | + timeout := false |
| 184 | + go func() { |
| 185 | + ticker := time.Tick(time.Second) |
| 186 | + select { |
| 187 | + case <-ctx.Done(): |
| 188 | + case <-ticker: |
| 189 | + cancel() |
| 190 | + timeout = true |
| 191 | + } |
| 192 | + }() |
| 193 | + conn, err := grpc.DialContext(ctx, addr, opts...) |
| 194 | + cancel() |
| 195 | + if timeout { |
| 196 | + log.Warning(ctx, "dial to controller timeout, try to another controller", map[string]interface{}{ |
| 197 | + "endpoint": addr, |
| 198 | + }) |
| 199 | + return nil |
| 200 | + } else if err != nil { |
| 201 | + log.Warning(ctx, "dial to controller failed, try to another controller", map[string]interface{}{ |
| 202 | + "endpoint": addr, |
| 203 | + }) |
| 204 | + return nil |
| 205 | + } |
| 206 | + return conn |
| 207 | +} |
0 commit comments