Attiva i DAG di Cloud Composer con Cloud Functions e l'API REST Airflow

Cloud Composer 1 | Cloud Composer 2 | Cloud Composer 3

Questa pagina descrive come utilizzare Cloud Functions per attivare i DAG di Cloud Composer in risposta agli eventi.

Apache Airflow è progettato per eseguire i DAG su una pianificazione regolare, ma puoi anche attivare i DAG in risposta agli eventi. Un modo per farlo è utilizzare Cloud Functions per attivare i DAG di Cloud Composer quando si verifica un evento specificato.

L'esempio in questa guida esegue un DAG ogni volta che si verifica una modifica in un bucket Cloud Storage. Le modifiche a qualsiasi oggetto in un bucket attivano una funzione. Questa funzione effettua una richiesta all'API REST Airflow del tuo ambiente Cloud Composer. Airflow elabora questa richiesta ed esegue un DAG. Il DAG restituisce le informazioni sulla modifica.

Prima di iniziare

Controlla la configurazione di rete del tuo ambiente

Questa soluzione non funziona nelle configurazioni dell'IP privato e dei Controlli di servizio VPC perché in queste configurazioni non è possibile configurare la connettività da Cloud Functions al server web Airflow.

In Cloud Composer 2, puoi utilizzare un altro approccio: Attivare i DAG utilizzando Cloud Functions e i messaggi Pub/Sub

Abilita le API per il progetto

Console

Abilita le API Cloud Composer and Cloud Functions.

Abilita le API

gcloud

Abilita le API Cloud Composer and Cloud Functions.

gcloud services enable cloudfunctions.googleapis.com composer.googleapis.com

Abilita l'API REST Airflow

Per Airflow 2, l'API REST stabile è già abilitata per impostazione predefinita. Se l'API stabile è disabilitata nel tuo ambiente, attiva l'API REST stabile.

Consenti le chiamate API all'API REST di Airflow utilizzando il controllo dell'accesso del server web

Cloud Functions può contattare l'API REST Airflow utilizzando un indirizzo IPv4 o IPv6.

Se hai dubbi su quale sarà l'intervallo IP chiamante, utilizza un'opzione di configurazione predefinita in Controllo dell'accesso del server web che sia All IP addresses have access (default) per non bloccare accidentalmente le tue funzioni Cloud Functions.

crea un bucket Cloud Storage

Questo esempio attiva un DAG in risposta alle modifiche in un bucket Cloud Storage. Crea un nuovo bucket da utilizzare in questo esempio.

Recupera l'URL del server web Airflow

In questo esempio vengono effettuate richieste API REST all'endpoint del server web di Airflow. Devi utilizzare l'URL del server web Airflow nel codice della funzione Cloud Function.

Console

  1. Nella console Google Cloud, vai alla pagina Ambienti.

    Vai ad Ambienti

  2. Fai clic sul nome dell'ambiente.

  3. Nella pagina Dettagli ambiente, vai alla scheda Configurazione dell'ambiente.

  4. L'URL del server web di Airflow è elencato nell'elemento della UI web di Airflow.

gcloud

Esegui questo comando:

gcloud composer environments describe ENVIRONMENT_NAME \
    --location LOCATION \
    --format='value(config.airflowUri)'

Sostituisci:

  • ENVIRONMENT_NAME con il nome dell'ambiente.
  • LOCATION con la regione in cui si trova l'ambiente.

Carica un DAG nel tuo ambiente

Carica un DAG nel tuo ambiente. Il DAG di esempio seguente restituisce la configurazione dell'esecuzione del DAG ricevuta. Attiva questo DAG da una funzione, che creerai più avanti in questa guida.

import datetime

import airflow
from airflow.operators.bash import BashOperator


with airflow.DAG(
    "composer_sample_trigger_response_dag",
    start_date=datetime.datetime(2021, 1, 1),
    # Not scheduled, trigger only
    schedule_interval=None,
) as dag:
    # Print the dag_run's configuration, which includes information about the
    # Cloud Storage object change.
    print_gcs_info = BashOperator(
        task_id="print_gcs_info", bash_command="echo {{ dag_run.conf }}"
    )

