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 6 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.
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
import requests
import sys
from flask import Flask
import services_config
app = Flask(__name__)
app.config['SERVICE_MAP'] = services_config.map_services('production')

@app.route('/env')
def get_env():
print(app.config['SERVICE_MAP'])
Copy link
Contributor

Choose a reason for hiding this comment

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

stray print?

return app.config
Copy link
Contributor

Choose a reason for hiding this comment

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

returning the entire app.config can be a security issue, can you limit the scope here?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Yeah. Meant to take that out that was just for me to play around with!


@app.route('/')
def root():
'''Gets index.html from the static file server'''
res = requests.get(app.config['SERVICE_MAP']['static'])
return res.content

@app.route('/hello/<service>')
def say_hello(service):
'''Recieves requests from the buttons on the front end and resopnds
or sends request to the static file server'''
#if 'gateway' is specified return immediate
if service == 'gateway':
return 'Gateway says hello'

responses = []
url = app.config['SERVICE_MAP'][service]
res = requests.get(url + '/hello')
responses.append(res.content)

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

@app.route('/<path>')
def static_file(path):
'''Handles static file requests from index.html'''
url = app.config['SERVICE_MAP']['static']
res = requests.get(url + '/' + 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['SERVICE_MAP'] = services_config.map_services('development')
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,29 @@
import os

#to add services insert key value pair of the name of the service and
#the port you want it to run on when running locally
SERVICES = {
'default': 5000,
'static': 8001
}

def map_services(environment):
url_map = {}
for service, local_port in SERVICES.items():
if environment == 'production':
url_map[service] = production_url(service)
if environment == 'development':
url_map[service] = local_url(local_port)
return url_map

def production_url(service_name):
project_id = os.environ.get('GAE_LONG_APP_ID') or 'flask-algo'
project_url = project_id + '.appspot.com'
template = 'https://{}{}'
Copy link
Contributor

Choose a reason for hiding this comment

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

use named interpolation if you use a template more than once, e.g. https://{service_name_prefix}{project_url}.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Named interpolation was really verbose so I removed the template.

if service_name == 'default':
        return 'https://{}'.format(project_url)
    else:
        return 'https://{}-dot-{}'.format(service_name, project_url)

if service_name == 'default':
return template.format('', project_url)
else:
return template.format(service_name + '-dot-', project_url)

def local_url(port):
return 'http://localhost:' + str(port)
Copy link
Contributor

Choose a reason for hiding this comment

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

Use format instead of concatenation.

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,17 @@
<!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='gateway'>Gateway</button>
<button class='request-button' id='static'>Static File Server</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,28 @@
import sys
from flask import Flask

app = Flask(__name__)

@app.route('/hello')
def say_hello():
return 'Static File Server 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.config['DEBUG'] = True
app.run(port=int(8001))
else:
app.run()