Sunday, December 21, 2014

apache cassandra 1.0.8 out of memory error unable to create new native thread

If you are using apache cassandra 1.0.8 and having the exception such as below, you may want to further read. Today, we will investigate on what this error means and what can we do to correct this situation.
ERROR [Thread-273] 2012-14-10 16:33:18,328 AbstractCassandraDaemon.java (line 139) Fatal exception in thread Thread[Thread-273,5,main]
java.lang.OutOfMemoryError: unable to create new native thread
at java.lang.Thread.start0(Native Method)
at java.lang.Thread.start(Thread.java:640)
at java.util.concurrent.ThreadPoolExecutor.addIfUnderMaximumPoolSize(ThreadPoolExecutor.java:727)
at java.util.concurrent.ThreadPoolExecutor.execute(ThreadPoolExecutor.java:657)
at org.apache.cassandra.thrift.CustomTThreadPoolServer.serve(CustomTThreadPoolServer.java:104)
at org.apache.cassandra.thrift.CassandraDaemon$ThriftServer.run(CassandraDaemon.java:214)

This is not good, the application crashed with this error during operation. To illustrate this environment, it is running using oracle java 6 with apache cassandra 1.0.8. It has 12GB of java heap assigned with stack size 128k, max user processes 260000 and open files capped at 65536.

Investigate into the java stack trace, reveal that, this error is not thrown by java code but native code. Below is the trace path.

  1. https://github.com/apache/cassandra/blob/cassandra-0.8/src/java/org/apache/cassandra/thrift/CassandraDaemon.java#L214

  2. https://github.com/apache/cassandra/blob/cassandra-1.0.8/src/java/org/apache/cassandra/thrift/CustomTThreadPoolServer.java#L104

  3. ThreadPoolExecutor.java line 657
    cassandra_investigation_1

  4. ThreadPoolExecutor.java line 727
    cassandra_investigation_2

  5. Thread.java line 640
    cassandra_investigation_3


A little explanation before we delve even deeper. Number 3 to 5, is jdk dependent. Hence, if you are using openjdk, the line number may be different. As mentioned early, I'm using oracle jdk. Unfortunately, it is not available online for browsing but you can download the source from oracle site.

Because this is a native call, we will look into code that is not in Java. If the following code looks alien to you, it sure looks alien to me as it is probably written in c++. If you have also notice, this code is taken from openjdk and it is not found in the oracle jdk. Probably it is a closed source but we will not go there. Let's just focus where this error thrown from and why. It is taken from here and the explanation here.
JVM_ENTRY(void, JVM_StartThread(JNIEnv* env, jobject jthread))
JVMWrapper("JVM_StartThread");
JavaThread *native_thread = NULL;

// We cannot hold the Threads_lock when we throw an exception,
// due to rank ordering issues. Example: we might need to grab the
// Heap_lock while we construct the exception.
bool throw_illegal_thread_state = false;

// We must release the Threads_lock before we can post a jvmti event
// in Thread::start.
{
// Ensure that the C++ Thread and OSThread structures aren't freed before
// we operate.
MutexLocker mu(Threads_lock);

// Since JDK 5 the java.lang.Thread threadStatus is used to prevent
// re-starting an already started thread, so we should usually find
// that the JavaThread is null. However for a JNI attached thread
// there is a small window between the Thread object being created
// (with its JavaThread set) and the update to its threadStatus, so we
// have to check for this
if (java_lang_Thread::thread(JNIHandles::resolve_non_null(jthread)) != NULL) {
throw_illegal_thread_state = true;
} else {
// We could also check the stillborn flag to see if this thread was already stopped, but
// for historical reasons we let the thread detect that itself when it starts running

jlong size =
java_lang_Thread::stackSize(JNIHandles::resolve_non_null(jthread));
// Allocate the C++ Thread structure and create the native thread. The
// stack size retrieved from java is signed, but the constructor takes
// size_t (an unsigned type), so avoid passing negative values which would
// result in really large stacks.
size_t sz = size > 0 ? (size_t) size : 0;
native_thread = new JavaThread(&thread_entry, sz);

// At this point it may be possible that no osthread was created for the
// JavaThread due to lack of memory. Check for this situation and throw
// an exception if necessary. Eventually we may want to change this so
// that we only grab the lock if the thread was created successfully -
// then we can also do this check and throw the exception in the
// JavaThread constructor.
if (native_thread->osthread() != NULL) {
// Note: the current thread is not being used within "prepare".
native_thread->prepare(jthread);
}
}
}

