Monday 13 August 2018

Did You Face Pods Stuck On Terminating Issue While Deleting The Namespace In Kubernetes ?

You might have faced a situation of "Pods getting stuck on terminating" issue when trying to delete the namespace. This could be irritating especially when you might need the namespace delete results instantly.









No Problem, Kubernetes has provided a way to deal with this situation. We need to force delete the pod providing the pod name and namespace

Force Delete Command➤

< kubectl delete pod "podname" -n "namespace" --grace-period=0 --force >

Now, What if you have 10 to 20 Pods listed in "terminating status" even when you have issued a delete namespace command. So Now, You may need to force delete all of them one by one. 

But deleting them manually could be a cumbersome job and needs a lot of patience.

Well, there is a way where you can deal with this situation as well:

Code 1➤ Groovy Code to force delete multiple pods

Code 2➤ Shell Script Code to force delete multiple pods



Shell Script Code To Force Delete Multiple Pods From Kubernetes

There might be a situation where you have 10 to 20 Pods listed in "terminating status" even when you have issued a delete namespace command. So Now, You may need to force delete all of them. 

But deleting them manually could be a cumbersome job and needs a lot of patience.

Well, there is a way where you can deal with this situation as well:











Code 2➤ Shell Script Code to force delete multiple pods
Create a folder and save below code to your sample.sh file. Now open the git bash and navigate to the folder where you have kept your sample.sh code.

Now run the below command.

➤ sh sample.sh

namespace="yournamespace"
outputPods=($(kubectl get pods -o=name -n $namespace))
podsCount=${#outputPods[@]}
if [ $podsCount -gt 0 ]
then
for (( i=0; i < ${podsCount}; i++ ));
do
   podName=(${outputPods[i]/pod\//})
   echo $(kubectl delete pod ${podName} -n $namespace --grace-period=0 --force)
done
else
   echo "No Pods listed"
fi


Groovy Code To Force Delete Multiple Pods From Kubernetes

There might be a situation where you have 10 to 20 Pods listed in "terminating status" even when you have issued a delete namespace command. So Now, You may need to force delete all of them. 

But deleting them manually could be a cumbersome job and needs a lot of patience.

Well, there is a way where you can deal with this situation as well:







Code 1➤ Groovy Code to force delete multiple pods
Create a folder and save below code to your sample.groovy file. Now open the command prompt or git bash and navigate to the folder where you have kept your sample.groovy code.

Now run the below command.

➤ groovy sample.groovy

NOTE: you have to install groovy if it is not installed already


nameSpace="yournamespace"
getPods="kubectl get pods -o=name -n "+nameSpace+""pods = getPods.execute().text

if(!pods.allWhitespace && !pods.equals("No resources found.")){

    def podNames = pods.split('\n')
    for (int i=0; i <  podNames.length; i++){
        command  = "kubectl delete pod "+""+podNames[i].replace( 'pod/', '' ).trim()+""+" -n "+nameSpace+" --grace-period=0 --force"        println command.execute().text
    }

}else{
    println "No Pods Listed"}
Code 2➤ Shell Script Code to force delete multiple pods



Saturday 11 August 2018

All You Need To Know About Efficient Network Access And Sending JSON object Using OkHttp

Sometime you may need to POST the events to the endpoint based on your project needs. There are various APIs available to request and get the response from the events in the market but when I came across OkHttp I started loving the simplicity of it.
It is one of the APIs that is very easy to understand and easy to use. OkHttp is mostly used to exchange data & media. Doing HTTP efficiently using it makes your data load faster and saves bandwidth.



Below are some of the features of OkHttp:
  1. Connection pooling reduces request latency
  2. It will silently recover from common connection problems
  3. If your service request has multiple IP addresses OkHttp will attempt alternate addresses if the first connection fails.
  4. OkHttp initiates new connections with modern TLS features (SNI, ALPN), and falls back to TLS 1.0 if the handshake fails.

Now why to wait, let's see how we use the OkHttp in our Code. So as part of this tutorial, I am performing below operations:

  1. Send Login Event
  2. CreateSession Event
  3. Publish Event
Sending Login Event:  You can create your own SampleUtil and add login method to that class. The method below is calling a login() method of SampleUtil. Login method will return the response object which will be stored in the reference variable "response". This variable later can be used to validate the response code which in this case is 200.  You need to fetch the "jwt" from the response which you will need to Create a Session event later.

public void iSendLoginRequest() throws Throwable {
    try {
        Response response = SampleUtil.login("http://loginurl:8080", jsonBody);
        assertEquals(responseCode, response.code());
        String responseBody = response.body().string();
        JSONObject object = new JSONObject(responseBody);
        String jwtToken = object.getString("jwt");
    } catch (Exception e) {
        System.out.println(e.getMessage());
    }
}
SampleUtil.java Code:
public static Response login(String loginUrl, String jsonBody) {
     try {
         RequestBody body = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), jsonBody);

         OkHttpClient client = new OkHttpClient();
         okhttp3.Request request = new okhttp3.Request.Builder()
                 .url(loginUrl)
                 .post(body)
                 .build();

         return client.newCall(request).execute();
     } catch (Exception e) {
         e.printStackTrace();
     }
     return null;
 }
Performing Create Session Event: createSession() takes the URL, JSON body and JWT as the parameters and method will return the response object which will be stored in the reference variable "response". This variable later can be used to validate the response code which in this case is 200. Along with that, you need to fetch the "sessionId" from the response which you need to Publish the event later.

public void iCreateSessionRequest() throws Throwable {
    try {
        Response response = SampleUtil.createSession("http://createsessionurl:8080",jsonBody, jwtToken);
        assertEquals(responseCode, response.code());
        String responseBody = response.body().string();
        JSONObject object = new JSONObject(responseBody);
        sessionId = object.getString("sessionId");

    } catch (Exception e) {
        e.printStackTrace();
    }
}

SampleUtil.java Code:
 public static Response createSession(String createSessionUrl, String jsonBody, String jwt) {
    try {
        RequestBody body = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), jsonBody);
        OkHttpClient client = new OkHttpClient();
        okhttp3.Request request = new okhttp3.Request.Builder()
                .url(createSessionUrl)
                .addHeader("Authorization", "Bearer " + jwt)
                .post(body)
                .build();

        return client.newCall(request).execute();

    } catch (Exception e) {
         e.printStackTrace();
    }
    return null;
}

Publishing the Event: publishEvent() takes the URL, JSON body and SESSION ID as the parameters and method will return the response object which will be stored in the reference variable "response". This variable later can be used to validate the response code which in this case is 200. Along with that, you need to fetch the "sessionId" from the response which you need to Publish the event later.

public void iPerformsAPublishEventRequest() throws Throwable {
    try {
        Response response = SampleUtil.publishEvent("http://publisheventurl:8080",jsonBody,sessionId);
        assertEquals(responseCode, response.code());
    } catch (Exception e) {
        System.out.println(e.getMessage());
    }
}

SampleUtil.java Code:
public static Response publishEvent(String url, String jsonBody, String sessionId) {
    try {
        RequestBody body = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), jsonBody);

        OkHttpClient client = new OkHttpClient();
        okhttp3.Request request = new okhttp3.Request.Builder()
                .url(url)
                .post(body)
                .addHeader("sessionId", sessionId)
                .build();
        return client.newCall(request).execute();

    } catch (Exception e) {
        e.printStackTrace();
    }
    return null;
}