khenaidoo | 2672188 | 2021-08-11 17:42:52 -0400 | [diff] [blame] | 1 | /* |
| 2 | * Copyright 2021-present Open Networking Foundation |
| 3 | * |
| 4 | * Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | * you may not use this file except in compliance with the License. |
| 6 | * You may obtain a copy of the License at |
| 7 | * |
| 8 | * http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | * |
| 10 | * Unless required by applicable law or agreed to in writing, software |
| 11 | * distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | * See the License for the specific language governing permissions and |
| 14 | * limitations under the License. |
| 15 | */ |
| 16 | package grpc |
| 17 | |
| 18 | import ( |
| 19 | "context" |
| 20 | "fmt" |
| 21 | "reflect" |
| 22 | "strings" |
| 23 | "sync" |
| 24 | "time" |
| 25 | |
| 26 | grpc_middleware "github.com/grpc-ecosystem/go-grpc-middleware" |
| 27 | grpc_opentracing "github.com/grpc-ecosystem/go-grpc-middleware/tracing/opentracing" |
| 28 | "github.com/opencord/voltha-lib-go/v7/pkg/log" |
| 29 | "github.com/opencord/voltha-lib-go/v7/pkg/probe" |
khenaidoo | b950321 | 2021-12-08 14:22:21 -0500 | [diff] [blame^] | 30 | "github.com/opencord/voltha-protos/v5/go/common" |
khenaidoo | a5feb8e | 2021-10-19 17:29:22 -0400 | [diff] [blame] | 31 | "github.com/opencord/voltha-protos/v5/go/core_service" |
| 32 | "github.com/opencord/voltha-protos/v5/go/olt_inter_adapter_service" |
| 33 | "github.com/opencord/voltha-protos/v5/go/onu_inter_adapter_service" |
khenaidoo | 2672188 | 2021-08-11 17:42:52 -0400 | [diff] [blame] | 34 | "google.golang.org/grpc" |
| 35 | "google.golang.org/grpc/keepalive" |
| 36 | ) |
| 37 | |
| 38 | type event byte |
| 39 | type state byte |
khenaidoo | b950321 | 2021-12-08 14:22:21 -0500 | [diff] [blame^] | 40 | type SetAndTestServiceHandler func(context.Context, *grpc.ClientConn, *common.Connection) interface{} |
khenaidoo | 2672188 | 2021-08-11 17:42:52 -0400 | [diff] [blame] | 41 | type RestartedHandler func(ctx context.Context, endPoint string) error |
| 42 | |
| 43 | type contextKey string |
| 44 | |
| 45 | func (c contextKey) String() string { |
| 46 | return string(c) |
| 47 | } |
| 48 | |
| 49 | var ( |
| 50 | grpcMonitorContextKey = contextKey("grpc-monitor") |
| 51 | ) |
| 52 | |
| 53 | const ( |
| 54 | grpcBackoffInitialInterval = "GRPC_BACKOFF_INITIAL_INTERVAL" |
| 55 | grpcBackoffMaxInterval = "GRPC_BACKOFF_MAX_INTERVAL" |
| 56 | grpcBackoffMaxElapsedTime = "GRPC_BACKOFF_MAX_ELAPSED_TIME" |
| 57 | grpcMonitorInterval = "GRPC_MONITOR_INTERVAL" |
| 58 | ) |
| 59 | |
| 60 | const ( |
| 61 | DefaultBackoffInitialInterval = 100 * time.Millisecond |
| 62 | DefaultBackoffMaxInterval = 5 * time.Second |
| 63 | DefaultBackoffMaxElapsedTime = 0 * time.Second // No time limit |
| 64 | DefaultGRPCMonitorInterval = 5 * time.Second |
| 65 | ) |
| 66 | |
| 67 | const ( |
| 68 | connectionErrorSubString = "SubConns are in TransientFailure" |
| 69 | connectionClosedSubstring = "client connection is closing" |
| 70 | connectionError = "connection error" |
| 71 | connectionSystemNotReady = "system is not ready" |
| 72 | ) |
| 73 | |
| 74 | const ( |
| 75 | eventConnecting = event(iota) |
| 76 | eventConnected |
| 77 | eventDisconnected |
| 78 | eventStopped |
| 79 | eventError |
| 80 | |
| 81 | stateConnected = state(iota) |
| 82 | stateConnecting |
| 83 | stateDisconnected |
| 84 | ) |
| 85 | |
| 86 | type Client struct { |
khenaidoo | b950321 | 2021-12-08 14:22:21 -0500 | [diff] [blame^] | 87 | clientEndpoint string |
| 88 | serverEndPoint string |
khenaidoo | 2672188 | 2021-08-11 17:42:52 -0400 | [diff] [blame] | 89 | connection *grpc.ClientConn |
| 90 | connectionLock sync.RWMutex |
| 91 | stateLock sync.RWMutex |
| 92 | state state |
| 93 | service interface{} |
| 94 | events chan event |
| 95 | onRestart RestartedHandler |
| 96 | backoffInitialInterval time.Duration |
| 97 | backoffMaxInterval time.Duration |
| 98 | backoffMaxElapsedTime time.Duration |
khenaidoo | 2672188 | 2021-08-11 17:42:52 -0400 | [diff] [blame] | 99 | monitorInterval time.Duration |
khenaidoo | 2672188 | 2021-08-11 17:42:52 -0400 | [diff] [blame] | 100 | done bool |
| 101 | livenessCallback func(timestamp time.Time) |
| 102 | } |
| 103 | |
| 104 | type ClientOption func(*Client) |
| 105 | |
khenaidoo | b950321 | 2021-12-08 14:22:21 -0500 | [diff] [blame^] | 106 | func NewClient(clientEndpoint, serverEndpoint string, onRestart RestartedHandler, opts ...ClientOption) (*Client, error) { |
khenaidoo | 2672188 | 2021-08-11 17:42:52 -0400 | [diff] [blame] | 107 | c := &Client{ |
khenaidoo | b950321 | 2021-12-08 14:22:21 -0500 | [diff] [blame^] | 108 | clientEndpoint: clientEndpoint, |
| 109 | serverEndPoint: serverEndpoint, |
khenaidoo | 2672188 | 2021-08-11 17:42:52 -0400 | [diff] [blame] | 110 | onRestart: onRestart, |
| 111 | events: make(chan event, 1), |
| 112 | state: stateDisconnected, |
| 113 | backoffInitialInterval: DefaultBackoffInitialInterval, |
| 114 | backoffMaxInterval: DefaultBackoffMaxInterval, |
| 115 | backoffMaxElapsedTime: DefaultBackoffMaxElapsedTime, |
| 116 | monitorInterval: DefaultGRPCMonitorInterval, |
| 117 | } |
| 118 | for _, option := range opts { |
| 119 | option(c) |
| 120 | } |
| 121 | |
| 122 | // Check for environment variables |
| 123 | if err := SetFromEnvVariable(grpcBackoffInitialInterval, &c.backoffInitialInterval); err != nil { |
| 124 | logger.Warnw(context.Background(), "failure-reading-env-variable", log.Fields{"error": err, "variable": grpcBackoffInitialInterval}) |
| 125 | } |
| 126 | |
| 127 | if err := SetFromEnvVariable(grpcBackoffMaxInterval, &c.backoffMaxInterval); err != nil { |
| 128 | logger.Warnw(context.Background(), "failure-reading-env-variable", log.Fields{"error": err, "variable": grpcBackoffMaxInterval}) |
| 129 | } |
| 130 | |
| 131 | if err := SetFromEnvVariable(grpcBackoffMaxElapsedTime, &c.backoffMaxElapsedTime); err != nil { |
| 132 | logger.Warnw(context.Background(), "failure-reading-env-variable", log.Fields{"error": err, "variable": grpcBackoffMaxElapsedTime}) |
| 133 | } |
| 134 | |
| 135 | if err := SetFromEnvVariable(grpcMonitorInterval, &c.monitorInterval); err != nil { |
| 136 | logger.Warnw(context.Background(), "failure-reading-env-variable", log.Fields{"error": err, "variable": grpcMonitorInterval}) |
| 137 | } |
| 138 | |
| 139 | logger.Infow(context.Background(), "initialized-client", log.Fields{"client": c}) |
| 140 | |
| 141 | // Sanity check |
| 142 | if c.backoffInitialInterval > c.backoffMaxInterval { |
| 143 | return nil, fmt.Errorf("initial retry delay %v is greater than maximum retry delay %v", c.backoffInitialInterval, c.backoffMaxInterval) |
| 144 | } |
| 145 | |
| 146 | return c, nil |
| 147 | } |
| 148 | |
| 149 | func (c *Client) GetClient() (interface{}, error) { |
| 150 | c.connectionLock.RLock() |
| 151 | defer c.connectionLock.RUnlock() |
| 152 | if c.service == nil { |
khenaidoo | b950321 | 2021-12-08 14:22:21 -0500 | [diff] [blame^] | 153 | return nil, fmt.Errorf("no connection to %s", c.serverEndPoint) |
khenaidoo | 2672188 | 2021-08-11 17:42:52 -0400 | [diff] [blame] | 154 | } |
| 155 | return c.service, nil |
| 156 | } |
| 157 | |
| 158 | // GetCoreServiceClient is a helper function that returns a concrete service instead of the GetClient() API |
| 159 | // which returns an interface |
khenaidoo | a5feb8e | 2021-10-19 17:29:22 -0400 | [diff] [blame] | 160 | func (c *Client) GetCoreServiceClient() (core_service.CoreServiceClient, error) { |
khenaidoo | 2672188 | 2021-08-11 17:42:52 -0400 | [diff] [blame] | 161 | c.connectionLock.RLock() |
| 162 | defer c.connectionLock.RUnlock() |
| 163 | if c.service == nil { |
khenaidoo | b950321 | 2021-12-08 14:22:21 -0500 | [diff] [blame^] | 164 | return nil, fmt.Errorf("no core connection to %s", c.serverEndPoint) |
khenaidoo | 2672188 | 2021-08-11 17:42:52 -0400 | [diff] [blame] | 165 | } |
khenaidoo | a5feb8e | 2021-10-19 17:29:22 -0400 | [diff] [blame] | 166 | client, ok := c.service.(core_service.CoreServiceClient) |
khenaidoo | 2672188 | 2021-08-11 17:42:52 -0400 | [diff] [blame] | 167 | if ok { |
| 168 | return client, nil |
| 169 | } |
| 170 | return nil, fmt.Errorf("invalid-service-%s", reflect.TypeOf(c.service)) |
| 171 | } |
| 172 | |
| 173 | // GetOnuAdapterServiceClient is a helper function that returns a concrete service instead of the GetClient() API |
| 174 | // which returns an interface |
khenaidoo | a5feb8e | 2021-10-19 17:29:22 -0400 | [diff] [blame] | 175 | func (c *Client) GetOnuInterAdapterServiceClient() (onu_inter_adapter_service.OnuInterAdapterServiceClient, error) { |
khenaidoo | 2672188 | 2021-08-11 17:42:52 -0400 | [diff] [blame] | 176 | c.connectionLock.RLock() |
| 177 | defer c.connectionLock.RUnlock() |
| 178 | if c.service == nil { |
khenaidoo | b950321 | 2021-12-08 14:22:21 -0500 | [diff] [blame^] | 179 | return nil, fmt.Errorf("no child adapter connection to %s", c.serverEndPoint) |
khenaidoo | 2672188 | 2021-08-11 17:42:52 -0400 | [diff] [blame] | 180 | } |
khenaidoo | a5feb8e | 2021-10-19 17:29:22 -0400 | [diff] [blame] | 181 | client, ok := c.service.(onu_inter_adapter_service.OnuInterAdapterServiceClient) |
khenaidoo | 2672188 | 2021-08-11 17:42:52 -0400 | [diff] [blame] | 182 | if ok { |
| 183 | return client, nil |
| 184 | } |
| 185 | return nil, fmt.Errorf("invalid-service-%s", reflect.TypeOf(c.service)) |
| 186 | } |
| 187 | |
| 188 | // GetOltAdapterServiceClient is a helper function that returns a concrete service instead of the GetClient() API |
| 189 | // which returns an interface |
khenaidoo | a5feb8e | 2021-10-19 17:29:22 -0400 | [diff] [blame] | 190 | func (c *Client) GetOltInterAdapterServiceClient() (olt_inter_adapter_service.OltInterAdapterServiceClient, error) { |
khenaidoo | 2672188 | 2021-08-11 17:42:52 -0400 | [diff] [blame] | 191 | c.connectionLock.RLock() |
| 192 | defer c.connectionLock.RUnlock() |
| 193 | if c.service == nil { |
khenaidoo | b950321 | 2021-12-08 14:22:21 -0500 | [diff] [blame^] | 194 | return nil, fmt.Errorf("no parent adapter connection to %s", c.serverEndPoint) |
khenaidoo | 2672188 | 2021-08-11 17:42:52 -0400 | [diff] [blame] | 195 | } |
khenaidoo | a5feb8e | 2021-10-19 17:29:22 -0400 | [diff] [blame] | 196 | client, ok := c.service.(olt_inter_adapter_service.OltInterAdapterServiceClient) |
khenaidoo | 2672188 | 2021-08-11 17:42:52 -0400 | [diff] [blame] | 197 | if ok { |
| 198 | return client, nil |
| 199 | } |
| 200 | return nil, fmt.Errorf("invalid-service-%s", reflect.TypeOf(c.service)) |
| 201 | } |
| 202 | |
| 203 | func (c *Client) Reset(ctx context.Context) { |
khenaidoo | b950321 | 2021-12-08 14:22:21 -0500 | [diff] [blame^] | 204 | logger.Debugw(ctx, "resetting-client-connection", log.Fields{"endpoint": c.serverEndPoint}) |
khenaidoo | 2672188 | 2021-08-11 17:42:52 -0400 | [diff] [blame] | 205 | c.stateLock.Lock() |
| 206 | defer c.stateLock.Unlock() |
| 207 | if c.state == stateConnected { |
| 208 | c.state = stateDisconnected |
| 209 | c.events <- eventDisconnected |
| 210 | } |
| 211 | } |
| 212 | |
| 213 | func (c *Client) clientInterceptor(ctx context.Context, method string, req interface{}, reply interface{}, |
| 214 | cc *grpc.ClientConn, invoker grpc.UnaryInvoker, opts ...grpc.CallOption) error { |
| 215 | // Nothing to do before intercepting the call |
| 216 | err := invoker(ctx, method, req, reply, cc, opts...) |
| 217 | // On connection failure, start the reconnect process depending on the error response |
| 218 | if err != nil { |
khenaidoo | b950321 | 2021-12-08 14:22:21 -0500 | [diff] [blame^] | 219 | logger.Errorw(ctx, "received-error", log.Fields{"error": err, "context": ctx, "endpoint": c.serverEndPoint}) |
khenaidoo | 2672188 | 2021-08-11 17:42:52 -0400 | [diff] [blame] | 220 | if strings.Contains(err.Error(), connectionErrorSubString) || |
| 221 | strings.Contains(err.Error(), connectionError) || |
| 222 | strings.Contains(err.Error(), connectionSystemNotReady) || |
| 223 | isGrpcMonitorKeyPresentInContext(ctx) { |
| 224 | c.stateLock.Lock() |
| 225 | if c.state == stateConnected { |
khenaidoo | 2672188 | 2021-08-11 17:42:52 -0400 | [diff] [blame] | 226 | c.state = stateDisconnected |
khenaidoo | b950321 | 2021-12-08 14:22:21 -0500 | [diff] [blame^] | 227 | logger.Warnw(context.Background(), "sending-disconnect-event", log.Fields{"endpoint": c.serverEndPoint, "error": err, "curr-state": stateConnected, "new-state": c.state}) |
khenaidoo | 2672188 | 2021-08-11 17:42:52 -0400 | [diff] [blame] | 228 | c.events <- eventDisconnected |
| 229 | } |
| 230 | c.stateLock.Unlock() |
| 231 | } else if strings.Contains(err.Error(), connectionClosedSubstring) { |
khenaidoo | b950321 | 2021-12-08 14:22:21 -0500 | [diff] [blame^] | 232 | logger.Errorw(context.Background(), "invalid-client-connection-closed", log.Fields{"endpoint": c.serverEndPoint, "error": err}) |
khenaidoo | 2672188 | 2021-08-11 17:42:52 -0400 | [diff] [blame] | 233 | } |
| 234 | return err |
| 235 | } |
| 236 | // Update activity on success only |
| 237 | c.updateActivity(ctx) |
| 238 | return nil |
| 239 | } |
| 240 | |
khenaidoo | b950321 | 2021-12-08 14:22:21 -0500 | [diff] [blame^] | 241 | // updateActivity updates the liveness channel |
khenaidoo | 2672188 | 2021-08-11 17:42:52 -0400 | [diff] [blame] | 242 | func (c *Client) updateActivity(ctx context.Context) { |
khenaidoo | b950321 | 2021-12-08 14:22:21 -0500 | [diff] [blame^] | 243 | logger.Debugw(ctx, "update-activity", log.Fields{"api-endpoint": c.serverEndPoint}) |
khenaidoo | 2672188 | 2021-08-11 17:42:52 -0400 | [diff] [blame] | 244 | |
khenaidoo | b950321 | 2021-12-08 14:22:21 -0500 | [diff] [blame^] | 245 | // Update liveness only in connected state |
| 246 | if c.livenessCallback != nil { |
| 247 | c.stateLock.RLock() |
| 248 | if c.state == stateConnected { |
| 249 | c.livenessCallback(time.Now()) |
khenaidoo | 2672188 | 2021-08-11 17:42:52 -0400 | [diff] [blame] | 250 | } |
khenaidoo | b950321 | 2021-12-08 14:22:21 -0500 | [diff] [blame^] | 251 | c.stateLock.RUnlock() |
khenaidoo | 2672188 | 2021-08-11 17:42:52 -0400 | [diff] [blame] | 252 | } |
| 253 | } |
| 254 | |
| 255 | func WithGrpcMonitorContext(ctx context.Context, name string) context.Context { |
| 256 | ctx = context.WithValue(ctx, grpcMonitorContextKey, name) |
| 257 | return ctx |
| 258 | } |
| 259 | |
| 260 | func isGrpcMonitorKeyPresentInContext(ctx context.Context) bool { |
| 261 | if ctx != nil { |
| 262 | _, present := ctx.Value(grpcMonitorContextKey).(string) |
| 263 | return present |
| 264 | } |
| 265 | return false |
| 266 | } |
| 267 | |
| 268 | // monitorActivity monitors the activity on the gRPC connection. If there are no activity after a specified |
| 269 | // timeout, it will send a default API request on that connection. If the connection is good then nothing |
| 270 | // happens. If it's bad this will trigger reconnection attempts. |
| 271 | func (c *Client) monitorActivity(ctx context.Context, handler SetAndTestServiceHandler) { |
khenaidoo | b950321 | 2021-12-08 14:22:21 -0500 | [diff] [blame^] | 272 | logger.Infow(ctx, "start-activity-monitor", log.Fields{"endpoint": c.serverEndPoint}) |
khenaidoo | 2672188 | 2021-08-11 17:42:52 -0400 | [diff] [blame] | 273 | |
khenaidoo | aa29096 | 2021-10-22 18:14:33 -0400 | [diff] [blame] | 274 | grpcMonitorCheckRunning := false |
| 275 | var grpcMonitorCheckRunningLock sync.RWMutex |
| 276 | |
khenaidoo | 2672188 | 2021-08-11 17:42:52 -0400 | [diff] [blame] | 277 | // Interval to wait for no activity before probing the connection |
| 278 | timeout := c.monitorInterval |
| 279 | loop: |
| 280 | for { |
| 281 | timeoutTimer := time.NewTimer(timeout) |
| 282 | select { |
| 283 | |
khenaidoo | b950321 | 2021-12-08 14:22:21 -0500 | [diff] [blame^] | 284 | case <-ctx.Done(): |
| 285 | // Stop and drain timer |
khenaidoo | 2672188 | 2021-08-11 17:42:52 -0400 | [diff] [blame] | 286 | if !timeoutTimer.Stop() { |
khenaidoo | aa29096 | 2021-10-22 18:14:33 -0400 | [diff] [blame] | 287 | select { |
| 288 | case <-timeoutTimer.C: |
| 289 | default: |
| 290 | } |
khenaidoo | 2672188 | 2021-08-11 17:42:52 -0400 | [diff] [blame] | 291 | } |
khenaidoo | 2672188 | 2021-08-11 17:42:52 -0400 | [diff] [blame] | 292 | break loop |
| 293 | |
| 294 | case <-timeoutTimer.C: |
| 295 | // Trigger an activity check if the state is connected. If the state is not connected then there is already |
| 296 | // a backoff retry mechanism in place to retry establishing connection. |
| 297 | c.stateLock.RLock() |
khenaidoo | aa29096 | 2021-10-22 18:14:33 -0400 | [diff] [blame] | 298 | grpcMonitorCheckRunningLock.RLock() |
| 299 | runCheck := (c.state == stateConnected) && !grpcMonitorCheckRunning |
| 300 | grpcMonitorCheckRunningLock.RUnlock() |
khenaidoo | 2672188 | 2021-08-11 17:42:52 -0400 | [diff] [blame] | 301 | c.stateLock.RUnlock() |
| 302 | if runCheck { |
| 303 | go func() { |
khenaidoo | aa29096 | 2021-10-22 18:14:33 -0400 | [diff] [blame] | 304 | grpcMonitorCheckRunningLock.Lock() |
| 305 | if grpcMonitorCheckRunning { |
| 306 | grpcMonitorCheckRunningLock.Unlock() |
khenaidoo | b950321 | 2021-12-08 14:22:21 -0500 | [diff] [blame^] | 307 | logger.Debugw(ctx, "connection-check-already-in-progress", log.Fields{"api-endpoint": c.serverEndPoint}) |
khenaidoo | aa29096 | 2021-10-22 18:14:33 -0400 | [diff] [blame] | 308 | return |
| 309 | } |
| 310 | grpcMonitorCheckRunning = true |
| 311 | grpcMonitorCheckRunningLock.Unlock() |
| 312 | |
khenaidoo | b950321 | 2021-12-08 14:22:21 -0500 | [diff] [blame^] | 313 | logger.Debugw(ctx, "connection-check-start", log.Fields{"api-endpoint": c.serverEndPoint}) |
khenaidoo | 2672188 | 2021-08-11 17:42:52 -0400 | [diff] [blame] | 314 | subCtx, cancel := context.WithTimeout(ctx, c.backoffMaxInterval) |
| 315 | defer cancel() |
| 316 | subCtx = WithGrpcMonitorContext(subCtx, "grpc-monitor") |
| 317 | c.connectionLock.RLock() |
| 318 | defer c.connectionLock.RUnlock() |
| 319 | if c.connection != nil { |
khenaidoo | b950321 | 2021-12-08 14:22:21 -0500 | [diff] [blame^] | 320 | response := handler(subCtx, c.connection, &common.Connection{Endpoint: c.clientEndpoint, KeepAliveInterval: int64(c.monitorInterval)}) |
| 321 | logger.Debugw(ctx, "connection-check-response", log.Fields{"api-endpoint": c.serverEndPoint, "up": response != nil}) |
khenaidoo | 2672188 | 2021-08-11 17:42:52 -0400 | [diff] [blame] | 322 | } |
khenaidoo | aa29096 | 2021-10-22 18:14:33 -0400 | [diff] [blame] | 323 | grpcMonitorCheckRunningLock.Lock() |
| 324 | grpcMonitorCheckRunning = false |
| 325 | grpcMonitorCheckRunningLock.Unlock() |
khenaidoo | 2672188 | 2021-08-11 17:42:52 -0400 | [diff] [blame] | 326 | }() |
| 327 | } |
| 328 | } |
| 329 | } |
khenaidoo | b950321 | 2021-12-08 14:22:21 -0500 | [diff] [blame^] | 330 | logger.Infow(ctx, "activity-monitor-stopping", log.Fields{"endpoint": c.serverEndPoint}) |
khenaidoo | 2672188 | 2021-08-11 17:42:52 -0400 | [diff] [blame] | 331 | } |
| 332 | |
| 333 | // Start kicks off the adapter agent by trying to connect to the adapter |
| 334 | func (c *Client) Start(ctx context.Context, handler SetAndTestServiceHandler) { |
khenaidoo | b950321 | 2021-12-08 14:22:21 -0500 | [diff] [blame^] | 335 | logger.Debugw(ctx, "Starting GRPC - Client", log.Fields{"api-endpoint": c.serverEndPoint}) |
khenaidoo | 2672188 | 2021-08-11 17:42:52 -0400 | [diff] [blame] | 336 | |
| 337 | // If the context contains a k8s probe then register services |
| 338 | p := probe.GetProbeFromContext(ctx) |
| 339 | if p != nil { |
khenaidoo | b950321 | 2021-12-08 14:22:21 -0500 | [diff] [blame^] | 340 | p.RegisterService(ctx, c.serverEndPoint) |
khenaidoo | 2672188 | 2021-08-11 17:42:52 -0400 | [diff] [blame] | 341 | } |
| 342 | |
khenaidoo | b950321 | 2021-12-08 14:22:21 -0500 | [diff] [blame^] | 343 | // Enable activity check |
| 344 | go c.monitorActivity(ctx, handler) |
khenaidoo | 2672188 | 2021-08-11 17:42:52 -0400 | [diff] [blame] | 345 | |
| 346 | initialConnection := true |
| 347 | c.events <- eventConnecting |
| 348 | backoff := NewBackoff(c.backoffInitialInterval, c.backoffMaxInterval, c.backoffMaxElapsedTime) |
| 349 | attempt := 1 |
| 350 | loop: |
| 351 | for { |
| 352 | select { |
| 353 | case <-ctx.Done(): |
khenaidoo | b950321 | 2021-12-08 14:22:21 -0500 | [diff] [blame^] | 354 | logger.Debugw(ctx, "context-closing", log.Fields{"endpoint": c.serverEndPoint}) |
khenaidoo | fe90ac3 | 2021-11-08 18:17:32 -0500 | [diff] [blame] | 355 | break loop |
khenaidoo | 2672188 | 2021-08-11 17:42:52 -0400 | [diff] [blame] | 356 | case event := <-c.events: |
khenaidoo | b950321 | 2021-12-08 14:22:21 -0500 | [diff] [blame^] | 357 | logger.Debugw(ctx, "received-event", log.Fields{"event": event, "endpoint": c.serverEndPoint}) |
khenaidoo | fe90ac3 | 2021-11-08 18:17:32 -0500 | [diff] [blame] | 358 | c.connectionLock.RLock() |
| 359 | // On a client stopped, just allow the stop event to go through |
| 360 | if c.done && event != eventStopped { |
| 361 | c.connectionLock.RUnlock() |
khenaidoo | b950321 | 2021-12-08 14:22:21 -0500 | [diff] [blame^] | 362 | logger.Debugw(ctx, "ignoring-event-on-client-stop", log.Fields{"event": event, "endpoint": c.serverEndPoint}) |
khenaidoo | fe90ac3 | 2021-11-08 18:17:32 -0500 | [diff] [blame] | 363 | continue |
| 364 | } |
| 365 | c.connectionLock.RUnlock() |
khenaidoo | 2672188 | 2021-08-11 17:42:52 -0400 | [diff] [blame] | 366 | switch event { |
| 367 | case eventConnecting: |
khenaidoo | 2672188 | 2021-08-11 17:42:52 -0400 | [diff] [blame] | 368 | c.stateLock.Lock() |
khenaidoo | b950321 | 2021-12-08 14:22:21 -0500 | [diff] [blame^] | 369 | logger.Debugw(ctx, "connection-start", log.Fields{"endpoint": c.serverEndPoint, "attempts": attempt, "curr-state": c.state}) |
khenaidoo | 2672188 | 2021-08-11 17:42:52 -0400 | [diff] [blame] | 370 | if c.state == stateConnected { |
| 371 | c.state = stateDisconnected |
| 372 | } |
| 373 | if c.state != stateConnecting { |
| 374 | c.state = stateConnecting |
| 375 | go func() { |
| 376 | if err := c.connectToEndpoint(ctx, handler, p); err != nil { |
| 377 | c.stateLock.Lock() |
| 378 | c.state = stateDisconnected |
| 379 | c.stateLock.Unlock() |
khenaidoo | b950321 | 2021-12-08 14:22:21 -0500 | [diff] [blame^] | 380 | logger.Errorw(ctx, "connection-failed", log.Fields{"endpoint": c.serverEndPoint, "attempt": attempt, "error": err}) |
khenaidoo | 2672188 | 2021-08-11 17:42:52 -0400 | [diff] [blame] | 381 | |
| 382 | // Retry connection after a delay |
| 383 | if err = backoff.Backoff(ctx); err != nil { |
| 384 | // Context has closed or reached maximum elapsed time, if set |
khenaidoo | b950321 | 2021-12-08 14:22:21 -0500 | [diff] [blame^] | 385 | logger.Errorw(ctx, "retry-aborted", log.Fields{"endpoint": c.serverEndPoint, "error": err}) |
khenaidoo | 2672188 | 2021-08-11 17:42:52 -0400 | [diff] [blame] | 386 | return |
| 387 | } |
| 388 | attempt += 1 |
khenaidoo | fe90ac3 | 2021-11-08 18:17:32 -0500 | [diff] [blame] | 389 | c.connectionLock.RLock() |
| 390 | if !c.done { |
| 391 | c.events <- eventConnecting |
| 392 | } |
| 393 | c.connectionLock.RUnlock() |
khenaidoo | 2672188 | 2021-08-11 17:42:52 -0400 | [diff] [blame] | 394 | } else { |
| 395 | backoff.Reset() |
| 396 | } |
| 397 | }() |
| 398 | } |
| 399 | c.stateLock.Unlock() |
| 400 | |
| 401 | case eventConnected: |
khenaidoo | 2672188 | 2021-08-11 17:42:52 -0400 | [diff] [blame] | 402 | attempt = 1 |
| 403 | c.stateLock.Lock() |
khenaidoo | b950321 | 2021-12-08 14:22:21 -0500 | [diff] [blame^] | 404 | logger.Debugw(ctx, "endpoint-connected", log.Fields{"endpoint": c.serverEndPoint, "curr-state": c.state}) |
khenaidoo | 2672188 | 2021-08-11 17:42:52 -0400 | [diff] [blame] | 405 | if c.state != stateConnected { |
| 406 | c.state = stateConnected |
| 407 | if initialConnection { |
khenaidoo | b950321 | 2021-12-08 14:22:21 -0500 | [diff] [blame^] | 408 | logger.Debugw(ctx, "initial-endpoint-connection", log.Fields{"endpoint": c.serverEndPoint}) |
khenaidoo | 2672188 | 2021-08-11 17:42:52 -0400 | [diff] [blame] | 409 | initialConnection = false |
| 410 | } else { |
khenaidoo | b950321 | 2021-12-08 14:22:21 -0500 | [diff] [blame^] | 411 | logger.Debugw(ctx, "endpoint-reconnection", log.Fields{"endpoint": c.serverEndPoint}) |
khenaidoo | 2672188 | 2021-08-11 17:42:52 -0400 | [diff] [blame] | 412 | // Trigger any callback on a restart |
| 413 | go func() { |
khenaidoo | b950321 | 2021-12-08 14:22:21 -0500 | [diff] [blame^] | 414 | err := c.onRestart(log.WithSpanFromContext(context.Background(), ctx), c.serverEndPoint) |
khenaidoo | 2672188 | 2021-08-11 17:42:52 -0400 | [diff] [blame] | 415 | if err != nil { |
khenaidoo | b950321 | 2021-12-08 14:22:21 -0500 | [diff] [blame^] | 416 | logger.Errorw(ctx, "unable-to-restart-endpoint", log.Fields{"error": err, "endpoint": c.serverEndPoint}) |
khenaidoo | 2672188 | 2021-08-11 17:42:52 -0400 | [diff] [blame] | 417 | } |
| 418 | }() |
| 419 | } |
| 420 | } |
| 421 | c.stateLock.Unlock() |
| 422 | |
| 423 | case eventDisconnected: |
| 424 | if p != nil { |
khenaidoo | b950321 | 2021-12-08 14:22:21 -0500 | [diff] [blame^] | 425 | p.UpdateStatus(ctx, c.serverEndPoint, probe.ServiceStatusNotReady) |
khenaidoo | 2672188 | 2021-08-11 17:42:52 -0400 | [diff] [blame] | 426 | } |
khenaidoo | aa29096 | 2021-10-22 18:14:33 -0400 | [diff] [blame] | 427 | c.stateLock.RLock() |
khenaidoo | b950321 | 2021-12-08 14:22:21 -0500 | [diff] [blame^] | 428 | logger.Debugw(ctx, "endpoint-disconnected", log.Fields{"endpoint": c.serverEndPoint, "curr-state": c.state}) |
khenaidoo | aa29096 | 2021-10-22 18:14:33 -0400 | [diff] [blame] | 429 | c.stateLock.RUnlock() |
khenaidoo | 2672188 | 2021-08-11 17:42:52 -0400 | [diff] [blame] | 430 | |
| 431 | // Try to connect again |
| 432 | c.events <- eventConnecting |
| 433 | |
| 434 | case eventStopped: |
khenaidoo | b950321 | 2021-12-08 14:22:21 -0500 | [diff] [blame^] | 435 | logger.Debugw(ctx, "endPoint-stopped", log.Fields{"adapter": c.serverEndPoint}) |
khenaidoo | 2672188 | 2021-08-11 17:42:52 -0400 | [diff] [blame] | 436 | go func() { |
| 437 | if err := c.closeConnection(ctx, p); err != nil { |
khenaidoo | b950321 | 2021-12-08 14:22:21 -0500 | [diff] [blame^] | 438 | logger.Errorw(ctx, "endpoint-closing-connection-failed", log.Fields{"endpoint": c.serverEndPoint, "error": err}) |
khenaidoo | 2672188 | 2021-08-11 17:42:52 -0400 | [diff] [blame] | 439 | } |
| 440 | }() |
| 441 | break loop |
| 442 | case eventError: |
khenaidoo | b950321 | 2021-12-08 14:22:21 -0500 | [diff] [blame^] | 443 | logger.Errorw(ctx, "endpoint-error-event", log.Fields{"endpoint": c.serverEndPoint}) |
khenaidoo | 2672188 | 2021-08-11 17:42:52 -0400 | [diff] [blame] | 444 | default: |
khenaidoo | b950321 | 2021-12-08 14:22:21 -0500 | [diff] [blame^] | 445 | logger.Errorw(ctx, "endpoint-unknown-event", log.Fields{"endpoint": c.serverEndPoint, "error": event}) |
khenaidoo | 2672188 | 2021-08-11 17:42:52 -0400 | [diff] [blame] | 446 | } |
| 447 | } |
| 448 | } |
khenaidoo | b950321 | 2021-12-08 14:22:21 -0500 | [diff] [blame^] | 449 | logger.Infow(ctx, "endpoint-stopped", log.Fields{"endpoint": c.serverEndPoint}) |
khenaidoo | 2672188 | 2021-08-11 17:42:52 -0400 | [diff] [blame] | 450 | } |
| 451 | |
| 452 | func (c *Client) connectToEndpoint(ctx context.Context, handler SetAndTestServiceHandler, p *probe.Probe) error { |
| 453 | if p != nil { |
khenaidoo | b950321 | 2021-12-08 14:22:21 -0500 | [diff] [blame^] | 454 | p.UpdateStatus(ctx, c.serverEndPoint, probe.ServiceStatusPreparing) |
khenaidoo | 2672188 | 2021-08-11 17:42:52 -0400 | [diff] [blame] | 455 | } |
| 456 | |
| 457 | c.connectionLock.Lock() |
| 458 | defer c.connectionLock.Unlock() |
| 459 | |
| 460 | if c.connection != nil { |
| 461 | _ = c.connection.Close() |
| 462 | c.connection = nil |
| 463 | } |
| 464 | |
| 465 | c.service = nil |
| 466 | |
| 467 | // Use Interceptors to: |
| 468 | // 1. automatically inject |
| 469 | // 2. publish Open Tracing Spans by this GRPC Client |
| 470 | // 3. detect connection failure on client calls such that the reconnection process can begin |
khenaidoo | b950321 | 2021-12-08 14:22:21 -0500 | [diff] [blame^] | 471 | conn, err := grpc.Dial(c.serverEndPoint, |
khenaidoo | 2672188 | 2021-08-11 17:42:52 -0400 | [diff] [blame] | 472 | grpc.WithInsecure(), |
| 473 | grpc.WithStreamInterceptor(grpc_middleware.ChainStreamClient( |
| 474 | grpc_opentracing.StreamClientInterceptor(grpc_opentracing.WithTracer(log.ActiveTracerProxy{})), |
| 475 | )), |
| 476 | grpc.WithUnaryInterceptor(grpc_middleware.ChainUnaryClient( |
| 477 | grpc_opentracing.UnaryClientInterceptor(grpc_opentracing.WithTracer(log.ActiveTracerProxy{})), |
| 478 | )), |
| 479 | grpc.WithUnaryInterceptor(c.clientInterceptor), |
| 480 | // Set keealive parameter - use default grpc values |
| 481 | grpc.WithKeepaliveParams(keepalive.ClientParameters{ |
| 482 | Time: c.monitorInterval, |
| 483 | Timeout: c.backoffMaxInterval, |
| 484 | PermitWithoutStream: true, |
| 485 | }), |
| 486 | ) |
| 487 | |
| 488 | if err == nil { |
| 489 | subCtx, cancel := context.WithTimeout(ctx, c.backoffMaxInterval) |
| 490 | defer cancel() |
khenaidoo | b950321 | 2021-12-08 14:22:21 -0500 | [diff] [blame^] | 491 | svc := handler(subCtx, conn, &common.Connection{Endpoint: c.clientEndpoint, KeepAliveInterval: int64(c.monitorInterval)}) |
khenaidoo | 2672188 | 2021-08-11 17:42:52 -0400 | [diff] [blame] | 492 | if svc != nil { |
| 493 | c.connection = conn |
| 494 | c.service = svc |
| 495 | if p != nil { |
khenaidoo | b950321 | 2021-12-08 14:22:21 -0500 | [diff] [blame^] | 496 | p.UpdateStatus(ctx, c.serverEndPoint, probe.ServiceStatusRunning) |
khenaidoo | 2672188 | 2021-08-11 17:42:52 -0400 | [diff] [blame] | 497 | } |
khenaidoo | b950321 | 2021-12-08 14:22:21 -0500 | [diff] [blame^] | 498 | logger.Infow(ctx, "connected-to-endpoint", log.Fields{"endpoint": c.serverEndPoint}) |
khenaidoo | 2672188 | 2021-08-11 17:42:52 -0400 | [diff] [blame] | 499 | c.events <- eventConnected |
| 500 | return nil |
| 501 | } |
| 502 | } |
| 503 | logger.Warnw(ctx, "Failed to connect to endpoint", |
| 504 | log.Fields{ |
khenaidoo | b950321 | 2021-12-08 14:22:21 -0500 | [diff] [blame^] | 505 | "endpoint": c.serverEndPoint, |
khenaidoo | 2672188 | 2021-08-11 17:42:52 -0400 | [diff] [blame] | 506 | "error": err, |
| 507 | }) |
| 508 | |
| 509 | if p != nil { |
khenaidoo | b950321 | 2021-12-08 14:22:21 -0500 | [diff] [blame^] | 510 | p.UpdateStatus(ctx, c.serverEndPoint, probe.ServiceStatusFailed) |
khenaidoo | 2672188 | 2021-08-11 17:42:52 -0400 | [diff] [blame] | 511 | } |
khenaidoo | b950321 | 2021-12-08 14:22:21 -0500 | [diff] [blame^] | 512 | return fmt.Errorf("no connection to endpoint %s", c.serverEndPoint) |
khenaidoo | 2672188 | 2021-08-11 17:42:52 -0400 | [diff] [blame] | 513 | } |
| 514 | |
| 515 | func (c *Client) closeConnection(ctx context.Context, p *probe.Probe) error { |
| 516 | if p != nil { |
khenaidoo | b950321 | 2021-12-08 14:22:21 -0500 | [diff] [blame^] | 517 | p.UpdateStatus(ctx, c.serverEndPoint, probe.ServiceStatusStopped) |
khenaidoo | 2672188 | 2021-08-11 17:42:52 -0400 | [diff] [blame] | 518 | } |
| 519 | |
| 520 | c.connectionLock.Lock() |
| 521 | defer c.connectionLock.Unlock() |
| 522 | |
| 523 | if c.connection != nil { |
| 524 | err := c.connection.Close() |
| 525 | c.connection = nil |
| 526 | return err |
| 527 | } |
| 528 | |
| 529 | return nil |
| 530 | } |
| 531 | |
| 532 | func (c *Client) Stop(ctx context.Context) { |
khenaidoo | fe90ac3 | 2021-11-08 18:17:32 -0500 | [diff] [blame] | 533 | c.connectionLock.Lock() |
| 534 | defer c.connectionLock.Unlock() |
khenaidoo | 2672188 | 2021-08-11 17:42:52 -0400 | [diff] [blame] | 535 | if !c.done { |
khenaidoo | fe90ac3 | 2021-11-08 18:17:32 -0500 | [diff] [blame] | 536 | c.done = true |
khenaidoo | 2672188 | 2021-08-11 17:42:52 -0400 | [diff] [blame] | 537 | c.events <- eventStopped |
| 538 | close(c.events) |
khenaidoo | 2672188 | 2021-08-11 17:42:52 -0400 | [diff] [blame] | 539 | } |
khenaidoo | b950321 | 2021-12-08 14:22:21 -0500 | [diff] [blame^] | 540 | logger.Infow(ctx, "client-stopped", log.Fields{"endpoint": c.serverEndPoint}) |
khenaidoo | 2672188 | 2021-08-11 17:42:52 -0400 | [diff] [blame] | 541 | } |
| 542 | |
| 543 | // SetService is used for testing only |
| 544 | func (c *Client) SetService(srv interface{}) { |
| 545 | c.connectionLock.Lock() |
| 546 | defer c.connectionLock.Unlock() |
| 547 | c.service = srv |
| 548 | } |
| 549 | |
| 550 | func (c *Client) SubscribeForLiveness(callback func(timestamp time.Time)) { |
| 551 | c.livenessCallback = callback |
| 552 | } |