container wip

This commit is contained in:
Your Name
2025-02-10 00:12:22 +00:00
parent 4a07bfdf36
commit c044c2fc04
4 changed files with 157 additions and 62 deletions
@@ -96,7 +96,7 @@ def add_container_workload():
# TODO - Check if this user has permissions to VIEW and LAUCNH_CONTAINER in this VDC
request_vdc=VirtualDataCenter.query.filter_by(id=uuid.UUID(validated_data['vdc'])).first()
if request_vdc is None:
# Raise an error or return a response indicating that no VDC was found
abort(404, description="Virtual Data Center not found") # Flask's abort function
@@ -132,7 +132,7 @@ def add_container_workload():
#Send the request off to the websocket server to have this container launched
payload = {
"worker_id": random_host.id,
"task_type": "container",
"task_type": "container-create",
"job_details": {
"tenancyID": 3,
"containers": [
@@ -194,7 +194,7 @@ def delete_container_workload(workload_id):
#Send the request off to the websocket server to have this container launched
payload = {
"worker_id": _container.workload_host_id,
"task_type": "container",
"task_type": "container-delete",
"job_details": {
"tenancyID": 3,
"containers": [
+143
View File
@@ -0,0 +1,143 @@
import docker
def find_namespace_controller(container_name):
"""
Finds the namespace controller (master container) for a given container name.
"""
# Initialize the Docker client
client = docker.from_env()
try:
# Get the container by name
container = client.containers.get(container_name)
container_info = container.attrs
# Get the NetworkMode from HostConfig
network_mode = container_info['HostConfig']['NetworkMode']
# Check if the network mode is linked to another container
if network_mode.startswith('container:'):
# Extract the master container ID
master_container_id = network_mode.split(':')[1]
# Look up the master container's name
try:
master_container = client.containers.get(master_container_id)
return {
'master_container_id': master_container_id,
'master_container_name': master_container.name
}
except docker.errors.NotFound:
return {
'master_container_id': master_container_id,
'master_container_name': "Unknown (container not found)"
}
else:
return None # No namespace controller found
except docker.errors.NotFound:
return None # Container not found
def find_linked_containers(master_container_name):
"""
Finds all child/linked containers for a given namespace controller (specified by container name).
"""
# Initialize the Docker client
client = docker.from_env()
try:
# Get the master container by name
master_container = client.containers.get(master_container_name)
master_container_id = master_container.id
# Get all containers
containers = client.containers.list(all=True)
# List to store linked containers
linked_containers = []
# Iterate through all containers
for container in containers:
container_info = container.attrs
# Get the NetworkMode from HostConfig
network_mode = container_info['HostConfig']['NetworkMode']
# Check if the network mode is linked to the master container
if network_mode == f'container:{master_container_id}':
linked_containers.append({
'container_id': container.id,
'container_name': container.name
})
return linked_containers
except docker.errors.NotFound:
return None # Master container not found
def check_network_links():
"""
Main function to check all containers and their network links.
"""
# Initialize the Docker client
client = docker.from_env()
# Get all containers
containers = client.containers.list(all=True)
# Dictionary to store container network links
network_links = {}
# Iterate through all containers
for container in containers:
# Inspect the container to get detailed information
container_info = container.attrs
# Get the NetworkMode from HostConfig
network_mode = container_info['HostConfig']['NetworkMode']
# Check if the network mode is linked to another container
if network_mode.startswith('container:'):
# Extract the master container ID
master_container_id = network_mode.split(':')[1]
# Look up the master container's name
try:
master_container = client.containers.get(master_container_id)
master_container_name = master_container.name
except docker.errors.NotFound:
master_container_name = "Unknown (container not found)"
# Store the link in the dictionary
network_links[container.id] = {
'master_container_id': master_container_id,
'master_container_name': master_container_name
}
# Print the results
if network_links:
print("Containers with linked networks:")
for container_id, link_info in network_links.items():
print(
f"Container ID: {container_id[:12]} "
f"is linked to master container ID: {link_info['master_container_id'][:12]} "
f"(Name: {link_info['master_container_name']})"
)
else:
print("No containers are linked to another container's network.")
if __name__ == "__main__":
# Example usage of the new functions
print("Testing find_namespace_controller:")
controller_info = find_namespace_controller("ac39a08c-7b7a-43f9-8545-82f54ef7ea0d")
if controller_info:
print(f"Namespace controller for 'my_container_name': {controller_info}")
else:
print("No namespace controller found or container does not exist.")
print("\nTesting find_linked_containers:")
linked_containers = find_linked_containers("nscontroller-3")
if linked_containers:
print(f"Containers linked to 'nscontroller-3':")
for container in linked_containers:
print(f"Container ID: {container['container_id'][:12]} (Name: {container['container_name']})")
else:
print("No linked containers found or master container does not exist.")
+11 -12
View File
@@ -20,22 +20,21 @@ def render_container_list():
with st.form("create_container"):
# Dropdown for VDC selection
selected_vdc_name = st.selectbox("VDC", list(vdc_options.keys()))
container_id = st.text_input("Container ID")
selected_host_name = st.selectbox("Workload Host ID (Optional)", list(workload_host_options.keys()))
status = st.selectbox("Status", ["running", "stopped", "pending"])
launch_params = st.text_input("Launch Parameters (Optional)")
container_name = st.text_input("Container Name")
docker_image = st.text_input("Docker Image", value="abc")
submit = st.form_submit_button("Create Container Workload")
if submit and selected_vdc_name and container_id:
if submit and selected_vdc_name and container_name:
# Use the selected VDC's ID
vdc_id = vdc_options[selected_vdc_name]
workload_host_id=workload_host_options[selected_host_name]
result = st.session_state.client.create_container({
"vdc_id": vdc_id,
"container_id": container_id,
"workload_host_id": workload_host_id,
"status": status,
"launch_params": launch_params
"vdc": vdc_id,
"containers": [
{
"docker_image": docker_image,
"container_name": container_name,
}
]
})
if result:
st.success("Container workload created successfully!")
@@ -53,7 +52,7 @@ def render_container_list():
st.text(f"Status: {container['status']}")
st.text(f"VDC ID: {container['vdc_id']}")
with col2:
st.text(f"ID: {container['id'][:8]}...")
st.text(f"ID: {container['id']}...")
with col3:
if st.button("View Details", key=f"view_{container['id']}"):
st.session_state.selected_resource = container
-47
View File
@@ -1,47 +0,0 @@
#!/bin/bash
# Configuration
API_URL="http://127.0.0.1:5000/api/workload_hosts/enroll"
REGION_ID="$1" # Region ID must be passed as an argument
# if [ -z "$REGION_ID" ]; then
# echo "Usage: $0 <region_id>"
# exit 1
# fi
REGION_ID=b9455aea-1219-450a-a44f-f585136ecec7
# Gather system information
SYSTEM_MANUFACTURER=$(cat /sys/class/dmi/id/sys_vendor 2>/dev/null || echo "Unknown")
SYSTEM_MODEL=$(cat /sys/class/dmi/id/product_name 2>/dev/null || echo "Unknown")
PHYSICAL_IDENTIFIER=$(cat /sys/class/dmi/id/product_serial 2>/dev/null || echo "Unknown")
DCIM_IDENTIFIER=$(dmidecode -s system-uuid 2>/dev/null || echo "Unknown")
INSTALLED_DATE=$(date -u +"%Y-%m-%dT%H:%M:%SZ")
HOSTNAME=$(hostname)
# Construct JSON payload
JSON_PAYLOAD=$(cat <<EOF
{
"region_id": "$REGION_ID",
"system_manufacturer": "$SYSTEM_MANUFACTURER",
"system_model": "$SYSTEM_MODEL",
"physical_identifier": "$PHYSICAL_IDENTIFIER",
"dcim_identifier": "$DCIM_IDENTIFIER",
"installed_date": "$INSTALLED_DATE",
"hostname": "$HOSTNAME"
}
EOF
)
# Send enrollment request
RESPONSE=$(curl -s -X POST "$API_URL" \
-H "Content-Type: application/json" \
-d "$JSON_PAYLOAD")
echo curl -s -X POST "$API_URL" \
-H "Content-Type: application/json" \
-d "$JSON_PAYLOAD"
# Handle response
if echo "$RESPONSE" | grep -q 'error'; then
echo "Enrollment failed: $RESPONSE"
exit 1
else
echo "Enrollment successful: $RESPONSE"
fi