Housekeeping task Post POD formation and before a POD dies

Vishvesh Paranjape
Dev Genius
Published in
5 min readMay 12, 2019

--

Photo by Sigmund on Unsplash

If you want to do some sort of housekeeping/cleanup work after the POD creation or before the POD dies, on Google Cloud Platform(GCP), then this is the article for you.

You will find lot of theory on what are PODs, Containers and how to built an empire using kubernetes and I will not go into the details of that, here is a quick reference for the kubernetes . I will try to keep the focus on how to call a program, once the POD is formed and when a POD is about to die, ……simple :).

We will try to use postStart and preStop container handlers. We will first see postStart, as we will be be able to look into the container and see the output. We will then try to delete a Google Cloud Pub/Sub subscription using preStop event. Refer here to understand container lifecycle event.

So lets begin the journey….

Step 1- Have your environment readyStep 2- Using "postStart" eventStep 3- Using "preStop" event

Step 1- Have your environment ready. Try to get or build a kubernetes environment (cluster) consisting of a POD with single container, having NodeJS. In this container I am expecting a demo.js file under “/usr” folder. There are different ways to create such a container. I created a new docker image of my own. Following steps should create your own image that will contain a demo.js file under “/usr”

1. docker pull node2. docker run -it — name=”hellonode_test” node:latest /bin/bash3. Goto "/usr" folder. Create a file demo.js and put following javascript code.function testimony() {console.log(‘This is function only to prove my point.’); } testimony()Easy way to do this is following

echo "function testimony() {console.log(‘This is function only to prove my point.’); } testimony()" > demo.js
4. docker commit -m=”This a test hellonode image” hellonode_test hellonodejs5. docker tag hellonodejs gcr.io/<your project id>/hellonodejs6. docker push gcr.io/<your project id>/hellonodejs

Step 2- Using “postStart” event- “Kubernetes sends the postStart event immediately after the Container is created”. I will try to demonstrate the use of postStart event here.

In Step 1, we have our image ready for deployment. Lets go ahead and deploy it using following minimal “.yaml” configuration as shown below.

apiVersion: extensions/v1beta1
kind: Deployment
metadata:
name: my-pod
spec:
replicas: 1
selector:
matchLabels:
app: testhellonode
template:
metadata:
labels:
app: testhellonode
spec:
containers:
— name: my-container
image: gcr.io/<your project id>/hellonodejs
imagePullPolicy: Always
command: [“/bin/sh”, “-c”, “while :; do sleep 1; done”]
lifecycle:
postStart:
exec:
command: [“/bin/sh”, “-c”, “node ./usr/demo.js > /usr/share/message”]

Command to push above configuration - kubectl apply -f “<path to yaml>”

Once the deployment is successful, which you can verify by using commands like kubectl get deployments and/or kubectl get pods. Try to get the name of the POD (POD_Name).Now try to run following command

kubectl exec -it <POD_Name> — /bin/bashcat /usr/share/message

You should see a message “This is function only to prove my point.” displayed.

This message was generated as a result of postStart handler where we have tried to run demo.js and have piped it to “/usr/share/message”. This proves that we should be able to call any programming logic to perform some task. In my case I have successfully called javascript.

Step 3- Using “preStop” event. To see a proof of “preStop” event we will not be able to use logs, as the POD will get destroyed and we cannot login into a POD to see the logs. So to see this event is working we will have to change some state externally, where we can go and verify. There are number of ways we can use, like writing an entry into a persistence storage(Database) etc. I will try to delete a existing Cloud Pub/Sub Subscription.

Prerequisites- Try to create a Cloud Pub/Sub subscription named, “hellosub” on topic “hellotopic”, manually. Refer here on how to create a subscription.

We will use following javascript code to delete a subscription when “preStop” event occurs. I will put this code in a file named “delsub.js”.

async function deleteSubscription() {const subscriptionName = ‘hellosub’;const { PubSub } = require(‘@google-cloud/pubsub’);const pubsub = new PubSub();await pubsub.subscription(subscriptionName).delete();}deleteSubscription()

Again for above code to work we will have to have a kubernetes environment (cluster) consisting of a POD with single container, having NodeJS and the required node modules ("@google-cloud/pubsub"). We can create a new image consisting all above required components and also try to put the file delsub.js created under “/usr” folder. Refer here for Cloud Pub/Sub client.

I will try to add following prestop entry next to PostStart in the previous yaml file

         preStop:
exec:
command: ["/bin/sh", "-c", "node ./usr/delsub.js"]

So the yaml file will now look as following

apiVersion: extensions/v1beta1
kind: Deployment
metadata:
name: my-pod
spec:
replicas: 1
selector:
matchLabels:
app: testhellonode
template:
metadata:
labels:
app: testhellonode
spec:
containers:
— name: my-container
image: gcr.io/<your project id>/hellonodejs
imagePullPolicy: Always
command: [“/bin/sh”, “-c”, “while :; do sleep 1; done”]
lifecycle:
postStart:
exec:
command: [“/bin/sh”, “-c”, “node ./usr/demo.js > /usr/share/message”]
preStop:
exec:
command: ["/bin/sh", "-c", "node ./usr/delsub.js"]

Do a re-deployment using above yaml file.

The preStop event is triggered only when a POD dies, so to reproduce/trigger the preStop event we will have to kill the POD, there are different ways to do this, but scaling down the POD size is simplest one. So I will scale down the POD size from 1 to 0 (zero). Once we scale down the size to 0, preStop event is triggered and this will delete the “hellosub” subscription. We can verify this by going and checking the list for Subscriptions.

Summary: In this post we saw how we can call a javascript code from “postStart” and “preStop”, Container lifecycle events. Which is a small step ahead of calling a simple script. Similarly we can define a handler to call a code or a script in some different programming language, I will leave it you for further exploration. To conclude, these events can be used for some housekeeping/important tasks to accomplish after a POD formation or before a POD dies.

--

--