Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Support YAML input for CloudBuildCreateOperator #8808

Merged
merged 8 commits into from
May 23, 2020
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions airflow/providers/google/cloud/example_dags/example_cloud_build.py
100644 → 100755
Original file line number Diff line number Diff line change
Expand Up @@ -99,6 +99,12 @@
task_id="create_build_from_repo_result",
)

create_build_from_file = CloudBuildCreateOperator(
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

task_id="create_build_from_file", project_id=GCP_PROJECT_ID, body='example_cloud_build.yaml'
)

create_build_from_storage >> create_build_from_storage_result # pylint: disable=pointless-statement

create_build_from_repo >> create_build_from_repo_result # pylint: disable=pointless-statement

create_build_from_file # pylint: disable=pointless-statement
joppevos marked this conversation as resolved.
Show resolved Hide resolved
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you 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
#
# http://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.

steps:
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Traceback (most recent call last):
  File "/usr/local/bin/airflow", line 11, in <module>
    load_entry_point('apache-airflow', 'console_scripts', 'airflow')()
  File "/opt/airflow/airflow/__main__.py", line 40, in main
    args.func(args)
  File "/opt/airflow/airflow/cli/cli_parser.py", line 52, in command
    return func(*args, **kwargs)
  File "/opt/airflow/airflow/utils/cli.py", line 84, in wrapper
    return f(*args, **kwargs)
  File "/opt/airflow/airflow/cli/commands/task_command.py", line 341, in task_test
    ti.run(ignore_task_deps=True, ignore_ti_state=True, test_mode=True)
  File "/opt/airflow/airflow/utils/session.py", line 61, in wrapper
    return func(*args, **kwargs)
  File "/opt/airflow/airflow/models/taskinstance.py", line 1143, in run
    session=session)
  File "/opt/airflow/airflow/utils/session.py", line 57, in wrapper
    return func(*args, **kwargs)
  File "/opt/airflow/airflow/sentry.py", line 140, in wrapper
    return func(task_instance, *args, session=session, **kwargs)
  File "/opt/airflow/airflow/models/taskinstance.py", line 1024, in _run_raw_task
    result = task_copy.execute(context=context)
  File "/opt/airflow/airflow/providers/google/cloud/operators/cloud_build.py", line 217, in execute
    body = BuildProcessor(body=self.body).process_body()
  File "/opt/airflow/airflow/providers/google/cloud/operators/cloud_build.py", line 99, in process_body
    self._verify_source()
  File "/opt/airflow/airflow/providers/google/cloud/operators/cloud_build.py", line 52, in _verify_source
    is_storage = "storageSource" in self.body["source"]
KeyError: 'source'

I'm afraid this file won't work. Can you make this optional key?
Can you make this

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

providing a source is optional for a build config. Should we always check and fail if the body misses a source?

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We should allow the build object to be passed without sources.

- name: 'ubuntu'
args: ['echo', 'hello world']
joppevos marked this conversation as resolved.
Show resolved Hide resolved
2 changes: 1 addition & 1 deletion airflow/providers/google/cloud/hooks/cloud_build.py
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,7 @@ def create_build(self, body: Dict, project_id: str) -> Dict:
Starts a build with the specified configuration.

:param body: The request body.
See: https://cloud.google.com/cloud-build/docs/api/reference/rest/Shared.Types/Build
See: https://cloud.google.com/cloud-build/docs/api/reference/rest/v1/projects.builds
:type body: dict
:param project_id: Optional, Google Cloud Project project_id where the function belongs.
If set to None or missing, the default project_id from the GCP connection is used.
Expand Down
24 changes: 21 additions & 3 deletions airflow/providers/google/cloud/operators/cloud_build.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,9 +18,11 @@
"""Operators that integrat with Google Cloud Build service."""
import re
from copy import deepcopy
from typing import Any, Dict, Iterable, Optional
from typing import Any, Dict, Iterable, Optional, Union
from urllib.parse import unquote, urlparse

import yaml

from airflow.exceptions import AirflowException
from airflow.models import BaseOperator
from airflow.providers.google.cloud.hooks.cloud_build import CloudBuildHook
Expand All @@ -39,7 +41,7 @@ class BuildProcessor:
* It is possible to provide the source as the URL address instead dict.

:param body: The request body.
See: https://cloud.google.com/cloud-build/docs/api/reference/rest/Shared.Types/Build
See: https://cloud.google.com/cloud-build/docs/api/reference/rest/v1/projects.builds
:type body: dict
"""
def __init__(self, body: Dict) -> None:
Expand Down Expand Up @@ -83,13 +85,29 @@ def _reformat_storage_source(self):

self.body["source"]["storageSource"] = self._convert_storage_url_to_dict(source)

def _load_body_to_dict(self):
"""
:param file:
file path to YAML build config
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can you also add JSON file support? This is not common, but build can also be defined as JSON files.

You can write the build config file using the YAML or the JSON syntax.

https://cloud.google.com/cloud-build/docs/build-config#structure_of_a_build_config_file

:return: dict
"""
try:
with open(self.body, 'r') as f:
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think, we should use template_ext to load file. This will cause us to still have text instead of the dictionary, so we need to overwrite the prepare_template method to convert the string to a dictionary

self.body = yaml.safe_load(f)
except yaml.YAMLError as e:
raise AirflowException("Exception when loading resource definition: %s\n" % e)

def process_body(self):
"""
Processes the body passed in the constructor

:return: the body.
:type: dict
"""

if isinstance(self.body, str):
self._load_body_to_dict()
return self.body
self._verify_source()
self._reformat_source()
return self.body
Expand Down Expand Up @@ -178,7 +196,7 @@ class CloudBuildCreateOperator(BaseOperator):

@apply_defaults
def __init__(self,
body: dict,
body: Union[dict, str],
joppevos marked this conversation as resolved.
Show resolved Hide resolved
project_id: Optional[str] = None,
gcp_conn_id: str = "google_cloud_default",
api_version: str = "v1",
Expand Down