├── docs └── img │ ├── cloud-shell.png │ └── screenshot.png ├── application ├── photoalbum │ ├── images │ │ └── default.png │ ├── src │ │ ├── templates │ │ │ ├── index.html │ │ │ └── photos.html │ │ ├── auth_decorator.py │ │ └── app.py │ └── Dockerfile ├── safeimage │ ├── Dockerfile │ └── src │ │ └── worker.py └── thumbnail │ ├── Dockerfile │ └── src │ └── worker.py ├── config ├── photoalbum-service.yaml ├── safeimage-deployment.yaml ├── thumbnail-deployment.yaml └── photoalbum-deployment.yaml ├── .gitignore ├── README.md └── LICENSE /docs/img/cloud-shell.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/GoogleCloudPlatform/gke-photoalbum-example/HEAD/docs/img/cloud-shell.png -------------------------------------------------------------------------------- /docs/img/screenshot.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/GoogleCloudPlatform/gke-photoalbum-example/HEAD/docs/img/screenshot.png -------------------------------------------------------------------------------- /application/photoalbum/images/default.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/GoogleCloudPlatform/gke-photoalbum-example/HEAD/application/photoalbum/images/default.png -------------------------------------------------------------------------------- /application/photoalbum/src/templates/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Photo Album 5 | 6 | 7 | 8 |

Open Photo Album

