File size: 16,421 Bytes
3b509f1 44fc8ec 3b509f1 e6237ad d1d6946 e6237ad d1d6946 e6237ad d1d6946 e6237ad d1d6946 e6237ad d1d6946 e6237ad d1d6946 e6237ad 3b509f1 e6237ad 3b509f1 e6237ad 3b509f1 e6237ad 3b509f1 e6237ad 3b509f1 1a16272 51f81fd 1a16272 3b509f1 5d0e7d7 3b509f1 e6237ad 51f81fd e6237ad 51f81fd e6237ad 3b509f1 d4112a3 3b509f1 d4112a3 3b509f1 e6237ad 3b509f1 |
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 |
import os
import subprocess
import tarfile
import asyncio
from fastapi import FastAPI, HTTPException, Form, UploadFile, File, Depends, Query, Response
from fastapi.responses import HTMLResponse, FileResponse, StreamingResponse
from pydantic import BaseModel
from tempfile import NamedTemporaryFile
from typing import List
from pydantic import BaseModel
from fastapi.staticfiles import StaticFiles
app = FastAPI()
REQUIREMENTS_FILE = "requirements1.txt"
class DockerImageParams(BaseModel):
image_name: str
tag: str = 'latest'
async def stream_log(file_path):
with open(file_path, 'r') as file:
while True:
line = file.readline()
if line:
yield line
else:
await asyncio.sleep(0.1)
import os
import subprocess
import urllib.request
import shutil
def install_python_version(python_version: str, use_deb: bool = False, install_dir: str = os.path.expanduser("~/local")):
base_url = "https://www.python.org/ftp/python"
python_bin = f"{install_dir}/bin/python{python_version}"
pip_bin = f"{install_dir}/bin/pip{python_version}"
# Check if Python is already installed
if os.path.isfile(python_bin):
return python_bin, pip_bin
try:
os.makedirs(install_dir, exist_ok=True)
if use_deb:
raise NotImplementedError("Debian package installation requires root permissions.")
else:
# For .tar.xz binary distribution
tar_url = f"{base_url}/{python_version}/Python-{python_version}-linux-x86_64.tar.xz"
tar_path = f"/tmp/Python-{python_version}.tar.xz"
# Download Python source tarball
urllib.request.urlretrieve(tar_url, tar_path)
# Extract tarball
subprocess.run(["tar", "-xf", tar_path, "-C", "/tmp"], check=True)
# Build and install Python to the specified directory
python_src_path = f"/tmp/Python-{python_version}"
subprocess.run([f"{python_src_path}/configure", f"--prefix={install_dir}"], cwd=python_src_path, check=True)
subprocess.run(["make", "-j"], cwd=python_src_path, check=True)
subprocess.run(["make", "install"], cwd=python_src_path, check=True)
# Clean up
os.remove(tar_path)
shutil.rmtree(python_src_path)
except urllib.error.HTTPError as e:
raise RuntimeError(f"HTTP Error: {str(e)}")
except subprocess.CalledProcessError as e:
raise RuntimeError(f"Error installing Python {python_version}: {str(e)}")
except Exception as e:
raise RuntimeError(f"Error: {str(e)}")
return python_bin, pip_bin
# @app.post("/download-dependencies")
# async def download_dependencies(requirements_file: UploadFile = File(...)):
# try:
# with NamedTemporaryFile(delete=False) as tmp:
# tmp.write(requirements_file.file.read())
# tmp_path = tmp.name
# # Ensure the directories exist
# os.makedirs("/tmp/dependencies", exist_ok=True)
# log_file_path = "/tmp/dependencies/download.log"
# with open(log_file_path, "w") as log_file:
# # Download dependencies
# result = subprocess.run(
# ["pip", "download", "-r", tmp_path, "-d", "/tmp/dependencies"],
# # stdout=log_file,
# # stderr=log_file
# )
# if result.returncode != 0:
# raise HTTPException(status_code=500, detail="Error downloading dependencies. See log file for details.")
# # Create a tar file
# tar_path = "/tmp/dependencies.tar.gz"
# with tarfile.open(tar_path, "w:gz") as tar:
# for root, _, files in os.walk("/tmp/dependencies"):
# for file in files:
# file_path = os.path.join(root, file)
# tar.add(file_path, arcname=file)
# tar.add(log_file_path, arcname="download.log")
# # Get the file size
# file_size = os.path.getsize(tar_path)
# # Return the tar file
# return StreamingResponse(open(tar_path, "rb"), media_type="application/gzip", headers={
# "Content-Disposition": f"attachment; filename=dependencies.tar.gz",
# "Content-Length": str(file_size)
# })
# except subprocess.CalledProcessError as e:
# raise HTTPException(status_code=500, detail=f"Error downloading dependencies: {str(e)}")
# except Exception as e:
# raise HTTPException(status_code=500, detail=str(e))
# finally:
# if os.path.exists(tmp_path):
# os.remove(tmp_path)
# if os.path.exists(log_file_path):
# os.remove(log_file_path)
# if os.path.exists(tar_path):
# os.remove(tar_path)
@app.post("/download-dependencies")
async def download_dependencies(
requirements_file: UploadFile = File(...),
python_version: str = Form(None),
):
tmp_path = None
log_file_path = None
tar_path = None
try:
# Use the current Python version if not specified
if not python_version:
python_version = "3.11" # Adjust to your current version or use `sys.version_info`
python_bin, pip_bin = install_python_version(python_version)
# Validate the installed Python and pip
if not os.path.isfile(python_bin):
raise HTTPException(status_code=400, detail=f"Python {python_version} installation failed.")
if not os.path.isfile(pip_bin):
raise HTTPException(status_code=400, detail=f"pip for Python {python_version} installation failed.")
with NamedTemporaryFile(delete=False) as tmp:
tmp.write(requirements_file.file.read())
tmp_path = tmp.name
# Ensure the directories exist
os.makedirs("/tmp/dependencies", exist_ok=True)
log_file_path = "/tmp/dependencies/download.log"
with open(log_file_path, "w") as log_file:
# Download dependencies using the specified Python version
result = subprocess.run(
[python_bin, "-m", "pip", "download", "-r", tmp_path, "-d", "/tmp/dependencies"],
stdout=log_file,
stderr=log_file
)
if result.returncode != 0:
raise HTTPException(status_code=500, detail="Error downloading dependencies. See log file for details.")
# Create a tar file
tar_path = "/tmp/dependencies.tar.gz"
with tarfile.open(tar_path, "w:gz") as tar:
for root, _, files in os.walk("/tmp/dependencies"):
for file in files:
file_path = os.path.join(root, file)
tar.add(file_path, arcname=file)
tar.add(log_file_path, arcname="download.log")
# Get the file size
file_size = os.path.getsize(tar_path)
# Return the tar file
return StreamingResponse(open(tar_path, "rb"), media_type="application/gzip", headers={
"Content-Disposition": f"attachment; filename=dependencies.tar.gz",
"Content-Length": str(file_size)
})
except subprocess.CalledProcessError as e:
raise HTTPException(status_code=500, detail=f"Error downloading dependencies: {str(e)}")
except Exception as e:
print(str(e), "dddddddddddddddddddd")
raise HTTPException(status_code=500, detail=str(e))
finally:
if tmp_path and os.path.exists(tmp_path):
os.remove(tmp_path)
if log_file_path and os.path.exists(log_file_path):
os.remove(log_file_path)
if tar_path and os.path.exists(tar_path):
os.remove(tar_path)
def download_docker_image(image_name, tag='latest', destination='/tmp/docker-images'):
try:
os.makedirs(destination, exist_ok=True)
tar_path = os.path.join(destination, f'{image_name.replace("/", "_")}.tar')
# Remove the existing tar file if it exists
if os.path.exists(tar_path):
os.remove(tar_path)
# Skopeo command to copy the image as a tar file
command = [
'skopeo', 'copy',
f'docker://{image_name}:{tag}',
f'docker-archive:{tar_path}'
]
subprocess.run(command, check=True)
print(f"Image '{image_name}:{tag}' downloaded successfully to {destination}.")
return tar_path
except subprocess.CalledProcessError as e:
print(f"Error downloading image: {str(e)}")
raise HTTPException(status_code=500, detail=f"Error downloading Docker image: {str(e)}")
# Serve static files
app.mount("/static", StaticFiles(directory="static"), name="static")
@app.get("/", response_class=HTMLResponse)
async def read_root():
html_content = """
<html>
<head>
<title>Azeez's Help Desk</title>
<link href="/static/css/index.css" rel="stylesheet">
<script src="/static/js/index.js"></script>
</head>
<body>
<h1>Welcome to Azeez's Help Desk :)</h1>
<div class="tab">
<button class="tablink" onclick="openTab(event, 'Docker')" id="defaultOpen">Docker Image Download</button>
<button class="tablink" onclick="openTab(event, 'Pip')">Pip Dependencies Download</button>
<button class="tablink" onclick="openTab(event, 'Deb')">Debian Packages Download</button>
</div>
<div id="Docker" class="tabcontent">
<h2>Docker Image Download</h2>
<form onsubmit="handleDockerFormSubmit(event)">
<label for="image_name">Docker Image Name:</label>
<input type="text" id="image_name" name="image_name" required><br><br>
<label for="tag">Docker Image Tag:</label>
<input type="text" id="tag" name="tag" value="latest" required><br><br>
<input type="submit" id="docker-submit-button" value="Download Docker Image">
</form>
<div id="docker-message" style="display: none; margin-top: 10px;"></div>
</div>
<div id="Pip" class="tabcontent">
<h2>Pip Dependencies Download</h2>
<form onsubmit="handlePipFormSubmit(event)">
<label for="requirements_file">Requirements File:</label>
<input type="file" id="requirements_file" name="requirements_file" accept=".txt" required><br><br>
<label for="python_version">Python Version</label>
<input type="text" id="python_version" name="python_version"><br><br>
<input type="submit" id="pip-submit-button" value="Download Dependencies">
</form>
<div id="pip-message" style="display: none; margin-top: 10px;"></div>
</div>
<div id="Deb" class="tabcontent">
<h2>Debian Packages Download</h2>
<form onsubmit="handleDebFormSubmit(event)">
<label for="deb_packages">Debian Package Names (comma-separated):</label>
<input type="text" id="deb_packages" name="deb_packages" required><br><br>
<input type="submit" id="deb-submit-button" value="Download Debian Packages">
</form>
<div id="deb-message" style="display: none; margin-top: 10px;"></div>
</div>
<div id="progress-container">
<div id="progress-bar">0%</div>
</div>
</body>
</html>
"""
return HTMLResponse(content=html_content)
@app.get("/download-docker-image")
async def download_docker_image_endpoint(image_name: str = Query(...), tag: str = Query('latest')):
tar_path = download_docker_image(image_name, tag)
file_size = os.path.getsize(tar_path)
def iterfile():
with open(tar_path, 'rb') as file:
while chunk := file.read(1024 * 1024): # Read in 1 MB chunks
yield chunk
headers = {
"Content-Disposition": f'attachment; filename="{image_name.replace("/", "_")}.tar"',
"Content-Length": str(file_size)
}
return StreamingResponse(iterfile(), media_type='application/x-tar', headers=headers)
def create_tar_file(files_to_package: List[str], tar_filename: str, destination_dir: str):
"""
Create a tar file containing specified files.
Args:
- files_to_package (list): List of paths to files to include in the tar file.
- tar_filename (str): Name of the tar file to create.
- destination_dir (str): Directory to save the tar file.
"""
try:
tar_path = os.path.join(destination_dir, tar_filename)
with tarfile.open(tar_path, "w:gz") as tar:
for file_path in files_to_package:
tar.add(file_path, arcname=os.path.basename(file_path))
print(f"Created tar file '{tar_filename}' successfully in '{destination_dir}'.")
return tar_path
except Exception as e:
print(f"Error creating tar file: {e}")
raise
def download_deb_packages(package_names: List[str], destination_dir: str) -> List[str]:
"""
Download Debian packages (`.deb`) and their dependencies using `apt-get download`.
Args:
- package_names (list): List of package names to download.
- destination_dir (str): Directory to save downloaded packages.
Returns:
- List of paths to downloaded `.deb` packages.
"""
try:
# Create the destination directory if it doesn't exist
os.makedirs(destination_dir, exist_ok=True)
downloaded_packages = []
# Download each package and its dependencies
for package_name in package_names:
# Run apt-get update to refresh package index
# subprocess.run(['apt-get', 'update'], check=True)
# Download the package to the destination directory
subprocess.run(['apt-get', 'download', package_name, '-d', destination_dir], check=True)
# Build the full path to the downloaded package
deb_filename = f"{package_name}.deb"
downloaded_packages.append(os.path.join(destination_dir, deb_filename))
return downloaded_packages
except subprocess.CalledProcessError as e:
print(f"Error downloading packages: {e}")
raise
import subprocess
def download_make_package(destination_dir):
try:
# Ensure the destination directory exists
subprocess.run(['mkdir', '-p', destination_dir])
# Download the make package
result = subprocess.run(['apt-get', 'download', 'make', '-d', destination_dir], check=True)
if result.returncode == 0:
print(f"Downloaded make package and dependencies to {destination_dir} successfully.")
else:
print("Failed to download make package.")
except subprocess.CalledProcessError as e:
print(f"Error downloading packages: {e}")
@app.post("/download-deb-packages")
async def download_deb_packages_handler(deb_packages: str = Form(...)):
try:
destination_dir = '/tmp/downloaded_packages'
subprocess.run(['mkdir', '-p', destination_dir]) # Ensure destination directory exists
package_name='make'
# Download the package using apt-get
result = subprocess.run(['apt-get', 'install', package_name], check=True)
# If download is successful, return the downloaded package
if result.returncode == 0:
tar_filename = f'{package_name}.tar.gz'
tar_path = f'{destination_dir}/{tar_filename}'
return FileResponse(tar_path, filename=tar_filename)
# If download fails, raise HTTPException
else:
raise HTTPException(status_code=500, detail=f"Failed to download {package_name} package.")
except subprocess.CalledProcessError as e:
error_message = str(e.stderr)
print(f"Error downloading packages: {error_message}")
raise HTTPException(status_code=500, detail=f"Error downloading {package_name} package: {error_message}")
except Exception as e:
print(f"Error: {str(e)}")
raise HTTPException(status_code=500, detail=f"Failed to download {package_name} package: {str(e)}")
if __name__ == "__main__":
import uvicorn
uvicorn.run(app, host="0.0.0.0", port=5000)
|