-
Notifications
You must be signed in to change notification settings - Fork 6.5k
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
Add samples for Cloud Tasks #1068
Changes from 3 commits
87c721f
507a54b
1a43939
ee920fb
fa4270c
4d1f228
5e7a379
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,105 @@ | ||
# Google Cloud Tasks App Engine Queue Samples | ||
|
||
Sample command-line program for interacting with the Cloud Tasks API | ||
using App Engine queues. | ||
|
||
App Engine queues push tasks to an App Engine HTTP target. This directory | ||
contains both the App Engine app to deploy, as well as the snippets to run | ||
locally to push tasks to it, which could also be called on App Engine. | ||
|
||
`app_engine_queue_snippets.py` is a simple command-line program to create tasks | ||
to be pushed to the App Engine app. | ||
|
||
`main.py` is the main App Engine app. This app serves as an endpoint to receive | ||
App Engine task attempts. | ||
|
||
`app.yaml` configures the App Engine app. | ||
|
||
|
||
## Prerequisites to run locally: | ||
|
||
Please refer to [Setting Up a Python Development Environment](https://cloud.google.com/python/setup). | ||
|
||
## Authentication | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Can you just link to our central auth docs? There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. You mean just link to this page: https://cloud.google.com/docs/authentication/ ? It seems way, way too complex for users who just want to run the samples. I'm not even clear on where I would click on this page in order to figure out how to run them. There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Specifically I meant here: https://cloud.google.com/docs/authentication/getting-started We should no longer recommend gcloud auth to users. There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Okay, I'll replace these sections with that link. |
||
|
||
To set up authentication locally, download the | ||
[Cloud SDK](https://cloud.google.com/sdk), and run | ||
|
||
gcloud auth application-default login | ||
|
||
On App Engine, authentication credentials will be automatically detected. | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. So is application-default login even necessary? There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. This authentication is for the component submitting the tasks, not for the app engine target of the tasks. The component submitting the tasks can be anywhere, not just on app engine. |
||
|
||
On Compute Engine and Container Engine, authentication credentials will be | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Are these necessary? Isn't the tutorial for App Engine queues targeted at App Engine endpoints? There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. As above |
||
automatically detected, but the instances must have been created with the | ||
necessary scopes. | ||
|
||
In any other environment, for example a Compute Engine instance without the | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. same as above There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. As above |
||
necessary scopes, you should set `GOOGLE_APPLICATION_CREDENTIALS` environment | ||
variable to a JSON key file for a service account. | ||
|
||
See the [authentication guide](https://cloud.google.com/docs/authentication) | ||
for more information. | ||
|
||
## Creating a queue | ||
|
||
To create a queue using the Cloud SDK, use the following gcloud command: | ||
|
||
gcloud alpha tasks queues create-app-engine-queue "my-appengine-queue" | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. you don't need to put the queue ID in quotes There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Done |
||
|
||
Note: A newly created queue will route to the default App Engine service and | ||
version unless configured to do otherwise. Read the online help for the | ||
`create-app-engine-queue` or the `update-app-engine-queue` commands to learn | ||
about routing overrides for App Engine queues. | ||
|
||
## Deploying the App Engine app | ||
|
||
Deploy the App Engine app with gcloud: | ||
|
||
gcloud app deploy | ||
|
||
Verify the index page is serving: | ||
|
||
gcloud app browse | ||
|
||
The App Engine app serves as a target for the push requests. It has an | ||
endpoint `/log_payload` that reads the payload (i.e., the request body) of the | ||
HTTP POST request and logs it. The log output can be viewed with: | ||
|
||
gcloud app logs read | ||
|
||
## Running the Samples | ||
|
||
The project ID must be specified either as a command line argument using | ||
`--project-id`, or by editing `DEFAULT_PROJECT_ID` within `task_snippets.py`. | ||
|
||
Set environment variables: | ||
|
||
First, your project ID: | ||
|
||
export PROJECT_ID=my-project-id | ||
|
||
Then the queue ID, as specified at queue creation time. Queue IDs already | ||
created can be listed with `gcloud alpha tasks queue list`. | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. the command is There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Done |
||
|
||
export QUEUE_ID=my-appengine-queue | ||
|
||
And finally the location ID, which can be discovered with | ||
`gcloud alpha tasks queue describe $QUEUE_ID`, with the location embedded in the | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Done |
||
"name" value (for instance, if the name is | ||
"projects/my-project/locations/us-central1/queues/my-appengine-queue", then the | ||
location is "us-central1"). | ||
|
||
export LOCATION_ID=us-central1 | ||
|
||
Create a task, targeted at the `set_payload` endpoint with a payload specified: | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Shouldn't this be log_payload? There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Done |
||
|
||
python create_app_engine_queue_task.py --project=$PROJECT_ID --queue=QUEUE_ID --location=LOCATION_ID --payload=hello | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. $ before variable names There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Done There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. curious why the queue_name parameter was removed in favor of breaking it out into three components? While I think the naming conventions of "queue name" vs. "queue" vs. "queue ID" are hard to follow, they're apparently in line with OnePlatform. Further, when we want to add more params like headers, App Engine routing, relative URL, and response view, the command will get pretty long. There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. I removed queue_name because gcloud queues list doesn't show the queue name. There's no real way to discover it without hitting the API separately. The queue name construct is still visible in the code itself, which seems appropriate for a sample. There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. But the There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Oh, that's right. I think using the "queue_name" is an awkward abstraction, but since "describe" shows the queue_name I could add it back in. I'll reconsider. There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. I discussed with Jon and he told me that our other samples that have resource paths under the hoods use a similar "pass in the components on the command line, and assemble the full path in the code itself" system. So, I think I'll keep it like this for now. I think it's awkward to have the user use "describe" to look at the resource path just to get the location out of it, but I've been assured that the resource path will be included in "list" output soon at which point that will no longer be necessary. |
||
|
||
Now view that the payload was received and verify the payload: | ||
|
||
gcloud app logs read | ||
|
||
Create a task that will be scheduled for a time in the future using the | ||
`--in_seconds` flag: | ||
|
||
python create_app_engine_queue_task.py --project=$PROJECT_ID --queue=QUEUE_ID --location=LOCATION_ID --payload=hello --in_seconds=30 | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. $ before variable names There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Done |
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,6 @@ | ||
runtime: python | ||
env: flex | ||
entrypoint: gunicorn -b :$PORT main:app | ||
|
||
runtime_config: | ||
python_version: 3 |
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,112 @@ | ||
# Copyright 2017 Google Inc. All Rights Reserved. | ||
# | ||
# 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 | ||
# | ||
# 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. | ||
|
||
from __future__ import print_function | ||
|
||
import argparse | ||
import base64 | ||
import datetime | ||
import pprint | ||
|
||
from googleapiclient import discovery | ||
|
||
|
||
def seconds_from_now_to_rfc3339_datetime(seconds): | ||
"""Return an RFC 3339 datetime string for a number of seconds from now.""" | ||
d = datetime.datetime.utcnow() + datetime.timedelta(seconds=seconds) | ||
return d.isoformat('T') + 'Z' | ||
|
||
|
||
def create_task(project, queue, location, payload=None, in_seconds=None): | ||
"""Create a task for a given queue with an arbitrary payload.""" | ||
client = get_client() | ||
|
||
url = '/log_payload' | ||
body = { | ||
'task': { | ||
'app_engine_task_target': { | ||
'http_method': 'POST', | ||
'relative_url': url | ||
} | ||
} | ||
} | ||
|
||
if payload is not None: | ||
# Payload is a string (unicode), so | ||
body['task']['app_engine_task_target']['payload'] = base64.b64encode( | ||
payload.encode()).decode() | ||
|
||
if in_seconds is not None: | ||
scheduled_time = seconds_from_now_to_rfc3339_datetime(in_seconds) | ||
body['task']['schedule_time'] = scheduled_time | ||
|
||
queue_name = 'projects/{}/locations/{}/queues/{}'.format( | ||
project, location, queue) | ||
|
||
print('Sending task {}'.format(pprint.pformat(body))) | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Might it be even better to print this as JSON? There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Done |
||
|
||
response = client.projects().locations().queues().tasks().create( | ||
parent=queue_name, body=body).execute() | ||
|
||
# By default CreateTaskRequest.responseView is BASIC, so not all | ||
# information is retrieved by default because some data, such as payloads, | ||
# might be desirable to return only when needed because of its large size | ||
# or because of the sensitivity of data that it contains. | ||
print('Created task {}'.format(response['name'])) | ||
return response | ||
|
||
|
||
def get_client(): | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. prefer that you just put this inline in the function above. There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Done |
||
"""Build an http client.""" | ||
DISCOVERY_URL = 'https://cloudtasks.googleapis.com/$discovery/rest?version=v2beta2' | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. it's not a constant, so it doesn't need to be capital. There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. It's not a constant? It's not modified or replaced anywhere, it's just a string literal with a name, right? |
||
client = discovery.build('cloudtasks', 'v2beta2', | ||
discoveryServiceUrl=DISCOVERY_URL) | ||
return client | ||
|
||
|
||
if __name__ == '__main__': | ||
parser = argparse.ArgumentParser( | ||
description=create_task.__doc__, | ||
formatter_class=argparse.RawDescriptionHelpFormatter) | ||
|
||
parser.add_argument( | ||
'--project', | ||
help='Project of the queue to add the task to.' | ||
) | ||
|
||
parser.add_argument( | ||
'--queue', | ||
help='ID (short name) of the queue to add the task to.' | ||
) | ||
|
||
parser.add_argument( | ||
'--location', | ||
help='Location of the queue to add the task to.' | ||
) | ||
|
||
parser.add_argument( | ||
'--payload', | ||
help='Optional payload to attach to the push queue.' | ||
) | ||
|
||
parser.add_argument( | ||
'--in_seconds', | ||
help='The number of seconds from now to schedule task attempt.' | ||
) | ||
|
||
args = parser.parse_args() | ||
|
||
create_task( | ||
args.project, args.queue, args.location, | ||
args.payload, args.in_seconds) |
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,32 @@ | ||
# Copyright 2016 Google Inc. All Rights Reserved. | ||
# | ||
# 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 | ||
# | ||
# 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. | ||
|
||
import mock | ||
|
||
import create_app_engine_queue_task | ||
|
||
TEST_PROJECT = 'mock-project' | ||
TEST_LOCATION = 'us-central1' | ||
TEST_QUEUE = 'my-appengine-queue' | ||
|
||
|
||
@mock.patch('create_app_engine_queue_task.get_client') | ||
def test_create_task(get_client): | ||
projects = get_client.return_value.projects.return_value | ||
locations = projects.locations.return_value | ||
create_function = locations.queues.return_value.tasks.return_value.create | ||
execute_function = create_function.return_value.execute | ||
execute_function.return_value = {'name': 'task_name'} | ||
create_app_engine_queue_task.create_task(TEST_PROJECT, TEST_QUEUE, TEST_LOCATION) | ||
assert execute_function.called |
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,41 @@ | ||
# Copyright 2016 Google Inc. | ||
# | ||
# 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 | ||
# | ||
# 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. | ||
|
||
"""App Engine app to serve as an endpoint for App Engine queue samples.""" | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. This is for push queues, yeah? Can we be explicit about that? There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Yeah, I asked about it but I was told by the PM that the "push queue" terminology is being dropped in favor of "App Engine queue". |
||
|
||
import logging | ||
|
||
from flask import Flask, request | ||
|
||
app = Flask(__name__) | ||
|
||
|
||
@app.route('/log_payload', methods=['POST']) | ||
def log_payload(): | ||
"""Log the request payload.""" | ||
payload = request.data or "empty payload" | ||
logging.warn(payload) | ||
return 'Logged request payload: {}'.format(payload) | ||
|
||
|
||
@app.route('/') | ||
def hello(): | ||
"""Basic index to verify app is serving.""" | ||
return 'Hello World!' | ||
|
||
|
||
if __name__ == '__main__': | ||
# This is used when running locally. Gunicorn is used to run the | ||
# application on Google App Engine. See entrypoint in app.yaml. | ||
app.run(host='127.0.0.1', port=8080, debug=True) |
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,46 @@ | ||
# Copyright 2016 Google Inc. All Rights Reserved. | ||
# | ||
# 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 | ||
# | ||
# 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. | ||
|
||
import mock | ||
import pytest | ||
|
||
|
||
@pytest.fixture | ||
def app(): | ||
import main | ||
main.app.testing = True | ||
return main.app.test_client() | ||
|
||
|
||
def test_index(app): | ||
r = app.get('/') | ||
assert r.status_code == 200 | ||
|
||
|
||
@mock.patch('logging.warn') | ||
def test_log_payload(logging_mock, app): | ||
payload = 'hello' | ||
|
||
r = app.post('/log_payload', payload) | ||
assert r.status_code == 200 | ||
|
||
assert logging_mock.called | ||
|
||
|
||
@mock.patch('logging.warn') | ||
def test_empty_payload(logging_mock, app): | ||
r = app.post('/log_payload') | ||
assert r.status_code == 200 | ||
|
||
assert logging_mock.called |
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,4 @@ | ||
Flask==0.11.1 | ||
google-api-python-client==1.6.0 | ||
google-cloud-datastore==0.22.0 | ||
gunicorn==19.6.0 |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Do any of the instances of "App Engine" in this document need to be "App Engine Standard" or "App Engine Flexible"? If not, can we actually explicitly say that "works in both App Engine Standard and Flexible"? I work at Google and I don't know, so I can only imagine our customers might have the same question.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
It works for both standard and flex.