Tuan Anh

container nerd. k8s || GTFO

How movies could change your perception

It’s interesting how much movies can change our perception: survey asking people in France who contributed the most to the defeat of Nazi Germany.

sondage nation contribue defaite nazis

link bài gốc

Fix WELD-001408 unsatisfied dependencies for type error when deploying to GlassFish

Took me half an hour today to figure this out when deploying to production servers. Apparently, the CDI extension loaded from a JAR in a WAR, thus different classloader, makes it uninjectable.

The problem can be fixed by simply disable implicit CDI on GlassFish

${GLASSFISH_HOME}/bin/asadmin set configs.config.server-config.cdi-service.enable-implicit-cdi=false

REST APIs made easy with StrongLoop

StrongLoop allows you to quickly create REST APIs using their graphic interface and CLI. SLC also supports debugging, profiling, tracing, deploying as well as monitoring features.

Creating REST APIs with slc is as easy as creating datasource and model. StrongLoop will do the rest for you.

I was very tempted to use StrongLoop for a recent project but I had to deal with a legacy database that use a very old odbc driver which force me to use node.js and express.

link bài gốc

Microsoft HoloLens

microsoft hololens

Microsoft is really on a roll lately. They are on the right track to regain their cool factor among devs. The device looks truly impressive and based on what we know so far, it looks a lot better than Google Glass and Oculus Rift.

When you change the way you see the world, you can change the world you see.

It’s interesting that Microsoft calls this holographic technology instead of augumented reality. Though it’s not technically correct, they’ve got themselves a better brand to distinguish their product.

There are zillions use case for this kind of technology: healthcare, entertainment, education; you name it. Just to name a few that pop up in my head real quick.

  • expert coaching

  • training

  • modelling

  • gaming

  • millitary applications

  • etc …

Not to mention, whenever a technology like this is introduce, people will find a way to use this in adult entertainment.

Let’s just hope that Microsoft will not overpromise like Google did and let it ended up where Google Glass is now.

link bài gốc

Create a contact form with jekyll

Since jekyll blog is static, we have to rely some some kind of service endpoint to send email to our mailbox. Good thing is that there are plenty of services for this purpose: heroku for free hosting and mailgun, mandrill or mailjet for sending email. Pick one of your choice.

I did a quick search before firing up Sublime Text to create a simple app for sending email and luckily, someone already wrote one. One less thing to do :)

Create Heroku and a Mandrill account

Sign up an account at Heroku. Download and install heroku toolbelt while you’re at it.

For sending email, you can go with Mandrill, Mailgun or Mailjet. They all come with free plan which is more than enough for personal use. If you pick something other than Mandrill, you will have to edit the app a bit use their own libraries. If you’re lazy, just go with Mandrill.

Install the app on heroku

heroku auth:login # enter your account credentials when asked

git clone https://github.com/ousenko/simple-contact-form.git
heroku create <YOUR_HEROKU_APP>
heroku config:set MANDRILL_API_KEY=<KEY>
heroku config:set USER_EMAIL=<YOUR EMAIL>
heroku config:set USER_SITE=<YOUR SITE>

git push heroku master # deploy

Create contact form on your website

Create a page with simple form like below. I’m using Bootstrap for my blog so styling is just a matter of adding a couple of CSS classes.

<form action="https://<YOUR_HEROKU_APP>.herokuapp.com/send">
  Email: <input type="text" name="name"><br>
  Name: <input type="text" name="email"><br>
  Subject: <input type="text" name="subject"><br>
  Message: <textarea name="message" cols="40" rows="5"></textarea>
  <input type="submit" value="Send Message">

Adding reCAPTCHA (optional)

Sign up for an API key pair and add it to your page. I don’t have a need for this, personally.

Here what’s mine like

contact form with jekyll

Fuck callbacks! Let's use generators

Let’s write a simple function hello that return a string when called.

var hello = function () { return 'Hello ' + name; }

Now convert it into a generator. Call hello() this time will return you an Object instead: the generator.

var hello = function *() { return 'Hello ' + name; }

Let’s consider the following snippet.

