Commit 6076a5fc authored by obbinti.rao's avatar obbinti.rao

first commit

parent 02414133
.env
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="GitToolBoxProjectSettings">
<option name="commitMessageIssueKeyValidationOverride">
<BoolValueOverride>
<option name="enabled" value="true" />
</BoolValueOverride>
</option>
<option name="commitMessageValidationEnabledOverride">
<BoolValueOverride>
<option name="enabled" value="true" />
</BoolValueOverride>
</option>
</component>
</project>
\ No newline at end of file
class Error(Exception):
pass
class UniqueCredentialError(Error):
pass
class ValueTooLargeError(Exception):
"""Raised when the input value is too large"""
pass
import configparser
import configparser
import json
import os
class EnvInterpolation(configparser.BasicInterpolation):
"""Interpolation which expands environment variables in values."""
def before_get(self, parser, section, option, value, defaults):
value = super().before_get(parser, section, option, value, defaults)
if not os.path.expandvars(value).startswith('$'):
return os.path.expandvars(value)
else:
return
config = configparser.ConfigParser(interpolation=EnvInterpolation())
CONFIGURATION_FILE = f"application.conf"
config.read(CONFIGURATION_FILE)
"""
Configuration module
Mongo Info
"""
MONGO_URI = config.get("mongo_db", "mongo_uri")
[mongo_db]
# mongo_constants_file_path= conf/mongo_encryption_constants.json
mongo_uri = $MONGO_URI
\ No newline at end of file
from pymongo import MongoClient
import app_configuration
class MongoConnect:
def __init__(self, uri):
try:
self.uri = uri
self.client = MongoClient(self.uri)
except Exception:
raise
...@@ -18,15 +18,24 @@ async def add_new_credentials(user: User): ...@@ -18,15 +18,24 @@ async def add_new_credentials(user: User):
# except pymongo.errors.DuplicateKeyError as d: # except pymongo.errors.DuplicateKeyError as d:
# print(d) # print(d)
# return {"message": f"credential name already exist, try again! {d}"} # return {"message": f"credential name already exist, try again! {d}"}
except Exception as e: except pymongo.errors.DuplicateKeyError:
return {"status": "failed", "message": f"credential name already exist, try again! {e.__class__}"}, 500 return {"status": "failed", "message": f"credential name already exist, try again!"}, 500
#
# except Exception as e:
# return {"status": "failed", "message": f"credential name already exist, try again! {e.__class__}"}, 500
@app.get("/credentials", tags=["List of Credentials"]) @app.get("/credentials", tags=["List of Credentials"])
def employee_details( def employee_details(
category: str = fastapi.Query(None, description="Enter Type of credentials or empty field will display all")): category: str = fastapi.Query(None, description="Enter Type of credentials or empty field will display all")):
if category: if category:
return myCollection.find_one({"type": category}, {"_id": 0, "parameters": {"password": 0}}) try:
res = myCollection.find_one({"type": category}, {"_id": 0, "parameters": {"password": 0}})
if res:
return res
raise Exception
except Exception:
return {"status": "failed", "message": f"credential not exist, try again! "}, 500
return list(myCollection.find({}, {"_id": 0, "parameters": {"password": 0}})) return list(myCollection.find({}, {"_id": 0, "parameters": {"password": 0}}))
...@@ -39,9 +48,9 @@ Optional[dict] = {"ports":{"8002":"5000"},"environment":{"key": "value"},"volume ...@@ -39,9 +48,9 @@ Optional[dict] = {"ports":{"8002":"5000"},"environment":{"key": "value"},"volume
def add_new_docker_credentials(user: LaunchCredential): def add_new_docker_credentials(user: LaunchCredential):
docker_obj = DockerExecutorEngine(user.credential_name) docker_obj = DockerExecutorEngine(user.credential_name)
try: try:
return str(docker_obj.launch_container(user.image, **user.variable_parameters)) return docker_obj.launch_container(user.image, **user.variable_parameters)
except Exception: except Exception as e:
return {"status": "failed", "message": "Invalid input data, try again!"}, 500 return {"status": "failed", "message": f" Failed to launch Container, try again! {e.__class__}"}, 500
# @app.post('/launchContainer', tags=["Enter details to launch container"]) # @app.post('/launchContainer', tags=["Enter details to launch container"])
...@@ -51,9 +60,6 @@ def add_new_docker_credentials(user: LaunchCredential): ...@@ -51,9 +60,6 @@ def add_new_docker_credentials(user: LaunchCredential):
# return str(docker_obj.launch_container(image, **data)) # return str(docker_obj.launch_container(image, **data))
@app.get("/status", tags=["Check the status of container"]) @app.get("/status", tags=["Check the status of container"])
def status_of_launched_containers(Container_id: str = fastapi.Query(None, description="Enter conteiner ID or empty " def status_of_launched_containers(Container_id: str = fastapi.Query(None, description="Enter conteiner ID or empty "
"field will display all " "field will display all "
...@@ -64,13 +70,10 @@ def status_of_launched_containers(Container_id: str = fastapi.Query(None, descri ...@@ -64,13 +70,10 @@ def status_of_launched_containers(Container_id: str = fastapi.Query(None, descri
ll = (docker_obj.all_container_status()) ll = (docker_obj.all_container_status())
result = [] result = []
for x in ll: for x in ll:
result.append(x.id) result.append(docker_obj.container_status(x.id))
return {"list_of_containers": result} return {"list_of_containers": result}
@app.get("/stop", tags=["Terminate container"]) @app.get("/stop", tags=["Terminate container"])
def remove_containers(Container_id: str): def remove_containers(Container_id: str):
docker_obj = DockerExecutorEngine() docker_obj = DockerExecutorEngine()
......
import docker import docker
import pymongo # import pymongo
from typing import Optional from typing import Optional
import pymongo
from pydantic import BaseModel from pydantic import BaseModel
client = pymongo.MongoClient("mongodb://localhost:27017/") from db_connection import MongoConnect
from app_configuration import MONGO_URI
# client = pymongo.MongoClient("mongodb://localhost:27017/")
# Access database # Access database
myDatabase = client['sankar_db'] # myDatabase = client['sankar_db']
mongo_connect_obj = MongoConnect(uri=MONGO_URI)
myDatabase = mongo_connect_obj.client['sankar_db']
# Access collection of the database # Access collection of the database
myCollection = myDatabase['docker_credentials'] myCollection = myDatabase['docker_credentials']
...@@ -53,14 +62,17 @@ class DockerExecutorEngine: ...@@ -53,14 +62,17 @@ class DockerExecutorEngine:
def launch_container(self, image, **kwargs): def launch_container(self, image, **kwargs):
return self.client.containers.run(image=image, detach=True, **kwargs) # return self.client.containers.run(image=image, detach=True, **kwargs)
r = self.client.containers.run(image=image, detach=True, **kwargs)
return self.container_status(r.id)
def container_status(self, container_id): def container_status(self, container_id):
a = self.container_details(container_id) a = self.container_details(container_id)
b = self.client.containers.get(container_id).status b = self.client.containers.get(container_id).status
data = [container_id, a['Name']] data = {"container_id": container_id, "container_name": a['Name']}
# data = [container_id, a['Name']]
resp = {"data": data, "status": b, "message": "Container launched successfully"} resp = {"data": data, "status": b, "message": "Container launched successfully"}
return resp return resp
...@@ -78,17 +90,17 @@ class DockerExecutorEngine: ...@@ -78,17 +90,17 @@ class DockerExecutorEngine:
return self.client.containers.get(container_id).remove() return self.client.containers.get(container_id).remove()
if __name__ == "__main__": # if __name__ == "__main__":
docker_obj = DockerExecutorEngine(credential_name="satyam-creds") # docker_obj = DockerExecutorEngine(credential_name="satyam-creds")
res = docker_obj.login_docker_account() # res = docker_obj.login_docker_account()
print(res) # print(res)
#
status = docker_obj.launch_container(image="redis:latest", detach=True, ports={800: 800}) # status = docker_obj.launch_container(image="redis:latest", detach=True, ports={800: 800})
# status = docker_obj.launch_container(image="redis:latest", command=["/bin/sh", "-c", 'echo 1 && echo 2'], # # status = docker_obj.launch_container(image="redis:latest", command=["/bin/sh", "-c", 'echo 1 && echo 2'],
# ports={10080: 8000}, # # ports={10080: 8000},
# volumes={'/PycharmProjects/newdocker/': {'bind': '/mnt/vol2', 'mode': 'rw'}, # # volumes={'/PycharmProjects/newdocker/': {'bind': '/mnt/vol2', 'mode': 'rw'},
# '/var/www': {'bind': '/mnt/vol1', 'mode': 'ro'}}) # # '/var/www': {'bind': '/mnt/vol1', 'mode': 'ro'}})
print(status) # print(status)
#
# print(docker_obj.stop_container("25d59d85223b")) # # print(docker_obj.stop_container("25d59d85223b"))
# print(docker_obj.terminate_container('c823b13533')) # # print(docker_obj.terminate_container('c823b13533'))
import docker
from typing import Optional
client = docker.from_env()
xx=client.containers.get('e57c61c057e1').attrs
print(type(xx['Name']))
# res = client.login(username='osr2000', password='oO@096689', email='obbinti.rao@knowledgelens.com',
# registry='https://index.docker.io/v1')
# def testing_method(image: str, myDict: Optional[dict]):
# if myDict:
# s = client.containers.run(image,detach=True, **myDict)
# print(s)
# s = client.containers.run(image,detach=True)
# print(s)
#
# testing_method('redis',{})
# def testing_method(image: str, myDict: Optional[dict]):
# s = client.containers.run(image,detach=True, **myDict)
# print(s)
# testing_method('redis',{})
# # testing_method('redis')
# print
# s = client.containers.run(image='redis', detach=True)
# print(s)c823b13533
# print(client.containers.get('c823b13533').status)
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment