Setup an f1-micro server, copy echo.py, install virtualenv
sudo apt-get update sudo apt-get install python-virtualenv virtualenv -p python3 ~/venv3 source ~/venv3/bin/activate pip install flask
Add to the crontab of root the following:
@reboot /home/gabor/venv3/bin/python /home/gabor/echo.py 5000
TODO: install a more roboust webserver for this or run uwsgi
Create a snapshot of the server Create an image from the snapshot Create an "Instance Template" that can create an instance of f1-micro using the above image.
Create an instance group
Networks Services - create a load balancer that uses the instance group.
from flask import Flask, request, jsonify
import sys
from datetime import datetime
import socket
import json
app = Flask(__name__)
version = 1
def myconverter(o):
if isinstance(o, datetime):
return o.__str__()
@app.route("/")
def hello():
logfile = '/tmp/echo.log'
data = {
'client': request.remote_addr,
'hostname': socket.gethostname(),
'port': port,
'now': datetime.now(),
'version': version,
}
with open(logfile, 'a') as fh:
fh.write(json.dumps(data, default = myconverter))
fh.write("\n")
return jsonify(data)
if __name__ == "__main__":
if len(sys.argv) < 2:
exit("Need port number")
port = int(sys.argv[1])
app.run(port = port, host='0.0.0.0')
examples/load-balancer/monitor.py
#!/usr/bin/env python
import requests
import time
import sys
url = 'http://10.2.11.5:5000/'
while True:
#print(time.time())
try:
res = requests.get(url, timeout=0.3)
if res.status_code == 200:
print(res.content, end="")
else:
print("ERROR: {}".format(res.status_code))
except Exception as e:
print("EXCEPTION {}".format(e))
sys.stdout.flush()
time.sleep(1)