Skip to content

Commit

Permalink
Merge pull request #1 from Maneesh3/merging-to-main
Browse files Browse the repository at this point in the history
Merging to main
  • Loading branch information
Maneesh3 authored Jan 12, 2025
2 parents 7e91a44 + 5a17156 commit 8b37cf9
Show file tree
Hide file tree
Showing 9 changed files with 426 additions and 0 deletions.
1 change: 1 addition & 0 deletions .dockerignore
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
__pycache__
178 changes: 178 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,178 @@


# Docker


# Python .gitignore

# Byte-compiled / optimized / DLL files
__pycache__/
*.py[cod]
*$py.class

# C extensions
*.so

# Distribution / packaging
.Python
build/
develop-eggs/
dist/
downloads/
eggs/
.eggs/
lib/
lib64/
parts/
sdist/
var/
wheels/
share/python-wheels/
*.egg-info/
.installed.cfg
*.egg
MANIFEST

# PyInstaller
# Usually these files are written by a python script from a template
# before PyInstaller builds the exe, so as to inject date/other infos into it.
*.manifest
*.spec

# Installer logs
pip-log.txt
pip-delete-this-directory.txt

# Unit test / coverage reports
htmlcov/
.tox/
.nox/
.coverage
.coverage.*
.cache
nosetests.xml
coverage.xml
*.cover
*.py,cover
.hypothesis/
.pytest_cache/
cover/

# Translations
*.mo
*.pot

# Django stuff:
*.log
local_settings.py
db.sqlite3
db.sqlite3-journal

# Flask stuff:
instance/
.webassets-cache

# Scrapy stuff:
.scrapy

# Sphinx documentation
docs/_build/

# PyBuilder
.pybuilder/
target/

# Jupyter Notebook
.ipynb_checkpoints

# IPython
profile_default/
ipython_config.py

# pyenv
# For a library or package, you might want to ignore these files since the code is
# intended to run in multiple environments; otherwise, check them in:
# .python-version

# pipenv
# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
# However, in case of collaboration, if having platform-specific dependencies or dependencies
# having no cross-platform support, pipenv may install dependencies that don't work, or not
# install all needed dependencies.
#Pipfile.lock

# UV
# Similar to Pipfile.lock, it is generally recommended to include uv.lock in version control.
# This is especially recommended for binary packages to ensure reproducibility, and is more
# commonly ignored for libraries.
#uv.lock

# poetry
# Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
# This is especially recommended for binary packages to ensure reproducibility, and is more
# commonly ignored for libraries.
# https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control
#poetry.lock

# pdm
# Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.
#pdm.lock
# pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it
# in version control.
# https://pdm.fming.dev/latest/usage/project/#working-with-version-control
.pdm.toml
.pdm-python
.pdm-build/

# PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
__pypackages__/

# Celery stuff
celerybeat-schedule
celerybeat.pid

# SageMath parsed files
*.sage.py

# Environments
.env
.venv
env/
venv/
ENV/
env.bak/
venv.bak/

# Spyder project settings
.spyderproject
.spyproject

# Rope project settings
.ropeproject

# mkdocs documentation
/site

# mypy
.mypy_cache/
.dmypy.json
dmypy.json

# Pyre type checker
.pyre/

# pytype static type analyzer
.pytype/

# Cython debug symbols
cython_debug/

# PyCharm
# JetBrains specific template is maintained in a separate JetBrains.gitignore that can
# be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
# and can be added to the global gitignore or merged into this file. For a more nuclear
# option (not recommended) you can uncomment the following to ignore the entire idea folder.
#.idea/

# PyPI configuration file
.pypirc
21 changes: 21 additions & 0 deletions Dockerfile
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
# Use the official Python Alpine base image
FROM python:3.10-alpine

# Set the working directory in the container
WORKDIR /app

# Install IPMI dependency
RUN apk add --no-cache ipmitool

# Install Python requirements
COPY web_app/requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt

# Copy the Python file into the container
COPY web_app/ .

# Expose port 8080
EXPOSE 8080

