Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP

Loading…

Initial version of GCE timeout sample #1

Merged
merged 27 commits into from

4 participants

@briandorsey
Owner

Compute folks, please review.

README.md
((50 lines not shown))
+`main.py`: Change the value of `GCE_PROJECT_ID` to your project id which has GCE enabled.
+
+Give your App Engine application's service account `edit` access to your GCE project.
+
+ * Log into the App Engine Admin Console.
+ * Click on the application you want to authorize.
+ * Click on Application Settings under the Administration section on the left-hand side.
+ * Copy the value under Service Account Name. This is the service account name of your application, in the format application-id@appspot.gserviceaccount.com. If you are using an App Engine Premier Account, the service account name for your application is in the format application-id.example.com@appspot.gserviceaccount.com.
+ * Use the Google APIs Console to add the service account name of the app as a team member to the project. Give the account `edit` permission.
+
+
+Verify
+------
+
+> As long as PRETEND_MODE is set to `True` (the default) in `main.py`, the application will only log deletes.
@fredsa Collaborator
fredsa added a note

Suggest DRY_RUN instead of PRETEND_MODE

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
main.py
((16 lines not shown))
+
+import datetime
+import httplib2
+import logging
+from pprint import pformat
+
+import jinja2
+import webapp2
+from apiclient.discovery import build
+from google.appengine.api import memcache
+from oauth2client.appengine import AppAssertionCredentials
+
+SAMPLE_NAME = 'Instance timeout helper'
+# Be careful, this application will delete instances unless they're tagged
+# with one of the SAFE_TAGS below.
+GCE_PROJECT_ID = 'briandpe-api'
@fredsa Collaborator
fredsa added a note

perhaps this should be 'replace-with-your-compute-engine-project-id'

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
app.yaml
@@ -0,0 +1,21 @@
+application: REPLACE-WITH-YOUR-APP-ID
@fredsa Collaborator
fredsa added a note

Suggest 'replace-with-your-app-id' to reinforce the fact that app ids are lower case

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
app.yaml
((3 lines not shown))
+runtime: python27
+api_version: 1
+threadsafe: yes
+
+handlers:
+- url: /favicon\.ico
+ static_files: favicon.ico
+ upload: favicon\.ico
+
+- url: .*
+ script: main.app
+ login: admin
+
+libraries:
+- name: webapp2
+ version: "2.5.2"
@fredsa Collaborator
fredsa added a note

using 'latest' here might be better for a sample app

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
cron.yaml
@@ -0,0 +1,4 @@
+cron:
+- description: check for expired Compute Engine instances to delete
+ url: /cron/delete
+ schedule: every 1 hours from 00:55 to 23:59
@fredsa Collaborator
fredsa added a note

Can we make start/end times less random?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
main.py
((49 lines not shown))
+def annotate_instances(instances):
+ """loops through the instances and adds exclusion, age and timeout"""
+ for instance in instances:
+ # set _excluded
+ excluded = False
+ for tag in instance.get('tags', []):
+ if tag.lower() in SAFE_TAGS:
+ excluded = True
+ break
+ instance['_excluded'] = excluded
+
+ # set _age and _timeout_expired (never True for _excluded instances)
+ creation = parse_iso8601tz(instance['creationTimestamp'])
+ now = datetime.datetime.now()
+ delta = now - creation
+ instance['_age'] = delta.seconds / 60
@fredsa Collaborator
fredsa added a note

suggest _age_hours instead

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
main.py
((21 lines not shown))
+
+import jinja2
+import webapp2
+from apiclient.discovery import build
+from google.appengine.api import memcache
+from oauth2client.appengine import AppAssertionCredentials
+
+SAMPLE_NAME = 'Instance timeout helper'
+# Be careful, this application will delete instances unless they're tagged
+# with one of the SAFE_TAGS below.
+GCE_PROJECT_ID = 'briandpe-api'
+TIMEOUT = 60 * 8 # in minutes, defaulting to 8 hours
+SAFE_TAGS = "production safetag".lower().split()
+# In pretend mode, deletes are only logged. Set this to False after you've
+# double-checked the status page and you're ready to enable the deletes.
+PRETEND_MODE = True
@fredsa Collaborator
fredsa added a note

Recommend moving all these config items into settings.py and then pulling them in via google.appengine.api.lib_config:
https://developers.google.com/appengine/docs/python/tools/appengineconfig?hl=en#Configuring_Your_Own_Modules

@briandorsey Owner

Thanks for the pointer to lib_config. It's very nice.