var hello = function *() {
  yield 'Stopped here!';
  return 'Hello ' + name;

var generator = hello('Clark Kent');
console.log(generator.next()); // {value: 'Stopped here', done: false}
console.log(generator.next()); // {value: 'Hello Clark Kent', done: true}

So what good can generators do for me? Generators can help eliminiating callbacks. Using callback for 1 or maybe 2 levels is fine. However, imagine if you have to use callbacks for 3 levels or more like the example below. URGH!!

func_1(arg, function(err, result) {
  if (err) { .... }
  else {
    func_2(result, function(err, result2) {
      if (err) { ... }
      else {
        func_3(result2, function(err, result3) {
          if (err) { ... }
          else {
            // LOST IN LIMBO !!!

Take an example: consider a scenario where you have to establish connection to a bunch of database servers at application startup. With generators, you can do something like this:

var init_all_connections = function *() {
  var result;
  result = yield init_connection(conn_str1);
  result = yield init_connection(conn_str2);
  result = yield init_connection(conn_str3);
  // ...


For the sake of conveniency, you can write a function to execute the generator until done is true, throw if an error occurs. So the whole thing looks as simple as this:

var init_all_connections = function *() {
  var result;
  result = yield init_connection(conn_str1);
  result = yield init_connection(conn_str2);
  result = yield init_connection(conn_str3);
  // ...

// execute

Look how the code is cleanly organized and so much readable compare with the callback hell above. Ain’t you glad you read this now ;)

IO performance benchmark on RamNode

Last update: 2015-01-18

I read a IO performance benchmark today comparing AWS vs DigitalOcean. It makes me curious about the IO performance on RamNode. Of course I wouldn’t expect something high since I’m running in one of the lowest tier offerred by them (It’s not even 100% SSD but just some kind of hybrid SSD-Cached). I will also ignore read test since all the VPS are container-based and read is probably heavily-cached anyway. As for the tool, I’m using fio for my IO benchmark.

Installing fio

sudo apt-get install fio
mkdir data # at ~ I suppose
nano testconfig.fio
# content of the file

numjobs=10 # check size and your free space left (df -h)


Result when blocksize=8k

Run status group 0 (all jobs):
   READ: io=2048.0MB, aggrb=6485KB/s, minb=6485KB/s, maxb=6485KB/s, mint=323357msec, maxt=323357msec

Result when blocksize=16k, bw peaks at 21249.

Run status group 0 (all jobs):
   READ: io=1024.0MB, aggrb=8154KB/s, minb=8154KB/s, maxb=8154KB/s, mint=128592msec, maxt=128592msec

Result interpretation

One thing to notice is the CPU load skyrocketted. Though I only went with numjobs=2 and size=1g, the CPU load hits 3.x (300%). This is expected behavior since I’m on their Massive VPS plan. Due to this CPU issue, this is probably not the highest write speed possible as well. I would have to try it on a higher plan where CPU is irrelevant to the test. Too bad, RamNode doesn’t allow me to quickly launch an instance to test and destroy after.

So overall, DigitalOcean > AWS > RamNode. RamNode is left behind by far margin, probably due to the CPU on their lowest plan. If your application is IO-heavy, you should probably look else where.

bluebird - a promise library with unmatched performance

The documentation of bluebird is so much better than Q - the library which I’m currently using. bluebird with nodejs is even better: it can convert an existing promise-unaware API to promise-returning API which is so awesome. Thid feature works with most popular libraries (which use error as first arg (as they all should)).

I’m sold!!


function getConnection(urlString) {
  return new Promise(function(resolve) {
    //Without new Promise, this throwing will throw an actual exception
    var params = parse(urlString);

or with promisifyAll method

var fs = require("fs");
// Now you can use fs as if it was designed to use bluebird promises from the beginning

fs.readFileAsync("file.js", "utf8").then(...)
link bài gốc

So I upgraded my VPS

I have little to none demand for web server’s power since my blog is static, plus a couple of small web apps I test on the VPS now and then. Recently, my interests shifted to Ionic framework, nodejs, mongodb and angularjs. I had quite a few ideas for pet projects, mostly for the purpose of learning. I decided to upgrade my VPS to a bit better plan - 256MB of RAM. Still a tiny machine but should be enough for what I have in mind.

I’ve also did a re-installation of the OS as I switch from 64bit Ubuntu 14.04 image to 32bit version. I have no plan to scale this VPS for anything serious so 32bit is good plenty for the purpose, plus all the additional bit of memory.

Migration process is rather painless. I just had to click Re-install OS, setup new user account, apt-get a couple of libs (rvm, ruby, jekyll), setup git server and then git push my blog. Everything is back to normal now I suppose.

Scaling node.js application with cluster

node.js’s single thread default architecture prevents it from utilizing multi-cores machines. When you create a new node.js application in WebStorm for example, this is what you get:

var debug = require('debug')('myApp');
var app = require('../app');

app.set('port', process.env.PORT || 3000);

var server = app.listen(app.get('port'), function() {
  debug('Express server listening on port ' + server.address().port);

// in app.listen method

app.listen = function(){
  var server = http.createServer(this);
  return server.listen.apply(server, arguments);

This code snippet will create a simple HTTP server on the given port, executed in a single-threaded process; doesn’t matter how many cores your machine has. This is where cluster comes in.

cluster allows you to create multiple processes, which can share the same port. Ideally, you should spawn only 1 thread per core.

var cluster = require("cluster"),
    http = require("http");
    cpuCount = require("os").cpus().length;
    port = process.env.PORT || 3000

if (cluster.isMaster) {
  for (var i = 0; i < cpuCount; ++i) {

  cluster.on("exit", function(worker, code, signal) {
} else {
  http.createServer(function(request, response) {
    // ...

That’s how you do it on a single machine. With a few more lines of code, you application can now utilize better modern hardware. If this isn’t enough and you need to scale across machines, take a look at load balancing using nginx. I will cover that in another post.