Skip to content

Commit 9c8f02e

Browse files
authored
Fix/suprctbl no output (#52)
* Updated Makefile Kind of want to update that deployment to properly use watchtower` * Fixed No File Output - Updated Makefile command for shelling intno the web app - Fixed No Output Issue. The issue happened because users would do `slopFile=dpronsbl_ree`, but we forgot to copy over dpronsbl_ree into the job directory. That would literally ensure that any request with dpronsbl_ree wouldn't output any files. Anyways that was a simple fix. - Also added logging * Added formatting and linting - Updated Makefile to include formatting and linting scripts. - Formatted and linted the code. - `rate_calc.py`: Commented out some variables that were literally unaccessed/unused. Maintains functionality whilst helping out the style a bit. * Updated glob package to fix security issue glob library had a big security issue so we had to update it. * Updated stack.yml poll time Updated back to 5 minutes. * Logging in auth.py Saw that auth.py had its own logger defined, so we just used our app logger instead.
1 parent bca983c commit 9c8f02e

16 files changed

Lines changed: 200 additions & 129 deletions

File tree

Makefile

Lines changed: 33 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,10 @@ TAG=latest
77

88
.PHONY: up down restart logs frontend deploy build
99

10+
11+
## -----------------------------------------------
12+
# Running app in dev + Debugging with logs and shell
13+
## -----------------------------------------------
1014
# Run the app in development env
1115
up:
1216
@echo "Building the project..."
@@ -27,23 +31,45 @@ logs:
2731

2832
# For running execing into the dev container
2933
shell:
30-
@docker exec -it $(shell docker ps -q -f "name=$(PROJECT_NAME)") /bin/sh
34+
@docker compose -f $(COMPOSE_FILE) exec web /bin/bash
3135

3236
# Run the react app only; good for when you just need to develop the frontend.
3337
frontend:
3438
@echo "Building the frontend..."
3539
@cd frontend && npm install && npm run dev
3640

37-
format:
38-
@echo "Formatting the code"
39-
@cd frontend && npm run format
40-
@cd backend && uv run ruff format
41-
41+
## -----------------------------------------------
42+
# Commands for starting up or shutting down prod
43+
## -----------------------------------------------
4244
build:
4345
@echo "Building the project..."
4446
@cd frontend && npm install && npm run build
4547
@docker build -t $(IMAGE_NAME):$(TAG) .
4648

4749
# Expect a wait about 5 seconds for the replicas to be created after you run the command
4850
deploy: build
49-
@docker stack deploy -c $(STACK_FILE) $(STACK_NAME)
51+
docker stack deploy -c $(STACK_FILE) $(STACK_NAME)
52+
53+
# Remove stack
54+
remove:
55+
docker stack rm $(STACK_NAME)
56+
57+
# Redeploy the stack
58+
redeploy: remove deploy
59+
60+
# View the logs of a service
61+
# e.g. make stack-logs SERVICE=watchtower
62+
stack-logs:
63+
docker service logs -f $(STACK_NAME)_$(SERVICE)
64+
65+
## -----------------------------------------------
66+
# Linting and Formatting
67+
## -----------------------------------------------
68+
format:
69+
@cd backend && uv run ruff format .
70+
@cd frontend && npm run format
71+
72+
# Checks for and fixes simple linting errors
73+
lint:
74+
@cd backend && uv run ruff check --fix .
75+
@cd frontend && npm run lint

backend/app/config.py

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,5 @@
11
import os
22
from pydantic_settings import BaseSettings
3-
from typing import Optional
43

54

65
class Settings(BaseSettings):

backend/app/db/database.py

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,6 @@
33
import pymysql
44
from sqlmodel import create_engine, Session, text
55
from contextlib import contextmanager
6-
import time
76
import urllib.parse
87

98
# Configure logging

backend/app/routes/auth.py

Lines changed: 19 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -1,21 +1,17 @@
11
from starlette.responses import RedirectResponse
22
from fastapi import Request, Response, APIRouter
3-
import os, requests
4-
import logging
3+
import os
4+
import requests
55
from sqlalchemy.exc import SQLAlchemyError
66
from sqlmodel import select
77
from app.db import User, get_session
8-
from datetime import datetime
9-
10-
# Configure logging
11-
logging.basicConfig(level=logging.INFO)
12-
logger = logging.getLogger(__name__)
8+
from app.services.logger import app_logger
139

1410
router = APIRouter()
1511

1612

1713
@router.get("/auth", tags=["auth"])
18-
async def auth_me():
14+
async def auth_redirect():
1915
"""
2016
Redirect for OIDC authentication.
2117
"""
@@ -74,7 +70,7 @@ async def auth_callback(code: str):
7470
if db_user and db_user.archived == 1:
7571
# User is archived, do not log in
7672
return RedirectResponse(url="/?alert=archived_user")
77-
except Exception as e:
73+
except Exception:
7874
# Optionally handle DB errors
7975
return RedirectResponse(url="/?alert=database_error")
8076

@@ -128,7 +124,7 @@ async def auth_me(request: Request, response: Response):
128124
timeout=2,
129125
)
130126
except requests.exceptions.RequestException as e:
131-
logger.error(f"Failed to fetch user info: {e}")
127+
app_logger.exception(f"Failed to fetch user info. Clearing access token cookie!")
132128
response.delete_cookie("access_token")
133129
return {
134130
"status": "failure",
@@ -138,7 +134,7 @@ async def auth_me(request: Request, response: Response):
138134

139135
if user_info_response.status_code == 200:
140136
try:
141-
logger.info("User info response received successfully")
137+
# app_logger.info("User info response received successfully")
142138
user_info = user_info_response.json()
143139

144140
# Get user authorization details from database using the email
@@ -149,32 +145,28 @@ async def auth_me(request: Request, response: Response):
149145

150146
if "email" in user_info:
151147
email = user_info["email"]
152-
logger.info(f"Looking up user authorization for email: {email}")
153-
148+
# app_logger.info(f"Looking up user email: {email}")
154149
try:
155150
with get_session() as session:
156151
if session is None:
157152
db_status = "warning"
158153
db_message = "Database connection unavailable"
159-
logger.warning("Database session is None, skipping user lookup")
154+
app_logger.warning("Database session is None, skipping user lookup")
160155
else:
161156
try:
162-
logger.info("Querying user_details table for existing user")
163157
statement = select(User).where(User.email == email)
164158
db_user = session.exec(statement).first()
165-
166159
if db_user:
167-
logger.info(f"Found existing user in database: {db_user.id}")
168-
160+
# app_logger.info(f"Found existing user with id '{db_user.id}'")
169161
if db_user.archived == 1:
170-
logger.info(
162+
app_logger.info(
171163
f"User with email '{db_user.email}' is archived. Cannot authenticate them!"
172164
)
173165
response.delete_cookie("access_token")
174166
return {
175167
"status": "failure",
176168
"message": "User is archived. Login prevented!",
177-
"details": str(e),
169+
"details": "User is archived. Please contact supcrt@iu.edu for support",
178170
}
179171

180172
# Convert SQLModel to dict and add to response
@@ -192,7 +184,7 @@ async def auth_me(request: Request, response: Response):
192184
"onboarded": db_user.onboarded,
193185
}
194186
else:
195-
logger.info(f"User {email} not found, creating minimal user entry")
187+
# app_logger.info(f"User {email} not found, creating minimal user entry")
196188

197189
# Get name components from CILogon data if available
198190
name = user_info.get("name", "")
@@ -216,7 +208,7 @@ async def auth_me(request: Request, response: Response):
216208
session.commit()
217209
# Refresh to get the assigned ID
218210
session.refresh(new_user)
219-
logger.info(f"Created new user with ID: {new_user.id}")
211+
# app_logger.info(f"Created new user with ID: {new_user.id}")
220212

221213
# Set flag for new user creation
222214
is_new_user = True
@@ -238,17 +230,17 @@ async def auth_me(request: Request, response: Response):
238230

239231
db_message = "New user created successfully"
240232
except SQLAlchemyError as add_error:
241-
logger.error(f"Failed to create new user: {add_error}")
233+
app_logger.exception(f"Failed to create new user: {add_error}")
242234
db_status = "error"
243235
db_message = f"Failed to create new user: {str(add_error)}"
244236
except Exception as table_error:
245237
db_status = "error"
246238
db_message = f"Error querying user_details table: {str(table_error)}"
247-
logger.error(db_message)
239+
app_logger.exception(db_message)
248240
except SQLAlchemyError as db_error:
249241
db_status = "error"
250242
db_message = f"Database connection error: {str(db_error)}"
251-
logger.error(db_message)
243+
app_logger.exception(db_message)
252244

253245
return {
254246
"status": "success",
@@ -261,15 +253,15 @@ async def auth_me(request: Request, response: Response):
261253
"access_token": access_token,
262254
}
263255
except requests.exceptions.JSONDecodeError:
264-
logger.error("Failed to decode user info response as JSON")
256+
app_logger.exception("Failed to decode user info response as JSON")
265257
response.delete_cookie("access_token")
266258
return {
267259
"status": "failure",
268260
"message": "Failed to decode user info response as JSON",
269261
"details": user_info_response.text,
270262
}
271263
else:
272-
logger.error(f"Failed to fetch user info: {user_info_response.status_code}")
264+
app_logger.exception(f"Failed to fetch user info: {user_info_response.status_code}")
273265
response.delete_cookie("access_token")
274266
return {
275267
"status": "failure",

backend/app/routes/co2/co2_calc.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -94,4 +94,4 @@ def co2_calculator_interceptor(temp: float, bar: float, mNaCl: float):
9494
raise HTTPException(status_code=500, detail="Internal Server Error")
9595
except FileNotFoundError as e:
9696
print(f"File not found: {binary_path} - {e.strerror}")
97-
raise HTTPException(status_code=500, detail=f"Internal Server Error")
97+
raise HTTPException(status_code=500, detail="Internal Server Error")

backend/app/routes/minerals.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
1-
from fastapi import Form, HTTPException, APIRouter, Request
1+
from fastapi import HTTPException, APIRouter, Request
22
import logging
3-
from sqlmodel import select, text
3+
from sqlmodel import text
44
from app.db.database import get_session
55

66
# Configure detailed logging

backend/app/routes/phreeqc/phreeqc_calc.py

Lines changed: 5 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,16 +1,14 @@
1-
import subprocess
2-
from fastapi import APIRouter, HTTPException, File, Form, UploadFile
1+
from fastapi import APIRouter, HTTPException, Form, UploadFile
32
from fastapi.responses import FileResponse
43
import os
54
from typing import Union, Optional
6-
from zipfile import ZipFile
75
import re
86
from datetime import datetime
9-
10-
router = APIRouter()
117
from typing import Annotated
128
from . import process_manager
139

10+
router = APIRouter()
11+
1412
databaseOptionList = [
1513
"geothermal.dat",
1614
"geothermal-ree.dat",
@@ -60,7 +58,7 @@ async def phreeqc_interceptor(
6058
inputFileDir = os.path.join(inputDir, inputFile.filename)
6159
files = []
6260
contents = (await inputFile.read()).decode("utf-8")
63-
lines = re.split(f"\r\n|\r|\n", contents)
61+
lines = re.split("\r\n|\r|\n", contents)
6462
for line in lines:
6563
line_parts = re.sub(r"\s+", " ", line).split(" ")
6664
for i in range(len(line_parts) - 1):
@@ -92,7 +90,7 @@ async def phreeqc_interceptor(
9290
with open(datFileDir, "w") as f:
9391
contents = (await customDataFile.read()).decode("utf-8")
9492
f.write(contents)
95-
except:
93+
except Exception:
9694
raise HTTPException(
9795
status_code=500,
9896
detail="Failed to parse your custom database file. Please double check it and try again later!",

backend/app/routes/phreeqc/process_manager.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@
33
import time
44
import threading
55
import json
6-
from typing import Dict, Optional
6+
from typing import Dict
77
from datetime import datetime
88

99
# Dictionary to keep track of running processes
@@ -189,7 +189,7 @@ def cleanup_old_processes():
189189
update_lock_file(
190190
process_info["lock_file"], "timeout", "Process killed after timeout"
191191
)
192-
except:
192+
except Exception:
193193
pass
194194
expired_processes.append(exp_id)
195195

0 commit comments

Comments
 (0)