Monday, March 23, 2015

More about Microservices

A long time since the last post.

I've now started a new job as a System Integrator, but I actually code Java the most.

So I thought a should ramble a bit about Microservices.

Pieces of a Microservice architecture:


Communication-technique

One of the big PROs with microservices is that they can be language independent. This however creates a demand for a language independent way to communicate.

Rest:
One of the most common ways right now is to make REST-services. Most languages have a httpclient-library to call services, usually urls built by Strings. For load-balancing you might need a services orchestration application, maybe Consul/Eureka/Zookeeper.

AMQP:
Another way is to use a message technique like AMQP. The AMQP-servers (Brokers) are very stable and have great clustering abilities. AMQP is a network protocol, which has it's perks. This way has less support but has almost automatic load-balancing (if several clients listen to one broker the use a round-robin strategy for messages). Request-respond actions can be a bit tricky (usually a queue for the request and then listen to a respond-queue).

Summary:
What do these have in common? They are stateless. This means you have to plan it in that way. Microservices demands a lot of modular thinking.

Data Persistance:

How about databases? How do we save data?
The important question is, how consistent must the data be?

One idea is to have a polyglot solution and have a datasource in every service which connects to eachother. Maybe MongoDB's sharding?

Another is to connect to a classic cluster of 2 or more databases.

Just be sure to not lock yourself in, don't forget that the individual microservices usually talk to the datasource, they need to be able to talk to them.

Another aspect is should the different services actually use any of the same data? If yes, then communication between teams (that code the services) needs to be top notch.

So preferably the answer is No.

Is DevOps a prequest for Microservices?

Microservice architecture has gotten a fresh start with the agile way of developing. And these small services are developed fast and change fast. There has to be a way to quickly deploy a new version of a service.

Many automation-tools have come together to solve the "pipeline", jenkins, go.cd, etc.

This is where Docker has made a good impact. If the service can be contained in a single container (or 2 if data is needed), it can move from development to test to production very easy.

But do we have time to teach a ops-guy how to administrate your service if it changes rapidly? If we need to scarp it and change the whole application-stack for another.

The developers are the experts, if they can administrate the service even in production, they have all the power to update, change and migrate the service.

So even if DevOps technically isn't a prequest for Microservices, it makes for a more agile way of developing.

Should I do Microservices?

The big question is SHOULD you do microservices?
Todays development is moving more to the modular architecture.
Which is a step towards microservices. But microservices are not a hail-mary solution. They come with a price, complexity. You need orchestration and communication-layer and a way to deploy all the services. They will probably take more performance too.

So what do we gain? Scalability and the option to quickly change parts of it.
Good modularity can also help against spaghetti code.

So my 2 cents if you should do microservices:

If you KNOW that you need to scale big some day or will aquire more functionality then microservices might be for you.

If your only doing a website, then microservices might only be unncecessary complex.


I will do a small Microservice project and put it on Github for a more concrete example, to show what I'm talking about. But it is not this day.

Happy Coding!


Wednesday, December 31, 2014

Microservices: Shared libraries or big services

After some fun with microservices a fork in the road has appeared.

Say we're developing an app (just like I am):

The web-part doesn't exist yet, it will be the web GUI (Spring boot MVC).

We have two small services:

  • UserRegistration
  • UserInfo

Since they use the same data I choose to group them with the same database.

So when we register a new user, the info will be sent to the UserRegistration-service by AMQP-message via RabbitMQ.

The UserRegistration-service puts the data in the database. To control the structure we make a POJO (JPA or other, depends on the database eg. MongoDB).

And there is the problem. The structure (the POJO) is in the UserRegistration-service project!

So when the UserInfo-service retrieves the data you probably want the same structure as you put it in.

There is probably more solutions but...

I see two obvious roads to go about:

  1. Make the services bigger and have all the user-related stuff in one big service
  2. Have a shared library with the code that needs to be shared
Personally I think option 1 is too risky. The service might become a giant service so the "micro"-part might disappear. 

So how do we do option 2? 
The code could either be a separate project and use some form of distributer to a artifact repository or try to make it part of one of the services (probably the one who puts it in the database) and try to package that part of the code some how.

This adds another level to the complexity. The need to share libraries, that the services can't be 100% independent.

This is a big part of the microservice architecture, it is somewhat complex. There is a lot of benefits to reap but you can probably solve this much easier in a monolith. 
On the other hand there is a lot of benefits if you can get the microservices right:
  • Fast development
  • Independent deployment of services
  • Scaling
  • Services can be in different programming languages
