-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfrontend.py
More file actions
611 lines (555 loc) · 29.3 KB
/
frontend.py
File metadata and controls
611 lines (555 loc) · 29.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
# Copyright 2021 Google LLC
# Licensed under the Apache License, Version 2.0 (the "License");
# http://www.apache.org/licenses/LICENSE-2.0
import concurrent.futures
import datetime
import json
import logging
import os
import socket
from decimal import Decimal, DecimalException
from time import sleep
from typing import Optional
import jwt
import requests
from flask import Flask, abort, jsonify, make_response, redirect, render_template, request, url_for
from requests.exceptions import HTTPError, RequestException
from opentelemetry import trace
from opentelemetry.exporter.cloud_trace import CloudTraceSpanExporter
from opentelemetry.instrumentation.flask import FlaskInstrumentor
from opentelemetry.instrumentation.jinja2 import Jinja2Instrumentor
from opentelemetry.instrumentation.requests import RequestsInstrumentor
from opentelemetry.propagate import set_global_textmap
from opentelemetry.sdk.trace import TracerProvider
from opentelemetry.sdk.trace.export import BatchSpanProcessor
from opentelemetry.propagators.cloud_trace_propagator import CloudTraceFormatPropagator
from api_call import ApiCall, ApiRequest
from traced_thread_pool_executor import TracedThreadPoolExecutor
BALANCE_NAME = "balance"
CONTACTS_NAME = "contacts"
TRANSACTION_LIST_NAME = "transaction_list"
def create_app():
app = Flask(__name__)
# ------------------------
# Utilities
# ------------------------
def decode_token(token):
return jwt.decode(algorithms='RS256', jwt=token, options={"verify_signature": False})
def verify_token(token):
app.logger.debug('Verifying token.')
if token is None:
return False
try:
jwt.decode(algorithms='RS256',
jwt=token,
key=app.config['PUBLIC_KEY'],
options={"verify_signature": True})
app.logger.debug('Token verified.')
return True
except jwt.exceptions.InvalidTokenError as err:
app.logger.error('Error validating token: %s', str(err))
return False
def format_timestamp_day(timestamp):
date = datetime.datetime.strptime(timestamp, app.config['TIMESTAMP_FORMAT'])
return date.strftime('%d')
def format_timestamp_month(timestamp):
date = datetime.datetime.strptime(timestamp, app.config['TIMESTAMP_FORMAT'])
return date.strftime('%b')
def format_currency(int_amount):
if int_amount is None:
return '$---'
from decimal import Decimal
amount_str = '${:0,.2f}'.format(abs(Decimal(int_amount)/100))
if int_amount < 0:
amount_str = '-' + amount_str
return amount_str
# Expose formatters to Jinja
app.jinja_env.globals.update(format_currency=format_currency)
app.jinja_env.globals.update(format_timestamp_month=format_timestamp_month)
app.jinja_env.globals.update(format_timestamp_day=format_timestamp_day)
# ------------------------
# Spend Guardian integration
# ------------------------
def get_spend_alert(account_id: str):
"""Fetch alert from spend-guardian; fail-closed (no banner) on errors."""
try:
base = app.config["SPEND_GUARDIAN_URL"].rstrip("/")
url = f"{base}/alerts/{account_id}"
r = requests.get(url, timeout=app.config['BACKEND_TIMEOUT'])
if r.ok:
data = r.json()
if isinstance(data, dict):
return {
"active": bool(data.get("active", False)),
"message": str(data.get("message", "")),
"score": float(data.get("score", 0.0)),
"ts": str(data.get("ts", "")),
}
except Exception as e:
app.logger.debug("SpendGuardian alert fetch failed: %s", e)
return {"active": False}
def _fetch_contacts_for_user(token: str, username: str) -> list:
"""Fetch contacts so the agent can resolve names like 'Alice' from text."""
try:
hed = {'Authorization': 'Bearer ' + token}
r = requests.get(
url=f'{app.config["CONTACTS_URI"]}/{username}',
headers=hed,
timeout=app.config['BACKEND_TIMEOUT']
)
if r.ok:
data = r.json()
return data if isinstance(data, list) else []
except Exception as e:
app.logger.debug("fetch contacts failed: %s", e)
return []
def ask_spend_guardian(account_id: str, question: str, recipient: Optional[str] = None, username: Optional[str] = None) -> str:
"""
Proxy a natural-language question to Spend Guardian /ask.
We include username so SG can resolve contact labels -> account numbers.
"""
try:
base = app.config["SPEND_GUARDIAN_URL"].rstrip("/")
payload = {"user_id": account_id, "question": question}
if recipient:
payload["recipient"] = recipient
if username:
payload["username"] = username
r = requests.post(f"{base}/ask", json=payload, timeout=app.config['BACKEND_TIMEOUT'])
if r.ok:
data = r.json()
if isinstance(data, dict):
return str(data.get("answer", ""))
except Exception as e:
app.logger.debug("Ask SpendGuardian failed: %s", e)
return "Sorry, I couldn’t get an answer right now."
# ------------------------
# Routes
# ------------------------
@app.route('/version', methods=['GET'])
def version():
return os.environ.get('VERSION'), 200
@app.route('/ready', methods=['GET'])
def readiness():
return 'ok', 200
@app.route('/whereami', methods=['GET'])
def whereami():
return "Cluster: " + cluster_name + ", Pod: " + pod_name + ", Zone: " + pod_zone, 200
@app.route("/")
def root():
token = request.cookies.get(app.config['TOKEN_NAME'])
if not verify_token(token):
return login_page()
return home()
@app.route("/agent/query", methods=["POST"])
def agent_query():
"""
UI text bar posts here; we forward to Spend Guardian /ask with the
authenticated account id and username (for contacts lookup).
Returns {answer: "..."}.
"""
token = request.cookies.get(app.config['TOKEN_NAME'])
if not verify_token(token):
return jsonify({"answer": "You’re not signed in."}), 401
try:
body = request.get_json(silent=True) or {}
q = (body.get("q") or "").strip()
recipient = (body.get("recipient") or "").strip() or None
claims = decode_token(token)
acct = claims['acct']
username = claims.get('user') # <-- needed for contacts lookup
if not q and not recipient:
return jsonify({"answer": "Ask me something like “how much have I paid 1033623433 in the last 90 days?”"}), 200
answer = ask_spend_guardian(acct, q, recipient, username)
return jsonify({"answer": answer}), 200
except Exception as e:
app.logger.debug("agent_query error: %s", e)
return jsonify({"answer": "Sorry, something went wrong."}), 500
@app.route("/home")
def home():
token = request.cookies.get(app.config['TOKEN_NAME'])
if not verify_token(token):
app.logger.debug('User isn\'t authenticated. Redirecting to login page.')
return redirect(url_for('login_page', _external=True, _scheme=app.config['SCHEME']))
token_data = decode_token(token)
display_name = token_data['name']
username = token_data['user']
account_id = token_data['acct']
hed = {'Authorization': 'Bearer ' + token}
api_calls = [
ApiCall(display_name=BALANCE_NAME,
api_request=ApiRequest(url=f'{app.config["BALANCES_URI"]}/{account_id}',
headers=hed, timeout=app.config['BACKEND_TIMEOUT']),
logger=app.logger),
ApiCall(display_name=TRANSACTION_LIST_NAME,
api_request=ApiRequest(url=f'{app.config["HISTORY_URI"]}/{account_id}',
headers=hed, timeout=app.config['BACKEND_TIMEOUT']),
logger=app.logger),
ApiCall(display_name=CONTACTS_NAME,
api_request=ApiRequest(url=f'{app.config["CONTACTS_URI"]}/{username}',
headers=hed, timeout=app.config['BACKEND_TIMEOUT']),
logger=app.logger)
]
api_response = {BALANCE_NAME: None, TRANSACTION_LIST_NAME: None, CONTACTS_NAME: []}
tracer = trace.get_tracer(__name__)
with TracedThreadPoolExecutor(tracer, max_workers=3) as executor:
future_to_api_call = {executor.submit(api_call.make_call): api_call for api_call in api_calls}
for future in concurrent.futures.as_completed(future_to_api_call):
if future.result():
api_call = future_to_api_call[future]
api_response[api_call.display_name] = future.result().json()
_populate_contact_labels(account_id,
api_response[TRANSACTION_LIST_NAME],
api_response[CONTACTS_NAME])
alert = get_spend_alert(account_id)
return render_template('index.html',
account_id=account_id,
balance=api_response[BALANCE_NAME],
bank_name=os.getenv('BANK_NAME', 'Bank of Anthos'),
cluster_name=cluster_name,
contacts=api_response[CONTACTS_NAME],
cymbal_logo=os.getenv('CYMBAL_LOGO', 'false'),
history=api_response[TRANSACTION_LIST_NAME],
message=request.args.get('msg', None),
name=display_name,
platform=platform,
platform_display_name=platform_display_name,
pod_name=pod_name,
pod_zone=pod_zone,
alert=alert)
def _populate_contact_labels(account_id, transactions, contacts):
app.logger.debug('Populating contact labels.')
if account_id is None or transactions is None or contacts is None:
return
contact_map = {c['account_num']: c.get('label') for c in contacts}
for trans in transactions:
if trans['toAccountNum'] == account_id:
trans['accountLabel'] = contact_map.get(trans['fromAccountNum'])
elif trans['fromAccountNum'] == account_id:
trans['accountLabel'] = contact_map.get(trans['toAccountNum'])
@app.route('/payment', methods=['POST'])
def payment():
token = request.cookies.get(app.config['TOKEN_NAME'])
if not verify_token(token):
app.logger.error('Error submitting payment: user is not authenticated.')
return abort(401)
try:
account_id = decode_token(token)['acct']
recipient = request.form['account_num']
if recipient == 'add':
recipient = request.form['contact_account_num']
label = request.form.get('contact_label', None)
if label:
_add_contact(label, recipient, app.config['LOCAL_ROUTING'], False)
user_input = request.form['amount']
payment_amount = int(Decimal(user_input) * 100)
transaction_data = {"fromAccountNum": account_id,
"fromRoutingNum": app.config['LOCAL_ROUTING'],
"toAccountNum": recipient,
"toRoutingNum": app.config['LOCAL_ROUTING'],
"amount": payment_amount,
"uuid": request.form['uuid']}
_submit_transaction(transaction_data)
app.logger.info('Payment initiated successfully.')
return redirect(code=303, location=url_for('home', msg='Payment successful',
_external=True, _scheme=app.config['SCHEME']))
except requests.exceptions.RequestException as err:
app.logger.error('Error submitting payment: %s', str(err))
except UserWarning as warn:
app.logger.error('Error submitting payment: %s', str(warn))
msg = 'Payment failed: {}'.format(str(warn))
return redirect(url_for('home', msg=msg, _external=True, _scheme=app.config['SCHEME']))
except (ValueError, DecimalException):
app.logger.error('Error submitting payment: invalid number')
return redirect(url_for('home', msg='Payment failed', _external=True, _scheme=app.config['SCHEME']))
@app.route('/deposit', methods=['POST'])
def deposit():
token = request.cookies.get(app.config['TOKEN_NAME'])
if not verify_token(token):
app.logger.error('Error submitting deposit: user is not authenticated.')
return abort(401)
try:
account_id = decode_token(token)['acct']
if request.form['account'] == 'add':
external_account_num = request.form['external_account_num']
external_routing_num = request.form['external_routing_num']
if external_routing_num == app.config['LOCAL_ROUTING']:
raise UserWarning("invalid routing number")
external_label = request.form.get('external_label', None)
if external_label:
_add_contact(external_label, external_account_num, external_routing_num, True)
else:
account_details = json.loads(request.form['account'])
external_account_num = account_details['account_num']
external_routing_num = account_details['routing_num']
transaction_data = {"fromAccountNum": external_account_num,
"fromRoutingNum": external_routing_num,
"toAccountNum": account_id,
"toRoutingNum": app.config['LOCAL_ROUTING'],
"amount": int(Decimal(request.form['amount']) * 100),
"uuid": request.form['uuid']}
_submit_transaction(transaction_data)
app.logger.info('Deposit submitted successfully.')
return redirect(code=303, location=url_for('home', msg='Deposit successful',
_external=True, _scheme=app.config['SCHEME']))
except requests.exceptions.RequestException as err:
app.logger.error('Error submitting deposit: %s', str(err))
except UserWarning as warn:
app.logger.error('Error submitting deposit: %s', str(warn))
msg = 'Deposit failed: {}'.format(str(warn))
return redirect(url_for('home', msg=msg, _external=True, _scheme=app.config['SCHEME']))
return redirect(url_for('home', msg='Deposit failed', _external=True, _scheme=app.config['SCHEME']))
def _submit_transaction(transaction_data):
app.logger.debug('Submitting transaction.')
token = request.cookies.get(app.config['TOKEN_NAME'])
hed = {'Authorization': 'Bearer ' + token, 'content-type': 'application/json'}
resp = requests.post(url=app.config["TRANSACTIONS_URI"],
data=json.dumps(transaction_data),
headers=hed,
timeout=app.config['BACKEND_TIMEOUT'])
try:
resp.raise_for_status()
except requests.exceptions.HTTPError as http_request_err:
raise UserWarning(resp.text) from http_request_err
sleep(0.25) # allow propagation
def _add_contact(label, acct_num, routing_num, is_external_acct=False):
app.logger.debug('Adding new contact.')
token = request.cookies.get(app.config['TOKEN_NAME'])
hed = {'Authorization': 'Bearer ' + token, 'content-type': 'application/json'}
contact_data = {
'label': label,
'account_num': acct_num,
'routing_num': routing_num,
'is_external': is_external_acct
}
token_data = decode_token(token)
url = '{}/{}'.format(app.config["CONTACTS_URI"], token_data['user'])
resp = requests.post(url=url, data=json.dumps(contact_data), headers=hed, timeout=app.config['BACKEND_TIMEOUT'])
try:
resp.raise_for_status()
except requests.exceptions.HTTPError as http_request_err:
raise UserWarning(resp.text) from http_request_err
@app.route("/login", methods=['GET'])
def login_page():
token = request.cookies.get(app.config['TOKEN_NAME'])
response_type = request.args.get('response_type')
client_id = request.args.get('client_id')
app_name = request.args.get('app_name')
redirect_uri = request.args.get('redirect_uri')
state = request.args.get('state')
if ('REGISTERED_OAUTH_CLIENT_ID' in os.environ and
'ALLOWED_OAUTH_REDIRECT_URI' in os.environ and
response_type == 'code'):
app.logger.debug('Login with response_type=code')
if client_id != os.environ['REGISTERED_OAUTH_CLIENT_ID']:
return redirect(url_for('login', msg='Error: Invalid client_id',
_external=True, _scheme=app.config['SCHEME']))
if redirect_uri != os.environ['ALLOWED_OAUTH_REDIRECT_URI']:
return redirect(url_for('login', msg='Error: Invalid redirect_uri',
_external=True, _scheme=app.config['SCHEME']))
if verify_token(token):
app.logger.debug('User already authenticated. Redirecting to /consent')
return make_response(redirect(url_for('consent',
state=state,
redirect_uri=redirect_uri,
app_name=app_name,
_external=True,
_scheme=app.config['SCHEME'])))
else:
if verify_token(token):
app.logger.debug('User already authenticated. Redirecting to /home')
return redirect(url_for('home', _external=True, _scheme=app.config['SCHEME']))
return render_template('login.html',
app_name=app_name,
bank_name=os.getenv('BANK_NAME', 'Bank of Anthos'),
cluster_name=cluster_name,
cymbal_logo=os.getenv('CYMBAL_LOGO', 'false'),
default_password=os.getenv('DEFAULT_PASSWORD', ''),
default_user=os.getenv('DEFAULT_USERNAME', ''),
message=request.args.get('msg', None),
platform=platform,
platform_display_name=platform_display_name,
pod_name=pod_name,
pod_zone=pod_zone,
redirect_uri=redirect_uri,
response_type=response_type,
state=state)
@app.route('/login', methods=['POST'])
def login():
return _login_helper(request.form['username'], request.form['password'], request.args)
def _login_helper(username, password, request_args):
try:
app.logger.debug('Logging in.')
req = requests.get(url=app.config["LOGIN_URI"],
params={'username': username, 'password': password},
timeout=app.config['BACKEND_TIMEOUT']*2)
req.raise_for_status()
token = req.json()['token']
claims = decode_token(token)
max_age = claims['exp'] - claims['iat']
if ('response_type' in request_args and
'state' in request_args and
'redirect_uri' in request_args and
request_args['response_type'] == 'code'):
resp = make_response(redirect(url_for('consent',
state=request_args['state'],
redirect_uri=request_args['redirect_uri'],
app_name=request_args.get('app_name'),
_external=True,
_scheme=app.config['SCHEME'])))
else:
resp = make_response(redirect(url_for('home', _external=True, _scheme=app.config['SCHEME'])))
resp.set_cookie(app.config['TOKEN_NAME'], token, max_age=max_age)
app.logger.info('Successfully logged in.')
return resp
except (RequestException, HTTPError) as err:
app.logger.error('Error logging in: %s', str(err))
return redirect(url_for('login', msg='Login Failed', _external=True, _scheme=app.config['SCHEME']))
@app.route("/consent", methods=['GET'])
def consent_page():
redirect_uri = request.args.get('redirect_uri')
state = request.args.get('state')
app_name = request.args.get('app_name')
token = request.cookies.get(app.config['TOKEN_NAME'])
consented = request.cookies.get(app.config['CONSENT_COOKIE'])
if verify_token(token):
if consented == "true":
app.logger.debug('User consent already granted.')
return _auth_callback_helper(state, redirect_uri, token)
return render_template('consent.html',
app_name=app_name,
bank_name=os.getenv('BANK_NAME', 'Bank of Anthos'),
cluster_name=cluster_name,
cymbal_logo=os.getenv('CYMBAL_LOGO', 'false'),
platform=platform,
platform_display_name=platform_display_name,
pod_name=pod_name,
pod_zone=pod_zone,
redirect_uri=redirect_uri,
state=state)
return make_response(redirect(url_for('login',
response_type="code",
state=state,
redirect_uri=redirect_uri,
app_name=app_name,
_external=True,
_scheme=app.config['SCHEME'])))
@app.route('/consent', methods=['POST'])
def consent():
consent = request.args['consent']
state = request.args['state']
redirect_uri = request.args['redirect_uri']
token = request.cookies.get(app.config['TOKEN_NAME'])
app.logger.debug('Checking consent. consent: %s', consent)
if consent == "true":
app.logger.info('User consent granted.')
resp = _auth_callback_helper(state, redirect_uri, token)
resp.set_cookie(app.config['CONSENT_COOKIE'], 'true')
else:
app.logger.info('User consent denied.')
resp = make_response(redirect(redirect_uri + '#error=access_denied', 302))
return resp
def _auth_callback_helper(state, redirect_uri, token):
try:
app.logger.debug('Retrieving authorization code.')
callback_response = requests.post(url=redirect_uri,
data={'state': state, 'id_token': token},
timeout=app.config['BACKEND_TIMEOUT'],
allow_redirects=False)
if callback_response.status_code == requests.codes.found:
app.logger.info('Successfully retrieved auth code.')
location = callback_response.headers['Location']
return make_response(redirect(location, 302))
app.logger.error('Unexpected response status: %s', callback_response.status_code)
return make_response(redirect(redirect_uri + '#error=server_error', 302))
except requests.exceptions.RequestException as err:
app.logger.error('Error retrieving auth code: %s', str(err))
return make_response(redirect(redirect_uri + '#error=server_error', 302))
@app.route('/logout', methods=['POST'])
def logout():
app.logger.info('Logging out.')
resp = make_response(redirect(url_for('login_page', _external=True, _scheme=app.config['SCHEME'])))
resp.delete_cookie(app.config['TOKEN_NAME'])
resp.delete_cookie(app.config['CONSENT_COOKIE'])
return resp
# ------------------------
# App config / env
# ------------------------
app.config["TRANSACTIONS_URI"] = f'http://{os.environ.get("TRANSACTIONS_API_ADDR")}/transactions'
app.config["USERSERVICE_URI"] = f'http://{os.environ.get("USERSERVICE_API_ADDR")}/users'
app.config["BALANCES_URI"] = f'http://{os.environ.get("BALANCES_API_ADDR")}/balances'
app.config["HISTORY_URI"] = f'http://{os.environ.get("HISTORY_API_ADDR")}/transactions'
app.config["LOGIN_URI"] = f'http://{os.environ.get("USERSERVICE_API_ADDR")}/login'
app.config["CONTACTS_URI"] = f'http://{os.environ.get("CONTACTS_API_ADDR")}/contacts'
app.config['PUBLIC_KEY'] = open(os.environ.get('PUB_KEY_PATH'), 'r').read()
app.config['LOCAL_ROUTING'] = os.getenv('LOCAL_ROUTING_NUM')
app.config['BACKEND_TIMEOUT'] = int(os.getenv('BACKEND_TIMEOUT', '4'))
app.config['TOKEN_NAME'] = 'token'
app.config['CONSENT_COOKIE'] = 'consented'
app.config['TIMESTAMP_FORMAT'] = '%Y-%m-%dT%H:%M:%S.%f%z'
app.config['SCHEME'] = os.environ.get('SCHEME', 'http')
app.config["SPEND_GUARDIAN_URL"] = os.getenv("SPEND_GUARDIAN_URL", "http://spend-guardian:8080")
# where am I?
metadata_server = os.getenv('METADATA_SERVER', 'metadata.google.internal')
metadata_url = f'http://{metadata_server}/computeMetadata/v1/'
metadata_headers = {'Metadata-Flavor': 'Google'}
global cluster_name, pod_name, pod_zone, platform, platform_display_name
cluster_name = os.getenv('CLUSTER_NAME', 'unknown')
try:
req = requests.get(metadata_url + 'instance/attributes/cluster-name',
headers=metadata_headers, timeout=app.config['BACKEND_TIMEOUT'])
if req.ok:
cluster_name = str(req.text)
except (RequestException, HTTPError):
app.logger.warning("Unable to retrieve cluster name from metadata server %s.", metadata_server)
pod_name = socket.gethostname()
pod_zone = os.getenv('POD_ZONE', 'unknown')
try:
req = requests.get(metadata_url + 'instance/zone',
headers=metadata_headers, timeout=app.config['BACKEND_TIMEOUT'])
if req.ok:
pod_zone = str(req.text.split("/")[3])
except (RequestException, HTTPError):
app.logger.warning("Unable to retrieve zone from metadata server %s.", metadata_server)
# tracing
app.logger.handlers = logging.getLogger('gunicorn.error').handlers
app.logger.setLevel(logging.getLogger('gunicorn.error').level)
app.logger.info('Starting frontend service.')
if os.environ.get('ENABLE_TRACING') == "true":
app.logger.info("✅ Tracing enabled.")
trace.set_tracer_provider(TracerProvider())
cloud_trace_exporter = CloudTraceSpanExporter()
trace.get_tracer_provider().add_span_processor(BatchSpanProcessor(cloud_trace_exporter))
set_global_textmap(CloudTraceFormatPropagator())
FlaskInstrumentor().instrument_app(app)
RequestsInstrumentor().instrument()
Jinja2Instrumentor().instrument()
else:
app.logger.info("🚫 Tracing disabled.")
platform = os.getenv('ENV_PLATFORM', None)
platform_display_name = None
if platform is not None:
platform = platform.lower()
if platform not in ['alibaba', 'aws', 'azure', 'gcp', 'local', 'onprem']:
app.logger.error("Platform '%s' not supported, defaulting to None", platform)
platform = None
else:
app.logger.info("Platform is set to '%s'", platform)
if platform == 'alibaba':
platform_display_name = "Alibaba Cloud"
elif platform == 'aws':
platform_display_name = "AWS"
elif platform == 'azure':
platform_display_name = "Azure"
elif platform == 'gcp':
platform_display_name = "Google Cloud"
elif platform == 'local':
platform_display_name = "Local"
elif platform == 'onprem':
platform_display_name = "On-Premises"
else:
app.logger.info("ENV_PLATFORM environment variable is not set")
return app
if __name__ == "__main__":
FRONTEND = create_app()
FRONTEND.run()