Skip to content

Commit

Permalink
[rest_gateway] Enhanced logging and error handling for gRPC gateway i…
Browse files Browse the repository at this point in the history
…nitialization (#1586)

- Added log messages for JWT validation, gRPC handler registration, and other rest_gateways logs
- Modified `jwtMiddleware` to log successful token validation and access requests
- Refactored gRPC handler registration into a centralized function
- Created `registerGRPCHandlers` function to streamline and consolidate the registration of multiple gRPC service handlers
- Simplified code structure by using a loop to register each handler, improving maintainability and readability
- Added logging for individual handler registration success and errors to facilitate debugging
  • Loading branch information
ramonfigueiredo authored Nov 14, 2024
1 parent 2c0a97e commit 63bb7f1
Showing 1 changed file with 36 additions and 41 deletions.
77 changes: 36 additions & 41 deletions rest_gateway/opencue_gateway/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -31,13 +31,15 @@ func getEnv(key string) string {

// Parse and validate the JWT token string
func validateJWTToken(tokenString string, jwtSecret []byte) (*jwt.Token, error) {
log.Println("Validating JWT token")
return jwt.Parse(tokenString, func(token *jwt.Token) (interface{}, error) {
// Ensure that the token's signing method is HMAC
if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
errorString := fmt.Sprintf("Unexpected signing method: %v", token.Header["alg"])
log.Printf(errorString)
return nil, fmt.Errorf(errorString)
}
log.Println("JWT signing method validated")
// Return the secret key for validation
return jwtSecret, nil
})
Expand Down Expand Up @@ -71,7 +73,7 @@ func jwtMiddleware(next http.Handler, jwtSecret []byte) http.Handler {
return
}

// If token is valid, pass it to the next handler
log.Println("Token validated successfully; passing request to next handler")
next.ServeHTTP(w, r)
})
}
Expand All @@ -89,56 +91,48 @@ func run() error {
// Note: Make sure the gRPC server is running properly and accessible
mux := runtime.NewServeMux()
opts := []grpc.DialOption{grpc.WithTransportCredentials(insecure.NewCredentials())}

// show.proto
errShow := gw.RegisterShowInterfaceHandlerFromEndpoint(ctx, mux, grpcServerEndpoint, opts)
if errShow != nil {
return errShow
}

errFrame := gw.RegisterFrameInterfaceHandlerFromEndpoint(ctx, mux, grpcServerEndpoint, opts)
if errFrame != nil {
return errFrame
}
errGroup := gw.RegisterGroupInterfaceHandlerFromEndpoint(ctx, mux, grpcServerEndpoint, opts)
if errGroup != nil {
return errGroup
}
errJob := gw.RegisterJobInterfaceHandlerFromEndpoint(ctx, mux, grpcServerEndpoint, opts)
if errJob != nil {
return errJob
}
errLayer := gw.RegisterLayerInterfaceHandlerFromEndpoint(ctx, mux, grpcServerEndpoint, opts)
if errLayer != nil {
return errLayer
// Register gRPC handlers
if err := registerGRPCHandlers(ctx, mux, grpcServerEndpoint, opts); err != nil {
return fmt.Errorf("failed to register gRPC handlers: %w", err)
}

// host.proto
errDeed := gw.RegisterDeedInterfaceHandlerFromEndpoint(ctx, mux, grpcServerEndpoint, opts)
if errDeed != nil {
return errDeed
}
errHost := gw.RegisterHostInterfaceHandlerFromEndpoint(ctx, mux, grpcServerEndpoint, opts)
if errHost != nil {
return errHost
}
errOwner := gw.RegisterOwnerInterfaceHandlerFromEndpoint(ctx, mux, grpcServerEndpoint, opts)
if errOwner != nil {
return errOwner
}
errProc := gw.RegisterProcInterfaceHandlerFromEndpoint(ctx, mux, grpcServerEndpoint, opts)
if errProc != nil {
return errProc
}
log.Println("All gRPC handlers registered successfully")

// Create a new HTTP ServeMux with middleware jwtMiddleware to protect the mux
httpMux := http.NewServeMux()
httpMux.Handle("/", jwtMiddleware(mux, jwtSecret))


log.Printf("Starting HTTP server on endpoint: %s, port %s", grpcServerEndpoint, port)

// Start HTTP server (and proxy calls to gRPC server endpoint)
return http.ListenAndServe(":" + port, httpMux)
}

func registerGRPCHandlers(ctx context.Context, mux *runtime.ServeMux, grpcServerEndpoint string, opts []grpc.DialOption) error {
log.Println("Registering gRPC handlers")
handlers := []func(context.Context, *runtime.ServeMux, string, []grpc.DialOption) error{
gw.RegisterShowInterfaceHandlerFromEndpoint,
gw.RegisterFrameInterfaceHandlerFromEndpoint,
gw.RegisterGroupInterfaceHandlerFromEndpoint,
gw.RegisterJobInterfaceHandlerFromEndpoint,
gw.RegisterLayerInterfaceHandlerFromEndpoint,
gw.RegisterDeedInterfaceHandlerFromEndpoint,
gw.RegisterHostInterfaceHandlerFromEndpoint,
gw.RegisterOwnerInterfaceHandlerFromEndpoint,
gw.RegisterProcInterfaceHandlerFromEndpoint,
}

for _, handler := range handlers {
if err := handler(ctx, mux, grpcServerEndpoint, opts); err != nil {
log.Printf("Error registering gRPC handler: %v", err)
return err
}
}
log.Println("All gRPC handlers registered")
return nil
}

func main() {
// Set up file to capture all log outputs
f, err := os.OpenFile("/logs/opencue_gateway.log", os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0666)
Expand All @@ -151,8 +145,9 @@ func main() {
log.SetOutput(mw)

flag.Parse()
log.Println("Starting main application")

if err := run(); err != nil {
grpclog.Fatal(err)
}
}
}

0 comments on commit 63bb7f1

Please sign in to comment.