So now I think I will deploy a Sonatype Nexus repository as a Docker-instance and share the User-structure.

To be continued...

Quick update:
After reading a bit about others experience concerning microservices another problem came to mind.
https://rclayton.silvrback.com/failing-at-microservices
If you have shared code between services, especially Models (entity structures) this is most likely written in a specific programming language. This takes away one of the aspects of microservices.

So how do we solve this? This will take some thinking (I would like a good place to discuss these problems). My first thought is to find some JSON-structure due to the AMQP and send all messages by JSON-format (formatted as Byte arrays). Hopefully this makes it possible to use the message in another language.

And Happy New Year!




Tuesday, December 23, 2014

Microservices continued: The messaging begins

So I've started with a fun project: http://java-viking.blogspot.com/2014/12/mircoservices-with-java-spring-boot-and.html

So the first piece of the puzzle was to have individual service running. This is easily solved with Spring Boot. Since most services doesn't even be need to run as Web services (run in a servlet-container) it can be as small as a few mb!

So I wanted all the communication between the services to be solved by messaging.
The "normal" way is point-to-point. The problem is that you are bound by the API, sure you can do good coding and use a interface so you actually can switch the implementation. But somewhere the implementation is bound. When you need to do a swap, that redeployment will disturb the things that uses it.

Can you do a redeploy without disturbing the system?

Answer: Not sure, but I will try!

My thought is this: If you have services that uses messages queues then you can theoretically have several instances of that service handling messages in the same queue (not the same messages but the same type of messages).

If that works then you could have an instance of the old version and an instance of a new version (where a bug is fixed) and then remove the old instance and work would probably not have been interrupted.

This is also the solution for scaling that I'm testing. Can you have several instances of the same service?
So far so good, my fear is when users and session come and messes things upp.

AMQP

So instead of JMS (Java Message System) I'm using AMQP (Advanced Message Queuing Protocol).
One of the reasons is that is has clients for several languages so you can have some services with another language.

"AMQP mandates the behavior of the messaging provider and client to the extent that implementations from different vendors are truly interoperable, in the same way as SMTP, HTTP, FTP, etc. have created interoperable systems. Previous attempts to standardizemiddleware have happened at the API level (e.g. JMS) and thus did not ensure interoperability.[2] Unlike JMS, which merely defines an API, AMQP is a wire-level protocol. A wire-level protocol is a description of the format of the data that is sent across the network as a stream of octets. Consequently any tool that can create and interpret messages that conform to this data format can interoperate with any other compliant tool irrespective of implementation language." (Wikipedia)

Spring, of course, has a project for this: Spring AMQP. I'm using Spring Boot Starter AMQP (not fully sure yet what the "starter" is about)

Status:

So where am I right now (December 23)?
I've done a service which listens to a queue on RabbitMQ (I named the queue and RabbitMQ is running in docker, use the official dockerfile/rabbitmq)

This service will handle every message in that queue, it will print what the message is and change the message.

If the service that sends the message demands that it wants a response, that service will get the changed message.

The other service just sends 10 messages (with Thread.sleep(1000) between each message) to the queue. This now works like a charm!

But I had some big problems with this! First off, I'm new to spring boot and messaging.
So I could quickly make these services with examples from the web.

Problems:

The problem was that this only worked with one instance at a time! No bueno!
I started the MessageHandler-service, no problem.
I started message-sending-service instance 1, no problem.
I started message-sending-service instance 2, the messages got jacked by instance 1!
And instance 1 saw it as the message was sent after the timeout (no kidding! since it actually already got a response before!)
The problem was that the MessageListenerContainer that was used was still running after the response-demand was fulfilled. 
If I stated instance 1 and 2 and then started the message-handler (love queues!) they got there responses correct.

So how do I fix this? (many hours of fun)

First came the o-so-fun task of actually finding out what it's called. (send-respond/receive-respond and more)

It seems that most people use either a separate queue for each client or each request!
This seemed like a performance hog.
But in RabbitMQ 3.4.0 there is a function for a pseudo-queue for just these occasions.
It's called Direct-to. We let the code and RabbitMQ handle the response (so that the right message comes to the right sender).

The Docker-RabbitMQ was version 3.4.2 lucky!
Next problem: this is supported in Spring AMQP 1.4.1.

What version does Spring Boot 1.2.0.RELEASE have of AMQP? 1.4.0....     O joy...

