May 3, 2020
Estimated Post Reading Time ~

OSGi Components – Simply Simple – Part II

Component Configurations
If you want to make your component configurable, the best way of doing this is to leverage the OSGi Configuration Admin (another spec from the OSGi compendium with again a great implementation at Apache Felix). Configuration Admin is a service persisting configurations – these configurations are dictionaries where the key is a string and the value can be one of the simple Java types or an array or collection of such a type. This is usually sufficient for most components.

Configuration Admin nicely abstracts managing the configuration from your component. As a component developer you don’t need to know where the actual configuration is stored and how it ends up there. Without a component container, you would ask the configuration admin for “your” configuration (though there is some injection support through the ManagedService interface) – but fortunately with DS the container takes care of this and provides your component with the configuration. The component might get the configuration as a parameter for the activate method.

As mentioned Configuration Admin stores configurations as dictionaries. Whereas the names are of type String, the value can be any type. While your component might expect an integer, e.g. for a port, the actual value stored might be of type String holding an integer value. Therefore it is good style to not assume a specific type but try to convert whatever you get into the expected type. To avoid putting the burden of doing this on the component developer and to support type safe configurations, the configuration for a component can be described in Java. While the following might look a little bit out of the ordinary, stick with me, you’ll get used to it pretty soon and simply love it.

The way to describe a configuration is by defining a so called Component Property Type: an annotation describing all configuration properties. Let’s assume our component has three configuration properties, then the following annotation would do:

public @interface MyComponentConfig {

String welcome_message() default "Hello World!";
int welcome_count() default 3;
boolean output_goodbye() default true;
}

Defining an annotation instead of a simple interface has the advantage that we can directly specify default values for each property. If no value for a property is stored in configuration admin, the default value is used. Let’s see how to use this:

import org.osgi.service.component.annotations.Activate;
import org.osgi.service.component.annotations.Component;

@Component
public class MyFirstComponent {

@Activate
protected void activate( MyComponentConfig config ) {
for(int i = 0; i < config.welcome_count(); i++ ) {
System.out.println(config.welcome_message());
}
}
}


When the above component is activated, SCR tries to get a configuration from the configuration admin and converts it into the used annotation type. Therefore the passed in object returns the value in the correct type for each property. As mentioned if there is no value, the default is returned. This makes handling of configurations very simple and avoids all the usual boilerplate code. The OSGi specification for Declarative Services explains in detail how the type conversion is done and what happens if a value can’t be converted. It also defines the conversion rule from the name of a property in the annotation to a property in configuration admin. In the example above we see the underscore in the names, this is acutally converted to a dot in the property name.

Taking configurations is as easy as this: define your set of configuration properties as an annotation and pass it as an argument to the activate method. Of course, if you don’t need configuration, leave out these steps and use the zero argument activate method signature – or if you don’t need the activate method at all, leave it out completely.

With this knowledge we can already develop configurable components capable of using other services. But how do you provide a service for others to be used?

Services
Offering a service usually consists of two steps. First you define the service API and second you implement this API. Of course, in some cases the API might already exist as someone else defined the interface. If you define your own interface, put it into a public package and export this package – however, as already noted above for the component, a service implementation should never be public but in a private package. It depends on your use case, if you put the interface and the implementation in the same bundle or create an API bundle and an implementation bundle. If you’re implementing an existing interface, this usually is already in another bundle and you can just import it. And if you create public API, don’t forget to use proper versioning for these packages. Have a look at the semantic versioning whitepaper!

Offering a service is implementing the corresponding interface and registering the component in the OSGi service registry as the service. With the annotations you can just use the @Component annotation. Assume there is an interface EventHandler and your component should be registered as a service for this interface:

import org.osgi.service.component.annotations.Component;

@Component
public class MyFirstService implements EventHandler {

....// implement the EventHandler interface

}

Without further specifying anything at the @Component annotation, a component is registered as a service for all interfaces it directly implements. In this case, this is the EventHandler. While this is very convenient, it comes with the problem, that as soon as your component is implementing an interface directly, it gets registered as this service. In some cases, this is not what you want. Therefore I suggest to:
Always explicitely list the service interfaces the component implements:

@Component(service = EventHandler.class}

As a default always set the service attribute of the component annotations to the empty array. This prevents automatic registration:

@Component(service = {})

If you follow these simple rules, you can see directly by looking at the @Component annotation which services this component implements and you avoid accidental service registrations, e.g. when refactoring your implementation.

The lifecycle of a Service
A component that does not provide a service is active for as long as it is satisfied (all referenced services are available and some other conditions we get to later). In contrast, services are instantiated lazy, or on demand by DS. This means, as long as no one is using your service, your service is never created nor activated! In most cases this is fine. But there is a catch with this approach one should be aware of: if someone else is starting to use your service, it gets created and activated. As soon as your service is not used anymore, it gets deactivated and destroyed.

The OSGi spec does not mandate this behavior. The implementation of Declarative Service is free to keep your service around for some time until it is disposed of. By default, the current Apache Felix implementation immediately disposes of such components. However, it is possible to configure such detailed disposal of components. But this leaves you with the problem of configuring this correctly which might not be that easy.

On the other hand, frequent creation and disposal of an “expensive” service might create a performance bottleneck. For example, if this happens being triggered by an event, a request and/or if your service is doing some computation in the activate method.

In many cases, your actual service is combining a “component” and a “service” part. While the “component” part is the expensive one and should only be done once, the “service” part is lightweight and might simply use the component part. In such cases, you might think about splitting your implementation accordingly.

Or you can either think about holding the service by someone else and therefore keep a reference to it around (which in general sounds hacky though there are valid use cases). Or you can use the immediate flag on the @Component:

@Component(service=EventHandler.class, immediate=true)

With immediate set to true, the component is activated as soon as possible and kept as long as possible. Obviously, this increases things like startup time, memory consumption, etc. So it should really be used with care and maybe only after problems are encountered in this area.

In the past, the only situation where we encountered this was implementing an event handler. But with today’s event admin implementations this isn’t even true anymore either. But for completeness lets have a look at that problem: an implementation of the event admin as defined in the OSGi Event Admin Specification might fetch an event handler (service org.osgi.service.event.EventHandler) each time an event should be delivered to this handler. Clearly, this has the advantage that event handlers are only used if there is an event for such a handler. While this might work with a few events, with very frequent events, especially in a multi threaded environment, the same event handler might receive quite a lot of events, even “in parallel”.

In the past, we suggest making your event handler implementation immediate as otherwise it is potentially created/destroyed with each event for this handler! However, even this is up to the implementation of the event admin. The latest Apache Felix event admin implementation and the Equinox event admin implementation do not create/destroy the instance on each request, they rather create it once the first event for this component arrives and keep a reference to it from that point on. But as this is implementation specific, the above advice might be handy. And again, only use immediately if really required.

And with this the simple introduction to Declarative Services ends: you now know:
  • how to create components
  • how to configure components
  • how to reference services
  • how to provide services
Of course with most of this, we only touched the simple case, which is really sufficient for most use cases. I’ll continue this series with more advanced stuff in the future.



By aem4beginner

No comments:

Post a Comment

If you have any doubts or questions, please let us know.