Esegui il deployment di una Cloud Function che attiva il DAG

Puoi eseguire il deployment di una Cloud Function utilizzando il linguaggio che preferisci supportato da Cloud Functions o Cloud Run. Questo tutorial mostra una Cloud Function implementata in Python e Java.

Specifica i parametri di configurazione della funzione Cloud Functions

  • Attiva. Per questo esempio, seleziona un trigger che funzioni quando viene creato un nuovo oggetto in un bucket o quando un oggetto esistente viene sovrascritto.

    • Tipo di trigger. di archiviazione ideale in Cloud Storage.

    • Tipo di evento. Finalizza / crea.

    • Bucket. Seleziona un bucket che deve attivare questa funzione.

    • Riprova in caso di errore. Ti consigliamo di disabilitare questa opzione ai fini di questo esempio. Se utilizzi la tua funzione in un ambiente di produzione, abilita questa opzione per gestire gli errori temporanei.

  • Account di servizio di runtime, nella sezione Impostazioni di runtime, build, connessioni e sicurezza. Utilizza una delle seguenti opzioni, a seconda delle tue preferenze:

    • Seleziona Account di servizio predefinito Compute Engine. Con le autorizzazioni IAM predefinite, questo account può eseguire funzioni che accedono agli ambienti Cloud Composer.

    • Crea un account di servizio personalizzato con il ruolo Utente Composer e specificalo come account di servizio di runtime per questa funzione. Questa opzione segue il principio del privilegio minimo.

  • Runtime e punto di ingresso, nel passaggio Codice:

    • (Python) Quando aggiungi codice per questo esempio, seleziona il runtime Python 3.7 o successivo e specifica trigger_dag_gcf come punto di ingresso.

    • (Java) Quando aggiungi il codice per questo esempio, seleziona il runtime Java 17 e specifica com.example.Example come punto di ingresso.

Aggiungi requisiti

Python

Specifica le dipendenze nel file requirements.txt:

google-auth==2.19.1
requests==2.32.2

Java

Aggiungi le seguenti dipendenze alla sezione dependencies nell'interfaccia utente pom.xml generata dalla UI di Google Cloud Functions.

    <dependency>
      <groupId>com.google.apis</groupId>
      <artifactId>google-api-services-docs</artifactId>
      <version>v1-rev20210707-1.32.1</version>
    </dependency>
    <dependency>
      <groupId>com.google.api-client</groupId>
      <artifactId>google-api-client</artifactId>
      <version>1.32.1</version>
    </dependency>
    <dependency>
      <groupId>com.google.auth</groupId>
      <artifactId>google-auth-library-credentials</artifactId>
      <version>1.14.0</version>
    </dependency>
    <dependency>
      <groupId>com.google.auth</groupId>
      <artifactId>google-auth-library-oauth2-http</artifactId>
      <version>1.14.0</version>
    </dependency>

Python

Aggiungi il codice per attivare i DAG utilizzando l'API REST Airflow. Crea un file denominato composer2_airflow_rest_api.py e inserisci il codice per effettuare chiamate API REST Airflow in questo file.

Non modificare le variabili. La funzione Cloud Functions importa questo file dal file main.py.

from __future__ import annotations

from typing import Any

import google.auth
from google.auth.transport.requests import AuthorizedSession
import requests


# Following GCP best practices, these credentials should be
# constructed at start-up time and used throughout
# https://cloud.google.com/apis/docs/client-libraries-best-practices
AUTH_SCOPE = "https://www.googleapis.com/auth/cloud-platform"
CREDENTIALS, _ = google.auth.default(scopes=[AUTH_SCOPE])


def make_composer2_web_server_request(
    url: str, method: str = "GET", **kwargs: Any
) -> google.auth.transport.Response:
    """
    Make a request to Cloud Composer 2 environment's web server.
    Args:
      url: The URL to fetch.
      method: The request method to use ('GET', 'OPTIONS', 'HEAD', 'POST', 'PUT',
        'PATCH', 'DELETE')
      **kwargs: Any of the parameters defined for the request function:
                https://github.com/requests/requests/blob/master/requests/api.py
                  If no timeout is provided, it is set to 90 by default.
    """

    authed_session = AuthorizedSession(CREDENTIALS)

    # Set the default timeout, if missing
    if "timeout" not in kwargs:
        kwargs["timeout"] = 90

    return authed_session.request(method, url, **kwargs)


