Skip to content
Open
Show file tree
Hide file tree
Changes from all 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
104 changes: 104 additions & 0 deletions azure-vote/main-copy-2.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,104 @@
from flask import Flask, request, render_template
import os
import random
import redis
import socket
import sys

app = Flask(__name__)

# Load configurations from environment or config file
app.config.from_pyfile('config_file.cfg')

if ("VOTE1VALUE" in os.environ and os.environ['VOTE1VALUE']):
button1 = os.environ['VOTE1VALUE']
else:
button1 = app.config['VOTE1VALUE']

if ("VOTE2VALUE" in os.environ and os.environ['VOTE2VALUE']):
button2 = os.environ['VOTE2VALUE']
else:
button2 = app.config['VOTE2VALUE']

if ("TITLE" in os.environ and os.environ['TITLE']):
title = os.environ['TITLE']
else:
title = app.config['TITLE']

# Redis Connection to a local server running on the same machine where the current FLask app is running.
r = redis.Redis()

"""
# The commented section below is used while deploying the application with two separate containers -
# One container for Redis and another for the frontend.

# Redis configurations
redis_server = os.environ['REDIS']

try:
if "REDIS_PWD" in os.environ:
r = redis.StrictRedis(host=redis_server,
port=6379,
password=os.environ['REDIS_PWD'])
else:
r = redis.Redis(redis_server)
r.ping()
except redis.ConnectionError:
exit('Failed to connect to Redis, terminating.')
"""

# Change title to host name to demo NLB
if app.config['SHOWHOST'] == "true":
title = socket.gethostname()

# Init Redis
if not r.get(button1): r.set(button1,0)
if not r.get(button2): r.set(button2,0)

@app.route('/', methods=['GET', 'POST'])
def index():

if request.method == 'GET':

# Get current values
vote1 = r.get(button1).decode('utf-8')
vote2 = r.get(button2).decode('utf-8')

# Return index with values
return render_template("index.html", value1=int(vote1), value2=int(vote2), button1=button1, button2=button2, title=title)

elif request.method == 'POST':

if request.form['vote'] == 'reset':

# Empty table and return results
r.set(button1,0)
r.set(button2,0)
vote1 = r.get(button1).decode('utf-8')
properties = {'custom_dimensions': {'Cats Vote': vote1}}
logger.info('Cats Vote', extra=properties)

vote2 = r.get(button2).decode('utf-8')
properties = {'custom_dimensions': {'Dogs Vote': vote2}}
logger.info('Dogs Vote', extra=properties)

return render_template("index.html", value1=int(vote1), value2=int(vote2), button1=button1, button2=button2, title=title)

else:

# Insert vote result into DB
vote = request.form['vote']
r.incr(vote,1)

# Get current values
vote1 = r.get(button1).decode('utf-8')
vote2 = r.get(button2).decode('utf-8')

# Return results
return render_template("index.html", value1=int(vote1), value2=int(vote2), button1=button1, button2=button2, title=title)

if __name__ == "__main__":
# comment line below when deploying to VMSS
app.run() # local
# uncomment the line below before deployment to VMSS
# app.run(host='0.0.0.0', threaded=True, debug=True) # remote
168 changes: 120 additions & 48 deletions azure-vote/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,66 @@
import redis
import socket
import sys
import requests

import logging
from datetime import datetime
# App Insights
# TODO: Import required libraries for App Insights
from opencensus.ext.azure.log_exporter import AzureLogHandler
from opencensus.ext.azure.log_exporter import AzureEventHandler
from opencensus.ext.azure import metrics_exporter
from opencensus.stats import aggregation as aggregation_module
from opencensus.stats import measure as measure_module
from opencensus.stats import stats as stats_module
from opencensus.stats import view as view_module
from opencensus.tags import tag_map as tag_map_module
from opencensus.trace import config_integration
from opencensus.ext.azure.trace_exporter import AzureExporter
from opencensus.trace.samplers import ProbabilitySampler
from opencensus.trace.tracer import Tracer
from opencensus.ext.flask.flask_middleware import FlaskMiddleware
# For metrics
stats = stats_module.stats
view_manager = stats.view_manager



