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 = """