I tried that version and it didn't work. I'm not sure if Spring Boot allows me to switch a version of one of its sub-projects. I didn't get it to work, but it might just be my incompetence .

So I took my chance with version 1.2.1.BUILD-SNAPSHOT! 

And hey what do you know, it worked! I deleted the response-listener completely in the message-sender, the Direct-to function handles it for ous.


Minor setback:

The "pseudo-queue" for the Direct-to function https://www.rabbitmq.com/direct-reply-to.html#use
Have an official queue name " amq.rabbitmq.reply-to", it needs to be exactly this!

I stumbled upon this in a StackOverflow answer. The Spring Documentation actually had a typo of this: http://docs.spring.io/spring-amqp/reference/html/amqp.html#direct-reply-to

under section 3.7.1 it said " amqp.rabbitmq.reply-to" that "p" should not be there!
And I understand how easy of a mistake this is, I thought it was the other way around, why would it be "amq" instead of "amqp"?

But no problem, I submitted the typo to the Spring Jira issue site (issue AMQP-458) and the awesome Gary Russell has already fixed it, it'll be in the 1.4.2 version: https://github.com/spring-projects/spring-amqp/commit/fca82ce3d54bb2024efa6275a2e661cd20829de6

You got to love Open Source!

I'm happy to help fix this, cause you don't get any fun errors if you do this typo.
You just don't get any response. The message gets handled but that's it. Now the message-senders is just waiting for the postman that never will come.


So I hope this will help someone, I will keep you posted with my findings and results. In the end I will probably give some code, just now it's not so pretty ^^ except the gradle, that is pretty!

If your trying to replicate my idea and get stuck, don't hesitate to comment and I will try to help you as best as I can.

PS: These services will have there own Docker-containers and be run from there. They don't need to know about each other or there respective IP-numbers, you gotta love Messaging systems.

So code away!




Sunday, December 21, 2014

Mircoservices with Java, Spring Boot and Docker

Intro to microservices

One of the current buzz-words flying around is "Microservices".

Most big java apps (web-based at least) are packaged as a big WAR-file. The project is one big app, a monolith. This comes with some problems concerning development.

First the obvious, if you change anything you need to redeploy the whole thing. Even the smallest thing.

Second is scaling. If you need to scale up then you scale the whole application.


So what is microservices? Instead of having a monolith you make services as separate projects.
A service would have just one area of responsibility ex. Login-service.