def trigger_dag(web_server_url: str, dag_id: str, data: dict) -> str:
    """
    Make a request to trigger a dag using the stable Airflow 2 REST API.
    https://airflow.apache.org/docs/apache-airflow/stable/stable-rest-api-ref.html

    Args:
      web_server_url: The URL of the Airflow 2 web server.
      dag_id: The DAG ID.
      data: Additional configuration parameters for the DAG run (json).
    """

    endpoint = f"api/v1/dags/{dag_id}/dagRuns"
    request_url = f"{web_server_url}/{endpoint}"
    json_data = {"conf": data}

    response = make_composer2_web_server_request(
        request_url, method="POST", json=json_data
    )

    if response.status_code == 403:
        raise requests.HTTPError(
            "You do not have a permission to perform this operation. "
            "Check Airflow RBAC roles for your account."
            f"{response.headers} / {response.text}"
        )
    elif response.status_code != 200:
        response.raise_for_status()
    else:
        return response.text

Inserisci il seguente codice nel file main.py. Sostituisci il valore della variabile web_server_url con l'indirizzo del server web Airflow che hai ottenuto in precedenza.

# Copyright 2021 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

"""
Trigger a DAG in a Cloud Composer 2 environment in response to an event,
using Cloud Functions.
"""

from typing import Any

import composer2_airflow_rest_api

def trigger_dag_gcf(data, context=None):
    """
    Trigger a DAG and pass event data.

    Args:
      data: A dictionary containing the data for the event. Its format depends
      on the event.
      context: The context object for the event.

    For more information about the arguments, see:
    https://cloud.google.com/functions/docs/writing/background#function_parameters
    """

    # TODO(developer): replace with your values
    # Replace web_server_url with the Airflow web server address. To obtain this
    # URL, run the following command for your environment:
    # gcloud composer environments describe example-environment \
    #  --location=your-composer-region \
    #  --format="value(config.airflowUri)"
    web_server_url = (
        "https://example-airflow-ui-url-dot-us-central1.composer.googleusercontent.com"
    )
    # Replace with the ID of the DAG that you want to run.
    dag_id = 'composer_sample_trigger_response_dag'

    composer2_airflow_rest_api.trigger_dag(web_server_url, dag_id, data)

Java

Inserisci il seguente codice nel file Example.java. Sostituisci il valore della variabile webServerUrl con l'indirizzo del server web Airflow ottenuto in precedenza.


// Copyright 2022 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package com.example;

import com.example.Example.GcsEvent;
import com.google.api.client.http.GenericUrl;
import com.google.api.client.http.HttpContent;
import com.google.api.client.http.HttpRequest;
import com.google.api.client.http.HttpRequestFactory;
import com.google.api.client.http.HttpResponse;
import com.google.api.client.http.HttpResponseException;
import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.api.client.http.json.JsonHttpContent;
import com.google.api.client.json.gson.GsonFactory;
import com.google.auth.http.HttpCredentialsAdapter;
import com.google.auth.oauth2.GoogleCredentials;
import com.google.cloud.functions.BackgroundFunction;
import com.google.cloud.functions.Context;
import java.util.HashMap;
import java.util.Map;
import java.util.logging.Logger;

/**
 * Cloud Function that triggers an Airflow DAG in response to an event (in
 * this case a Cloud Storage event).
 */
public class Example implements BackgroundFunction<GcsEvent> {
  private static final Logger logger = Logger.getLogger(Example.class.getName());

