| 1 |
# Copyright 2015 Google Inc. All rights reserved. |
| 2 |
# |
| 3 |
# Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 |
# you may not use this file except in compliance with the License. |
| 5 |
# You may obtain a copy of the License at |
| 6 |
# |
| 7 |
# http://www.apache.org/licenses/LICENSE-2.0 |
| 8 |
# |
| 9 |
# Unless required by applicable law or agreed to in writing, software |
| 10 |
# distributed under the License is distributed on an "AS IS" BASIS, |
| 11 |
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 |
# See the License for the specific language governing permissions and |
| 13 |
# limitations under the License. |
| 14 |
|
| 15 |
|
| 16 |
"""Frontend for Fractal demo. |
| 17 |
|
| 18 |
Application server for a 3 tier web app. Submits fractal image generation |
| 19 |
requests. Manages metadata database. Renders pages with Jinja2. |
| 20 |
""" |
| 21 |
|
| 22 |
import datetime |
| 23 |
import json |
| 24 |
import os |
| 25 |
import socket |
| 26 |
import sys |
| 27 |
import time |
| 28 |
import uuid |
| 29 |
|
| 30 |
import flask |
| 31 |
import httplib2 |
| 32 |
import jinja2 |
| 33 |
|
| 34 |
from cassandra.auth import PlainTextAuthProvider |
| 35 |
from cassandra.cluster import Cluster |
| 36 |
from cassandra.cluster import NoHostAvailable |
| 37 |
|
| 38 |
CONF = None |
| 39 |
for i in xrange(1, 60): |
| 40 |
try: |
| 41 |
with open('conf.json') as conf_file: |
| 42 |
CONF = json.load(conf_file) |
| 43 |
except IOError: |
| 44 |
time.sleep(1) |
| 45 |
|
| 46 |
|
| 47 |
if CONF == None: |
| 48 |
sys.stderr.write('ERROR: Could not open conf.json.') |
| 49 |
sys.exit(1) |
| 50 |
|
| 51 |
|
| 52 |
class DbError(Exception): |
| 53 |
def __init__(self, msg): |
| 54 |
self.msg = msg |
| 55 |
def __str__(self): |
| 56 |
return self.msg |
| 57 |
|
| 58 |
|
| 59 |
session = None |
| 60 |
|
| 61 |
|
| 62 |
app = flask.Flask(__name__) |
| 63 |
app.config['PROPAGATE_EXCEPTIONS'] = True |
| 64 |
|
| 65 |
|
| 66 |
JINJA_ENVIRONMENT = jinja2.Environment( |
| 67 |
loader=jinja2.FileSystemLoader(os.path.dirname(__file__)), |
| 68 |
extensions=['jinja2.ext.autoescape'], |
| 69 |
autoescape=True) |
| 70 |
|
| 71 |
|
| 72 |
def render_error(code, msg): |
| 73 |
return flask.make_response(my_render_template('error.html', code=code, msg=msg), code) |
| 74 |
|
| 75 |
|
| 76 |
def db_execute(s, t=()): |
| 77 |
global session |
| 78 |
if session == None: |
| 79 |
try: |
| 80 |
ap = PlainTextAuthProvider(username=CONF['database_user'], |
| 81 |
password=CONF['database_pass']) |
| 82 |
cluster = Cluster(CONF['db_endpoints'], auth_provider=ap) |
| 83 |
session = cluster.connect() |
| 84 |
session.set_keyspace(CONF['database_name']) |
| 85 |
return session.execute(s, t) |
| 86 |
except NoHostAvailable: |
| 87 |
session = None |
| 88 |
raise DbError("Unable to contact database backend.") |
| 89 |
else: |
| 90 |
try: |
| 91 |
return session.execute(s, t) |
| 92 |
except NoHostAvailable: |
| 93 |
session = None |
| 94 |
return db_execute(s, t) |
| 95 |
|
| 96 |
def my_render_template(filename, **context): |
| 97 |
context.update(CONF) |
| 98 |
return flask.render_template(filename, **context) |
| 99 |
|
| 100 |
def db_clear(): |
| 101 |
db_execute('TRUNCATE discoveries;') |
| 102 |
|
| 103 |
def db_partition(dt): |
| 104 |
#return "%04d-%02d-%02d" % (dt.year, dt.month, dt.day) |
| 105 |
return "FIXED" |
| 106 |
|
| 107 |
def db_remember(text, x, y, level): |
| 108 |
u = uuid.uuid1() |
| 109 |
dt = datetime.datetime.fromtimestamp((u.time - 0x01b21dd213814000L)*100/1e9) |
| 110 |
db_execute("INSERT INTO discoveries (Date, TimeId, X, Y, L, Text)" |
| 111 |
+ " VALUES (%s, %s, %s, %s, %s, %s)", |
| 112 |
(db_partition(dt), u, x, y, level, text)) |
| 113 |
|
| 114 |
def db_list(): |
| 115 |
latest = [] |
| 116 |
# Keep executing calls until we find 10 or we reach 2013 |
| 117 |
day_counter = datetime.datetime.now() |
| 118 |
last_partition = None |
| 119 |
while len(latest) < 10 and day_counter >= datetime.datetime(2013, 1, 1): |
| 120 |
curr_partition = db_partition(day_counter) |
| 121 |
if last_partition != curr_partition: |
| 122 |
last_partition = curr_partition |
| 123 |
q = "SELECT * FROM discoveries WHERE Date = '%s' ORDER BY TimeId DESC limit 10;" |
| 124 |
rows = db_execute(q % curr_partition) |
| 125 |
for row in rows: |
| 126 |
u = row[1] |
| 127 |
dt = datetime.datetime.fromtimestamp((u.time - 0x01b21dd213814000L)*100/1e9) |
| 128 |
|
| 129 |
latest += [ |
| 130 |
{'text': row[3], 'x': row[4], 'y': row[5], 'l': row[2], 'ts': dt.isoformat()} |
| 131 |
] |
| 132 |
day_counter -= datetime.timedelta(1) |
| 133 |
return latest |
| 134 |
|
| 135 |
|
| 136 |
@app.route("/") |
| 137 |
def default_handler(): |
| 138 |
return my_render_template('page.html') |
| 139 |
|
| 140 |
|
| 141 |
@app.route("/clear_db") |
| 142 |
def cleardb_handler(): |
| 143 |
try: |
| 144 |
db_clear() |
| 145 |
return 'Done' |
| 146 |
except DbError as dbe: |
| 147 |
return render_error(500, "Internal error: " + dbe.msg) |
| 148 |
|
| 149 |
|
| 150 |
@app.route("/remember", methods=['POST']) |
| 151 |
def remember_handler(): |
| 152 |
try: |
| 153 |
j = flask.request.json |
| 154 |
x = j['x'] |
| 155 |
y = j['y'] |
| 156 |
level = j['l'] |
| 157 |
text = j['text'][:50] |
| 158 |
if x < -2: x = -2 |
| 159 |
if x > 2: x = 2 |
| 160 |
if y < -2: y = -2 |
| 161 |
if y > 2: y = 2 |
| 162 |
if level < 0: level = 0 |
| 163 |
if level > 50: level = 50 |
| 164 |
db_remember(text, x, y, level) |
| 165 |
return 'Done' |
| 166 |
except DbError as dbe: |
| 167 |
return render_error(500, "Internal error: " + dbe.msg) |
| 168 |
|
| 169 |
|
| 170 |
@app.route("/remembered_list") |
| 171 |
def remembered_list_handler(): |
| 172 |
try: |
| 173 |
latest = db_list() |
| 174 |
return flask.jsonify(latest=latest) |
| 175 |
except DbError as dbe: |
| 176 |
return render_error(500, "Internal error: " + dbe.msg) |
| 177 |
|
| 178 |
|
| 179 |
@app.errorhandler(404) |
| 180 |
def error_404(error): |
| 181 |
return render_error(404, 'Nothing at this URL.') |
| 182 |
|
| 183 |
|
| 184 |
@app.errorhandler(500) |
| 185 |
def error_500(error): |
| 186 |
return render_error(500, 'Internal error') |
| 187 |
|
| 188 |
|
| 189 |
if __name__ == "__main__": |
| 190 |
app.run(host="0.0.0.0", debug=True) |