config_integration.trace_integrations(['logging'])
config_integration.trace_integrations(['requests'])
# Standard Logging
logger = logging.getLogger(__name__)
handler = AzureLogHandler(connection_string='InstrumentationKey=0d798b12-ed86-4926-8602-745764ba51d2;IngestionEndpoint=https://westeurope-5.in.applicationinsights.azure.com/')
handler.setFormatter(logging.Formatter('%(traceId)s %(spanId)s %(message)s'))
logger.addHandler(handler)
# Logging custom Events
logger.addHandler(AzureEventHandler(connection_string='InstrumentationKey=0d798b12-ed86-4926-8602-745764ba51d2;IngestionEndpoint=https://westeurope-5.in.applicationinsights.azure.com/'))
# Set the logging level
logger.setLevel(logging.INFO)

# Metrics
exporter = metrics_exporter.new_metrics_exporter(
enable_standard_metrics=True,
connection_string='InstrumentationKey=0d798b12-ed86-4926-8602-745764ba51d2;IngestionEndpoint=https://westeurope-5.in.applicationinsights.azure.com/')
view_manager.register_exporter(exporter)

# Tracing
tracer = Tracer(
exporter=AzureExporter(
connection_string='InstrumentationKey=0d798b12-ed86-4926-8602-745764ba51d2;IngestionEndpoint=https://westeurope-5.in.applicationinsights.azure.com/'),
sampler=ProbabilitySampler(1.0),
)

app = Flask(__name__)

# Requests
middleware = FlaskMiddleware(
app,
exporter=AzureExporter(connection_string="InstrumentationKey=0d798b12-ed86-4926-8602-745764ba51d2;IngestionEndpoint=https://westeurope-5.in.applicationinsights.azure.com/"),
sampler=ProbabilitySampler(rate=1.0)
)


# Load configurations from environment or config file
app.config.from_pyfile('config_file.cfg')

Expand All @@ -25,26 +82,25 @@
else:
title = app.config['TITLE']

# Redis Connection to a local server running on the same machine where the current FLask app is running.
# Redis configurations

# Redis Connection

r = redis.Redis()

"""
# The commented section below is used while deploying the application with two separate containers -
# One container for Redis and another for the frontend.

# Redis configurations
redis_server = os.environ['REDIS']

try:
if "REDIS_PWD" in os.environ:
r = redis.StrictRedis(host=redis_server,
port=6379,
port=25000,
password=os.environ['REDIS_PWD'])
else:
r = redis.Redis(redis_server)
r.ping()
except redis.ConnectionError:
exit('Failed to connect to Redis, terminating.')

"""

# Change title to host name to demo NLB
Expand All @@ -55,50 +111,66 @@
if not r.get(button1): r.set(button1,0)
if not r.get(button2): r.set(button2,0)


@app.route('/', methods=['GET', 'POST'])
def index():

if request.method == 'GET':

# Get current values
vote1 = r.get(button1).decode('utf-8')
vote2 = r.get(button2).decode('utf-8')

# Return index with values
return render_template("index.html", value1=int(vote1), value2=int(vote2), button1=button1, button2=button2, title=title)

elif request.method == 'POST':

if request.form['vote'] == 'reset':

# Empty table and return results
r.set(button1,0)
r.set(button2,0)
vote1 = r.get(button1).decode('utf-8')
properties = {'custom_dimensions': {'Cats Vote': vote1}}
logger.info('Cats Vote', extra=properties)

vote2 = r.get(button2).decode('utf-8')
properties = {'custom_dimensions': {'Dogs Vote': vote2}}
logger.info('Dogs Vote', extra=properties)

return render_template("index.html", value1=int(vote1), value2=int(vote2), button1=button1, button2=button2, title=title)

else:

# Insert vote result into DB
vote = request.form['vote']
r.incr(vote,1)

# Get current values
vote1 = r.get(button1).decode('utf-8')
vote2 = r.get(button2).decode('utf-8')

# Return results
return render_template("index.html", value1=int(vote1), value2=int(vote2), button1=button1, button2=button2, title=title)
if request.method == 'GET':

# Get current values
vote1 = r.get(button1).decode('utf-8')
# TODO: use tracer object to trace cat vote
with tracer.span(name="Cats Vote") as span:
print("Cats Vote")

vote2 = r.get(button2).decode('utf-8')
# TODO: use tracer object to trace dog vote
with tracer.span(name="Dogs Vote") as span:
print("Dogs Vote")