  // TODO(developer): replace with your values
  // Replace webServerUrl with the Airflow web server address. To obtain this
  // URL, run the following command for your environment:
  // gcloud composer environments describe example-environment \
  //  --location=your-composer-region \
  //  --format="value(config.airflowUri)"
  @Override
  public void accept(GcsEvent event, Context context) throws Exception {
    String webServerUrl = "https://example-airflow-ui-url-dot-us-central1.composer.googleusercontent.com";
    String dagName = "composer_sample_trigger_response_dag";
    String url = String.format("%s/api/v1/dags/%s/dagRuns", webServerUrl, dagName);

    logger.info(String.format("Triggering DAG %s as a result of an event on the object %s.",
      dagName, event.name));
    logger.info(String.format("Triggering DAG via the following URL: %s", url));

    GoogleCredentials googleCredentials = GoogleCredentials.getApplicationDefault()
        .createScoped("https://www.googleapis.com/auth/cloud-platform");
    HttpCredentialsAdapter credentialsAdapter = new HttpCredentialsAdapter(googleCredentials);
    HttpRequestFactory requestFactory =
      new NetHttpTransport().createRequestFactory(credentialsAdapter);

    Map<String, Map<String, String>> json = new HashMap<String, Map<String, String>>();
    Map<String, String> conf = new HashMap<String, String>();
    conf.put("bucket", event.bucket);
    conf.put("name", event.name);
    conf.put("generation", event.generation);
    conf.put("operation", context.eventType());
    json.put("conf", conf);
    HttpContent content = new JsonHttpContent(new GsonFactory(), json);
    HttpRequest request = requestFactory.buildPostRequest(new GenericUrl(url), content);
    request.getHeaders().setContentType("application/json");
    HttpResponse response;
    try {
      response = request.execute();
      int statusCode = response.getStatusCode();
      logger.info("Response code: " + statusCode);
      logger.info(response.parseAsString());
    } catch (HttpResponseException e) {
      // https://cloud.google.com/java/docs/reference/google-http-client/latest/com.google.api.client.http.HttpResponseException
      logger.info("Received HTTP exception");
      logger.info(e.getLocalizedMessage());
      logger.info("- 400 error: wrong arguments passed to Airflow API");
      logger.info("- 401 error: check if service account has Composer User role");
      logger.info("- 403 error: check Airflow RBAC roles assigned to service account");
      logger.info("- 404 error: check Web Server URL");
    } catch (Exception e) {
      logger.info("Received exception");
      logger.info(e.getLocalizedMessage());
    }
  }

  /** Details of the storage event. */
  public static class GcsEvent {
    /** Bucket name. */
    String bucket;
    /** Object name. */
    String name;
    /** Object version. */
    String generation;
  }
}

Testa la funzione

Per verificare che la funzione e il DAG funzionino come previsto:

  1. Attendi il deployment della funzione.
  2. Carica un file nel bucket Cloud Storage. In alternativa, puoi attivare la funzione manualmente selezionando l'azione Testa la funzione nella console Google Cloud.
  3. Controlla la pagina DAG nell'interfaccia web di Airflow. Il DAG deve avere un'esecuzione del DAG attiva o già completata.
  4. Nella UI di Airflow, controlla i log delle attività per questa esecuzione. Dovresti vedere che l'attività print_gcs_info restituisce i dati ricevuti dalla funzione nei log:

Python

[2021-04-04 18:25:44,778] {bash_operator.py:154} INFO - Output:
[2021-04-04 18:25:44,781] {bash_operator.py:158} INFO - Triggered from GCF:
    {bucket: example-storage-for-gcf-triggers, contentType: text/plain,
    crc32c: dldNmg==, etag: COW+26Sb5e8CEAE=, generation: 1617560727904101,
    ... }
[2021-04-04 18:25:44,781] {bash_operator.py:162} INFO - Command exited with
    return code 0h

Java

[2023-02-08, 08:00:09 UTC] {subprocess.py:86} INFO - Output:
[2023-02-08, 08:00:09 UTC] {subprocess.py:93} INFO - {bucket: example-storage-for-gcf-triggers, generation: 1675843189006715, name: file.txt, operation: google.storage.object.create}
[2023-02-08, 08:00:09 UTC] {subprocess.py:97} INFO - Command exited with return code 0

Passaggi successivi