# Specify the default command to run the Python script
CMD ["gunicorn", "-k", "uvicorn.workers.UvicornWorker", "-b", "0.0.0.0:8080", "app:app"]
19 changes: 19 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
# IPMI Fan control web service

- Fast API, Docker, ipmi_tool on shell

## Testing
- `sudo apt install ipmitool`
- `uvicorn app:app --reload --host 0.0.0.0 --port 18081`
- `gunicorn -k uvicorn.workers.UvicornWorker -b 0.0.0.0:18081 app:app`

## Production ready
- `docker build -t ipmi_web_tool:v1.0 .`
- `docker run -d -p 18050:8080 ipmi_web_tool:v1.0`


## TODO
- [ ] set timeout for all requests
- [ ] set security, running shell commands
- [ ] initial request (enabling manual fan control)
- [ ] save config user based or login based
72 changes: 72 additions & 0 deletions web_app/app.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
from fastapi import FastAPI, Request, Form
from fastapi.responses import HTMLResponse, JSONResponse
from fastapi.staticfiles import StaticFiles
from fastapi.templating import Jinja2Templates
from fastapi.responses import JSONResponse
from fastapi.middleware.cors import CORSMiddleware
from ipmi_cmd import run_command_test, fan_control_command

# Create a FastAPI instance
app = FastAPI()



# Mount the static directory to serve CSS and other assets
app.mount("/static", StaticFiles(directory="static"), name="static")
# Configure Jinja2 templates for rendering HTML
templates = Jinja2Templates(directory="templates")

# Add CORS middleware (Optional, based on your use case)
app.add_middleware(
CORSMiddleware,
allow_origins=["*"], # Adjust allowed origins in production
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)

# Health check endpoint (useful for production readiness probes)
@app.get("/health")
async def health_check():
return {"status": "healthy"}

# Define a simple test endpoint
@app.get("/test")
async def test_page():
return {"message": "Hello, FastAPI!"}

@app.get("/test_run")
async def run_script():
code, result = await run_command_test()
return {"Code":str(code),"response": str(result)}

@app.get("/")
async def root_page(request: Request):
return templates.TemplateResponse("index.html", {"request": request, "message": None})

# Process the submitted form data
@app.post("/")
async def submit_data(request: Request,
username: str = Form(...),
password: str = Form(...),
ipaddress: str = Form(...),
fanspeed: int = Form(...)):
request_data = {
"username" : username, "password" : password, "ipaddress" : ipaddress, "fanspeed" : fanspeed
}
# print(request_data)
response_data = await fan_control_command(request_data)

return templates.TemplateResponse("index.html", {
"request": request,
"code": response_data["code"],
"message": response_data["message"]
})

# Custom exception handler (example for improved error handling)
@app.exception_handler(Exception)
async def custom_exception_handler(request: Request, exc: Exception):
return JSONResponse(
status_code=500,
content={"error": "An unexpected error occurred"},
)
22 changes: 22 additions & 0 deletions web_app/ipmi_cmd.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
import subprocess

async def run_command_test():
command = "ipmitool -V"
result = subprocess.run(command, shell=True, text=True, capture_output=True)
if result.returncode == 0: # Check if the command was successful
print("Output:", result.stdout)
return "Success", result.stdout
else:
print("Error:", result.stderr)
return "Error", result.stdout


async def fan_control_command(request:dict)->dict:
command = f"ipmitool -I lanplus -H {request['ipaddress']} -U {request['username']} -P {request['password']} raw 0x30 0x30 0x02 0xff {hex(request['fanspeed'])}"
# print(command)
result = subprocess.run(command, shell=True, text=True, capture_output=True)
# need to add more error types
if result.returncode == 0: # Check if the command was successful
return {"code": "success", "message" : f"Fan speed set to {request['fanspeed']}% for IP {request['ipaddress']}"}
else:
return {"code": "error", "message" : f"Command error : {result.stdout}"}
5 changes: 5 additions & 0 deletions web_app/requirements.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
fastapi
uvicorn
gunicorn
jinja2
python-multipart
Loading

0 comments on commit 8b37cf9

Please sign in to comment.