Get execution ID for Google Cloud Functions triggered from PubSub event

荒凉一梦 提交于 2020-06-17 07:54:05

问题


For Google Cloud Functions triggered from HTTP, it is possible to retrieve the execution id by inspecting the headers of the HTTP request ("Function-Execution-Id") :

package p

import (
    "fmt"
    "net/http"
)

func F(w http.ResponseWriter, r *http.Request) {
    executionID := r.Header.Get("Function-Execution-Id")
    fmt.Println(executionID)
}

However, for GCF triggered by PubSub events, I can't find how to retrieve this execution ID :

package p

import (
    "context"
)

type PubSubMessage struct {
    Data []byte `json:"data"`
}

func F(ctx context.Context, m PubSubMessage) error {
    executionID := "" // ???
    fmt.Println(executionID)
    return nil
}

I have looked into the PubSubMessage (https://cloud.google.com/pubsub/docs/reference/rest/v1/PubsubMessage), but it only contains data + an empty attributes map.

I have also checked if execution ID is in the metadata handled by the context. However, from my tests, and the docs (https://godoc.org/cloud.google.com/go/functions/metadata#FromContext), only EventID, Timestamp, EventType and Resource are present.

How can I retrieve the execution id of a GCF function triggered by a PubSub event?


回答1:


A Pub/Sub-triggered event does not have an execution ID; instead it has an EventID contained in the context metadata, which is a unique ID for the event.

You can access the EventID as follows:

import (
    "context"
    "log"
    "cloud.google.com/go/functions/metadata"
)

func F(ctx context.Context, m PubSubMessage) error {
    ctxMetadata, err := metadata.FromContext(ctx)
    if err != nil {
        log.Fatal(err);
    }
    log.Println("EventID: " + ctxMetadata.EventID)
    return nil
}



回答2:


No, it is currently not possible to get execution id from pubsub triggered events.

You can get the event id from context as Lauren stated but that does not match execution id.

Also, pubsub triggered events do have execution ids. You can see this by using a default logger to log the event id. In stackdriver there will be an attached execution id label and it will not match the event id. We have observed that event id is numeric while execution id is alphanumeric.

Further, if the function is retried, it will keep the same event id but get a different execution id.

This is a recent (undocumented) change but can be easily observed.



来源:https://stackoverflow.com/questions/56152806/get-execution-id-for-google-cloud-functions-triggered-from-pubsub-event

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!