9 | 10 | 11 | -------------------------------------------------------------------------------- /config/photoalbum-service.yaml: -------------------------------------------------------------------------------- 1 | apiVersion: v1 2 | kind: Service 3 | metadata: 4 | labels: 5 | name: photoalbum-service 6 | name: photoalbum-service 7 | spec: 8 | ports: 9 | - protocol: TCP 10 | port: 80 11 | targetPort: 8080 12 | selector: 13 | name: photoalbum-app 14 | type: LoadBalancer 15 | -------------------------------------------------------------------------------- /config/safeimage-deployment.yaml: -------------------------------------------------------------------------------- 1 | apiVersion: apps/v1 2 | kind: Deployment 3 | metadata: 4 | labels: 5 | name: safeimage-worker 6 | name: safeimage-worker 7 | spec: 8 | replicas: 3 9 | selector: 10 | matchLabels: 11 | name: safeimage-worker 12 | template: 13 | metadata: 14 | labels: 15 | name: safeimage-worker 16 | spec: 17 | containers: 18 | - name: safeimage-worker 19 | image: us-central1-docker.pkg.dev/[PROJECT_ID]/photoalbum-repo/safeimage-worker@[DIGEST] 20 | env: 21 | - name: PROJECT_ID 22 | value: "[PROJECT_ID]" 23 | -------------------------------------------------------------------------------- /application/safeimage/Dockerfile: -------------------------------------------------------------------------------- 1 | FROM marketplace.gcr.io/google/debian10 2 | LABEL maintainer "Etsuji Nakai" 3 | ENV REFRESHED_AT 2021/07/07 4 | 5 | RUN apt-get update && apt-get upgrade -y && \ 6 | apt-get install -y python3 python3-dev wget 7 | RUN wget https://bootstrap.pypa.io/get-pip.py 8 | RUN python3 get-pip.py 9 | 10 | RUN pip install --upgrade google-cloud-core==1.7.1 \ 11 | google-cloud-pubsub==2.6.0 google-cloud-storage==1.40.0 \ 12 | google-cloud-vision==2.3.2 Pillow==8.3.1 pytz==2022.7.1 13 | 14 | ADD src /opt/safeimage/bin 15 | RUN chmod u+x /opt/safeimage/bin/worker.py 16 | CMD ["/opt/safeimage/bin/worker.py"] 17 | -------------------------------------------------------------------------------- /application/thumbnail/Dockerfile: -------------------------------------------------------------------------------- 1 | FROM marketplace.gcr.io/google/debian10 2 | LABEL maintainer "Etsuji Nakai" 3 | ENV REFRESHED_AT 2021/07/07 4 | 5 | RUN apt-get update && apt-get upgrade -y && \ 6 | apt-get install -y python3 python3-dev wget 7 | RUN wget https://bootstrap.pypa.io/get-pip.py 8 | RUN python3 get-pip.py 9 | 10 | RUN pip install --upgrade google-cloud-core==1.7.1 \ 11 | google-cloud-pubsub==2.6.0 google-cloud-storage==1.40.0 \ 12 | google-cloud-vision==2.3.2 Flask==2.2.3 Flask-SQLAlchemy==3.0.3 \ 13 | Pillow==8.3.1 PyMySQL==1.0.2 pytz==2022.7.1 14 | 15 | ADD src /opt/thumbnail/bin 16 | RUN chmod u+x /opt/thumbnail/bin/worker.py 17 | CMD ["/opt/thumbnail/bin/worker.py"] 18 | -------------------------------------------------------------------------------- /application/photoalbum/Dockerfile: -------------------------------------------------------------------------------- 1 | FROM marketplace.gcr.io/google/debian10 2 | LABEL maintainer "Etsuji Nakai" 3 | ENV REFRESHED_AT 2021/07/07 4 | 5 | RUN apt-get update && apt-get upgrade -y && \ 6 | apt-get install -y python3 python3-dev wget 7 | RUN wget https://bootstrap.pypa.io/get-pip.py 8 | RUN python3 get-pip.py 9 | 10 | RUN pip install --upgrade google-cloud-core==1.7.1 \ 11 | google-cloud-pubsub==2.6.0 google-cloud-storage==1.40.0 \ 12 | google-cloud-vision==2.3.2 Flask==2.2.3 Flask-SQLAlchemy==3.0.3 \ 13 | Flask-WTF==0.15.1 Pillow==8.3.1 PyMySQL==1.0.2 pytz==2022.7.1 14 | 15 | ADD src /opt/photoalbum/bin 16 | RUN chmod u+x /opt/photoalbum/bin/app.py 17 | EXPOSE 8080 18 | CMD ["/opt/photoalbum/bin/app.py"] 19 | -------------------------------------------------------------------------------- /config/thumbnail-deployment.yaml: -------------------------------------------------------------------------------- 1 | apiVersion: apps/v1 2 | kind: Deployment 3 | metadata: 4 | labels: 5 | name: thumbnail-worker 6 | name: thumbnail-worker 7 | spec: 8 | replicas: 3 9 | selector: 10 | matchLabels: 11 | name: thumbnail-worker 12 | template: 13 | metadata: 14 | labels: 15 | name: thumbnail-worker 16 | spec: 17 | containers: 18 | - name: thumbnail-worker 19 | image: us-central1-docker.pkg.dev/[PROJECT_ID]/photoalbum-repo/thumbnail-worker@[DIGEST] 20 | env: 21 | - name: PROJECT_ID 22 | value: "[PROJECT_ID]" 23 | - name: DB_USER 24 | value: "appuser" 25 | - name: DB_PASS 26 | value: "pas4appuser" 27 | - name: cloudsql-proxy 28 | image: gcr.io/cloudsql-docker/gce-proxy:1.23.0 29 | command: ["/cloud_sql_proxy", 30 | "-instances=[CONNECTION_NAME]=tcp:3306"] 31 | securityContext: 32 | runAsUser: 2 33 | allowPrivilegeEscalation: false 34 | -------------------------------------------------------------------------------- /config/photoalbum-deployment.yaml: -------------------------------------------------------------------------------- 1 | apiVersion: apps/v1 2 | kind: Deployment 3 | metadata: 4 | labels: 5 | name: photoalbum-app 6 | name: photoalbum-app 7 | spec: 8 | replicas: 3 9 | selector: 10 | matchLabels: 11 | name: photoalbum-app 12 | template: 13 | metadata: 14 | labels: 15 | name: photoalbum-app 16 | spec: 17 | containers: 18 | - name: photoalbum-app 19 | image: us-central1-docker.pkg.dev/[PROJECT_ID]/photoalbum-repo/photoalbum-app@[DIGEST] 20 | tty: true 21 | ports: 22 | - containerPort: 8080 23 | env: 24 | - name: PROJECT_ID 25 | value: "[PROJECT_ID]" 26 | - name: DB_USER 27 | value: "appuser" 28 | - name: DB_PASS 29 | value: "pas4appuser" 30 | - name: cloudsql-proxy 31 | image: gcr.io/cloudsql-docker/gce-proxy:1.23.0 32 | command: ["/cloud_sql_proxy", 33 | "-instances=[CONNECTION_NAME]=tcp:3306"] 34 | securityContext: 35 | runAsUser: 2 36 | allowPrivilegeEscalation: false 37 | -------------------------------------------------------------------------------- /application/photoalbum/src/auth_decorator.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | # Copyright 2017 Google LLC 4 | # 5 | # Licensed under the Apache License, Version 2.0 (the "License"); 6 | # you may not use this file except in compliance with the License. 7 | # You may obtain a copy of the License at 8 | # 9 | # http://www.apache.org/licenses/LICENSE-2.0 10 | # 11 | # Unless required by applicable law or agreed to in writing, software 12 | # distributed under the License is distributed on an "AS IS" BASIS, 13 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | # See the License for the specific language governing permissions and 15 | # limitations under the License. 16 | 17 | 18 | from functools import wraps 19 | 20 | from flask import request 21 | from flask import Response 22 | 23 | 24 | USERNAME = 'username' 25 | PASSWORD = 'passw0rd' 26 | 27 | 28 | def check_auth(username, password): 29 | return username == USERNAME and password == PASSWORD 30 | 31 | 32 | def authenticate(): 33 | return Response( 34 | 'You have to login with proper credentials', 401, 35 | {'WWW-Authenticate': 'Basic realm="Login Required"'}) 36 | 37 | 38 | def requires_auth(f): 39 | @wraps(f) 40 | def decorated(*args, **kwargs): 41 | auth = request.authorization 42 | if not auth or not check_auth(auth.username, auth.password): 43 | return authenticate() 44 | return f(*args, **kwargs) 45 | return decorated 46 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | *$py.class 5 | 6 | # C extensions 7 | *.so 8 | 9 | # Distribution / packaging 10 | .Python 11 | build/ 12 | develop-eggs/ 13 | dist/ 14 | downloads/ 15 | eggs/ 16 | .eggs/ 17 | lib/ 18 | lib64/ 19 | parts/ 20 | sdist/ 21 | var/ 22 | wheels/ 23 | *.egg-info/ 24 | .installed.cfg 25 | *.egg 26 | MANIFEST 27 | 28 | # PyInstaller 29 | # Usually these files are written by a python script from a template 30 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 31 | *.manifest 32 | *.spec 33 | 34 | # Installer logs 35 | pip-log.txt 36 | pip-delete-this-directory.txt 37 | 38 | # Unit test / coverage reports 39 | htmlcov/ 40 | .tox/ 41 | .coverage 42 | .coverage.* 43 | .cache 44 | nosetests.xml 45 | coverage.xml 46 | *.cover 47 | .hypothesis/ 48 | .pytest_cache/ 49 | 50 | # Translations 51 | *.mo 52 | *.pot 53 | 54 | # Django stuff: 55 | *.log 56 | local_settings.py 57 | db.sqlite3 58 | 59 | # Flask stuff: 60 | instance/ 61 | .webassets-cache 62 | 63 | # Scrapy stuff: 64 | .scrapy 65 | 66 | # Sphinx documentation 67 | docs/_build/ 68 | 69 | # PyBuilder 70 | target/ 71 | 72 | # Jupyter Notebook 73 | .ipynb_checkpoints 74 | 75 | # pyenv 76 | .python-version 77 | 78 | # celery beat schedule file 79 | celerybeat-schedule 80 | 81 | # SageMath parsed files 82 | *.sage.py 83 | 84 | # Environments 85 | .env 86 | .venv 87 | env/ 88 | venv/ 89 | ENV/ 90 | env.bak/ 91 | venv.bak/ 92 | 93 | # Spyder project settings 94 | .spyderproject 95 | .spyproject 96 | 97 | # Rope project settings 98 | .ropeproject 99 | 100 | # mkdocs documentation 101 | /site 102 | 103 | # mypy 104 | .mypy_cache/ 105 | -------------------------------------------------------------------------------- /application/safeimage/src/worker.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # -*- coding: utf-8 -*- 3 | 4 | # Copyright 2018 Google LLC 5 | # 6 | # Licensed under the Apache License, Version 2.0 (the "License"); 7 | # you may not use this file except in compliance with the License. 8 | # You may obtain a copy of the License at 9 | # 10 | # http://www.apache.org/licenses/LICENSE-2.0 11 | # 12 | # Unless required by applicable law or agreed to in writing, software 13 | # distributed under the License is distributed on an "AS IS" BASIS, 14 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | # See the License for the specific language governing permissions and 16 | # limitations under the License. 17 | 18 | 19 | import json 20 | import logging 21 | import os 22 | import sys 23 | import tempfile 24 | 25 | from PIL import Image, ImageFilter 26 | 27 | from google.cloud import pubsub_v1, storage, vision 28 | 29 | 30 | project_id = os.environ['PROJECT_ID'] 31 | 32 | subscription_name = 'safeimage-workers' 33 | bucket_name = '{}-photostore'.format(project_id) 34 | content_types = {'jpg': 'image/jpeg', 'jpeg': 'image/jpeg', 35 | 'png': 'image/png', 'gif': 'image/gif'} 36 | 37 | subscriber = pubsub_v1.SubscriberClient() 38 | subscription_path = subscriber.subscription_path( 39 | project_id, subscription_name) 40 | 41 | 42 | def blur_image(filename): 43 | bucket = storage.Client().get_bucket(bucket_name) 44 | logger.info('Blurring an image: {}'.format(filename)) 45 | with tempfile.NamedTemporaryFile() as temp: 46 | blob = bucket.blob(filename) 47 | blob.download_to_filename(temp.name) 48 | im = Image.open(temp.name) 49 | im = im.filter(ImageFilter.GaussianBlur(16)) 50 | extention = filename.split('.')[-1].lower() 51 | temp_filename = '{}.{}'.format(temp.name, extention) 52 | im.save(temp_filename) 53 | content_type = content_types[extention] 54 | blob = bucket.blob(filename) 55 | blob.upload_from_filename(temp_filename, content_type=content_type) 56 | blob.make_public() 57 | logger.info('Blurred an image: {}'.format(filename)) 58 | 59 | 60 | def validate_image(filename): 61 | logger = logging.getLogger(__name__) 62 | vision_client = vision.ImageAnnotatorClient() 63 | image = vision.Image() 64 | image.source.image_uri = 'gs://{}/{}'.format(bucket_name, filename) 65 | logger.info('Detecting levels: {}'.format(filename)) 66 | response = vision_client.safe_search_detection(image=image) 67 | safe = response.safe_search_annotation 68 | logger.info('Detected levels for {}: {}'.format(filename, (safe.adult, safe.violence))) 69 | if safe.adult >= 3 or safe.violence >= 2: 70 | blur_image(filename) 71 | 72 | 73 | def callback(message): 74 | logger = logging.getLogger(__name__) 75 | try: 76 | data = message.data.decode('utf-8') 77 | attributes = message.attributes 78 | message.ack() 79 | if attributes['eventType'] != 'OBJECT_FINALIZE' or 'overwroteGeneration' in attributes: 80 | return 81 | object_metadata = json.loads(data) 82 | filename = object_metadata['name'] 83 | logger.info('Processing a file: {}'.format(filename)) 84 | validate_image(filename) 85 | logger.info('Processed a file: {}'.format(filename)) 86 | except Exception as e: 87 | logger.error('Something wrong happened: {}'.format(e.args)) 88 | 89 | 90 | def setup_logger(): 91 | logger = logging.getLogger(__name__) 92 | logger.propagate = False 93 | stdout_handler = logging.StreamHandler(sys.stdout) 94 | stdout_handler.setLevel(logging.DEBUG) 95 | stdout_handler.addFilter(lambda r: r.levelno < logging.WARNING) 96 | logger.addHandler(stdout_handler) 97 | 98 | stderr_handler = logging.StreamHandler(sys.stderr) 99 | stderr_handler.setLevel(logging.DEBUG) 100 | stderr_handler.addFilter(lambda r: r.levelno >= logging.WARNING) 101 | logger.addHandler(stderr_handler) 102 | logger.setLevel(logging.DEBUG) 103 | 104 | 105 | setup_logger() 106 | 107 | streaming_pull_future = subscriber.subscribe( 108 | subscription_path, callback=callback) 109 | logger = logging.getLogger(__name__) 110 | logger.info('Waiting for messages on {}'.format(subscription_path)) 111 | 112 | with subscriber: 113 | try: 114 | streaming_pull_future.result() 115 | except TimeoutError: 116 | streaming_pull_future.cancel() 117 | streaming_pull_future.result() 118 | -------------------------------------------------------------------------------- /application/photoalbum/src/templates/photos.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | Photo Album Example 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 |
17 | Photo Album Example 18 |
19 |
20 | 21 | 22 | 23 | 24 |

The latest 10 photos are shown.

25 |
26 |
27 | 28 | 29 |
30 | 31 | 32 | 33 | 34 |
Select your file (jpg, jpeg, png, gif)
35 |
36 | 37 | attach_file 38 | 39 |
40 | 41 | Upload 42 | 43 | 44 | Refresh 45 | 46 |
47 |
48 |
49 | {% for photo in photos %} 50 | 51 | 52 |
53 | 54 | {% if photo.has_thumbnail %} 55 | 56 |
[{{ photo.label }}] 57 | {% else %} 58 | 59 |
Thumbnail will appear soon. 60 | {% endif %} 61 |
62 |
63 | 64 | Delete 65 | 66 |
67 |
68 |
69 |
70 | {% endfor %} 71 |
72 | 73 | 74 | 75 | 76 | 77 | 78 | 81 | 82 | 116 | 117 | 118 | -------------------------------------------------------------------------------- /application/photoalbum/src/app.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # -*- coding: utf-8 -*- 3 | 4 | # Copyright 2018 Google LLC 5 | # 6 | # Licensed under the Apache License, Version 2.0 (the "License"); 7 | # you may not use this file except in compliance with the License. 8 | # You may obtain a copy of the License at 9 | # 10 | # http://www.apache.org/licenses/LICENSE-2.0 11 | # 12 | # Unless required by applicable law or agreed to in writing, software 13 | # distributed under the License is distributed on an "AS IS" BASIS, 14 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | # See the License for the specific language governing permissions and 16 | # limitations under the License. 17 | 18 | 19 | import os 20 | import tempfile 21 | import uuid 22 | 23 | from auth_decorator import requires_auth 24 | from flask import Flask, render_template, request, redirect, url_for 25 | from flask_sqlalchemy import SQLAlchemy 26 | from flask_wtf.file import FileField 27 | from sqlalchemy import desc 28 | from werkzeug.datastructures import CombinedMultiDict 29 | from werkzeug.utils import secure_filename 30 | from wtforms import Form, ValidationError 31 | 32 | from google.cloud import storage, pubsub_v1 33 | 34 | 35 | project_id = os.environ['PROJECT_ID'] 36 | dbuser = os.environ['DB_USER'] 37 | dbpass = os.environ['DB_PASS'] 38 | 39 | 40 | app = Flask(__name__) 41 | app.config['SQLALCHEMY_DATABASE_URI'] = \ 42 | 'mysql+pymysql://{}:{}@localhost:3306/photo_db'.format(dbuser, dbpass) 43 | app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False 44 | app.app_context().push() 45 | db = SQLAlchemy(app) 46 | bucket_name = '{}-photostore'.format(project_id) 47 | bucket = storage.Client().get_bucket(bucket_name) 48 | storage_path = 'https://storage.googleapis.com/{}'.format(bucket_name) 49 | 50 | 51 | content_types = {'jpg': 'image/jpeg', 'jpeg': 'image/jpeg', 52 | 'png': 'image/png', 'gif': 'image/gif'} 53 | extensions = sorted(content_types.keys()) 54 | 55 | 56 | @app.before_request 57 | @requires_auth 58 | def before_request(): 59 | pass 60 | 61 | 62 | class Photo(db.Model): 63 | id = db.Column(db.Integer, primary_key=True) 64 | filename = db.Column(db.String(128)) 65 | label = db.Column(db.String(64)) 66 | has_thumbnail = db.Column(db.Boolean) 67 | 68 | def __init__(self, filename): 69 | self.filename = filename 70 | self.label = None 71 | self.has_thumbnail = False 72 | 73 | 74 | db.create_all() 75 | 76 | 77 | def publish_message(topic_name, data): 78 | publisher = pubsub_v1.PublisherClient() 79 | topic_path = publisher.topic_path(project_id, topic_name) 80 | publisher.publish(topic_path, data.encode('utf-8')) 81 | 82 | 83 | def is_photo(): 84 | def _is_photo(_, field): 85 | if not field.data: 86 | raise ValidationError('No file') 87 | if field.data and \ 88 | field.data.filename.split('.')[-1].lower() not in extensions: 89 | raise ValidationError('Invalid file name') 90 | return _is_photo 91 | 92 | 93 | class UploadForm(Form): 94 | input_photo = FileField('Photo file (jpg, jpeg, png, gif)', 95 | validators=[is_photo()]) 96 | 97 | 98 | @app.route('/') 99 | def index(): 100 | return render_template('index.html') 101 | 102 | 103 | def show_photos(form): 104 | last_photos = Photo.query.order_by(desc(Photo.id)).limit(10) 105 | last_photos = [photo for photo in last_photos] 106 | return render_template('photos.html', form=form, storage_path=storage_path, 107 | photos=last_photos) 108 | 109 | 110 | @app.route('/photos') 111 | def photos(): 112 | form = UploadForm(request.form) 113 | return show_photos(form) 114 | 115 | 116 | @app.route('/post', methods=['POST']) 117 | def post(): 118 | form = UploadForm(CombinedMultiDict((request.files, request.form))) 119 | if request.method == 'POST' and form.validate(): 120 | filename = '{}.{}'.format( 121 | str(uuid.uuid4()), 122 | secure_filename(form.input_photo.data.filename)) 123 | content_type = content_types[filename.split('.')[-1].lower()] 124 | with tempfile.NamedTemporaryFile() as temp: 125 | form.input_photo.data.save(temp.name) 126 | blob = bucket.blob(filename) 127 | blob.upload_from_filename(temp.name, content_type=content_type) 128 | blob.make_public() 129 | db.session.add(Photo(filename)) 130 | db.session.commit() 131 | publish_message('thumbnail-service', filename) 132 | return show_photos(form) 133 | 134 | 135 | @app.route('/delete', methods=['POST']) 136 | def delete(): 137 | photo_id = list(request.form.keys())[0] 138 | photo = db.session.query(Photo).filter_by(id=photo_id).first() 139 | bucket.delete_blobs( 140 | [photo.filename, 'thumbnails/{}'.format(photo.filename)], 141 | on_error=lambda _: None) 142 | db.session.delete(photo) 143 | db.session.commit() 144 | return redirect(url_for('photos')) 145 | 146 | 147 | if __name__ == '__main__': 148 | app.run(host='0.0.0.0', port=8080, debug=False) 149 | -------------------------------------------------------------------------------- /application/thumbnail/src/worker.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # -*- coding: utf-8 -*- 3 | 4 | # Copyright 2018 Google LLC 5 | # 6 | # Licensed under the Apache License, Version 2.0 (the "License"); 7 | # you may not use this file except in compliance with the License. 8 | # You may obtain a copy of the License at 9 | # 10 | # http://www.apache.org/licenses/LICENSE-2.0 11 | # 12 | # Unless required by applicable law or agreed to in writing, software 13 | # distributed under the License is distributed on an "AS IS" BASIS, 14 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | # See the License for the specific language governing permissions and 16 | # limitations under the License. 17 | 18 | 19 | import logging 20 | import os 21 | import sys 22 | import tempfile 23 | 24 | from flask import Flask 25 | from flask_sqlalchemy import SQLAlchemy 26 | from PIL import Image 27 | 28 | from google.cloud import pubsub_v1, storage, vision 29 | 30 | 31 | project_id = os.environ['PROJECT_ID'] 32 | dbuser = os.environ['DB_USER'] 33 | dbpass = os.environ['DB_PASS'] 34 | 35 | subscription_name = 'thumbnail-workers' 36 | bucket_name = '{}-photostore'.format(project_id) 37 | content_types = {'jpg': 'image/jpeg', 'jpeg': 'image/jpeg', 38 | 'png': 'image/png', 'gif': 'image/gif'} 39 | 40 | app = Flask(__name__) 41 | app.config['SQLALCHEMY_DATABASE_URI'] = \ 42 | 'mysql+pymysql://{}:{}@localhost:3306/photo_db'.format(dbuser, dbpass) 43 | app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False 44 | app.app_context().push() 45 | db = SQLAlchemy(app) 46 | 47 | subscriber = pubsub_v1.SubscriberClient() 48 | subscription_path = subscriber.subscription_path( 49 | project_id, subscription_name) 50 | 51 | def setup_logger(): 52 | logger = logging.getLogger(__name__) 53 | logger.propagate = False 54 | stdout_handler = logging.StreamHandler(sys.stdout) 55 | stdout_handler.setLevel(logging.DEBUG) 56 | stdout_handler.addFilter(lambda r: r.levelno < logging.WARNING) 57 | logger.addHandler(stdout_handler) 58 | 59 | stderr_handler = logging.StreamHandler(sys.stderr) 60 | stderr_handler.setLevel(logging.DEBUG) 61 | stderr_handler.addFilter(lambda r: r.levelno >= logging.WARNING) 62 | logger.addHandler(stderr_handler) 63 | logger.setLevel(logging.DEBUG) 64 | 65 | 66 | class Photo(db.Model): 67 | id = db.Column(db.Integer, primary_key=True) 68 | filename = db.Column(db.String(128)) 69 | label = db.Column(db.String(64)) 70 | has_thumbnail = db.Column(db.Boolean) 71 | 72 | def __init__(self, filename): 73 | self.filename = filename 74 | self.label = None 75 | self.has_thumbnail = False 76 | 77 | 78 | def create_thumbnail(filename): 79 | logger = logging.getLogger(__name__) 80 | bucket = storage.Client().get_bucket(bucket_name) 81 | 82 | logger.info('Creating a thumbnail: {}'.format(filename)) 83 | with tempfile.NamedTemporaryFile() as temp: 84 | blob = bucket.blob(filename) 85 | blob.download_to_filename(temp.name) 86 | im = Image.open(temp.name) 87 | im.thumbnail((128, 128), Image.ANTIALIAS) 88 | 89 | extention = filename.split('.')[-1].lower() 90 | temp_filename = '{}.{}'.format(temp.name, extention) 91 | im.save(temp_filename) 92 | content_type = content_types[extention] 93 | blob = bucket.blob('thumbnails/{}'.format(filename)) 94 | blob.upload_from_filename(temp_filename, content_type=content_type) 95 | blob.make_public() 96 | logger.info('Created a thumbnail: {}'.format(filename)) 97 | 98 | 99 | def update_db(filename): 100 | logger = logging.getLogger(__name__) 101 | vision_client = vision.ImageAnnotatorClient() 102 | image = vision.Image() 103 | image.source.image_uri = 'gs://{}/{}'.format(bucket_name, filename) 104 | logger.info('Detecting labels: {}'.format(filename)) 105 | response = vision_client.label_detection(image=image, max_results=3) 106 | labels = [label.description for label in response.label_annotations] 107 | logger.info('Detected labels for {}: {}'.format( 108 | filename, ', '.join(labels))) 109 | 110 | logger.info('Updating the database: {}'.format(filename)) 111 | with app.app_context(): 112 | photo = db.session.query(Photo).filter_by(filename=filename).first() 113 | photo.label = ', '.join(labels) 114 | photo.has_thumbnail = True 115 | db.session.commit() 116 | logger.info('Updated the database: {}'.format(filename)) 117 | 118 | 119 | def callback(message): 120 | logger = logging.getLogger(__name__) 121 | try: 122 | filename = message.data.decode() 123 | logger.info('Processing a file: {}'.format(filename)) 124 | message.ack() 125 | create_thumbnail(filename) 126 | update_db(filename) 127 | logger.info('Processed a file: {}'.format(filename)) 128 | except Exception as e: 129 | logger.error('Something wrong happened: {}'.format(e.args)) 130 | 131 | 132 | setup_logger() 133 | 134 | streaming_pull_future = subscriber.subscribe( 135 | subscription_path, callback=callback) 136 | logger = logging.getLogger(__name__) 137 | logger.info('Waiting for messages on {}'.format(subscription_path)) 138 | 139 | with subscriber: 140 | try: 141 | streaming_pull_future.result() 142 | except TimeoutError: 143 | streaming_pull_future.cancel() 144 | streaming_pull_future.result() 145 | 146 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # GKE Photo Album Example 2 | 3 | Disclaimer: This is not an official Google product. 4 | 5 | This is an example application demonstrating how Cloud Pub/Sub can be used 6 | to implement asynchronous service calls for applications running on GKE. 7 | 8 | ![](docs/img/screenshot.png) 9 | 10 | ## Products 11 | - [Kubernetes Engine][1] 12 | - [Cloud Storage][2] 13 | - [Cloud Pub/Sub][3] 14 | - [Cloud SQL][4] 15 | - [Cloud Build][5] 16 | - [Cloud Vision][6] 17 | 18 | ## Language 19 | - [Python][7] 20 | 21 | [1]: https://cloud.google.com/kubernetes-engine//docs 22 | [2]: https://cloud.google.com/storage/ 23 | [3]: https://cloud.google.com/pubsub/ 24 | [4]: https://cloud.google.com/sql/ 25 | [5]: https://cloud.google.com/cloud-build/ 26 | [6]: https://cloud.google.com/vision/ 27 | [7]: https://python.org 28 | 29 | ## Prerequisites 30 | 1. A Google Cloud Platform Account 31 | 2. [A new Google Cloud Platform Project][8] for this lab with billing enabled 32 | 3. Enable the following APIs from 33 | [the API Manager][9] 34 | 35 | - Kubernetes Engine API 36 | - Cloud SQL Admin API 37 | - Cloud Build API 38 | - Cloud Vision API 39 | - Artifact Registry API 40 | 41 | [8]: https://console.developers.google.com/project 42 | [9]: https://console.developers.google.com 43 | 44 | ## Do this first 45 | In this section you will start your [Google Cloud Shell][10] and clone the 46 | application code repository to it. 47 | 48 | 1. [Open the Cloud Console][11] 49 | 50 | 2. Click the Google Cloud Shell icon in the top-right and wait for your shell 51 | to open: 52 | 53 | ![](docs/img/cloud-shell.png) 54 | 55 | 3. Clone the lab repository in your cloud shell, then `cd` into that dir: 56 | 57 | ``` 58 | git clone https://github.com/GoogleCloudPlatform/gke-photoalbum-example.git 59 | cd gke-photoalbum-example 60 | ``` 61 | 62 | [10]: https://cloud.google.com/cloud-shell/docs/ 63 | [11]: https://console.cloud.google.com/ 64 | 65 | 66 | ## Deploy Photo Album Application 67 | 68 | ### Prepare Storage Bucket 69 | 70 | Create a storage bucket from the Cloud Shell. 71 | 72 | ``` 73 | export PROJECT_ID=$(gcloud config list project --format "value(core.project)") 74 | gsutil mb -c regional -l us-central1 gs://${PROJECT_ID}-photostore 75 | ``` 76 | 77 | Upload the default thumbnail file and make it public. 78 | 79 | ``` 80 | gsutil cp ./application/photoalbum/images/default.png gs://${PROJECT_ID}-photostore/thumbnails/default.png 81 | gsutil acl ch -u AllUsers:R gs://${PROJECT_ID}-photostore/thumbnails/default.png 82 | ``` 83 | 84 | ### Create CloudSQL Instance 85 | 86 | Create a CloudSQL instance for MySQL database. 87 | 88 | - Use "MySQL Development" instance. 89 | - Set Instance ID as `photoalbum-db`. 90 | - Set Root password as your choice. 91 | - Open "Enable auto backups and high availability" and uncheck "Automate backups". 92 | - Others can be left as default. 93 | 94 | When the instance creation has been completed, click on the Instance ID name (`photoalbum-db`) and check the Instance connection name. The connection name will be `[Project ID]:us-central1:photoalbum-db` if you chose the configuration options as above. 95 | 96 | Connect to the CloudSQL instance from the Cloud Shell and create database `photo_db` and application user `appuser`. 97 | 98 | ``` 99 | gcloud sql connect photoalbum-db --user=root --quiet 100 | 101 | CREATE DATABASE photo_db; 102 | CREATE USER 'appuser'@'%' IDENTIFIED BY 'pas4appuser'; 103 | GRANT ALL ON photo_db.* TO 'appuser'@'%' WITH GRANT OPTION; 104 | FLUSH PRIVILEGES; 105 | exit 106 | ``` 107 | 108 | ### Create Pub/Sub Topic and Subscription 109 | 110 | ``` 111 | gcloud pubsub topics create thumbnail-service 112 | gcloud pubsub subscriptions create --topic thumbnail-service thumbnail-workers 113 | ``` 114 | 115 | ### Create GKE cluster 116 | 117 | - Set cluster name as `photoalbum-cluster`. 118 | - Set Number of nodes as `5`. 119 | - Set Access scopes as "Allow full access to all Cloud APIs". 120 | - Set Zone as `us-central1-a` 121 | - Others can be left as default. 122 | 123 | ### Create Artifact Registry Repository 124 | 125 | ``` 126 | gcloud artifacts repositories create photoalbum-repo --repository-format=docker --location=us-central1 --description="Docker repository" 127 | ``` 128 | 129 | ### Build Container Images 130 | 131 | This application has a simple user authentication mechanism. You can change the username and password by modifying the following part in `application/photoalbum/src/auth_decorator.py`. 132 | 133 | ``` 134 | USERNAME = 'username' 135 | PASSWORD = 'passw0rd' 136 | ``` 137 | 138 | Build container images using Cloud Build. 139 | 140 | ``` 141 | export PROJECT_ID=$(gcloud config list project --format "value(core.project)") 142 | gcloud builds submit ./application/photoalbum -t us-central1-docker.pkg.dev/$PROJECT_ID/photoalbum-repo/photoalbum-app 143 | gcloud builds submit ./application/thumbnail -t us-central1-docker.pkg.dev/$PROJECT_ID/photoalbum-repo/thumbnail-worker 144 | ``` 145 | 146 | Check image digests. 147 | 148 | ``` 149 | gcloud container images describe us-central1-docker.pkg.dev/$PROJECT_ID/photoalbum-repo/photoalbum-app:latest --format "value(image_summary.digest)" 150 | gcloud container images describe us-central1-docker.pkg.dev/$PROJECT_ID/photoalbum-repo/thumbnail-worker:latest --format "value(image_summary.digest)" 151 | ``` 152 | 153 | ### Deploy Application 154 | 155 | Modify the config file `config/photoalbum-deployment.yaml`. 156 | 157 | - Change `[PROJECT_ID]` to your project id. 158 | - Change `[CONNECTION_NAME]` to Cloud SQL's connection name that you have checked in the section "Create CloudSQL Instance". 159 | - Change `[DIGEST]` to the image digest of Photo Album application that you have checked in the previous step. 160 | 161 | Modify the config file `config/thumbnail-deployment.yaml`. 162 | - Change `[PROJECT_ID]` to your project id. 163 | - Change `[CONNECTION_NAME]` to Cloud SQL's connection name that you have checked in the section "Create CloudSQL Instance". 164 | - Change `[DIGEST]` to the image digest of Thumbnail Generation service that you have checked in the previous step. 165 | 166 | You can copy-and-paste the following commands to apply these modifications. 167 | 168 | ``` 169 | PROJECT_ID=$(gcloud config list project --format "value(core.project)") 170 | connection_name=$(gcloud sql instances describe photoalbum-db --format "value(connectionName)") 171 | 172 | digest_photoalbum=$(gcloud container images describe us-central1-docker.pkg.dev/$PROJECT_ID/photoalbum-repo/photoalbum-app:latest --format "value(image_summary.digest)") 173 | sed -i.bak "s/\[PROJECT_ID\]/$PROJECT_ID/;s/\[CONNECTION_NAME\]/$connection_name/;s/\[DIGEST\]/$digest_photoalbum/" config/photoalbum-deployment.yaml 174 | 175 | digest_thumbnail=$(gcloud container images describe us-central1-docker.pkg.dev/$PROJECT_ID/photoalbum-repo/thumbnail-worker:latest --format "value(image_summary.digest)") 176 | sed -i.bak "s/\[PROJECT_ID\]/$PROJECT_ID/;s/\[CONNECTION_NAME\]/$connection_name/;s/\[DIGEST\]/$digest_thumbnail/" config/thumbnail-deployment.yaml 177 | ``` 178 | 179 | Create GKE resources. 180 | 181 | ``` 182 | gcloud container clusters get-credentials photoalbum-cluster --zone us-central1-a 183 | kubectl create -f config/photoalbum-deployment.yaml 184 | kubectl create -f config/thumbnail-deployment.yaml 185 | kubectl create -f config/photoalbum-service.yaml 186 | ``` 187 | 188 | ### Test Application 189 | 190 | Confirm that there are three pods for each of photoalbum-app and thembail-worker with STATUS Running, and EXTERNAL-IP is assigned to photoalbum-service. It may take a few minutes until they are all set and running. 191 | 192 | ``` 193 | $ kubectl get pods 194 | NAME READY STATUS RESTARTS AGE 195 | photoalbum-app-555f7cbdb7-cp8nw 2/2 Running 0 2m 196 | photoalbum-app-555f7cbdb7-ftlc6 2/2 Running 0 2m 197 | photoalbum-app-555f7cbdb7-xsr4b 2/2 Running 0 2m 198 | thumbnail-worker-86bd95cd68-728k5 2/2 Running 0 2m 199 | thumbnail-worker-86bd95cd68-hqxqr 2/2 Running 0 2m 200 | thumbnail-worker-86bd95cd68-xnxhc 2/2 Running 0 2m 201 | 202 | $ kubectl get services 203 | NAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) AGE 204 | kubernetes ClusterIP 10.23.240.1 443/TCP 20m 205 | photoalbum-service LoadBalancer 10.23.253.241 146.148.111.115 80:32657/TCP 2m 206 | ``` 207 | 208 | Now you can try the application thorugh the URI `http://[EXTERNAL-IP]`. 209 | 210 | ## Adding Safeimage Feature 211 | 212 | You add a safeimage feature that detect offensive images and blur them automatically. 213 | 214 | ### Create Pub/Sub Topic and Subscription 215 | 216 | ``` 217 | gcloud pubsub topics create safeimage-service 218 | gcloud pubsub subscriptions create --topic safeimage-service safeimage-workers 219 | ``` 220 | 221 | ### Setup Pub/Sub Notification 222 | ``` 223 | export PROJECT_ID=$(gcloud config list project --format "value(core.project)") 224 | gsutil notification create -t safeimage-service -f json gs://${PROJECT_ID}-photostore 225 | ``` 226 | 227 | ### Build Container Image 228 | 229 | Build a container image using Cloud Build. 230 | 231 | ``` 232 | export PROJECT_ID=$(gcloud config list project --format "value(core.project)") 233 | gcloud builds submit ./application/safeimage -t us-central1-docker.pkg.dev/$PROJECT_ID/photoalbum-repo/safeimage-worker 234 | ``` 235 | 236 | Check an image digest. 237 | 238 | ``` 239 | gcloud container images describe us-central1-docker.pkg.dev/$PROJECT_ID/photoalbum-repo/safeimage-worker:latest --format "value(image_summary.digest)" 240 | ``` 241 | 242 | ### Deploy application 243 | 244 | Modify the config file `config/safeimage-deployment.yaml`. 245 | 246 | - Change `[PROJECT_ID]` to your project id. 247 | - Change `[DIGEST]` to the image digest of Safeimage service that you have checked in the previous step. 248 | 249 | You can copy-and-paste the following commands to apply these modifications. 250 | 251 | ``` 252 | digest_safeimage=$(gcloud container images describe us-central1-docker.pkg.dev/$PROJECT_ID/photoalbum-repo/safeimage-worker:latest --format "value(image_summary.digest)") 253 | sed -i.bak "s/\[PROJECT_ID\]/$PROJECT_ID/;s/\[CONNECTION_NAME\]/$connection_name/;s/\[DIGEST\]/$digest_safeimage/" config/safeimage-deployment.yaml 254 | ``` 255 | 256 | Create a deployment resource to roll out Safeimage service. 257 | ``` 258 | kubectl create -f config/safeimage-deployment.yaml 259 | ``` 260 | 261 | Confirm that there are three pods of safeimage-worker with STATUS Running. It may take a few minutes until they are all set and running. 262 | 263 | ``` 264 | $ kubectl get pods 265 | NAME READY STATUS RESTARTS AGE 266 | photoalbum-app-555f7cbdb7-cp8nw 2/2 Running 0 30m 267 | photoalbum-app-555f7cbdb7-ftlc6 2/2 Running 0 30m 268 | photoalbum-app-555f7cbdb7-xsr4b 2/2 Running 8 30m 269 | safeimage-worker-7dc8c84f54-6sqzs 1/1 Running 0 2m 270 | safeimage-worker-7dc8c84f54-9bskw 1/1 Running 0 2m 271 | safeimage-worker-7dc8c84f54-b7gtp 1/1 Running 0 2m 272 | thumbnail-worker-86bd95cd68-9wrpv 2/2 Running 0 30m 273 | thumbnail-worker-86bd95cd68-kbhsn 2/2 Running 2 30m 274 | thumbnail-worker-86bd95cd68-n4rj7 2/2 Running 0 30m 275 | ``` 276 | 277 | Test the feature using the sample file of a [violent picture](https://pixabay.com/en/zombie-flesh-eater-dead-spooky-949916/). (This is a picture of a zombie biting a human.) 278 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | --------------------------------------------------------------------------------