2023-06-12 07:45:34 -04:00
|
|
|
/*
|
|
|
|
Copyright (c) Edgeless Systems GmbH
|
|
|
|
|
|
|
|
SPDX-License-Identifier: AGPL-3.0-only
|
|
|
|
*/
|
|
|
|
|
|
|
|
// grpclog provides a logging utilities for gRPC.
|
|
|
|
package grpclog
|
|
|
|
|
|
|
|
import (
|
|
|
|
"context"
|
2024-02-08 09:20:01 -05:00
|
|
|
"fmt"
|
2023-06-12 07:45:34 -04:00
|
|
|
"sync"
|
|
|
|
|
|
|
|
"google.golang.org/grpc/connectivity"
|
|
|
|
"google.golang.org/grpc/peer"
|
|
|
|
)
|
|
|
|
|
|
|
|
// PeerAddrFromContext returns a peer's address from context, or "unknown" if not found.
|
|
|
|
func PeerAddrFromContext(ctx context.Context) string {
|
|
|
|
p, ok := peer.FromContext(ctx)
|
|
|
|
if !ok {
|
|
|
|
return "unknown"
|
|
|
|
}
|
|
|
|
return p.Addr.String()
|
|
|
|
}
|
|
|
|
|
|
|
|
// LogStateChangesUntilReady logs the state changes of a gRPC connection.
|
|
|
|
func LogStateChangesUntilReady(ctx context.Context, conn getStater, log debugLog, wg *sync.WaitGroup, isReadyCallback func()) {
|
|
|
|
wg.Add(1)
|
|
|
|
go func() {
|
|
|
|
defer wg.Done()
|
|
|
|
state := conn.GetState()
|
2024-04-03 09:49:03 -04:00
|
|
|
log.Debug(fmt.Sprintf("Connection state started as %q", state))
|
2023-06-12 07:45:34 -04:00
|
|
|
for ; state != connectivity.Ready && conn.WaitForStateChange(ctx, state); state = conn.GetState() {
|
2024-04-03 09:49:03 -04:00
|
|
|
log.Debug(fmt.Sprintf("Connection state changed to %q", state))
|
2023-06-12 07:45:34 -04:00
|
|
|
}
|
|
|
|
if state == connectivity.Ready {
|
2024-02-08 09:20:01 -05:00
|
|
|
log.Debug("Connection ready")
|
2023-06-12 07:45:34 -04:00
|
|
|
isReadyCallback()
|
|
|
|
} else {
|
2024-04-03 09:49:03 -04:00
|
|
|
log.Debug(fmt.Sprintf("Connection state ended with %q", state))
|
2023-06-12 07:45:34 -04:00
|
|
|
}
|
|
|
|
}()
|
|
|
|
}
|
|
|
|
|
|
|
|
type getStater interface {
|
|
|
|
GetState() connectivity.State
|
|
|
|
WaitForStateChange(context.Context, connectivity.State) bool
|
|
|
|
}
|
|
|
|
|
|
|
|
type debugLog interface {
|
2024-02-08 09:20:01 -05:00
|
|
|
Debug(msg string, args ...any)
|
2023-06-12 07:45:34 -04:00
|
|
|
}
|