if (throw_illegal_thread_state) {
THROW(vmSymbols::java_lang_IllegalThreadStateException());
}

assert(native_thread != NULL, "Starting null thread?");

if (native_thread->osthread() == NULL) {
// No one should hold a reference to the 'native_thread'.
delete native_thread;
if (JvmtiExport::should_post_resource_exhausted()) {
JvmtiExport::post_resource_exhausted(
JVMTI_RESOURCE_EXHAUSTED_OOM_ERROR | JVMTI_RESOURCE_EXHAUSTED_THREADS,
"unable to create new native thread");
}
THROW_MSG(vmSymbols::java_lang_OutOfMemoryError(),
"unable to create new native thread");
}

Thread::start(native_thread);

JVM_END

As I don't have knowledge in cpp, hence, there is no analysis into this snippet above, but if you understand what it does, I will be happy if you can give your analysis as a comment below of this article. It certainly looks to me that the operating system cannot create a thread at this point due to a few errors, JVMTI_RESOURCE_EXHAUSTED_OOM_ERROR and / or JVMTI_RESOURCE_EXHAUSTED_THREADS. Let's google to find out what is that supposed to mean. Below are some which is interesting.

To summarize the analysis from the links above.

  • stack is created when thread is created and when more threads are created, hence the total of stacks also increased as a result.

  • A Java Virtual Machine stack stores frames. A Java Virtual Machine stack is analogous to the stack of a conventional language such as C: it holds local variables and partial results, and plays a part in method invocation and return.

  • Java stack is not within of java heap, hence, even if you increase java heap to the cassandra via parameter -Xms or -Xmx, this error will happen again if the condition is met again in the future.

  • If Java Virtual Machine stacks can be dynamically expanded, and expansion is attempted but insufficient memory can be made available to effect the expansion, or if insufficient memory can be made available to create the initial Java Virtual Machine stack for a new thread, the Java Virtual Machine throws an OutOfMemoryError.


Until current analysis, it certainly looks to me that when cassandra instance trying to create a new thread, it was not able to. It was not able to because the underlying operating system cannot create the thread due to two errors. It actually looks like the operating system does not have sufficient memory to create the thread, hence increasing -Xms or -Xmx will not solve the problem. Note that the file descriptor set in this case is not met neither as most of the criterias pretty much infinite.

It's pretty interesting to note that, if such error is thrown, to solve the problem is to decrease the -Xss or even the heap -Xms and -Xmx. Although I don't understand the logic behind of such method used, perhaps you should try but I seriously doubt so. If cassandra node has high usage of heap, decreasing heap will only create another type of problem.

If you know or have encountered such problem before and has a good fix, please leave the comment below this article. To end this article, there is currently as of this writing, a discussion happen at cassandra mailing list.

Saturday, December 20, 2014

Speed up android emulator startup in eclipse

When exploring hello world android development app in eclipse, the emulator just painfully slow to even launch. To me, the speed matter because if it is slow, the test and development cycle will be affected and thus, the development experience will not be pleasant. So today, before we go into hello world article, we will first explore if it is possible to improve the speed of android emulator startup in eclipse.

I have google and found a few links, there are as of following.

To summarize the solution used to the links above, there are Intel Hardware Accelerated Execution Manager (HAXM), linux kvm or virtualbox, android virtual device (AVD) snapshot, increase device ram, GPU acceleration, disable antivirus ?!, 3rd party android emulator, using actual android device instead of emulator, etc.

Because every developer has different development environment and every sdk and improvement over time may render these method describe later in this article invalid. Thus, the speed gain in your environment when android emulator start may vary and thus create unnecessary confusion. Thus, you should always read on the links and find a solution that work best in your environment. The following steps improved my environment in such a way.

  1. Before it start need 10minutes and then even after waited 10minutes, then it crashed. With this, on my i3 intel cpu, with 8GB of ram, the speed increase in within less than 2minutes and response is emulator is manageable.

  2. The emulator start over time is persistence. There are situation when once the android virtual device is created, the second time it boot, the android screen in the emulator get gibberish and unclickable. So with my method describe later, this will not be a problem.


Before we go into the solution, let's understand what emulator is. Emulator according to wikipedia

In computing, an emulator is hardware or software or both that duplicates (or emulates) the functions of one computer system (the guest) in another computer system (the host), different from the first one, so that the emulated behavior closely resembles the behavior of the real system (the guest).

