Pages

Showing posts with label java. Show all posts
Showing posts with label java. Show all posts

Saturday, 1 February 2020

Automating Heap Dumps For Java Containers in Google Kubernetes Engine

Heap dumps are an indispensable tool for debugging memory issues in Java processes. The typical way of taking a memory dump is using the jmap command

jmap -dump:format=b;file=/tmp/heap.dump 2592

This will trigger a heap dump for the process with id 2592 (assuming it's a Java process) and store it in a file /tmp/heap.dump. This can be analyzed later with a heap dump analyzer like jhat, MAT, or VisualVM - which are free tools.

Triggering a heap dump for a Java process that is running in a container, inside a pod, in a Google Kubernetes Engine (GKE) cluster node is not so straightforward. There are many layers of infrastructure that you have to cross to get at the Java process. Your process would usually run as part of a managed abstraction like a Deployment or a StatefulSet in your Kubernetes cluster. Your starting point would be just the pod name.

But,

- Knowing the pod name is not enough - you also have to locate the cluster node where it's running and ssh into it.
- A GKE node might be running many pods, and many Java processes - you have to identify the correct one once once you have ssh'ed into it. "docker ps" can help here.
- The GKE node might not have jmap. It's not straightforward to install the JDK there  because it would typically be running COS. So you have to get inside the container and trigger the dump.
- You have to copy the dump to an accessible location, maybe a GCS bucket, from where you can download it to analyze. Uploading to a GCS bucket requires gsutil, which is not present by default in a COS node.

I have automated this entire process using just shell scripts and gcloud commands. The source code is on GitHub. They also use the toolbox utility that Google provides as a container for running debug tools. Invoking "toolbox" inside your GKE node will launch this container.

These scripts have an assumption which might not be valid for your cluster - I'll point it out at the relevant point in the code.

Here's a step by step explanation of the flow.

There are 3 shell scripts - k8s-debug-client.sh being the one to run from your dev box or bastion host. This one invokes k8s-debug-vm.sh (inside the GKE cluster node, i.e. the VM) which in turn invokes the k8s-debug-toolbox.sh.

First we find out the node on which the pod is running

node_name=`kubectl get pod ${pod_name} -o json | jq '. | .spec.nodeName'`

and get its public IP

public_ip=`gcloud compute instances list --filter="name=(${node_name})" --format="value(networkInterfaces[].accessConfigs[0].natIP)"`

copy the other two scripts to it

scp -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null -i ${keyfile} k8s-debug-vm.sh k8s-debug-toolbox.sh ${user}@${public_ip}:

and trigger them

ssh -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null -i ${keyfile} ${user}@${public_ip} sh k8s-debug-vm.sh ${pod_name} ${action} ${bucket}

I turn off the ssh warnings as I trigger this from a CI system on demand. If you run them manually, you can remove the -o options.

Inside the GKE node, k8s-debug-vm.sh figures out the correct container id and uses docker exec to trigger a heap dump inside it. 

container_id=`docker ps | grep ${pod_name} | grep -v "POD" | awk '{print $1}'`
docker exec ${container_id} sh -c "jmap -dump:format=b,file=heap.dump 1"

Note that the heap dump is inside the container, and not in the VM. You may not be able to push it to a GCS bucket from the container as there is no gsutil and no permissions. So we need to copy the dump to the VM. We copy it to a uniquely named file.

dttime=`echo $(date '+%d-%b-%Y-%H-%M-%S')`
filename=${pod_name}-${dttime}.hdump
docker cp ${container_id}:heap.dump ${filename}

Now you have the dump file in the VM but there is no gsutil. So you need to invoke toolbox, which has gsutil inside it. Does that mean we need to copy the dump inside toolbox now? No, because toolbox mounts several useful directories by default from the VM it's running on. 

So we just invoke toolbox and pass it the path to the k8s-debug-toolbox.sh (which is in the home directory of the user you are logged in as in the VM) as it would appear from inside toolbox (since the home directory is also mounted inside toolbox).

Inside toolbox, we can use gsutil to upload the dump file (which is also available inside toolbox because it's in the home directory of the user you are logged in as in the VM). But here's a catch. gsutil requires permissions to upload to a GCS bucket. One way to provide this permission is with an IAM permissions JSON file. But how does it get to the VM? 

This is the caveat I mentioned above. In the infrastructure I manage, almost every Java pod has a config map with a permissions file that the pod uses to access Google Cloud services. This file is accessible as a mounted directory inside toolbox, so, voila!

/google-cloud-sdk/bin/gcloud auth activate-service-account --key-file=${dir}/key.json
/google-cloud-sdk/bin/gsutil cp /media/root/home/${user}/${filename} gs://${bucket}/kdev-debug/${filename}

If you don't have this shortcut, you will a need to set the permissions somehow. There are multiple ways of doing it - one being to run a custom container instead of toolbox that has gsutil installed and can mount a config map which has the permissions. Another is to upload the permissions file to the VM when you run the command, use it from inside toolbox, and then delete it. The second one is a tad risky.

These scripts can be modified to be usable for any Kubernetes cluster and not just GKE. Most of the changes will be in the commands that fetch the list of running nodes. If you are using another OS for your K8S VMs, you can install Java directly on the VM and trigger the dump, after you find out the mapping between the container ids and the process ids as visible from the VM.

Saturday, 4 May 2013

Thoughts on "A Note on Distributed Computing"

A Note on Distributed Computing by Jim Waldo, Geoff Wyant, Ann Wollrath, and Sam Kendall is a widely cited paper. I have been reading and trying to understand it for sometime. It's available here - http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.41.7628

The title of the paper is innocuous but it's much more than a "note". It analyzes the key differences between local and distributed computing, and explains why attempts to unify their programming models are misguided because of the fundamental differences underlying them.


The authors used to be part of the erstwhile Sun Microsystems when they wrote it - it dates from 1994. Later some of them were members of the JINI technology team and also wrote RMI, and if you look at the Java RMI source code,  you can see some of their names.


But in 1994 when this paper was written, Java had not emerged yet. There was no J2EE and CORBA was still young.

I wish to share my thoughts after reading it, and the realization that the opinions expressed in it influenced the design of Java's RMI.


Unification

Briefly, unification = unification of the local and the distributed programming models. Note that we are talking about distributed object oriented systems here.

The unification attempts assume that objects are essentially of a single top level type (like in Java), which might span different address spaces on the same or different machines (like different JVMs on the same or different machines in the case of Java) and they can communicate in the same way irrespective of where they are located. In other words, location (same JVM versus another JVM in another country) is merely an implementation detail that can be abstracted away behind the interfaces used to communicate between two objects without any side effects.


Such a (hypothetical) system would have the following characteristics

  1. Program functionality is not affected by the location of the object on which an operation has been invoked. Or viewing it from a slightly higher level, there is a single design as to how a system communicates irrespective of whether it's deployed in one address space or in multiple ones. 
  2. Maintenance and upgrades can be done to individual objects without affecting the rest of the system. 
  3. There is no need to handle failure and performance issues in the system design.
  4. Object interfaces are always the same regardless of the context (i.e. remote or local)
The authors contend that all these statements are flawed. I'll not attempt to go into those details - the paper explains them well.

The paper then goes onto examine the 4 areas where local and distributed computing differ drastically:
    Latency

    Memory Access
    Partial Failure
    Concurrency

Those of us who have worked on distributed enterprise and internet software have come across these. These 4 differences cannot be papered over to present a 'unified' view of objects which lie on different machines.

 

Java RMI
If you look at RMI, you can see its design influenced by the assumption that the above 4 points are invalid.
  • "Remote" objects have to extend the java.rmi.Remote interface. "Remote" objects - objects that can be invoked from another JVM - are different from local objects.
  • Remote (inter-JVM) method calls have to explicitly handle the java.rmi.RemoteException, which is a checked exception, thus highlighting the fact that a distributed call is subject to modes of failure that are non-existent in a local call. In fact, it extends java.io.IOException and the javadoc is explicit about network issues "is the common superclass for a number of communication-related exceptions that may occur during the execution of a remote method call".
Let's look at #2 again. From the paper:
"As long as the interfaces between objects remain constant, the implementations of those objects can be altered at will".
Premonition of SOA, anyone? This concept would be familiar today to anybody who is acquainted with the fundamental principles of service oriented system design (replace 'object' with 'service'). But since these statements are challenged and refuted later in the paper, the question naturally arises - how come SOA is successful?  

SOA assumes that things are independent and distributed services, and any invocation of a service assumes that there are failure modes which exist because of the communication's distributed nature. This builds on the same RMI concept as having to explicitly throw RemoteException when making a remote (distributed) call. This same concept is taken into consideration while writing any SOA system, which is another way of saying that the authors of the paper were correct.

Note: A short and readable summary of Java RMI is to be found in Jim Waldo's book Java: The Good Parts.

Thursday, 15 November 2012

No more PermGen in the JDK

PermGen space is familiar to anybody who has debugged memory issues in large JEE applications. Starting with JDK 8, it is being removed. The JDK Enhancement Proposal says "remove", but it's more like it's being moved to native memory outside the JVM.

The goal as mentioned in the JEP is "to remove the need to tune the size of the permanent generation."

The beginnings of the change are already in JDK7, with interned strings being no longer part of the PermGen, but of the main Java heap - http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6962931

There's a summary of changes in the OpenJDK mailing list
http://mail.openjdk.java.net/pipermail/hotspot-dev/2012-September/006679.html

What does this mean for Java developers? Well, at least the following
- There will no longer be any need to set the sizes of the Perm Gen space with JVM startup parameters.
- The class metadata previously stored in the PermGen will now be stored in a native memory space called "Metaspace".
- The default maximum size of the metaspace will be limited only by the available memory on the machine. However, it can be limited by using the MaxMetaspaceSize option.
- It's not entirely clear yet as to how debugging tools like jmap and jhat will change, if at all, as a result of this, or if it will bring in more complications.

And of course, if you have classloader-leaks-based OutOfMemory problems in your application, they are not magically going away. They will just be transferred to another space with more memory than is allocated to your JVM now.

I could not find any reference to the origin of the term "metaspaces" except in this paper (PDF) - http://www.ssw.uni-linz.ac.at/General/Staff/TS/optimized_class_metadata_memory_management_in_a_jvm.draft.pdf
Familiarity with the JVM's memory management strategies is required to understand it - which I don't have currently - so it's on my to-read list as of now.

Sunday, 23 May 2010

Instance Initializers in Java

Take a look at this simple code

Code Snippet 1

public class Init {
  {
    System.out.println("In the beginning was the command line");
  }

  public Init()
  {
    System.out.println("Created an instance");
  }

  public static void main(String[] args)
  {
    Init init = new Init();
  }
}

What do you think the output is? It's this -
    In the beginning was the command line
    Created an instance

The 'hanging' braces at the start of the class definition are instance initializers. Most of us are more familiar with static initializers -

Code Snippet 2
static
{
  //Do stuff
}


Instance initializers (II) are not seen often in everyday Java code - so they might seem odd at first. They are executed every time an instance of that class is created, before the statements in the constructor are executed. (See The Java Language Specification 3 section 8.6).

One use of IIs can be to execute something whenever an instance is created, and the class has multiple constructors, without calling it in every single constructor.
Another one which has become popular is populating collections during declaration, in the style of Ruby or Python single-line initializers -

Code Snippet 3
private Set<String> names = new HashSet<String>() {
  {
    add("Rigel");
    add("Vega");
    add("Antares");
  }
};


This idiom was how I encountered IIs first while reading somebody's blog.
What is actually happening here?
  1. An anonymous inner class is created.
  2. An instance initializer block is added to the anon inner class.
  3. Objects are added to the instance of that class when the names variable is initialized.

Now take this scenario:

Code Snippet4
public class WrongUsage {

  private Set<String> names;
  {
    add("pleiades");
  }

  public void WrongUsage()
  {
    names = new HashSet<String>();
  }

  public void add(String name)
  {
    names.add(name);
  }
}

Based on what we have seen above, the names set is used before it's initialized. So this throws a NullPointerException.
Let's take another case - similar to the above but involving inheritance.

Code Snippet 5

public class MyHashSet extends HashSet {
  {
    add("pleiades");
    System.out.println("Added");
  }

  public MyHashSet()
  {
    super();
    System.out.println("After calling super");
  }

  public static void main(String[] args)
  {
    Set set = new MyHashSet();
  }
}


This runs, with the output being
    Added
    After calling super

In this case, add() internally uses the inner HashMap inside HashSet which is initialized in the HashSet constructor. This implies that the instance initializer is invoked before the class constructor, but after the superclass constructor (The super call is redundant here. It will be called anyway).

So the sequence is
  1. Superclass initialization (this includes superclass instance initializers and constructor)
  2. Current class's Instance initializers
  3. Current class's Constructor

This is why the code in Code Snippet 3 does not throw an NPE - because it's a case of inheritance (the anon inner class is a subclass of HashSet)

Sunday, 30 August 2009

Wondering about the state of Java Developers

A friend of mine forwarded this article by Yakov Fain on sys-con.com -

http://in.sys-con.com/node/1040135

The essence of the article is this

The author interviewed a lot of people for developer positions, and most of them who call themselves Java developers and cite extensive experience in J2EE lack basic knowledge of core Java.

This might sound suspiciously like a gross generalization, but I believe that's not the case. I had a similar experience when I interviewed people for developer positions on my team last month. The position called for both Java and Javascript experience. These are the things I encountered -

  • Most people who have worked solely on services (read outsourced) projects list all J* technologies on their resume, but know very little in depth of Java programming.
  • There are people who lack any kind of programmer mentality or skills at all and put their current role as something like Programmer Analyst, and this fact cannot be ascertained from their resume alone. They often try to highlight other (non-software development) achievements.
  • SCJP certification is no guarantee that a person can code in Java (Surprise? Not at all)
  • There are people who have 3.5 years of experience, with multiple services projects under their belts, and familiarity with a host of technologies, who cannot write a Java class which will print out the prime numbers between 0 and 100.
  • Most core CS concepts are forgotten after 2-3 years of working in services projects.

Please note that I am not generalizing, but these facts do indicate a problem somewhere. These developers actually a represent a very small distinct sample of the worldwide developer community, since all my interviews were done in India (both face to face in my Hyderabad office and over the phone).

Another interesting point I noted was that most non-Javascript developers think that Javascript is used only for form validation. Such usage also qualifies as 'extensive Javascript knowledge' in their resumes.
What should I conclude from this? Is this malaise widespread in other parts of the world as well? Is it specific to developers in India working on outsourced projects? (No, as the link by Yakov Fain shows) Is it a result of outsourcing, leading to a lack of innovation? Or is the innovation there, but the signal to noise ratio too low?