Commit 729326ba authored by Santhosh Kumar's avatar Santhosh Kumar

full function

parent 7745ed2b
from kubernetes import client, config
import time
# Docker Hub username (replace with your Docker Hub username)
docker_username = "msanth"
def build_and_push_image(function_name):
"""
Build the Docker image and push it to Docker Hub.
"""
# Change directory to function directory
os.chdir(function_name)
# Build Docker image
subprocess.run(["docker", "build", "-t", f"{docker_username}/{function_name}:latest", "."], check=True)
# Push Docker image to Docker Hub
subprocess.run(["docker", "push", f"{docker_username}/{function_name}:latest"], check=True)
# Change back to original directory
os.chdir("..")
def deploy_function(function_name):
# Load Kubernetes config from default location
image_name = function_name+":latest"
config.load_kube_config()
# Initialize Kubernetes API client
api_instance = client.AppsV1Api()
# Define deployment object
deployment = client.V1Deployment()
deployment.metadata = client.V1ObjectMeta(name=function_name)
deployment.spec = client.V1DeploymentSpec(
replicas=1,
selector=client.V1LabelSelector(
match_labels={"app": function_name}
),
template=client.V1PodTemplateSpec(
metadata=client.V1ObjectMeta(labels={"app": function_name}),
spec=client.V1PodSpec(
containers=[
client.V1Container(
name=function_name,
image=image_name
)
]
)
)
)
# Create deployment
print("Creating deployment...")
api_instance.create_namespaced_deployment(namespace="default", body=deployment)
# Wait for deployment to succeed
while True:
time.sleep(5) # Check deployment status every 5 seconds
deployment_status = api_instance.read_namespaced_deployment_status(name=function_name, namespace="default")
if deployment_status.status.ready_replicas == 1:
print("Deployment succeeded.")
break
def create_service(function_name):
"""
Create a Kubernetes Service resource for the function.
"""
service_manifest = {
"apiVersion": "v1",
"kind": "Service",
"metadata": {"name": f"{function_name}-service"},
"spec": {
"selector": {"app": function_name},
"ports": [{"protocol": "TCP", "port": 8080, "targetPort": 5000}], # Assuming function listens on port 8080
"type": "LoadBalancer" # Expose service only within the cluster
}
}
# Create Service in Kubernetes
#k8s_client.create_namespaced_service(namespace="default", body=service_manifest)
api_instance = client.CoreV1Api()
api_instance.create_namespaced_service(namespace="default", body=service_manifest)
print(f"Service created for {function_name}.")
def create_network_trigger(function_name):
# Initialize Kubernetes API client
trigger_name = fimctopm_name + "-trigger"
api_instance = client.CustomObjectsApi()
# Define trigger object
trigger = {
"apiVersion": "networking.knative.dev/v1",
"kind": "Trigger",
"metadata": {
"name": trigger_name
},
"spec": {
"broker": "default",
"filter": {
"attributes": {
"type": "sh.keptn.event.project.create"
}
},
"subscriber": {
"ref": {
"apiVersion": "serving.knative.dev/v1",
"kind": "Service",
"name": function_name
}
}
}
}
# Create trigger
print("Creating network trigger...")
api_instance.create_namespaced_custom_object(group="networking.knative.dev", version="v1", namespace="default", plural="triggers", body=trigger)
# Wait for trigger to be successfully created
while True:
time.sleep(5) # Check trigger status every 5 seconds
try:
api_instance.get_namespaced_custom_object(group="networking.knative.dev", version="v1", namespace="default", plural="triggers", name=trigger_name)
print("Trigger created successfully.")
break
except client.rest.ApiException as e:
if e.status != 404:
raise
def get_trigger_url(function_name):
trigger_name = function_name + "-network"
# Initialize Kubernetes API client
api_instance = client.CustomObjectsApi()
# Get trigger details
trigger = api_instance.get_namespaced_custom_object(group="networking.knative.dev", version="v1", namespace="default", plural="triggers", name=trigger_name)
url = trigger["spec"]["subscriber"]["ref"]["name"]
print("Trigger URL:", url)
if __name__ == "__main__":
# Deploy function
function_name = "example2"
deploy_function(function_name)
# Create service
create_service(function_name)
# Create network trigger
create_network_trigger(function_name)
# Get trigger URL
get_trigger_url(function_name)
FROM python:3.9-slim
RUN mkdir /app
# Set the working directory in the container
WORKDIR /app
ADD . /app/
# Copy the function code into the container
COPY function.py .
# Install any dependencies
RUN pip install -r requirements.txt
EXPOSE 5000
# Define the command to run the function
CMD ["python", "/app/function.py"]
from flask import Flask
app = Flask(__name__)
@app.route("/")
def hello():
return "Hello from Python function"
if __name__ == "__main__":
app.run(host='0.0.0.0')
This diff is collapsed.
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