In android sense, this emulator actually emulate a smartphone environment including hardware instruction, from workstation cpu x86 to the android device which uses arm. Because of Android Emulator emulates a real ARM processor on top of an x86 processor, this create a lot of overhead. Connection of real device through usb via eclipse integration is not available for linux environment. Thus, for initial learning phase, a android emulator is a good start.

eclipse-android-sdk-manager

Launch Android Virtual Device Manager from eclipse.

eclipse-android-virtual-device-manager

create a new android virtual device, as seem below with this setting.

android-virtual-device-setting

As you can see, the target for the application is being currently latest at Android 5.0 - API Level 21. The important part now is to choose CPU/ABI to Intel Atom(x86_64). Of cause smartphone device mostly with arm cpu but as mentioned previously, we want emulator be a quick test environment.

If you notice, I have left Use Host GPU uncheck. When this is check with my environment, there is no speed up and when the android evironment started, the colour became gibberish and not clickable. Now start the device and experience the clicking in the environment.

Happy develop in android.

 

Friday, December 19, 2014

Setting up eclipse with Android development environment

Today, we will explore something different. Android is a very well known brand in the public now and can be found in devices such as smartphone, tablet, wearable like watch and glass, any end user device like tv or smart appliances. So we will take a look from programming point of view. This is a fresh start article and if you come from java development background and has zero knowledge on android development then this is an article for you. More on android development articles will come later.

To reduce the learning curve and to have a better learning and development experience in android, you should really setup android developer toolkit plugin in an IDE. If you have been develop Java for sometime now, IDE such as eclipse or netbeans should come in mind. Eclipse has always been my favourite IDE for java development and in this article, I will share on how to install ADT plugin in eclipse for android environment.

This article is based on this instruction. You should refer that for any changes or error encountered if you read this article in the future. As of this writing, I'm using eclipse luna for this ADT plugin installation. Let's start the installation.

  1. Launch eclipse and click Help then Install New Software... then click on Add button.

  2. We will add ADT plugin repository to this eclipse IDE. In the pop up window, add as following and then click on OK.
    Name: ADT Plugin
    Location: https://dl-ssl.google.com/android/eclipse/
    eclipse_add_repository_adt

  3. Wait a while for the update to pull in by eclipse and the in the Available Software dialog, select the checkbox next to Developer Tools and click on Next.
    eclipse_available_software

  4. In the next window, you'll see a list of the tools to be downloaded. Click Next.

  5. Read and accept the license agreements, then click Finish.
    If you get a security warning saying that the authenticity or validity of the software can't be established, click OK.

  6. When the installation completes, restart Eclipse.

  7. Once Eclipse restarts, you must specify the location of your Android SDK directory. Because this is a new installation, there is no android sdk installed and click on Open Preferences.
    eclipse_welcome_to_android_development eclipse_android_sdk

  8. In the "Welcome to Android Development" window that appears, select Install new SDK. Then wait until the installation is complete.
    eclipse_welcome_to_android_development_install_new_sdk
    eclipse_welcome_to_android_development_installing_new_sdk

  9. When sdk is installed, a new window popup requesting to install new build tool. Click on Open SDK Manager.
    eclipse_android_sdk_install_build-tools

  10. There are preselected build-tools and as of this moment, just accept the default preselected tools and click Install button. We can install more tools later.
    eclipse_android_sdk_managereclipse_android_sdk_manager_confirm_install_packages

  11. Wait until the installation is complete and it is done.


That's it, now start the first session for android hello world development.

Sunday, December 7, 2014

Gnome goodies: add hardware sensor in panel. add stock indicator in the panel.

Today we will add two more applets to the gnome panel. You might want to look into the past article about gnome applets that were configured before. Okay, let's start by installing an applet that will show hardware temperature.

There is a nice package, psensor and it can be install as easy as
$ sudo apt-get install psensor
$ psensor

So just launch the application from the terminal, then see the screenshot below.

psensor

On the left, I have configured three temperature to be plotted. Because hardware in different computer are different, so you can enable plotting for different hardware. On the right, it is the psensor preferences, and I have enabled checkbox for Launch on session startup and Hide window on startup.

Next, we will install a stock applet as a favor for a friend. Because in debian, this is not available and now we will download from ubuntu repository. Point your browser to https://launchpad.net/~ce3a/+archive/ubuntu/indicator-stocks/+packages and download latest version of indicator-stocks. As of this writing, I'm installing indicator-stocks_0.2.4-0ubuntu1_amd64
user@localhost:~/Desktop$ sudo dpkg -i indicator-stocks_0.2.4-0ubuntu1_amd64.deb 
Selecting previously unselected package indicator-stocks.
(Reading database ... 321688 files and directories currently installed.)
Preparing to unpack indicator-stocks_0.2.4-0ubuntu1_amd64.deb ...
Unpacking indicator-stocks (0.2.4-0ubuntu1) ...
dpkg: dependency problems prevent configuration of indicator-stocks:
indicator-stocks depends on libappindicator0.1-cil; however:
Package libappindicator0.1-cil is not installed.

