6/17/15

Using Camel, CDI inside Kubernetes with Fabric8

Prologue

I recently blogged about Injecting Kubernetes Services with CDI. In this post I am going to take things one step further and bring Apache Camel into the picture. So, I am going to use Camel's CDI support to wire my components and routes, along with Fabric8's CDI extension to automatically inject Kubernetes services into my components.

I am going to reuse stuff from my previous post (so give it a read if u haven't already) to build an standalone camel cdi application that is going to expose the contents of a database via http (a simple http to jdbc and back again). Everything will run in Docker and orchestration will be done by Kubernetes.

So first thing first. How camel and cdi works....

The camel cdi registry

Apache Camel is using the notion of a registry. It uses the registry to lookup for objects, that are needed by the routes. Those lookups may by type or by name.

The most common use of the registry is when the endpoint uri is processed, camel will parse the scheme and will lookup the registry by name for the appropriate component. Other cases involve passing bean references to endpoints by name and so on...

 In other words Apache Camel may perform lookups on the bean registry on runtime.

Any extension that needs to play nicely with Apache Camel needs to provide beans with a predictable names.

The @Alias annotation

Fabric8's CDI extension, for any given service, may register more than one beans (one per service per type, per protocol ...). So, it's impossible to have service beans named after the service. Also the user shouldn't have to memorise the naming conventions that are used internally...

"So, how does Fabric8 play with frameworks that rely on 'by name' lookups?"

Fabric8 provides the @Alias annotation which allows the developer to explicitly specify the bean name of the injected service. Here's an example:

"What happens here?"
The Fabric8 cdi extension will receive an event that there is an injection point of type String, with 2 qualifiers:

  1. ServiceName with value "mysql".
  2. Alias with value "mysqldb".
So when it creates beans and producers for that service it will use the "mysqldb" as a name. This is what allows control over the Fabric8 managed beans and makes name lookups possible.

Using @Factory to create or configure Camel components or endpoints
In my previous post, I went through some examples on how you could use Fabric8's @Factory annotation in order to create jdbc connections. Now, I am going to create a factory for a jdbc datasource, which then is going to be added to the Apache Camel Cdi Bean Registry.

Now if we wanted to refer this datasource from an Apache Camel endpoint, we would have to specify the "name" of the datasource to the endpoint uri. For example "jdbc:custmersds", where customersds is the name of the datasource.

"But, how can I name the fabric8 managed datasource?"

This is how the @Alias saves the day:


This is a typical RouteBuilder for CDI based Camel application. What is special about it is that we inject a DataSource named "customersds".

 "Who provides the DataSource?"

Short answer: Fabric8.

Not so short answerThe @ServiceName("mysql") annotation tells Fabric8 that the DataSource refers to the "mysql" Kubernetes service.  Fabric8 will obtain the url to that service for us. Since the type of the field is neither String, nor URL but DataSource, Fabric8 will lookup for @Factory methods that are capable of converting a String to a DataSource. In our case it will find the DataSourceFactory class which does exactly that. As this was not awesome enough the DataSourceFactory also accepts @Configuration MysqlConfiguration, so that we can specify things like database name, credentials etc (see my previous post).

Configuring the DataSource
Before I start explaining how we can configure the DataSource, let me take one step back and recall MysqlConfiguration from my previous post:
As I mentioned in my previous post we can use environment variables in order to pass configuration to our app. Remember this app is intended to live inside a Docker container....

MysqlConfiguration contains 3 fields:

  1. Field username for environment variable USERNAME
  2. Field password for environment variable PASSWORD
  3. Field databseName for environmnet variable DATABASE_NAME 
So we need 3 environment variables one for each fields. Then our DataSourceFactory will be passed an instance of MysqlConfiguration with whatever values can be retrieved from the environment, so that it create the actual DataSource.

 "But how could I reuse MysqlConfiguration to configure multiple different services ?"


So, the idea is that a @Factory and a @Configuration can be reusable. After all no need to have factories and model classes bound to the underlying services, right?

Fabric8 helps by using the service name as a prefix for the environment variables. It does that on runtime and it works like this:


  1. The Fabric8 extension discovers an Injection Point annotated with @ServiceName
  2. It will check the target type and it will lookup for a @Factory if needed.
  3. The @Factory accepts the service URL and an instance MysqlConfiguration
  4. MysqlConfiguration will be instantiated using the value of @ServiceName as an environment variable prefix.
So for our example to work we would need to package our application as a Docker container and then use the following Kubernetes configuration:



Now if we need to create an additional DataSource (say for a jdbc to jdbc bridge) inside the same container, we would have to just specify additional environment variable for the additional Kubernetes. Now, if the name of the service was  "mysql-target", then our Kubernetes configuration  would need to look like:

... and we could use that by adding to our project an injection point with the qualifier @ServiceName("mysql-target").

You can find similar examples inside the Fabric8 quickstarts. And more specifically the camel-cdi-amq quick start.

Stay tuned
I hope you enjoyed it. There are going to be more related topics soon (including writing integration tests for Java application running on Kubernetes).





6/15/15

Injecting Kubernetes Services in CDI managed beans using Fabric8

Prologue

The thing I love the most in Kubernetes is the way services are discovered. Why?

Mostly because the user code doesn't have to deal with registering, looking up services and also because there are no networking surprises (if you've ever tried a registry based approach, you'll know what I am talking about).

This post is going to cover how you can use Fabric8 in order to inject Kubernetes services in Java using CDI.

Kubernetes Services

Covering in-depth Kubernetes Services is beyond the scope of this post, but I'll try to give a very brief overview of them.

In Kubernetes,  applications are packaged as Docker containers.  Usually, it's a nice idea to split the application into individual pieces, so you will have multiple Docker containers that most probably need communicate with each other. Some containers may be collocated together by placing them in the same Pod, while others may be remote and need a way to talk to each other. This is where Services get in the picture.

A container may bind to one or more ports providing one or more "services" to other containers. For example:
  • A database server.
  • A message broker.
  • A rest service.

The question is "How other containers know how to access those services?"

So, Kubernetes allows you to "label" each Pod and use those labels to "select" Pods that provide a logical service. Those labels are simple key, value pairs.

Here's an example of how we can "label" a pod by specifying a label with key name and value mysql.
And here's an example of how we can define a Service that exposes the mysql port. The service selector is using the key/value pair we specified above in order to define which are the pod(s) that provide the service.

The Service information passed to each container as environment variables by Kubernetes. For each container that gets created Kubernetes will make sure that the appropriate environment variables will be passed for ALL services visible to the container.

For the mysql service of the example above, the environment variables will be:
  • MYSQL_SERVICE_HOST
  • MYSQL_SERVICE_PORT

Fabric8 provides a CDI extension which can be used in order to simplify development of Kubernetes apps, by providing injection of Kubernetes resources.

Getting started with the Fabric8 CDI extension
To use the cdi extension the first step is to add the dependency to the project. Next step is to decide which service you want to inject to what field and then add a @ServiceName annotation to it.
In the example above we have a class that needs a JDBC connection to a mysql database that is available via Kubernetes Services.

The injected serivceUrl will have the form: [tcp|udp]://[host]:[port]. Which is a perfectly fine url, but its not a proper jdbc url. So we need a utility to convert that. This is the purpose of the toJdbcUrl.

Even though its possible to specify the protocol when defining the service, one is only able to specify core transportation protocols such as TCP or UDP and not something like http, jdbc etc.

The @Protocol annotation

Having to find and replace the "tcp" or "udp" values with the application protocol, is smelly and it gets old really fast. To remove that boilerplate Fabric8 provides the @Protocol annotation. This annotation allows you to select that application protocol that you want in your injected service url. In the previous example that is "jdbc:mysql". So the code could look like:

Undoubtably, this is much cleaner. Still it doesn't include information about the actual database or any parameters that are usually passed as part of the JDBC Url, so there is room for improvement here.

One would expect that in the same spirit a @Path or a @Parameter annotations would be available, but both of these are things that belong to configuration data and are not a good fit for hardcoding into code. Moreover, the CDI extension of Fabric8 doesn't aspire to become a URL transformation framework. So, instead it takes things up a notch by allowing you to directly instantiate the client for accessing any given service and inject it into the source.

Creating clients for Services using the @Factory annotation

In the previous example we saw how we could obtain the url for a service and create a JDBC connection with it. Any project that wants a JDBC connection can copy that snippet and it will work great, as long as the user remembers that he needs to set the actual database name.

Wouldn't it be great, if instead of copying and pasting that snippet one could component-ise it and reuse it? Here's where the factory annotation kicks in. You can annotate with @Factory any method that accept as an argument a service url and returns an object created using the URL (e.g. a client to a service).  So for the previous example we could have a MysqlConnectionFactory:
Then instead of injecting the URL one could directly inject the connection, as shown below.
What happens here?

When the CDI application starts, the Fabric8 extension will receive events about all annotated methods. It will track all available factories, so for for any non-String injection point annotated with @ServiceName, it will create a Producer that under the hood uses the matching @Factory.

In the example above first the MysqlConnectionFactory will get registered, and when Connection instance with the @ServiceName qualifier gets detected a Producer that delegates to the MysqlConnectionFactory will be created (all qualifiers will be respected).

This is awesome, but it is also simplistic too. Why?
Because rarely a such a factory only requires a url to the service. In most cases other configuration parameters are required, like:

  • Authentication information
  • Connection timeouts
  • more ....

Using @Factory with @Configuration

In the next section we are going to see factories that use configuration data. I am going to use the mysql jdbc example and add support for specifying configurable credentials. But before that I am going to ask a rhetorical question?

"How, can you configure a containerised application?" 

The shortest possible answer is "Using Environment Variables".

So in this example I'll assume that the credentials are passed to the container that needs to access mysql using the following environment variables:
  • MYSQL_USERNAME
  • MYSQL_PASSWORD
Now we need to see how our @Factory can use those.

I've you wanted to use environment variables inside CDI in the past, chances are that you've used Apache DeltaSpike. This project among other provides the @ConfigProperty annotation, which allows you to inject an environment variable into a CDI bean (it does more than that actually).


This bean could be combined with the @Factory method, so that we can pass configuration to the factory itself.

But what if we had multiple database servers, configured with a different set of credentials, or multiple databases? In this case we could use the service name as a prefix, and let Fabric8 figure out which environment variables it should look up for each @Configuration instance.


Now, we have a reusable component that can be used with any mysql database running inside kubernetes and is fully configurable.

There are additional features in the Fabric8 CDI extension, but since this post is already too long, they will be covered in future posts.

Stay tuned.