Docker Developer Questions

Starting new with docker, there are a lot of open questions that are not covered by the buzz word explanations on the internet. I will try to find brief but concrete answers to the following questions:

How does docker integrate with my buildserver (e.g. jenkins)?

What is a typical Docker dev pipeline like?

How can I use docker on my development PC? Does my IDE allow me to build images?

How do I add configuration to a docker images/container?
Concrete: I want to adjust the catalina.sh from a tomcat inside a container.

Where/when/how are passwords, certificates or even less sensitive, but environment dependend values added?

You use Docker Swarm mode which comes with Docker Secret. In short – swarm is managing multiple docker nodes, to distribute containers over a multiple servers. Swarm can also be used on the same machine as the docker node and can only have one node (which we will use).

Swarm safes the passwords/secrets encrypted and send’s them on startup of a container over a secured TLS connection to the node. The node mounts an „in memory“ file in the running container and thus shares the secrets/passwords. On teardown of the container, the file is unmounted and removed from the nodes cache.
See: https://docs.docker.com/engine/swarm/secrets/#build-support-for-docker-secrets-into-your-images

How to handle stateful applications like databases?
Do not include the state in the image. Mount a shared system volume where the database data is stored. This way each docker container has access to the same data and they remain stateful. Dockerize only the accessing application e.g. MySQL.

E.G:

docker run -dit -v /var/myapp/data:/var/lib/postgresql/data postgres

See
https://success.docker.com/Architecture/Docker_Reference_Architecture%3A_Development_Pipeline_Best_Practices_Using_Docker_EE and
https://docs.docker.com/engine/tutorials/dockervolumes/#mount-a-host-directory-as-a-data-volume

Single Responsibility Principle

The SRP states, that every class/module/unit of work/component should only implement functionality for a single responsibility. Examples: Persistence, Logic, View rendering.

Why is this so important? Why bloating your code, by creating more classes/../components than necessary?

Advantages can be found in: Testing, Collaboration, Deployment

Testing: The more functionality you have in one component the more complex your tests get. Code coverage for a function with one if clause requires 2 tests. Make that 2 and you already need 4 tests. The complexity multiplies and soon you will not be able to cover all paths of your code. When having small units, you can control the complexity and test them easily, with less effort.

Collaboration: Of course it’s also easier to work on a single code basis with several developers, if you have different components. Even in the time of git.

Deployment: More separation means more stability. Having a bug in a component? Fix it and deploy only that component. No need to test the whole system again. This idea stretches from single classes, to microservices.

The consequences of SRP are layered architecture, MVC and even microservices. The implications of this principle are huge and widely overlooked.

An Anti-Pattern for SRP is for example the Active Record Pattern. There persistence logic is build into the domain objects, so you have functions like this:

obj.setProperty();
obj.merge(); // merges the object changes into the database

This makes it very hard to test the persistence layer. In DI Frameworks like Spring you can use reflection to mock the persistence layer, but this is more complicated than necessary and needs lots of insight and time.

Read for more explanations: http://moleseyhill.com/blog/2009/07/13/active-record-verses-repository/

Punchline: SRP has many benefits and implications. Most of my design/architectural problems with legacy code are a result from not following SRP.

Glassfish deployment error

The Descriptor files glassfish-web.xml includes a link to the schema files in the doctype, such as

!DOCTYPE glassfish-web-app PUBLIC „-//GlassFish.org//DTD GlassFish Application Server 4.1 Servlet 3.0//EN“ „http://glassfish.org/dtds/glassfish-web-app_3_0-1.dtd“

Glassfish seems to have canceled the support for that URL, such that the DTD files are not available anymore. This leads to an error on redeployment, because when glassfish is downloading the schema to check it against the descriptor file and it can’t, the deployment fails.

Fix the URL to: „http://glassfish.java.net/dtds/glassfish-web-app_3_0-1.dtd“ so it finds the dtds again. Normally, there should be a local repository in the glassfish installation that has the schema and I haven’t figured out yet, why it tried to download them again.