I tried a version with lib_config (08c0ab9) , but I think the extra layer of abstraction is a bit too much for a sample. Also, it becomes attractive to change the defaults right in main.py, but have them overwritten by the values in settings.py.

@fredsa Collaborator
fredsa added a note
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
main.py
((70 lines not shown))
+
+def list_instances():
+ """returns a list of dictionaries containing GCE instance data"""
+ request = compute.instances().list(project=GCE_PROJECT_ID)
+ response = request.execute()
+ instances = response.get('items', [])
+ annotate_instances(instances)
+ return instances
+
+
+class MainHandler(webapp2.RequestHandler):
+ """index handler, displays app configuration and instance data"""
+ def get(self):
+ instances = list_instances()
+
+ config = {}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
main.py
((114 lines not shown))
+ else:
+ logging.info("DELETE: %s", name)
+ request = compute.instances().delete(project=GCE_PROJECT_ID,
+ instance=name)
+ response = request.execute()
+ logging.info(response)
+
+
+class DeleteHandler(webapp2.RequestHandler):
+ """delete handler - HTTP endpoint for the GAE cron job"""
+ def get(self):
+ delete_expired_instances()
+
+
+app = webapp2.WSGIApplication([
+ ('/', MainHandler),
@fredsa Collaborator
fredsa added a note

recommend putting '/' after the more specific handlers

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
main.py
((29 lines not shown))
+# Be careful, this application will delete instances unless they're tagged
+# with one of the SAFE_TAGS below.
+GCE_PROJECT_ID = 'briandpe-api'
+TIMEOUT = 60 * 8 # in minutes, defaulting to 8 hours
+SAFE_TAGS = "production safetag".lower().split()
+# In pretend mode, deletes are only logged. Set this to False after you've
+# double-checked the status page and you're ready to enable the deletes.
+PRETEND_MODE = True
+
+# Obtain App Engine AppAssertion credentials and authorize HTTP connection.
+# https://developers.google.com/appengine/docs/python/appidentity/overview
+credentials = AppAssertionCredentials(
+ scope='https://www.googleapis.com/auth/compute')
+HTTP = credentials.authorize(httplib2.Http(memcache))
+
+compute = build('compute', 'v1beta13', http=HTTP)
@fredsa Collaborator
fredsa added a note

Can you explain v1beta13 in a comment?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
README.md
((19 lines not shown))
+-------------
+
+1. A Google API project with the Google Compute Engine API enabled.
+2. Admin rights on an App Engine application.
+3. The App Engine Python SDK installed on your computer.
+
+
+Setup
+-----
+
+Clone the git repository for this project to your computer:
+
+ $ git clone REPOSITORY-URL
+
+Install [Goolge API Python Client with dependencies for App Engine](http://code.google.com/p/google-api-python-client/downloads/list).
@dhermes
dhermes added a note

Typo "Goolge API"

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
index.yaml
@@ -0,0 +1,12 @@
+indexes:
@dhermes
dhermes added a note

Does this really need to be included if no indexes are created?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
main.py
((19 lines not shown))
+import logging
+from pprint import pformat
+
+import jinja2
+import webapp2
+from apiclient.discovery import build
+from google.appengine.api import memcache
+from oauth2client.appengine import AppAssertionCredentials
+
+SAMPLE_NAME = 'Instance timeout helper'
+# Be careful, this application will delete instances unless they're tagged
+# with one of the SAFE_TAGS below.
+GCE_PROJECT_ID = 'replace-with-your-compute-engine-project-id'
+TIMEOUT = 60 * 8 # in minutes, defaulting to 8 hours
+SAFE_TAGS = "production safetag".lower().split()
+# In pretend mode, deletes are only logged. Set this to False after you've
@dhermes
dhermes added a note

Should change this comment "In pretend mode" to reflect the change in the constant name to DRY_RUN

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
main.py
((95 lines not shown))
+ data['title'] = SAMPLE_NAME
+ data['instances'] = instances
+ data['raw_instances'] = pformat(instances)
+
+ template = jinja_environment.get_template('index.html')
+ self.response.out.write(template.render(data))
+
+
+def delete_expired_instances():
+ """logs all expired instances, calls delete API when not DRY_RUN"""
+ instances = list_instances()
+
+ # filter instances, keep only expired instances
+ instances = [i for i in instances if i['_timeout_expired']]
+
+ logging.info("delete cron: %s instance%s to delete",
@dhermes
dhermes added a note

Inconsistent use of single quote and double quote.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
main.py
((140 lines not shown))
+ """return a datetime object for a string in ISO 8601 format.
+
+ This function parses strings in exactly this format:
+ '2012-12-26T13:31:47.823-08:00'
+
+ Sadly, datetime.strptime's %z format is unavailable on many platforms,
+ so we can't use a single strptime() call.
+ """
+
+ dt = datetime.datetime.strptime(date_string[:-6],
+ '%Y-%m-%dT%H:%M:%S.%f')
+
+ # parse the timezone offset separately
+ delta = datetime.timedelta(minutes=int(date_string[-2:]),
+ hours=int(date_string[-5:-3]))
+ if date_string[-6:-5] == u'-':
@dhermes
dhermes added a note

You don't need a slice here, nor a unicode u'-' for comparison.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
@dhermes

Using lowercase as global is a bit scary, especially because you end up using it in MainHandler.get

briandorsey added some commits
@briandorsey briandorsey fix quoting inconsistency; simplify parse_iso8601tz() implementation a641a66
@briandorsey briandorsey convert from lib_config to a config dictionary
lib_config is nice, but I think the extra layer of abstraction is too
much for a sample. Also, it's too attractive to change the defaults right
in main.py, but have them overwritten by the values in settings.py.
8026624
@briandorsey briandorsey fix bug in date calculation and corrected _age_hours --> _age_minutes f4fab25
@briandorsey briandorsey removed index.yaml - no indexes 8be4366
@marcacohen marcacohen was assigned
main.py
((20 lines not shown))
+from pprint import pformat
+
+import jinja2
+import webapp2
+from apiclient.discovery import build
+from google.appengine.api import memcache
+from oauth2client.appengine import AppAssertionCredentials
+
+SAMPLE_NAME = 'Instance timeout helper'
+
+CONFIG= {
+ # In DRY_RUN mode, deletes are only logged. Set this to False after you've
+ # double-checked the status page and you're ready to enable the deletes.
+ 'DRY_RUN': True,
+
+ # Be careful, this application will delete all instances in the project
@marcacohen Collaborator

This comment seems to apply to the next dict key (SAFE_TAGS). Perhaps this should be moved to be adjacent to that def and a comment could be added here re: where to find the project id?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
@marcacohen marcacohen commented on the diff
((40 lines not shown))
+ 'SAFE_TAGS': ['production', 'safetag'],
+
+ # Instances are deleted after they have been running for TIMEOUT minutes.
+ 'TIMEOUT': 60 * 8, # in minutes, defaulting to 8 hours
+}
+CONFIG['SAFE_TAGS'] = [t.lower() for t in CONFIG['SAFE_TAGS']]
+
+# Obtain App Engine AppAssertion credentials and authorize HTTP connection.
+# https://developers.google.com/appengine/docs/python/appidentity/overview
+credentials = AppAssertionCredentials(
+ scope='https://www.googleapis.com/auth/compute')
+HTTP = credentials.authorize(httplib2.Http(memcache))
+
+# Build object for the 'v1beta13' version of the GCE API.
+# https://developers.google.com/compute/docs/reference/v1beta13/
+compute = build('compute', 'v1beta13', http=HTTP)
@marcacohen Collaborator

The API version is likely to change often. Should that be pulled out into a separate constant for easy maintenance?

@briandorsey Owner

This is a good idea... I'd like to take it bit further and say that we should have a variable name we agree to use in all samples, so it's easy to update them all at once. Something like GCE_API_VERSION? I'll make a separate proposal about this.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
main.py
((54 lines not shown))
+# https://developers.google.com/compute/docs/reference/v1beta13/
+compute = build('compute', 'v1beta13', http=HTTP)
+jinja_environment = jinja2.Environment(
+ loader=jinja2.FileSystemLoader('templates'))
+
+
+def annotate_instances(instances):
+ """loops through the instances and adds exclusion, age and timeout"""
+ for instance in instances:
+ # set _excluded
+ excluded = False
+ for tag in instance.get('tags', []):
+ if tag.lower() in CONFIG['SAFE_TAGS']:
+ excluded = True
+ break
+ instance['_excluded'] = excluded
@marcacohen Collaborator

I've seen the underscore convention for instance variables but not for dictionary keys. Is that a standard, or just a personal preference? Not a problem either way, just curious.

@briandorsey Owner

It's not a standard. Or even personal preference in general... but in this case I wanted it to be obvious which keys were added by the sample when looking at the overview web page. Could also use a sample-specific prefix, I suppose.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
main.py
((62 lines not shown))
+ for instance in instances:
+ # set _excluded
+ excluded = False
+ for tag in instance.get('tags', []):
+ if tag.lower() in CONFIG['SAFE_TAGS']:
+ excluded = True
+ break
+ instance['_excluded'] = excluded
+
+ # set _age_minutes and _timeout_expired
+ # _timeout_expired is never True for _excluded inst
+ creation = parse_iso8601tz(instance['creationTimestamp'])
+ now = datetime.datetime.now()
+ delta = now - creation
+ instance['_age_minutes'] = delta.seconds / 60
+ if delta.seconds > CONFIG['TIMEOUT'] * 60 and not instance['_excluded']:
@marcacohen Collaborator

This might just be me but I prefer parenthesizing (CONFIG['TIMEOUT'] * 60), not because it's needed (it's not) but because I find it more readabie.

@marcacohen Collaborator

Consider reversing and operands to avoid doing calculation on excluded instances?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
@briandorsey briandorsey merged commit b59a5ad into master
@briandorsey briandorsey deleted the initial branch
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Commits on Dec 26, 2012
  1. @briandorsey

    GAE template

    briandorsey authored
  2. @briandorsey
  3. @briandorsey

    pep8

    briandorsey authored
  4. @briandorsey

    added .gitignore

    briandorsey authored
  5. @briandorsey
Commits on Dec 27, 2012
  1. @briandorsey
  2. @briandorsey
  3. @briandorsey
  4. @briandorsey
  5. @briandorsey
  6. @briandorsey

    tweak index page

    briandorsey authored
  7. @briandorsey
  8. @briandorsey
  9. @briandorsey

    tweaked table spacing

    briandorsey authored
  10. @briandorsey
Commits on Dec 28, 2012
  1. @briandorsey
  2. @briandorsey

    cron config simplification

    briandorsey authored
  3. @briandorsey
  4. @briandorsey

    tweaked README wording

    briandorsey authored
  5. @briandorsey
  6. @briandorsey

    README tweaks

    briandorsey authored
  7. @briandorsey
  8. @briandorsey

    convert from lib_config to a config dictionary

    briandorsey authored
    lib_config is nice, but I think the extra layer of abstraction is too
    much for a sample. Also, it's too attractive to change the defaults right
    in main.py, but have them overwritten by the values in settings.py.
  9. @briandorsey
  10. @briandorsey
Commits on Dec 31, 2012
  1. @briandorsey
  2. @briandorsey

    pep8 cleanup

    briandorsey authored
This page is out of date. Refresh to see the latest.
View
2  .gitignore
@@ -0,0 +1,2 @@
+*.swp
+*.pyc
View
202 LICENSE
@@ -0,0 +1,202 @@
+
+ Apache License
+ Version 2.0, January 2004
+ http://www.apache.org/licenses/
+
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+ 1. Definitions.
+
+ "License" shall mean the terms and conditions for use, reproduction,
+ and distribution as defined by Sections 1 through 9 of this document.
+
+ "Licensor" shall mean the copyright owner or entity authorized by
+ the copyright owner that is granting the License.
+
+ "Legal Entity" shall mean the union of the acting entity and all
+ other entities that control, are controlled by, or are under common
+ control with that entity. For the purposes of this definition,
+ "control" means (i) the power, direct or indirect, to cause the
+ direction or management of such entity, whether by contract or
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
+ outstanding shares, or (iii) beneficial ownership of such entity.
+
+ "You" (or "Your") shall mean an individual or Legal Entity
+ exercising permissions granted by this License.
+
+ "Source" form shall mean the preferred form for making modifications,
+ including but not limited to software source code, documentation
+ source, and configuration files.
+
+ "Object" form shall mean any form resulting from mechanical
+ transformation or translation of a Source form, including but
+ not limited to compiled object code, generated documentation,
+ and conversions to other media types.
+
+ "Work" shall mean the work of authorship, whether in Source or
+ Object form, made available under the License, as indicated by a
+ copyright notice that is included in or attached to the work
+ (an example is provided in the Appendix below).
+
+ "Derivative Works" shall mean any work, whether in Source or Object
+ form, that is based on (or derived from) the Work and for which the
+ editorial revisions, annotations, elaborations, or other modifications
+ represent, as a whole, an original work of authorship. For the purposes
+ of this License, Derivative Works shall not include works that remain
+ separable from, or merely link (or bind by name) to the interfaces of,
+ the Work and Derivative Works thereof.
+
+ "Contribution" shall mean any work of authorship, including
+ the original version of the Work and any modifications or additions
+ to that Work or Derivative Works thereof, that is intentionally
+ submitted to Licensor for inclusion in the Work by the copyright owner
+ or by an individual or Legal Entity authorized to submit on behalf of
+ the copyright owner. For the purposes of this definition, "submitted"
+ means any form of electronic, verbal, or written communication sent
+ to the Licensor or its representatives, including but not limited to
+ communication on electronic mailing lists, source code control systems,
+ and issue tracking systems that are managed by, or on behalf of, the
+ Licensor for the purpose of discussing and improving the Work, but
+ excluding communication that is conspicuously marked or otherwise
+ designated in writing by the copyright owner as "Not a Contribution."
+
+ "Contributor" shall mean Licensor and any individual or Legal Entity
+ on behalf of whom a Contribution has been received by Licensor and
+ subsequently incorporated within the Work.
+
+ 2. Grant of Copyright License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ copyright license to reproduce, prepare Derivative Works of,
+ publicly display, publicly perform, sublicense, and distribute the
+ Work and such Derivative Works in Source or Object form.
+
+ 3. Grant of Patent License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ (except as stated in this section) patent license to make, have made,
+ use, offer to sell, sell, import, and otherwise transfer the Work,
+ where such license applies only to those patent claims licensable
+ by such Contributor that are necessarily infringed by their
+ Contribution(s) alone or by combination of their Contribution(s)
+ with the Work to which such Contribution(s) was submitted. If You
+ institute patent litigation against any entity (including a
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
+ or a Contribution incorporated within the Work constitutes direct
+ or contributory patent infringement, then any patent licenses
+ granted to You under this License for that Work shall terminate
+ as of the date such litigation is filed.
+
+ 4. Redistribution. You may reproduce and distribute copies of the
+ Work or Derivative Works thereof in any medium, with or without
+ modifications, and in Source or Object form, provided that You
+ meet the following conditions:
+
+ (a) You must give any other recipients of the Work or
+ Derivative Works a copy of this License; and
+
+ (b) You must cause any modified files to carry prominent notices
+ stating that You changed the files; and
+
+ (c) You must retain, in the Source form of any Derivative Works
+ that You distribute, all copyright, patent, trademark, and
+ attribution notices from the Source form of the Work,
+ excluding those notices that do not pertain to any part of
+ the Derivative Works; and
+
+ (d) If the Work includes a "NOTICE" text file as part of its
+ distribution, then any Derivative Works that You distribute must
+ include a readable copy of the attribution notices contained
+ within such NOTICE file, excluding those notices that do not
+ pertain to any part of the Derivative Works, in at least one
+ of the following places: within a NOTICE text file distributed
+ as part of the Derivative Works; within the Source form or
+ documentation, if provided along with the Derivative Works; or,
+ within a display generated by the Derivative Works, if and
+ wherever such third-party notices normally appear. The contents
+ of the NOTICE file are for informational purposes only and
+ do not modify the License. You may add Your own attribution
+ notices within Derivative Works that You distribute, alongside
+ or as an addendum to the NOTICE text from the Work, provided
+ that such additional attribution notices cannot be construed
+ as modifying the License.
+
+ You may add Your own copyright statement to Your modifications and
+ may provide additional or different license terms and conditions
+ for use, reproduction, or distribution of Your modifications, or
+ for any such Derivative Works as a whole, provided Your use,
+ reproduction, and distribution of the Work otherwise complies with
+ the conditions stated in this License.
+
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
+ any Contribution intentionally submitted for inclusion in the Work
+ by You to the Licensor shall be under the terms and conditions of
+ this License, without any additional terms or conditions.
+ Notwithstanding the above, nothing herein shall supersede or modify
+ the terms of any separate license agreement you may have executed
+ with Licensor regarding such Contributions.
+
+ 6. Trademarks. This License does not grant permission to use the trade
+ names, trademarks, service marks, or product names of the Licensor,
+ except as required for reasonable and customary use in describing the
+ origin of the Work and reproducing the content of the NOTICE file.
+
+ 7. Disclaimer of Warranty. Unless required by applicable law or
+ agreed to in writing, Licensor provides the Work (and each
+ Contributor provides its Contributions) on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ implied, including, without limitation, any warranties or conditions
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+ PARTICULAR PURPOSE. You are solely responsible for determining the
+ appropriateness of using or redistributing the Work and assume any
+ risks associated with Your exercise of permissions under this License.
+
+ 8. Limitation of Liability. In no event and under no legal theory,
+ whether in tort (including negligence), contract, or otherwise,
+ unless required by applicable law (such as deliberate and grossly
+ negligent acts) or agreed to in writing, shall any Contributor be
+ liable to You for damages, including any direct, indirect, special,
+ incidental, or consequential damages of any character arising as a
+ result of this License or out of the use or inability to use the
+ Work (including but not limited to damages for loss of goodwill,
+ work stoppage, computer failure or malfunction, or any and all
+ other commercial damages or losses), even if such Contributor
+ has been advised of the possibility of such damages.
+
+ 9. Accepting Warranty or Additional Liability. While redistributing
+ the Work or Derivative Works thereof, You may choose to offer,
+ and charge a fee for, acceptance of support, warranty, indemnity,
+ or other liability obligations and/or rights consistent with this
+ License. However, in accepting such obligations, You may act only
+ on Your own behalf and on Your sole responsibility, not on behalf
+ of any other Contributor, and only if You agree to indemnify,
+ defend, and hold each Contributor harmless for any liability
+ incurred by, or claims asserted against, such Contributor by reason
+ of your accepting any such warranty or additional liability.
+
+ END OF TERMS AND CONDITIONS
+
+ APPENDIX: How to apply the Apache License to your work.
+
+ To apply the Apache License to your work, attach the following
+ boilerplate notice, with the fields enclosed by brackets "[]"
+ replaced with your own identifying information. (Don't include
+ the brackets!) The text should be enclosed in the appropriate
+ comment syntax for the file format. We also recommend that a
+ file or class name and description of purpose be included on the
+ same "printed page" as the copyright notice for easier
+ identification within third-party archives.
+
+ Copyright [yyyy] [name of copyright owner]
+
+ 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.
View
83 README.md
@@ -1,4 +1,83 @@
-compute-appengine-timeout-python
+Instance timeout helper
================================
-Delete Google Compute Engine instances after X hours. Avoid accidentally running instances for a long time.
+This App Engine application monitors your Google Compute Engine instances and deletes any non-production instances once they're 8 hours old. This helps avoid accidentally running instances for a long time. Any instances tagged "production" will be left running.
+
+> WARNING: When instances are stopped, all data on ephemeral disks is destroyed. This application looks at ALL instances in a project and will delete any instances which aren't tagged "production". For extra safety, the application defaults to running in DRY_RUN mode, where deletes are logged, but not applied.
+
+This sample application demonstrates:
+
+ * Using the [Compute Engine API](https://developers.google.com/compute/docs/reference/v1beta13/) from App Engine, specifically: listing instances and deleting instances. The same pattern can be used for other GCE API calls.
+ * [App identity based API authorization](https://developers.google.com/appengine/docs/python/appidentity/overview) from AppEngine - no shared secrets, no passwords, minimal configuration.
+
+You can configure how often the application checks the instances, which tags will be left alone and how long instances are allowed to run before deleting them.
+
+
+Prerequisites
+-------------
+
+1. A Google API project with the Google Compute Engine API enabled.
+2. Admin rights on an App Engine application.
+3. The App Engine Python SDK installed on your computer.
+
+
+Setup
+-----
+
+Clone the git repository for this project to your computer:
+
+ $ git clone REPOSITORY-URL
+
+Install [Google API Python Client with dependencies for App Engine](http://code.google.com/p/google-api-python-client/downloads/list).
+Visit the download page, find "Full Dependecies Build for Google App Engine Projects" and download it into the root of your repository, for example:
+
+ $ wget http://google-api-python-client.googlecode.com/files/google-api-python-client-gae-1.0.zip
+
+Unzip it into the root of your repository:
+
+ $ unzip google-api-python-client-gae-1.0.zip
+
+
+Configuration
+-------------
+
+You will need to make three configuration changes before deploying.
+
+`app.yaml`: Change the value of `application:` to your App Engine application ID.
+
+`main.py`: Change the value of `GCE_PROJECT_ID` to your project id which has GCE enabled.
+
+Give your App Engine application's service account `edit` access to your GCE project.
+
+ * Log into the App Engine Admin Console.
+ * Click on the application you want to authorize.
+ * Click on Application Settings under the Administration section on the left-hand side.
+ * Copy the value under Service Account Name. This is the service account name of your application, in the format application-id@appspot.gserviceaccount.com. If you are using an App Engine Premier Account, the service account name for your application is in the format application-id.example.com@appspot.gserviceaccount.com.
+ * Use the Google APIs Console to add the service account name of the app as a team member to the project. Give the account `edit` permission.
+
+
+Verify
+------
+
+> As long as DRY_RUN is set to `True` (the default) in `main.py`, the application will only log deletes.
+
+Deploy the application to App Engine:
+
+ $ appcfg.py update .
+
+> Note: Because this application is using GAE app identity for authentication to GCE, it will not work on the local development server.
+
+View the index at the root of the application, at `http://YOUR-APP-ID.appspot.com`.
+Check that production instances are being excluded and older instances would be deleted.
+
+To create instances tagged "production", add the instance using the GCE Console and include "production" in the tags field. Or add it using gcutil:
+
+ $ gcutil addinstance instance-name --tags=production,another-tag
+
+You can optionally run the cron task manually and check the logs to verify that the correct instances will be deleted.
+
+Visit `http://YOUR-APP-ID.appspot.com/cron/delete` to run deletes immediately. Then check the AppEngine logs. You should see "DRY_RUN, not deleted" if any instances are old enough to be deleted.
+
+Once everything looks good, edit `main.py` and change `DRY_RUN` to `False`.
+
+Happy Computing!
View
21 app.yaml
@@ -0,0 +1,21 @@
+application: replace-with-your-app-id
+version: 1
+runtime: python27
+api_version: 1
+threadsafe: yes
+
+handlers:
+- url: /favicon\.ico
+ static_files: favicon.ico
+ upload: favicon\.ico
+
+- url: .*
+ script: main.app
+ login: admin
+
+libraries:
+- name: webapp2
+ version: latest
+
+- name: jinja2
+ version: latest
View
4 cron.yaml
@@ -0,0 +1,4 @@
+cron:
+- description: check for expired Compute Engine instances to delete
+ url: /cron/delete
+ schedule: every 1 hours synchronized
View
BIN  favicon.ico
Binary file not shown
View
164 main.py
@@ -0,0 +1,164 @@
+#!/usr/bin/env python
+#
+# Copyright 2012 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.
+
+import datetime
+import httplib2
+import logging
+from pprint import pformat
+
+import jinja2
+import webapp2
+from apiclient.discovery import build
+from google.appengine.api import memcache
+from oauth2client.appengine import AppAssertionCredentials
+
+SAMPLE_NAME = 'Instance timeout helper'
+
+CONFIG = {
+ # In DRY_RUN mode, deletes are only logged. Set this to False after you've
+ # double-checked the status page and you're ready to enable the deletes.
+ 'DRY_RUN': True,
+
+ # Be careful, this application could delete all instances in this project.
+ # Your project id can be found on the overview tab of the Google APIs
+ # Console: https://code.google.com/apis/console/
+ 'GCE_PROJECT_ID': 'replace-with-your-compute-engine-project-id',
+
+ # Instances created with these tags will never be deleted.
+ 'SAFE_TAGS': ['production', 'safetag'],
+
+ # Instances are deleted after they have been running for TIMEOUT minutes.
+ 'TIMEOUT': 60 * 8, # in minutes, defaulting to 8 hours
+}
+CONFIG['SAFE_TAGS'] = [t.lower() for t in CONFIG['SAFE_TAGS']]
+
+# Obtain App Engine AppAssertion credentials and authorize HTTP connection.
+# https://developers.google.com/appengine/docs/python/appidentity/overview
+credentials = AppAssertionCredentials(
+ scope='https://www.googleapis.com/auth/compute')
+HTTP = credentials.authorize(httplib2.Http(memcache))
+
+# Build object for the 'v1beta13' version of the GCE API.
+# https://developers.google.com/compute/docs/reference/v1beta13/
+compute = build('compute', 'v1beta13', http=HTTP)
@marcacohen Collaborator

The API version is likely to change often. Should that be pulled out into a separate constant for easy maintenance?

@briandorsey Owner

This is a good idea... I'd like to take it bit further and say that we should have a variable name we agree to use in all samples, so it's easy to update them all at once. Something like GCE_API_VERSION? I'll make a separate proposal about this.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
+jinja_environment = jinja2.Environment(
+ loader=jinja2.FileSystemLoader('templates'))
+
+
+def annotate_instances(instances):
+ """loops through the instances and adds exclusion, age and timeout"""
+ for inst in instances:
+ # set _excluded
+ excluded = False
+ for tag in inst.get('tags', []):
+ if tag.lower() in CONFIG['SAFE_TAGS']:
+ excluded = True
+ break
+ inst['_excluded'] = excluded
+
+ # set _age_minutes and _timeout_expired
+ # _timeout_expired is never True for _excluded inst
+ creation = parse_iso8601tz(inst['creationTimestamp'])
+ now = datetime.datetime.now()
+ delta = now - creation
+ inst['_age_minutes'] = delta.seconds / 60
+ if not inst['_excluded'] and delta.seconds > (CONFIG['TIMEOUT'] * 60):
+ inst['_timeout_expired'] = True
+ else:
+ inst['_timeout_expired'] = False
+
+
+def list_instances():
+ """returns a list of dictionaries containing GCE instance data"""
+ request = compute.instances().list(project=CONFIG['GCE_PROJECT_ID'])
+ response = request.execute()
+ instances = response.get('items', [])
+ annotate_instances(instances)
+ return instances
+
+
+class MainHandler(webapp2.RequestHandler):
+ """index handler, displays app configuration and instance data"""
+ def get(self):
+ instances = list_instances()
+
+ data = {}
+ data['config'] = CONFIG
+ data['title'] = SAMPLE_NAME
+ data['instances'] = instances
+ data['raw_instances'] = pformat(instances)
+
+ template = jinja_environment.get_template('index.html')
+ self.response.out.write(template.render(data))
+
+
+def delete_expired_instances():
+ """logs all expired instances, calls delete API when not DRY_RUN"""
+ instances = list_instances()
+
+ # filter instances, keep only expired instances
+ instances = [i for i in instances if i['_timeout_expired']]
+
+ logging.info('delete cron: %s instance%s to delete',
+ len(instances), '' if len(instances) == 1 else 's')
+
+ for instance in instances:
+ name = instance['name']
+ if CONFIG['DRY_RUN']:
+ logging.info("DRY_RUN, not deleted: %s", name)
+ else:
+ logging.info("DELETE: %s", name)
+ request = compute.instances().delete(
+ project=CONFIG['GCE_PROJECT_ID'], instance=name)
+ response = request.execute()
+ logging.info(response)
+
+
+class DeleteHandler(webapp2.RequestHandler):
+ """delete handler - HTTP endpoint for the GAE cron job"""
+ def get(self):
+ delete_expired_instances()
+
+
+app = webapp2.WSGIApplication([
+ ('/cron/delete', DeleteHandler),
+ ('/', MainHandler),
+], debug=True)
+
+
+# ------------------------------------------------
+# helpers
+def parse_iso8601tz(date_string):
+ """return a datetime object for a string in ISO 8601 format.
+
+ This function parses strings in exactly this format:
+ '2012-12-26T13:31:47.823-08:00'
+
+ Sadly, datetime.strptime's %z format is unavailable on many platforms,
+ so we can't use a single strptime() call.
+ """
+
+ dt = datetime.datetime.strptime(date_string[:-6],
+ '%Y-%m-%dT%H:%M:%S.%f')
+
+ # parse the timezone offset separately
+ delta = datetime.timedelta(minutes=int(date_string[-2:]),
+ hours=int(date_string[-5:-3]))
+ if date_string[-6] == '-':
+ dt = dt - delta
+ else:
+ dt = dt + delta
+ return dt
View
64 templates/index.html
@@ -0,0 +1,64 @@
+<html>
+ <head>
+ <title>{{title}}</title>
+ </head>
+ <style type="text/css">
+ table {
+ border-spacing: 0px;
+ }
+ td {
+ border-bottom: solid black 1px;
+ padding: 10px;
+ empty-cells: show;
+ }
+ thead td {
+ font-weight: bold;
+ }
+ tr.expired {
+ background-color: #FFE9A6;
+ }
+ </style>
+ <body>
+ <h1>{{title}}</h1>
+ <h2>Configuration:</h2>
+ <ul>
+ <li>DRY_RUN: {{config.DRY_RUN}}
+ <li>GCE_PROJECT_ID: {{config.GCE_PROJECT_ID}}
+ <li>SAFE_TAGS: {{', '.join(config.SAFE_TAGS)}}
+ <li>TIMEOUT: {{config.TIMEOUT}}
+ </ul>
+ <h2>Instances:</h2>
+ <table>
+ <thead>
+ <td>Name</td>
+ <td>Age</td>
+ <td>Creation timestamp</td>
+ <td>Type</td>
+ <td>Excluded</td>
+ <td>Tags</td>
+ <td>Description</td>
+ </thead>
+ {% for i in instances %}
+ <tr {{'class="expired"' if i._timeout_expired}}>
+ <td>{{i.name}}</td>
+ <td>{{i._age_minutes}}</td>
+ <td>{{i.creationTimestamp}}</td>
+ <td>{{i.machineType.split('/')[-1]}}</td>
+ <td>{{i._excluded}}</td>
+ <td>{{', '.join(i.tags)}}</td>
+ <td>{{i.description}}</td>
+ </tr>
+ {% endfor %}
+ </table>
+ <h3>Legend</h3>
+ <table>
+ <tr class="expired">
+ <td>Expired - will be deleted soon</td>
+ </tr>
+ </table>
+ <br/><br/>
+ <h3>Raw instance data:</h3>
+ <pre>{{raw_instances}}</pre>
+ </body>
+</html>
+
Something went wrong with that request. Please try again.