Commit 7745ed2b authored by Santhosh Kumar's avatar Santhosh Kumar

initial working code for deployment

parent 376680b5
......@@ -2,3 +2,11 @@ kubectl create secret generic regcred --from-file=.dockerconfigjson=faas/con
kubectl config view --minify --raw > kube_config
# Copy this kube_config to ~/.kube/config and use kubectl to access my kubernetes cluster.
kubectl delete service <name>
sudo kubeadm token create --print-join-command
# Run this command to join.
No preview for this file type
apiVersion: v1
kind: Service
metadata:
name: hello-python-service
spec:
selector:
app: hello-python
ports:
- protocol: "TCP"
port: 6000
targetPort: 5000
type: LoadBalancer
---
apiVersion: apps/v1beta1
kind: Deployment
metadata:
name: hello-python
spec:
replicas: 4
template:
metadata:
labels:
app: hello-python
spec:
containers:
- name: hello-python
image: msanth/example1:latest
imagePullPolicy: Never
ports:
- containerPort: 5000
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 requests
RUN pip install -r requirements.txt
EXPOSE 5000
# Define the command to run the function
CMD ["python", "function.py"]
CMD ["python", "/app/function.py"]
def main(request):
"""
Entry point of the function.
"""
if request is not None and 'name' in request:
name = request['name']
return f"Hello, {name}!"
else:
return "Hello, World!"
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')
......@@ -45,7 +45,7 @@ def create_deployment(function_name):
"containers": [{
"name": function_name,
"image": f"{docker_username}/{function_name}:latest",
"ports": [{"containerPort": 8080}] # Assuming function listens on port 8080
"ports": [{"containerPort": 5000}] # Assuming function listens on port 8080
}]
}
}
......@@ -67,8 +67,8 @@ def create_service(function_name):
"metadata": {"name": f"{function_name}-service"},
"spec": {
"selector": {"app": function_name},
"ports": [{"protocol": "TCP", "port": 8080, "targetPort": 8080}], # Assuming function listens on port 8080
"type": "ClusterIP" # Expose service only within the cluster
"ports": [{"protocol": "TCP", "port": 8080, "targetPort": 5000}], # Assuming function listens on port 8080
"type": "LoadBalancer" # Expose service only within the cluster
}
}
......
......@@ -40,7 +40,7 @@ def deploy_function(function_name, image):
'containers': [{
'name': function_name,
'image': image,
'ports': [{'containerPort': 8080}]
'ports': [{'containerPort': 5000}]
}]
}
}
......@@ -75,8 +75,9 @@ def scale_function(function_name, replicas):
}
# Create HPA in Kubernetes
api_instance = client.CoreV1Api()
k8s_client.create_namespaced_horizontal_pod_autoscaler(namespace='default', body=hpa_spec)
#api_instance = client.CoreV1Api()
api_instance = client.AutoscalingV1Api(k8s_client)
api_instance.create_namespaced_horizontal_pod_autoscaler(namespace='default', body=hpa_spec)
print(f"Function {function_name} auto-scaler created with max replicas {replicas}.")
......@@ -85,12 +86,15 @@ def handle_function(event):
Handle function events (create, update, delete).
"""
function = event['object']
function_name = function['metadata']['name']
#metadata = function['metadata']
#function_name = metadata.get('name')
function_name = function.metadata.name
function_status = event['type']
if function_status == 'ADDED':
print(f"Function {function_name} added.")
deploy_function(function_name, function['spec']['image'])
#deploy_function(function_name, function['spec']['image'])
#deploy_function(function_name, function.spec['image'])
scale_function(function_name, 10) # Initially scale to max replicas of 10
elif function_status == 'MODIFIED':
print(f"Function {function_name} modified.")
......@@ -104,13 +108,25 @@ def watch_functions():
Watch for changes to function resources.
"""
resource_version = ''
v1 = client.CoreV1Api()
api_instance = client.AppsV1Api(k8s_client)
w = watch.Watch()
my_resource = {
"apiVersion": "example.com/v1",
"kind": "deployment",
"metadata": {"name": "my-new-cron-object"},
"spec": {
"cronSpec": "* * * * */5",
"image": "my-awesome-cron-image"
}
}
while True:
stream = w.stream(v1.list_namespaced_custom_object, group='example.com', version='v1', namespace='default', plural='functions', resource_version=resource_version)
for event in stream:
resource_version = event['object']['metadata']['resourceVersion']
deployment_watch = watch.Watch().stream(api_instance.list_namespaced_deployment, namespace='default')
#stream = w.stream(client.CustomObjectsApi().list_namespaced_custom_object, group='example.com', version='v1', namespace='default', plural='functions', resource_version=resource_version)
#for event in stream:
for event in deployment_watch:
#resource_version = event['object']['metadata']['resourceVersion']
print(event)
handle_function(event)
......
{'type': 'ADDED', 'object': {'api_version': 'apps/v1',
'kind': 'Deployment',
'metadata': {'annotations': None,
'creation_timestamp': datetime.datetime(2024, 4, 18, 19, 9, 19, tzinfo=tzutc()),
'deletion_grace_period_seconds': None,
'deletion_timestamp': None,
'finalizers': None,
'generate_name': None,
'generation': 1,
'labels': None,
'managed_fields': [{'api_version': 'apps/v1',
'fields_type': 'FieldsV1',
'fields_v1': {'f:spec': {'f:progressDeadlineSeconds': {},
'f:replicas': {},
'f:revisionHistoryLimit': {},
'f:selector': {},
'f:strategy': {'f:rollingUpdate': {'.': {},
'f:maxSurge': {},
'f:maxUnavailable': {}},
'f:type': {}},
'f:template': {'f:metadata': {'f:labels': {'.': {},
'f:app': {}}},
'f:spec': {'f:containers': {'k:{"name":"example1"}': {'.': {},
'f:image': {},
'f:imagePullPolicy': {},
'f:name': {},
'f:ports': {'.': {},
'k:{"containerPort":8080,"protocol":"TCP"}': {'.': {},
'f:containerPort': {},
'f:protocol': {}}},
'f:resources': {},
'f:terminationMessagePath': {},
'f:terminationMessagePolicy': {}}},
'f:dnsPolicy': {},
'f:restartPolicy': {},
'f:schedulerName': {},
'f:securityContext': {},
'f:terminationGracePeriodSeconds': {}}}}},
'manager': 'OpenAPI-Generator',
'operation': 'Update',
'subresource': None,
'time': datetime.datetime(2024, 4, 18, 19, 9, 19, tzinfo=tzutc())}],
'name': 'example1',
'namespace': 'default',
'owner_references': None,
'resource_version': '195714',
'self_link': None,
'uid': '75c9bba1-f1e5-4789-862f-ede6eea0ed29'},
'spec': {'min_ready_seconds': None,
'paused': None,
'progress_deadline_seconds': 600,
'replicas': 1,
'revision_history_limit': 10,
'selector': {'match_expressions': None,
'match_labels': {'app': 'example1'}},
'strategy': {'rolling_update': {'max_surge': '25%',
'max_unavailable': '25%'},
'type': 'RollingUpdate'},
'template': {'metadata': {'annotations': None,
'creation_timestamp': None,
'deletion_grace_period_seconds': None,
'deletion_timestamp': None,
'finalizers': None,
'generate_name': None,
'generation': None,
'labels': {'app': 'example1'},
'managed_fields': None,
'name': None,
'namespace': None,
'owner_references': None,
'resource_version': None,
'self_link': None,
'uid': None},
'spec': {'active_deadline_seconds': None,
'affinity': None,
'automount_service_account_token': None,
'containers': [{'args': None,
'command': None,
'env': None,
'env_from': None,
'image': 'msanth/example1:latest',
'image_pull_policy': 'Always',
'lifecycle': None,
'liveness_probe': None,
'name': 'example1',
'ports': [{'container_port': 8080,
'host_ip': None,
'host_port': None,
'name': None,
'protocol': 'TCP'}],
'readiness_probe': None,
'resize_policy': None,
'resources': {'claims': None,
'limits': None,
'requests': None},
'restart_policy': None,
'security_context': None,
'startup_probe': None,
'stdin': None,
'stdin_once': None,
'termination_message_path': '/dev/termination-log',
'termination_message_policy': 'File',
'tty': None,
'volume_devices': None,
'volume_mounts': None,
'working_dir': None}],
'dns_config': None,
'dns_policy': 'ClusterFirst',
'enable_service_links': None,
'ephemeral_containers': None,
'host_aliases': None,
'host_ipc': None,
'host_network': None,
'host_pid': None,
'host_users': None,
'hostname': None,
'image_pull_secrets': None,
'init_containers': None,
'node_name': None,
'node_selector': None,
'os': None,
'overhead': None,
'preemption_policy': None,
'priority': None,
'priority_class_name': None,
'readiness_gates': None,
'resource_claims': None,
'restart_policy': 'Always',
'runtime_class_name': None,
'scheduler_name': 'default-scheduler',
'scheduling_gates': None,
'security_context': {'fs_group': None,
'fs_group_change_policy': None,
'run_as_group': None,
'run_as_non_root': None,
'run_as_user': None,
'se_linux_options': None,
'seccomp_profile': None,
'supplemental_groups': None,
'sysctls': None,
'windows_options': None},
'service_account': None,
'service_account_name': None,
'set_hostname_as_fqdn': None,
'share_process_namespace': None,
'subdomain': None,
'termination_grace_period_seconds': 30,
'tolerations': None,
'topology_spread_constraints': None,
'volumes': None}}},
'status': {'available_replicas': None,
'collision_count': None,
'conditions': None,
'observed_generation': None,
'ready_replicas': None,
'replicas': None,
'unavailable_replicas': None,
'updated_replicas': None}}, 'raw_object': {'kind': 'Deployment', 'apiVersion': 'apps/v1', 'metadata': {'name': 'example1', 'namespace': 'default', 'uid': '75c9bba1-f1e5-4789-862f-ede6eea0ed29', 'resourceVersion': '195714', 'generation': 1, 'creationTimestamp': '2024-04-18T19:09:19Z', 'managedFields': [{'manager': 'OpenAPI-Generator', 'operation': 'Update', 'apiVersion': 'apps/v1', 'time': '2024-04-18T19:09:19Z', 'fieldsType': 'FieldsV1', 'fieldsV1': {'f:spec': {'f:progressDeadlineSeconds': {}, 'f:replicas': {}, 'f:revisionHistoryLimit': {}, 'f:selector': {}, 'f:strategy': {'f:rollingUpdate': {'.': {}, 'f:maxSurge': {}, 'f:maxUnavailable': {}}, 'f:type': {}}, 'f:template': {'f:metadata': {'f:labels': {'.': {}, 'f:app': {}}}, 'f:spec': {'f:containers': {'k:{"name":"example1"}': {'.': {}, 'f:image': {}, 'f:imagePullPolicy': {}, 'f:name': {}, 'f:ports': {'.': {}, 'k:{"containerPort":8080,"protocol":"TCP"}': {'.': {}, 'f:containerPort': {}, 'f:protocol': {}}}, 'f:resources': {}, 'f:terminationMessagePath': {}, 'f:terminationMessagePolicy': {}}}, 'f:dnsPolicy': {}, 'f:restartPolicy': {}, 'f:schedulerName': {}, 'f:securityContext': {}, 'f:terminationGracePeriodSeconds': {}}}}}}]}, 'spec': {'replicas': 1, 'selector': {'matchLabels': {'app': 'example1'}}, 'template': {'metadata': {'creationTimestamp': None, 'labels': {'app': 'example1'}}, 'spec': {'containers': [{'name': 'example1', 'image': 'msanth/example1:latest', 'ports': [{'containerPort': 8080, 'protocol': 'TCP'}], 'resources': {}, 'terminationMessagePath': '/dev/termination-log', 'terminationMessagePolicy': 'File', 'imagePullPolicy': 'Always'}], 'restartPolicy': 'Always', 'terminationGracePeriodSeconds': 30, 'dnsPolicy': 'ClusterFirst', 'securityContext': {}, 'schedulerName': 'default-scheduler'}}, 'strategy': {'type': 'RollingUpdate', 'rollingUpdate': {'maxUnavailable': '25%', 'maxSurge': '25%'}}, 'revisionHistoryLimit': 10, 'progressDeadlineSeconds': 600}, '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