# Return index with values
return render_template("index.html", value1=int(vote1), value2=int(vote2), button1=button1, button2=button2, title=title)

elif request.method == 'POST':

if request.form['vote'] == 'reset':

# Empty table and return results
r.set(button1,0)
r.set(button2,0)
vote1 = r.get(button1).decode('utf-8')
properties = {'custom_dimensions': {'Cats Vote': vote1}}
# TODO: use logger object to log cat vote
logger.info('Cats Vote', extra=properties)

vote2 = r.get(button2).decode('utf-8')
properties = {'custom_dimensions': {'Dogs Vote': vote2}}
# TODO: use logger object to log dog vote
logger.info('Dogs Vote', extra=properties)

return render_template("index.html", value1=int(vote1), value2=int(vote2), button1=button1, button2=button2, title=title)

else:

# Insert vote result into DB
vote = request.form['vote']
r.incr(vote,1)

# Get current values
vote1 = r.get(button1).decode('utf-8')
properties = {'custom_dimensions': {'Cats Vote': vote1}}
# TODO: use logger object to log cat vote
logger.info('Cats Vote', extra=properties)

vote2 = r.get(button2).decode('utf-8')
properties = {'custom_dimensions': {'Dogs Vote': vote2}}
# TODO: use logger object to log dog vote
logger.info('Dogs Vote', extra=properties)

# Return results
return render_template("index.html", value1=int(vote1), value2=int(vote2), button1=button1, button2=button2, title=title)

if __name__ == "__main__":
# comment line below when deploying to VMSS
app.run() # local
# uncomment the line below before deployment to VMSS
# app.run(host='0.0.0.0', threaded=True, debug=True) # remote
# Deployment configuration for VMSS
# app.run(host='0.0.0.0', threaded=True, debug=True) # remote
4 changes: 2 additions & 2 deletions azure-vote/templates/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@

</head>
<body>
<h1>This is a manual deployment.</h1>
<h1>This is a insight deployment.</h1>
<div id="container">
<form id="form" name="form" action="/"" method="post"><center>
<div id="logo">{{title}}</div>
Expand All @@ -27,4 +27,4 @@ <h1>This is a manual deployment.</h1>
</div>
</div>
</body>
</html>
</html>
30 changes: 30 additions & 0 deletions cloud-init-copy2.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
#cloud-config
package_upgrade: true
packages:
- python3
- python-pip
- python3-pip
- redis-server
- nginx
write_files:
- owner: www-data:www-data
path: /etc/nginx/sites-available/default
content: |
server {
listen 80;
access_log /var/log/nginx/flask.log;
location / {
proxy_pass http://localhost:5000;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection keep-alive;
proxy_set_header Host $host;
proxy_cache_bypass $http_upgrade;
}
}

runcmd:
- sed -i.bak 's/^supervised no/supervised systemd/' /etc/redis/redis.conf
- service redis restart
- apt update
- pip3 install --upgrade pip
35 changes: 35 additions & 0 deletions cloud-init.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
#cloud-config
package_upgrade: true
packages:
- python3
- python-pip
- python3-pip
- redis-server
- nginx
write_files:
- owner: www-data:www-data
path: /etc/nginx/sites-available/default
content: |
server {
listen 80;
access_log /var/log/nginx/flask.log;
location / {
proxy_pass http://localhost:5000;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection keep-alive;
proxy_set_header Host $host;
proxy_cache_bypass $http_upgrade;
}
}

runcmd:
- sed -i.bak 's/^supervised no/supervised systemd/' /etc/redis/redis.conf
- service redis restart
- apt-get update
- sudo -H pip3 install --upgrade pip
- git clone https://github.com/udoyen/azure-voting-app-redis.git /home/udacityadmin/azure-voting-app-redis --branch Deploy_to_VMSS
- cd /home/udacityadmin/azure-voting-app-redis/azure-vote/
- sed -E -i.bak 's/^(\s*)(app\.run\(\)[[:space:]]*\#[[:space:]]*local)/\1\# \2/' main.py
- sed -E -i.bak 's/^(\s*)\#\s*(app\.run\(host.*\)\s*\#\s*remote)/\1\2/' main.py

Loading