Skip to content

How to write finalizing (clean up) logic in Cloud Functions (both event driven, http)? #271

@kokokotestuser

Description

@kokokotestuser

Hello, I am looking for the way how to write finalising logic using functions-framework-go.
(finalising means, call database, logging, etc, close, telemetry shutdown, etc)
It seems like Cloud Runs sends SIGTERM signal before shutting down the instance. However, I try to write graceful shutdown logic like Cloud Runs, event deployment happens, Cloud Functions doesn't handle it.
Potentially, we can call sync.Once inside the endpoint method. However, this way is generally used by initialisation instead of finalisation.
I searched examples on GitHub repos, but I never found out.
If there is any proper way to handle finalising, please let me know. Thank you for being so helpful.

This is a very rough example of what I tried, but it doesn't work.

func init(){
   // init some resource
  db := initDb() 
  logger, _ := logging.NewClient(ctx, projectID)
 shutdown := initTelemetry(ctx)

  c := make(chan os.Signal, 1)
  signal.Notify(c, os.Interrupt, syscall.SIGTERM)
  go func() { // start --- this part is clean up logic
    <-c
    ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
    defer cancel()
    
    // some resource closing logic
    db.Close() 
    logger.Close()
    shutdown(ctx)

    os.Exit(0)
  }() // end  --- this part is clean up logic

  functions.HTTP("CloudFunctionEndpoint", CloudFunctionEndpoint)
}


Metadata

Metadata

Assignees

No one assigned

    Labels

    P3Low PriorityquestionFurther information is requested

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions