Skip to content

add microservices demo #509

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

Merged
merged 12 commits into from
Oct 11, 2016
Merged
Show file tree
Hide file tree
Changes from 5 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
56 changes: 56 additions & 0 deletions appengine/flexible/multiple_services/api_gateway/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
# Python Google Cloud Microservices Example - API Gateway

This example demonstrates how to deploy multiple python services to [App Engine flexible environment](https://cloud.google.com/appengine/docs/flexible/)

## To Run Locally
Copy link
Contributor

Choose a reason for hiding this comment

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

This local run story is pretty rough, and some of that blame of course falls on Google. Do you have any ideas on how we can improve this for this sample (procfile + honcho)? Overall?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

@jonparrott I've got it running now so that it will work as previously in production, and the user can run locally by using a --development flag from the command line without having to do anything with the code. Is that sufficient?

Copy link
Contributor

Choose a reason for hiding this comment

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

Sounds reasonable, push the code up?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

OK. Needs the other changes though, and testing with deployed code. Will push up now so you can see and again when changes complete.


1. You will need to install Python 3 on your local machine

2. Install virtualenv
```Bash
$ pip install virtualenv
```

3. To setup the environment in each server's directory:
```Bash
$ virtualenv -p python3 env
$ source env/bin/activate
$ pip install -r requirements.txt
$ deactivate
```

4. Change the url's in the API gateway `gateway/api_gateway.py` to the
development ports specified in line `gateway/api_gateway.py:6`
```Python
development ports {static: 8003, flask1: 8001, flask2: 8002}
```

## To Deploy to App Engine

### YAML Files

Each directory contains an `app.yaml file`. This file will be the same as if
each service were its own project except for the `service` line. For the gateway:
Copy link
Contributor

Choose a reason for hiding this comment

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

I would prefer to remove the line "This file will be the same as if
+each service were its own project except for the service line.", perhaps "These files all describe a separate App Engine service within the same project".


[Gateway <default>](gateway/app.yaml)

This is the `default` service. There must be one (and not more). The deployed
url will be `https://<your project id>.appspot.com`

For the other services:

[Flask Server 1 <flask1>](flask/app.yaml)
[Flask Server 2 <flask2](flask2/app.yaml)
[Static File Server <static>](static/app.yaml)

Make sure the `entrypoint` line matches the filename of the server you want to deploy.

The deployed url will be `https://<service name>-dot-<your project id>.appspot.com`

### Deployment

To deploy a service cd into its directory and run: `gcloud app deploy app.yaml`
and enter `Y` when prompted. Or to skip the check add `-q`.

To test if a service is successfully deployed, simply navigate to the root
and you will see a message.
10 changes: 10 additions & 0 deletions appengine/flexible/multiple_services/api_gateway/flask/app.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
service: flask1
runtime: python
vm: true
entrypoint: gunicorn -b :$PORT flask_server:app

runtime_config:
python_version: 3

manual_scaling:
Copy link
Contributor

Choose a reason for hiding this comment

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

blank newline above this, please.

instances: 1
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
import sys
from flask import Flask

app = Flask(__name__)

@app.route('/hello')
def say_hello():
return 'Flask server 1 says hello!'

@app.route('/')
def root():
return 'This is flask server 1.'

if __name__ == "__main__":
if len(sys.argv) > 1 and sys.argv[1] == '--development':
Copy link
Contributor

Choose a reason for hiding this comment

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

How awful would it be to introduce argparse here?

Copy link
Contributor

Choose a reason for hiding this comment

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

You could also make the port an arg. :)

app.run(port=int(8001))
Copy link
Contributor

Choose a reason for hiding this comment

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

debug=True?

else:
app.run()
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
click==6.6
Flask==0.11.1
gunicorn==19.6.0
itsdangerous==0.24
Jinja2==2.8
MarkupSafe==0.23
requests==2.11.1
Werkzeug==0.11.11
10 changes: 10 additions & 0 deletions appengine/flexible/multiple_services/api_gateway/flask2/app.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
service: flask2
runtime: python
vm: true
entrypoint: gunicorn -b :$PORT flask_server:app

runtime_config:
python_version: 3

manual_scaling:
instances: 1
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
import sys
from flask import Flask

app = Flask(__name__)

@app.route('/hello')
def say_hello():
return 'Flask server 2 says hello!'

@app.route('/')
def root():
return 'This is flask server 2.'

if __name__ == "__main__":
if len(sys.argv) > 1 and sys.argv[1] == '--development':
app.run(port=int(8002))
else:
app.run()
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
click==6.6
Flask==0.11.1
gunicorn==19.6.0
itsdangerous==0.24
Jinja2==2.8
MarkupSafe==0.23
requests==2.11.1
Werkzeug==0.11.11
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
import requests
import sys
import os
from flask import Flask
app = Flask(__name__)

@app.route('/environment')
def get_env():
configuration = 'production'
Copy link
Contributor

Choose a reason for hiding this comment

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

unused variable?

return app.config['MODE']

@app.route('/test')
def test():
return "GATEWAY OPERATIONAL"

@app.route('/')
def root():
urls = {
Copy link
Contributor

Choose a reason for hiding this comment

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

You could make this a constant?

'development': 'http://localhost:8003',
'production': 'https://static-dot-' + os.environ.get('GAE_LONG_APP_ID', '') + '.appspot.com'
}
environment = app.config['MODE']
print(environment)
Copy link
Contributor

Choose a reason for hiding this comment

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

leftover prints?

print(urls[environment])
res = requests.get(urls[environment])
return res.content

@app.route('/hello/<service>')
def say_hello(service):
environment = app.config['MODE']
services = {
'production': {
'flask1': { 'url': 'https://flask1-dot-' + os.environ.get('GAE_LONG_APP_ID', '') + '.appspot.com', 'send': False },
'flask2': { 'url': 'https://flask2-dot-' + os.environ.get('GAE_LONG_APP_ID', '') + '.appspot.com', 'send': False }
},
'development': {
'flask1': {'url': 'http://localhost:8001', 'send': False },
'flask2': {'url': 'http://localhost:8002', 'send': False }
}
}
environment = app.config['MODE']
if service == 'everyone':
for key, val in services[environment].items():
val['send'] = True
else:
services[environment][service]['send'] = True

responses = []
for key, val in services[environment].items():
if val['send'] == True:
res = requests.get(val['url'] + '/hello')
responses.append(res.content)

return '\n'.encode().join(responses)

@app.route('/<path>')
def static_file(path):
environment = app.config['MODE']
url = {
'development': 'http://localhost:8003',
'production': 'https://static-dot-' + os.environ.get('GAE_LONG_APP_ID', '') + '.appspot.com'
}
res = requests.get(url[environment] + '/' + path)
return res.content, 200, {'Content-Type': res.headers['Content-Type']}


if __name__ == "__main__":
if len(sys.argv) > 1 and sys.argv[1] == '--development':
app.config['MODE'] = 'development'
app.config['DEBUG'] = True
app.run(port=int(8000))
else:
app.config['MODE'] = 'production'
app.run()
10 changes: 10 additions & 0 deletions appengine/flexible/multiple_services/api_gateway/gateway/app.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
service: default
runtime: python
vm: true
entrypoint: gunicorn -b :$PORT api_gateway:app

runtime_config:
python_version: 3

manual_scaling:
instances: 1
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
click==6.6
Flask==0.11.1
gunicorn==19.6.0
itsdangerous==0.24
Jinja2==2.8
MarkupSafe==0.23
requests==2.11.1
Werkzeug==0.11.11
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
service: static
runtime: python
vm: true
entrypoint: gunicorn -b :$PORT static_server:app

runtime_config:
python_version: 3
manual_scaling:
instances: 1
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
click==6.6
Flask==0.11.1
gunicorn==19.6.0
itsdangerous==0.24
Jinja2==2.8
MarkupSafe==0.23
requests==2.11.1
Werkzeug==0.11.11
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<link rel="stylesheet" type="text/css" href="style.css" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="index.js"></script>
<title>API Gateway on App Engine Flexible Environment</title>
</head>
<body>
<h1>API GATEWAY DEMO</h1>
<p>Say hi to:</p>
<button class='request-button' id='flask1'>Flask Server 1</button>
<button class='request-button' id='flask2'>Flask Server 2</button>
<button class='request-button' id='everyone'>Everyone</button>
<ul class='responses'></ul>
</body>
</html>
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
function handleResponse(resp){
const li = document.createElement('li');
li.innerHTML = resp;
document.querySelector('.responses').appendChild(li)
}

function handleClick(event){
$.ajax({
url: `hello/${event.target.id}`,
type: `GET`,
success(resp){
handleResponse(resp);
}
});
}

document.addEventListener('DOMContentLoaded', () => {
const buttons = document.getElementsByTagName('button')
for (var i = 0; i < buttons.length; i++) {
buttons[i].addEventListener('click', handleClick);
}
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
h1 {
color: red;
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
import sys
from flask import Flask

app = Flask(__name__)

@app.route('/hello')
def say_hello():
return 'Flask server 2 says hello!'

@app.route('/')
def root():
return app.send_static_file('index.html')

@app.route('/<path:path>')
def static_file(path):
mimetype = ''
if path.split('.')[1] == 'css':
mimetype = 'text/css'
if path.split('.')[1] == 'js':
mimetype = 'application/javascript'
return app.send_static_file(path), 200, {'Content-Type': mimetype}

if __name__ == "__main__":
if len(sys.argv) > 1 and sys.argv[1] == '--development':
Copy link
Contributor

Choose a reason for hiding this comment

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

argparse?

app.run(port=int(8003))
else:
app.run()