EventArc with CloudRun
Google Cloud EventArc provides a simple way to act on events generated by a variety of Google Cloud Services.
Consider an example.
When a Cloud Build trigger is run, I want to be notified of this event –
Eventarc makes this integration simple
The internals of how it does this is documented well. Based on the source, the event is either received by EventArc directly or via Cloud Audit Logs. EventArc then dispatches the event to the destination via another pub/sub topic that it maintains.
These underlying details are well hidden though, so as a developer concerned only about consuming the Build Events, I can focus on the payload of the event and ignore the mechanics of how EventArc gets the message from the source to my service.
Sample EventArc listener
Since I am interested in just the events and its payload, all I have to do from an application perspective is to expose an HTTP endpoint responding to a POST message with the Content being the event that I am concerned about. Here is such an endpoint in Java using Spring Boot as the framework:
@RestController public class EventArcMessageController { ... @RequestMapping(value = "/", method = RequestMethod.POST) public Mono<ResponseEntity<JsonNode>> receiveMessage( @RequestBody JsonNode body, @RequestHeader Map<String, String> headers) { LOGGER.info("Received message: {}, headers: {}", JsonUtils.writeValueAsString(body, objectMapper), headers); return Mono.just(ResponseEntity.ok(body)); } }
The full sample is available here
In this specific instance all the endpoint is doing is to log the message and the headers accompanying the message. As long as the response code is 200, EventArc would consider the handling to be successful.
EventArc supports over 130 Google Cloud Services, so consuming myriad events from a bunch of services is easy.
EventArc Trigger
Once I have the EventArc deployed as a Cloud Run service, to integrate this with the Cloud Build Events in EventArc, all I have to do is to create an EventArc trigger. This can be done using the UI:
or using command line:
gcloud eventarc triggers update cloud-build-trigger \ --location=us-west1 \ --destination-run-service=cloudbuild-eventarc-sample \ --destination-run-region=us-west1 \ --destination-run-path="/" \ --event-filters="type=google.cloud.audit.log.v1.written" \ --event-filters="serviceName=cloudbuild.googleapis.com" \ --event-filters="methodName=google.devtools.cloudbuild.v1.CloudBuild.CreateBuild"
and that is it, EventArc handles all the underlying details of the integration.
Conclusion
I have the full java code available here which shows what a full code would look like. EventArc makes it very simple to integrate events from Google Cloud Services with custom applications.
Published on Java Code Geeks with permission by Biju Kunjummen, partner at our JCG program. See the original article here: EventArc with CloudRun Opinions expressed by Java Code Geeks contributors are their own. |