from email.quoprimime import body_check from http.client import HTTPException from turtle import title from typing import Optional from fastapi import FastAPI, Response, status, HTTPException from fastapi.params import Body from pydantic import BaseModel from random import randrange import os import subprocess from podman import PodmanClient import json import yaml app = FastAPI() uri = "unix:///run/user/1000/podman/podman.sock" podmanapi = PodmanClient(base_url=uri) yaml_file = open("containers.yaml", 'r') yaml_content = yaml.load(yaml_file,Loader=yaml.FullLoader) class Post(BaseModel): title: str content: str published: bool = True rating: Optional[int] = None class Environment(BaseModel): username: str uid: str my_posts= [{"title": "title of post 1", "content": "contents of post 1", "id": 1},{"title": "title of post 2", "content": "contents of post 2", "id": 2}] def find_post(id): for p in my_posts: if p["id"] == id: return p def find_index_post(id): for i, p in enumerate(my_posts): if p['id'] == id: return i @app.get("/") async def root(): return {"message": "Welcome to my api!!"} @app.get("/posts") async def get_posts(): return {"data": my_posts} @app.post("/posts", status_code=status.HTTP_201_CREATED) async def create_posts(post: Post): post_dict = post.dict() post_dict['id'] = randrange(0, 1000000) my_posts.append(post_dict) return {"data": post_dict} @app.get("/posts/{id}") async def get_post(id: int): post = find_post(id) if not post: raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=f"Post id {id} not found") return {"post_detail": post} @app.delete("/posts/{id}", status_code=status.HTTP_204_NO_CONTENT) async def delete_post(id: int): index = find_index_post(id) if index == None: raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=f"Post id {id} not found") my_posts.pop(index) return Response(status_code=status.HTTP_204_NO_CONTENT) @app.put("/posts/{id}") async def update_post(id: int, post: Post): index = find_index_post(id) if index == None: raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=f"Post id {id} not found") post_dict = post.dict() post_dict['id'] = id my_posts[index] = post_dict return {"data": post_dict} @app.post("/create_env", status_code=status.HTTP_201_CREATED) async def create_env(env: Environment): env_dict = env.dict() #print(env_dict) #cmd = subprocess.run(["cat","list"],stdout=subprocess.PIPE, stderr=subprocess.PIPE, check=True, text=True) # store the output in the list #output = (f"{cmd.stdout}") for container in yaml_content['Containers']: #print(container['name'],'-', env_dict['username'],'-',env_dict['uid'],sep='') container = podmanapi.containers.run(image="docker.io/library/nginx:latest",name=container['name']+'-'+env_dict['username']+'-'+env_dict['uid'],detach=True,publish_all_ports=True) return @app.get("/environment/{id}") async def get_env(id: str): cmd = subprocess.run(["cat list | grep %s" % id],stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True) if cmd.returncode != 0: raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=f"Post id {id} not found") else: return {"environment_detail": cmd} @app.delete("/delete_env", status_code=status.HTTP_204_NO_CONTENT) async def get_env(env: Environment): env_dict = env.dict() #cmd = subprocess.run(["cat list | grep %s" % id],stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True) for container in yaml_content['Containers']: container = podmanapi.containers.remove(container_id=container['name']+'-'+env_dict['username']+'-'+env_dict['uid'],force=True,v=True) #if container: # raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=f"Post id {id} not found") #else: return @app.get("/list") async def list_env(): # send one packet of data to the host # this is specified by '-c 1' in the argument list #outputlist = [] # Iterate over all the servers in the list and ping each server # get the output as a string #output = str(os.system(cmd)) #cmd = subprocess.run(["/bin/ls", "-al"],stdout=subprocess.PIPE, stderr=subprocess.PIPE, check=True, text=True) #cmd = subprocess.run(["cat list"],stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True) #cmd = subprocess.run(["ls /usr/bin"],stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True) #output2 = (f'{cmd.stdout.decode("utf-8").lower()}') #print (output2) #for image in podmanapi.images.list(): # print(image, image.id, "\n") #for key, value in yaml_content.items(): # print(f"{key}: {value}") #image = podmanapi.images.pull("docker.io/nginx", tag="latest") #for container in yaml_content['Containers']: # container = podmanapi.containers.run(image="docker.io/library/nginx:latest",name=container['name'],detach=True,publish_all_ports=True) #output = podmanapi.images.list() #json_str = json.dumps(podmanapi.df(), indent=4) #container = podmanapi.containers.create(image="docker.io/library/nginx:latest",name='test',detach=True,publish_all_ports=True) containers = podmanapi.containers.list(all=True,filters='status=running') #for cont_id in containers: # cont_name = podmanapi.containers.get(container_id=cont_id) # print(cont_name) #first_name = containers['Names'][0] for container in containers: cont_name = podmanapi.containers.get(container) print(cont_name, cont_name.id) #print(f"{container}") #print(containers[0]) #for contain in containers: # print(contain[0]) #container = podmanapi.containers.get(first_name) #print(container, container.id, "\n") # available fields #print(sorted(container.attrs.keys())) #run_container = podmanapi.containers.run(image="docker.io/library/nginx:latest",name='test',stdout=True, stderr=False) #json_str = json.dumps(podmanapi.containers.list(), indent=4) #print(json.dumps(podmanapi.version(), indent=4)) return Response(content='fdf', media_type='application/json')