UPDATE:

/glassfish/lib/dtds/ should have all the Schemas. Only if the XML has a syntax error, glassfish seems to try that URL.

AspectJ for performance monitoring in Spring

Aspects in general allow you to „weave“ code into classes from the outside. This is like decorating a class, only on class file level. The code can be woven in on load-time (ltw, when the class is loaded into the jvm) or on compile-time.

The idea is to add external functionality without being invasive in the existing code, which can be helpful for legacy code, or for logging purposes, to not pollute the whole code. Downside: you don’t have all your code in one class anymore and the more Aspects you apply, the more confusing it might get, so apply them wisely.

Short notice: There is a difference between Spring AOP and AspectJ.
Spring can also apply Aspects, but uses runtime-weaving, which creates proxy objects and adds a lot of overhead that we don’t need.

This is the code for our performance monitoring:

import java.util.logging.Level;
import java.util.logging.Logger;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.context.annotation.EnableLoadTimeWeaving;

@Aspect
public class ExecuTimeLogger {

	/**
	 * Pointcut to select all public methods in all classes of a sub package, so
	 * the advice will be called for all the methods.
	 */
	@Pointcut("execution(* com.web.controller.Controller.*(..))")
	public void selectControllerMethods() {
	}

	@Around("selectControllerMethods()")
	public Object logTime(ProceedingJoinPoint thisJoinPoint) throws Throwable {
		final long start, end;
		Object[] args = thisJoinPoint.getArgs();
		start = System.nanoTime();
		Object result = thisJoinPoint.proceed(args);
		end = System.nanoTime();
		 Logger.getLogger(TimeLogger.class.getName()).log( Level.WARNING,
		 "Method: " + thisJoinPoint.getSignature() + " " + (end - start) / 1000 / 1000 + " ms");
		return result;
	}
}

The @pointcut annotated method defines the expression to select the methods we want to weave into.

The @Around annotated method is the logic that is executed.

More information and details explanations can be found here:

@AspectJ cheat sheet

UTF-8 headache

I was recently tasked to support Chinese characters in our Spring and MySQL based application. The setup looked as follows:

Mobile App <—> Spring based webservice <—> MySQL Database

The Mobile App already supported UFT-8. Spring is usually  also already configured to use UTF-8, e.g.:


 <bean
 class="org.springframework.context.support.ReloadableResourceBundleMessageSource"
 id="messageSource" p:basenames="WEB-INF/i18n/messages,WEB-INF/i18n/application"
 p:fallbackToSystemLocale="false">
<property name="defaultEncoding" value="UTF-8" />
 </bean>

If you edit the message.properties files in eclipse, make sure that eclipse understands they are UFT-8. Just right click->properties->Text file encoding -> UTF-8.

Otherwise importet charaters will be encoded to something like: \u00AE from your editor, which makes reading them pretty messy.

Next the JDBC must also be initialized as UTF-8 connection, so the connection string has to look like this:

„jdbc:mysql://HOST/DBName ?useUnicode=true&characterEncoding=UTF-8&characterSetResults=UTF-8“

Now the database had to be migrated. In our case we had to dump and reimport the database, for other reasons, but the most common way seemed to be just an good old alter table.

In MySQL you can choose between so many UTF-8 implementations, that I got irritated. You would imagine, that UTF-8 is UTF-8, but hell no. A short stackoverflow search showed some serious flaws, when using utf8_general_ci.

  1. it converts chars, e.g. ß  in upper case to SS
  2. combined chars, e.g. â are converted to uppercase and the accent is removed.

Number 2 leads to the problem that searching for any chars like ‚ä‘ will not work. But every search for ‚A‘ will also match ‚ä‘.

To prevent to screw your whole application, use uft8_unicode_ci !

See the links for more detailed and important information on this topic:

 

http://stackoverflow.com/a/766996/1969813

http://stackoverflow.com/a/1036459/1969813