Pros:
Fast development and deployments
Easier to write tests (small project > don't disturb other tests)
Can redeploy that service without redeploying everything
Scaling, just start another instance of the service (needs a good framework for this!)

Problems

So is it a hail mary-technique?

As always, this technique/architecture has its own flaws and problems.

The main con is the complexity of service-handling. The services needs some way of connecting to each other. And "hard-coding" the connection gives us a BIG risk. Because if you change one service, all the services that uses the API of that service might crash in runtime, fun to be that admin.

And how do we know that a service is down?
Say the login-service goes down, the positive is that the app might still work for the people that is already logged in. But no new logins can occur until the service is up again.
With a good health monitoring system ex. Nagios it can check if the service is down, some can even fix the problem!

Solutions

So how do we solve these problems?

First the decoupling from the API. If the services are decouple and doesn't use the API one-to-one we'll escape the hellish nightmare of the total system crash (in this case, might be others).

So we can use some form of integration system like an ESB (Enterprise Service Buss) or just a messaging system (ex. RabbitMQ or ActiveMQ).
This will send the message in to a queue, the service will then grab the message and handle it (complexity gets higher).


Second

A awesome system would be some form of clustering over different locations, load balancing, service discovery and health monitoring.

Some frameworks can actually call the "mother ship" and say "hey I'm bla bla service and I'm ready to Rock! I'm at this location".
The service would have an adjacent health monitoring script.

Is there an actual solution for ALL of this? Answer: Not that I know, but there is some puzzle-pieces.

My Experiment (the plan!)

I'm going to try to make a simple project using microservices.

I'm going to use Spring Boot for the service. Spring Boot is a small application which has a jetty/tomcat server in it and it can either be run as a WAR or by itself.
I'm going to run it by itself. This becomes a app with 12-20 mb per service.
Gradle will be used for the build and dependency scripts.

After the service-app is done, I will contain it in a simple Docker image that is built on start.

Ain't it a problem to start all these docker containers (I will have 3-5 services)?
No, I will use fig (http://www.fig.sh/index.html) to start all the services at once, and to document all the start-commands, linkages, port exposures and more. To sum it: A docker kick-starter.


Ok so Java: check
Containers: check


So regarding the health monitoring. I will try out Consul (https://consul.io/intro/index.html).
I hope I can rock it good with docker and use both the service discovery and the health monitoring.


Onwards

So right now I have made a test-service (hello world in spring boot) and made a docker image of it and ran it successfully.

I will keep you posted of my results, hopefully I can put it all on github when it's done so you can get all the source code.

Another hope I have is that Docker Swarm takes of and either becomes powerful enough on its own or that some awesome frameworks gets created that uses it.

Sunday, October 26, 2014

Docker and Mule

So I've been looking in to Mule ESB (Enterprise Service Bus) for my new job.

After testing it, it seemed like a lot of fun. Another of my projects was to learn Docker (scorching hot right now).

So I thought "Why not combine them?", little did I know that I was in for a world of Internet-searching, documentation exploring and more.

So first some more Info on Mule and Docker:

Mule ESB


Is kind of an adapter between services. It's message-based and has a lot of functionality already done.

Ex: Say you have a Java site that needs paypal. Mule can sit between, take the request by JMS, HTTP and more and pipe it to paypal and then back again. Maybe you want a facebook post for every 1000 visitor? No problem.

Why do this when you can code it your self? One of the reasons is that you can use much of the code again, you can separate some of the work to this Mule server or you can do a microservice style and have Mule be the glue between them all.

Docker (Docker.io)

Docker is a way to make Linux Containers (LXC) manageable and share-able. It's a technology for making small VM's where you can isolate you app.

Why? Say that your a developer. Your app works in your developer environment. But that's not always the case for the production environment. 
What if you could have a environment under development and just ship the whole environment? That's what you do with Docker.

It's also a good subject if you want have microservice's, every service can have its own Docker Container. 

And it's scalable, you can have servers with CoreOS (made for running in HUGE clusters, we're talking Google-size) and run your Docker Container.

Cause that's one of the best perks, your Docker Container runs ANYWHERE where there is a Docker Engine. You can develop under Windows and Mac with boot2docker via Virtualbox and then Deploy to a real Linux Server running Docker Engine.

 And people share many of their Docker Containers via buildfiles (DockerFile). You can have your own private registry of Images or use the Central DockerHub.

My Problem

So there is a couple of people that have done Docker Containers for Mule Server.
And I could not get this to work!

I was a rookie at Docker so I blamed my lack of knowledge.
I followed the guide and it would not work.

The regular Mule Server and my test app work perfectly.

The Docker version blocked the right ports, but it would not give me a response.

I scratched my head...

Spinning up a Wildfly server in docker was 2 commands and it worked perfectly. 

So I compared the DockerFiles, but nothing looked weird. Was there something special with Mule?
But why? The creator seemed to get it to work without problem.

After that I found a solution!... Or so I thought. I was able to publish the port so I could run and get a response...from localhost but not from a remote computer.

But wildfly worked with the remote computer, what was the difference???

Frankly I thought I was missing a puzzle piece with Docker, like firewall, config or something.

After 2 weeks of leaving and coming back to it (Googled some on breaks at works, coming up with new ideas what it could be) I finally found the answer.

After being really frustrated I started to really look at the test app and compare it to the Docker Container Creators test app.

My app said that localhost should run the http start-point, the other app said 0.0.0.0....

OF COURSE! So I was looking at the wrong place!
I thought I made the simplest test app ever, a little hello world, but I succeeded in not doing it correctly. 

After changing it to 0.0.0.0 it worked flawlessly. So simple that it's extra hard to find.

But on the up side I learned A LOT about Docker and how to use it.


So I can recommend Docker and Mule, Docker is not as hard as some think, just know what your putting in it before blaming Docker.

Code ahoy!


Saturday, September 20, 2014

Spring MVC Step 1


So I've been digging around Spring. It's a very versatile framework. So you might need to research which parts you actually need.

I'm into Java EE Web so I want the core-part and the web-mvc (yes they actually have a subproject tailored to MVC on the web).

So I went and found the easiest tutorial I could find. Some tutorials are great but they give you like 50 classes from the start. If you'r trying to learn Spring then you might want to know if all the classes are needed or not.

But I found one that was small with good explanations (http://examples.javacodegeeks.com/enterprise-java/spring/mvc/spring-mvc-hello-world-example/)


So I will first show my setup (I use Gradle instead of Maven like the tutorial uses).

Folder-Structure

Project
--src
----main
----test
--build.gradle

The src just hade a package structure for one class, the HelloWorldController.java
Right now the test-folder is empty, it will be used for future junit-tests.

build.gradle:

The rest is identical to the tutorial. If you want to run it in a Wildfly-server (the tutorial uses tomcat), you just run "gradle assemble" and either copy the war to the deployment-folder or you can use the web-managment and deploy it there.

So now some explanation of how it all binds together:

DispatcherServlet

The most central part is the DispatcherServlet. This is a servlet that Spring have created to mediate all the traffic. The http-request come to dispatcher and it then uses the RequestMappings from the controller-classes to retrieve the right view and model.

It reminds me a bit of the FacesServlet that all the facelets with JSF goes through.

So in web.xml you define the DispatcherSevlet just like you would do any (before the Annotation-trend started) and map it to the "/" url-pattern.

When you define the DispatcherServlet you may pick a name for it. It will then look for this name as a xml file: "name-servlet.xml" in WEB-INF.

So what would we set up in this xml? How the dispatcher will resolve the connections.
You can define all the components one by one, do a component-scan or a component-scan via Annotations (not in the xml).

In the tutorial (which I also use) they defined a bean, in this cause a bean of "org.springframework.web.servlet.view.InternalResourceViewResolver". This will be used to resolve the views.

In it we set some properties:
prefix: the folder where the views are.
suffix: .jsp

This makes it easy for the classes. They can return a String "hello" and it can be resolved to /WEB-INF/views/hello.jsp". This makes the Controller classes more readable.

Then we need a Controller to actually do anything. I put a "index.jsp" that just says welcome. It shows when the "/" url is requested. My web-app folder structure looks like:



Controller

A controller is a class with @Controller annotation. It is likely that you want the @RequestMapping("/hello") also. 

You can then do a method that returns a String. This method should have the @RequestMapping(method = RequestMethod.GET) annotation. This only registers so that when a request is used via GET, this method is returned. 

This means that you can have seperate methods for the others ex. POST

You can now return "hello" or "helloWorld" depending on what you named your jsp-file.

Conclusion:

We need:
A web.xml which configs the DispatcherServlet
A dispatcher-servlet.xml which configs the view-resolver.
A Controller

The dispatcher will register all the mappings from the controllers and direct the traffic.
The controller will return the name of the view to the view-resolver which puts prefix and suffix on it.

If you put your views in the WEB-INF users can't directly request them, they have to use the url-mappings of the controllers, which is a very good thing.


(EDIT: and after the ViewResolver sends it back to the dispatcher the dispatcher sends the html to the user that requested it)


So that's the first step in Spring Web MVC. I find Spring very interesting and will continue to learn and explore. I will continue to use Wildfly and Gradle. One of the things I want to do is an automatic deployment without a IDE. You can do this with Cargo-plugin but I want to find a different way.

Happy Coding!



Sunday, September 14, 2014

Early Spring

I'm almost done with my first real Java EE project (JSF, JPA, Wildfly) and its currently running on a raspberry pi.

My next project will be learning the Spring Framework.
I will also try to do some post about how to start with Spring.

Initial impression:

My first impression of Spring is that its a well made framework that fills every part of your development (specific test-suite and more). The different modules of the framework really gives you a good feeling of security for functions.

But there is a big step for a newbie to just jump into Spring!

First problem: Overview
What does what and how "do they want you to code". With pure Java EE you can do as you want,
but in Spring there is a certain way "they" want you to code. I'm not saying it's bad. But there is a problem of learning it.

Second problem: Too big tutorials
Many of the tutorials start to big with 20+ ready to use classes. And the tutorial uses these classes. This makes you feel like you jump into the middle of things and not understand the whole process.

Third problem: Spring Boot
Lovely little thing that really can kickstart your project, but it doesn't help you in understanding much.

Fourth problem: Name usage
Some of the names conflicts with pure Java EE7 names. A Spring Bean is configured differently then a regular Bean that can be Dependency Injected.
Dependency Injection in Spring is different then Pure Java EE7. EE7 has @Inject while Spring uses @Autowired that usally is a Interface that a config-class or a xml has mapped to a implementation class.


So that's some of the hurdles a rookie will deal with.

On of the links I've found useful (haven't had time to read to much yet) is: springbyexample.org/examples/core-concepts.htm

This site ACTUALLY explains the core concepts.

So when I have some more information about the core concepts that are essential I will make a post about it.

Happy Coding!