diff --git a/.dockerignore b/.dockerignore new file mode 100644 index 0000000..ed8ebf5 --- /dev/null +++ b/.dockerignore @@ -0,0 +1 @@ +__pycache__ \ No newline at end of file diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..84f035f --- /dev/null +++ b/.gitignore @@ -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 \ No newline at end of file diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 0000000..48e06b4 --- /dev/null +++ b/Dockerfile @@ -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"] diff --git a/README.md b/README.md new file mode 100644 index 0000000..95c7c64 --- /dev/null +++ b/README.md @@ -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 \ No newline at end of file diff --git a/web_app/app.py b/web_app/app.py new file mode 100644 index 0000000..e310628 --- /dev/null +++ b/web_app/app.py @@ -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"}, + ) \ No newline at end of file diff --git a/web_app/ipmi_cmd.py b/web_app/ipmi_cmd.py new file mode 100644 index 0000000..9f9ee40 --- /dev/null +++ b/web_app/ipmi_cmd.py @@ -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}"} \ No newline at end of file diff --git a/web_app/requirements.txt b/web_app/requirements.txt new file mode 100644 index 0000000..7f63add --- /dev/null +++ b/web_app/requirements.txt @@ -0,0 +1,5 @@ +fastapi +uvicorn +gunicorn +jinja2 +python-multipart \ No newline at end of file diff --git a/web_app/static/styles.css b/web_app/static/styles.css new file mode 100644 index 0000000..5c6a997 --- /dev/null +++ b/web_app/static/styles.css @@ -0,0 +1,74 @@ +body { + font-family: Arial, sans-serif; + background-color: #f4f4f9; + margin: 0; + padding: 0; + display: flex; + justify-content: center; + align-items: center; + height: 100vh; +} + +.form-container { + background: #ffffff; + padding: 20px 40px; + border-radius: 8px; + box-shadow: 0 4px 10px rgba(0, 0, 0, 0.1); + text-align: center; + width: 300px; +} + +h1 { + margin-bottom: 20px; + color: #333; +} + +label { + display: block; + margin: 10px 0 5px; + font-weight: bold; +} + +input { + width: 100%; + padding: 8px; + margin-bottom: 15px; + border: 1px solid #ccc; + border-radius: 4px; + box-sizing: border-box; +} + +button { + background-color: #007BFF; + color: white; + border: none; + padding: 10px 15px; + cursor: pointer; + font-size: 16px; + border-radius: 4px; + width: 100%; +} + +button:hover { + background-color: #0056b3; +} + +.response-message { + margin-top: 20px; + padding: 10px; + border-radius: 4px; + font-weight: bold; + text-align: center; +} + +.success { + background-color: #d4edda; + border: 1px solid #c3e6cb; + color: #155724; +} + +.error { + background-color: #f8d7da; + border: 1px solid #f5c6cb; + color: #721c24; +} diff --git a/web_app/templates/index.html b/web_app/templates/index.html new file mode 100644 index 0000000..0876b48 --- /dev/null +++ b/web_app/templates/index.html @@ -0,0 +1,34 @@ + + +
+ + +