dpkg: error processing package indicator-stocks (--install):
dependency problems - leaving unconfigured
Processing triggers for gnome-menus (3.13.3-2) ...
Processing triggers for mime-support (3.57) ...
Processing triggers for desktop-file-utils (0.22-1) ...
Processing triggers for hicolor-icon-theme (0.13-1) ...
Errors were encountered while processing:
indicator-stocks

As you can read above, there is a dependency problem during installing indicator-stocks. So just use apt-get install for the remaining package. It should be simple process to resolved that using apt. So it is finally installed, check the screenshot below. You can configured a few symbols, it is from finance.yahoo.com.

indicator-stocks

That's it, from the past and in this articles, I hope your desktop should present as much information as possible.

Saturday, December 6, 2014

Gnome goodies: common keyboard shortcut. Remembering state of num lock.

If you have been using linux and there is a key on your keyboard with windows logo, it is known as Super key. This super key will be widely used in gnome 3. Today, we will learn some of the commonly used keyboard shortcut. You can also find other keyboard shortcut in gnome-control-center keyboard shortcut.



































































Keyboard ShortcutDescription
Super+UpMaximize window
Super+DownUnmaximaze window
Super+Left ArrowFill half to the left side of the screen
Super+Right ArrowFill half to the right side of the screen
Super+click then moveMove window anywhere on screen
Super+mTo bring up a message tray at the bottom of the screen.
alt+tabswitch between applications
alt+`switch through window of current applications.
superbring up a new apperance known as activities overview
drag application to dashthis is to add an application which you used often to the dash so you can easily accessed.
drop application to gridremove application from dash by dragging from dash and then drop into the grid
ctrl+alt+up arrowswitch to the workspace above
type in a file windowTo quickly search for file in the file windows.
alt+PrintScntake a screenshot of the current window only.
shift+PrintScnselect a specific area of the screen.

Not sure why each time of operating system reboot, the state of num lock on keyboard get forgotten. This is really quite puzzling considering gnome has been evolve for so many cycle. But that's okay, we will learn to configure gnome so that it will remember the state of num lock between system boot. Let's launch dconf-editor and expand in the tree in such path. org -> gnome -> settings-daemon -> peripherals -> keyboard. Check remember-numlock-state and check the screenshot below.

dconf-editor-remember-nulock-state

With this article, I hope you navigate better in gnome-shell environment.

Friday, December 5, 2014

Poll statistics from Asus router RT-N14UH through http and plot in mrtg

If you have Asus router model RT-N14UHP, you should probably read on. This is a pretty decent router capable for a lot of feature including supporting qos and ipv6. It's pretty odd somehow this router does not come preinstall with net-snmp package. For your information, snmp allow a device to be poll for statistics collection purposes.

ASUS-RT-N14UHP

I have been requesting to poll statistics from the router using snmp from asus support some time around September 2014. The response I got is the development has taken this request however there is no guarantee when it would be made available. I have taken a deeper look into if the router support net-snmp. Google around and check if someone has similar problem and done it before unfortunately there is none as of this writing. There are a few come closer, this and this. The idea is to make the router by mounting an USB disk and then router will install ipkg (a package manager for the router). By using ipkg, you can install package net-snmp however, the package will be install on the mounted USB drive rather than the router itself. That's a pity if usb disk is unmounted, then thing will not work. Example of command below:
user@RT-N14UHP:/asusware# ipkg install net-snmp
Installing net-snmp (5.4.2.1-1) to /opt/...
Downloading http://ipkg.nslu2-linux.org/feeds/optware/oleg/cross/stable/net-snmp_5.4.2.1-1_mipsel.ipk
Configuring net-snmp
Successfully terminated.

user@RT-N14UHP:/asusware# app_set_enabled.sh net-snmp yes
Restarting the package...

Today, we will try differently. We will poll statistics from the router through http and then plot the graph using the well known software, mrtg. MRTG by default poll device for statistics using snmp. However, it also allow data collection using script, that's something very nifty! Let's start by installing this package in the client.
$ sudo apt-get install mrtg apache2

The package apache is for you to access the graph via browser. There should a cron running every five minute, /etc/cron.d/mrtg . So statistics will always be poll and graph will always be generate and update. Configuration for apache2 and where mrtg is accessible from web is left an exercises for you. (Hint : apache by default place in /var/www).

Create a script that will poll statistics from the router. Below is the script and you can download this bash script, routerStats.sh and place it in /bin/routerStats.sh

There are a few configuration you need to change. The obvious is the router IP. This router has IP 192.168.133.20, so change to your router IP. hwaddr is the hardware address of eth0 in your router. To get hwaddr from your router, you need to enable telnet from the router web graphic user interface and then login from command line. Then issue the command such as below.
user@RT-N14UHP:/tmp/home/root# ip addr show eth0
2: eth0: <BROADCAST,MULTICAST,UP,10000> mtu 1500 qdisc pfifo_fast qlen 1000
    link/ether 40:40:40:40:40:40 brd ff:ff:ff:ff:ff:ff
    inet6 fe80::1234:1234:1234:1234/64 scope link 
       valid_lft forever preferred_lft forever

the value for field link/ether will be the value for hwaddr in the url. To get the value of http_id, issue the command such as below in the router terminal.
admin@RT-N14UHP:/www# nvram get http_id
TIDeeeeeeeeeeeeeeee

Then install firefox live http header plugin and then start it, when the browser is pointed to router url and successfully logged in, then a line such as below should be identified. Use the string after Basic and fill into the url.
Authorization: Basic YGG3333d3BjMTQ5PPP=

With all these changed, the script is good to go. Next, we will configure mrtg configuration file.
### Global Config Options

#  for Debian
WorkDir: /var/www/router

### Global Defaults

#  to get bits instead of bytes and graphs growing to the right
# Options[_]: growright, bits
Options[_]: growright

EnableIPv6: no

Target[router-to-inet_1]: `/bin/routerStats.sh`
MaxBytes[router-to-inet_1]: 700000
Title[router-to-inet_1]: Network traffic between router and internet
PageTop[router-to-inet_1]: <h1>Network traffic between router and internet</h1>

It's a pretty simple configuration file and you can place it in /etc/mrtg.conf. The one that need some explanation, probably is routerStats.sh. This is actually the script that generated the statistics from the router. The script is placed in /bin and you can place anywhere as long as mrtg has the permission to execute this file. Note that the script you amended previously is actually get used by mrtg here. For the parameter in the configuration file, you can find more explanation here.

Now in the terminal, executed this script,
user@localhost:~# env LANG=C /usr/bin/mrtg /etc/mrtg.cfg
2014-10-22 20:26:54, Rateup WARNING: /usr/bin/rateup could not read the primary log file for router-to-inet_1
2014-10-22 20:26:54, Rateup WARNING: /usr/bin/rateup The backup log file for router-to-inet_1 was invalid as well
2014-10-22 20:26:54, Rateup WARNING: /usr/bin/rateup Can't rename router-to-inet_1.log to router-to-inet_1.old updating log file
user@localhost:~# env LANG=C /usr/bin/mrtg /etc/mrtg.cfg
user@localhost:~#

Don't know why there is error, it is probably initialization but next command execution should finish without any error. Now check in web server, directory, by default in debian for mrtg, it is in
user@localhost:/var/www/router$ ls
mrtg-l.png  mrtg-r.png        router-to-inet_1.html  router-to-inet_1-month.png  router-to-inet_1-week.png
mrtg-m.png  router-to-inet_1-day.png  router-to-inet_1.log   router-to-inet_1.old  router-to-inet_1-year.png

A few files should have been generated. That's good. When you installed package mrtg, a cron should installed by default at /etc/cron.d/mrtg. Take a look at the following:
*/5 * * * * root if [ -x /usr/bin/mrtg ] && [ -r /etc/mrtg.cfg ] && [ -d "$(grep '^[[:space:]]*[^#]*[[:space:]]*WorkDir' /etc/mrtg.cfg | awk '{ print $NF }')" ]; then mkdir -p /var/log/mrtg ; env LANG=C /usr/bin/mrtg /etc/mrtg.cfg 2>&1 | tee -a /var/log/mrtg/mrtg.log ; fi

So every five minute, the statistics will get collected. If you do not have this, just make a cron file. That's it, now point your browser to the web server url, example for mine,  http://192.168.133.30/router/router-to-inet_1.html.

mrtg-asus-rt-n14uhp

I hope you find it useful for you too.

UPDATE : You can also find the source file here, https://github.com/jasonwee/asus-rt-n14uhp-mrtg