Obtaining list of installed OSGI bundles at runtime - osgi

My application obtains class names from a properties file. Classes represented by these class names could reside in certain OSGI bundles unknown at advance so in order to instantiate them I firstly have to find which bundle these classes belong to. I'm thinking about getting all installed bundles from BundleContext#getBundles, this means I have to obtain reference to BundleContext in AbstractUIPlugin#start. But I'm not sure if holding reference to BundleContext is the right thing to do since it's should be used only in the start method. So I need advice from OSGI experts here about the alternatives to get list of bundles.
Any help would be greatly appreciated.
Regards,
Setya

This is not really how OSGi is intended. If a bundle has something to add to the 'global' context, you should register a service. So each bundle that has something to share can do that in its own start method.
Some other component (DS, ServiceTracker, Blueprint, something like that) can then listen to these events, and act accordingly.
This is really important, if you start manually searching through all bundles you completely lose the advantages of OSGi.

Like written before you should try to use services to achieve what you want. I guess you have an Interface with one or more implementations that should be installable at runtime. So if you control the bundles that implement the interface then simply let them install their implementation as a service by using an Activator or a blueprint context. You can use service properties to describe your implementation.
The bundles that need the implementation can then lookup the services using a service tracker or a service reference in blueprint.
If that is not possible then you can use the bundle context to obtain the running bundles and instantiate the classes but this is not how OSGi should work. You will run into classloading problems as the bundle that tries to instantiate the classes will not have direct access to them.

Your bundle gets control at start up through the bundle activator, or better, through DS. At that time it can register services with the services registry so others can find/use them.
The route your planning to go (properties that name classes) is evil since you undoubtedly will run in class loading hell. Modularity is about hiding your implementation details, the name of your implementation classes are such details.
Exposing implementation classes in properties files is really bad practice and it looses the advantage of modularity. It does not matter if another class refers to your implementation class or a property file, the problem is that the impl. class is exposed.
Unfortunately this model has become so prevalent in our industry that many developers think it is normal :-(
OSGi allows you share instances typed by interfaces in a way that allows the implementation class to only be known inside the module.

Related

Create A Service And Allow Only One Bundle To Hold That Service At any Time

I'm trying to create a service such that once it is created it only allows itself to be held by a single consumer/bundle at any one time. (If this is against the philosophy/specification of OSGi then that obviously provides a quick answer but reference to the OSGi specs. stating this would be appreciated.)
To implement such a requirement I implemented the ServiceFactory interface thinking that whenever there was a requirement for the service the getService(Bundle bundle, ServiceRegistration<S> registration) method would be called and it would be where I could determine if the Bundle was a new consumer or not and act accordingly.
It appears that this is not the case in the scenario I have tested this in.
Using a Apache Karaf and instantiating a consumer of the Service via Blueprint it would seem that the getService method is never called. Instead the consumer's binding method for the service is called directly but injecting a proxy service object.
While I understand that Blueprint uses proxies surely there is still the obligation of the ServiceFactory contract to fulfil even if it's a proxy object consuming the service?
Why do I want to do this?
I am attempting to wrap JavaFX and the Stage class and because JavaFX isn't OSGi friendly I am attempting to co-ordinate access to the Stage object. I'm aware that there are frameworks such as Drombler but a brief look at them made me think that it doesn't suit my use case. They appear too restrictive for my needs e.g. I don't necessarily wish to layout an application in the manner Drombler uses.
It depends what you mean by a consumer. ServiceFactory does give you the chance to create a separate instance of a service per bundle that calls getService on your service. It's not clear from your question but I suspect you weren't seeing the getService invoked multiple times because you were fetching the service from the same consumer bundle. In this case, ServiceFactory simply returns the same object repeatedly.
As for your general question about restricting access to a single consumer, no that really goes against the OSGi philosophy. I'm sorry I don't have a spec reference for you but the clue is in the name: it's a service that is available to all.
I'm aware that there are frameworks such as Drombler but a brief look at them made me think that it doesn't suit my use case. They appear too restrictive for my needs e.g. I don't necessarily wish to layout an application in the manner Drombler uses.
Please note that the layout of Drombler FX applications is pluggable so you can provide your own implementation tailored to your needs. This allows you to get the most out of Drombler FX and JavaFX.
While this feature is available for some time, there is now a new tutorial trail explaining it in more detail.

OSGi: when to use component framework and when to create objects yourself

I've been an AEM developer for almost a year now. I know AEM uses 'Declarative Services component framework' to manage life cycle of OSGi components.
Consider a scenario when i would export a package from a bundle and import that package from another bundle, i could create objects of classes in first bundle inside second bundle as well. it's a import-export contract in this case.
my question is when i should be using component framework to manage the lifecycle of my objects and when to handle it myself by creating them when required.
In an ideal design, you would NOT in fact be able to create objects from the exported package; because that package would contain only interfaces. This makes it a "pure" contract (API) export. If there are classes in there that you can directly instantiate, then they are implementation classes.
In general it is far better to export only pure APIs and to keep implementation classes hidden. There are two main reasons:
Implementation classes tend to have downstream dependencies. If you depend directly from implementation class to implementation class then you get a very large and fragile dependency graph... and eventually that graph will contain a cycle. In fact it's almost inevitable that it will. At that point, your application is not modular because you cannot deploy or change any part of it independently.
Pure interfaces can be analysed for compatibility between versions. As a consumer or a provider of an API, you know exactly which versions of the API you can support because the API does not contain executable code. However if you have a dependency onto an implementation class, then you never really know when they break compatibility because the breakage could happen deep down in executable code that you can't easily analyse.
If your objects are services then there's no question, they have to be OSGi components.
For other things, my first choice is OSGi components, unless they're trivial objects like data holders or something similar.
If an object requires configuration or refers to OSGi services then it's also clearly an OSGi component.
In general, it's best IMO to think in services and define your package exports as the minimum that allows other bundles to use a bundle's services. Unless a bundle is clearly a reusable library like commons-io (to take a simple example).

Restlet converter registration in OSGI environment

We run Restlet 2.1 in an OSGi environment (Equinox) as bundle (ie. not as library within a bundle). The problem is that the Restlet Engine does not detect helpers (like converters) that are provided by Restlet extensions. Specifically, the EngineClassLoader#getResources() call does not return any result. The extensions are also deployed as OSGi bundles in the target platform.
Is automatic converter registration actually supposed to work within OSGi environments?
In fact, Restlet supports such feature thanks to a dedicated activator (see the Activator class in the package org.restlet.engine.internal).
This activator introspects bundles to find out the following things:
servers corresponding to registered servers
servers corresponding to registered clients
authenticators corresponding to registered clients
converters
Be aware that to use this feature, we must use the OSGi edition of Restlet since it's the only that has the MANIFEST file of the org.restlet bundle with the activator class specified. Otherwise you don't have to care about the bundle loading order...
Hope it helps you.
Thierry
Unless the Restlet-bundle explicitly imports the packages that contain the extensions (and I doubt it does, and it shouldn't), it wouldn't be able to load them, because bundles have isolated class-spaces.
A possible solution would be to provide the extensions as fragments attached to the Restlet-bundle. Thus, if you make it use the bundle-classloader (the documentation says this can be done by setting the Engines classloader), it would be able to load classes from the fragments.
Indeed it doesn't quite work for OSGi, as it depends on the ability to see the entire class space.
The way to do this in OSGi would be to use the service registry for the extensions, but that only works for OSGi aware libraries.
There is some help on the way: In the recently released OSGi 5 (Service Loader Mediator) there will be support to 'bridge' META-INF/services (I don't know if Restlet uses those, though) onto OSGi services, so 'legacy' libraries should work well within OSGi.
There is an implementation in Apache Aries called Spi-Fly. I looked at it briefly a while back. It might do the trick for you, it might not.

OSGI service vs. Singleton?

I am a beginner to OSGI and I am wondering if someone can enlighten me about the difference between creating OSGI service vs singleton pattern. For example, suppose I have a bundle core which provides IService, and multiple bundles that needs to access this. I can:
register a service in the core-bundle, in which the plugins can access
provide a singleton class, which provides the service
Using OSGI service seems to be quite cumbersome; and since the plugins have to depend on Core anyways (to get the interface), what's the advantage of using OSGI service?
Services are the connections between independent modules. Having modules depend on services (with their specification packages) can significantly reduce coupling between modules and thus provide much of the benefits of modularity.
I think the singleton pattern is used in two different ways: you just want a single object be shared between a set of users (e.g. a Log Service) or you can really only have one instance (e.g. there is only one piece of hardware). In general, I see that most people in the enterprise software world talk about the former. However, experience shows that when projects grow, singletons become less singleton but more a shared object, or at least an appearing to be shared object.
The nice thing in OSGi is that you can model both and the clients of the "singleton" are oblivious of it, nor does it require some central configuration. The reason is that OSGi relies on modules in charge, registering a service is a local decision as is listening to a service.
The power of services are not in its dynamics (they are cool though, especially during development), the essence of service is that they provide full local control inside the module without central configuration. Once you understand how powerful this is, there is no way back :-)
Last, OSGi services are not cumbersome, not since we have DS with annotations. Registering a service is now much simpler than creating a Spring bean, no xml, no central configuration:
// A component registered as a ISingleton service
#Component
public class MyImpl implements ISingleton {
void doSingle() { ... }
}
// A component that uses the ISingleton component
#Component
public class MyConsumer {
#Reference
void setISingleton(ISingleton is) { ... }
}
... And the dynamics come largely for free ...
Short answer: if you don't -- and won't -- need the benefit of an OSGi service (e.g., dynamically-managed service implementations and service searches), then you don't need an OSGi service.
But there is more to consider here than whether or not the service would be cumbersome. Heck, OSGi itself can be considered cumbersome. Will another bundle need to provide an implementation of that class? Maybe not. Will the Core bundle ever shut down or otherwise be unable to provide an implementation on demand? Maybe.
To determine if a service is right for the class in question, read the run-down of the specific benefits of a service on the OSGi Alliance's What Is OSGi page. They have a very good explanation of how your singleton class may become more cumbersome than a service.
Good luck.
My OSGi Threading Model 's poc is resulted into believing me that, every service is a singleton for a service consumer. As the only one service object get registered into the osgi service registry. (but you can override this behavior also). So as far as programming is considered, the behavior of a singleton class and an OSGi service is the same. Your class level variables are shared among the various service consumer calls.
I will say OSGI Service is Singleton++
But there are also differences.
OSGi gives you a separate class-loader for each service which is not possible in a singleton. All {singleton} classes are loaded by a single classloader. We can't have two classes with the same name (fully qualified name) in a singleton but this is possible in OSGi.
In certain situations we must be confirmed that a class should be loaded only once (making hibernate session factory, hdfc service initialization, POJO creations which are heavy initializations required only once). Now if you are living in a Java EE scenario some times your singleton class gets loaded twice by two different classloaders. So this results into two times the execution of a static block; an unnecessary job.
Such classloader problems are easily handled by OSGi (as you are a beginner I feel classloading itself is a problem for you in the next few days).
Another great feature provided by OSGi is updating a bundle.
Consider you changed the code in your singleton class. Now you need to deploy this updated class in your running application. You essentially need to restart the system, so that every singleton class loader updates the new instance of the singleton. This is not required in OSGi, just update the bundle.
I will say if you're going to design for larger applications (enterprise scale), or if you need to design code for a limited hardware capacity (low memory constraints, low computing power) then go for OSGi, it is best for the extreme ends. For all others your normal java coding will work perfectly.
You can manage the life cycle (deploy new version of the service, concurrently run multiple versions etc) of a service but you can't manage the life cycle of singleton without restarting the JVM (even with restart you can just have 1 version available at any point of time).

Is separate OSGI bundles for api and implementation common practice?

I have a class with dependencies which I want to hot deploy without restarting the dependencies. The class has an interface but there's only one concrete implementation.
Initially I created a single bundle with exported the interface and registered the implementation using activator and implementation classes which were not exported. However, if I update the bundle, bundles which use the registered service get restarted after the update when PackageAdmin#refreshPackages is called (this is automatic when using fileinstall).
I have fixed this by creating a separate api bundle.
Is this the best way to achieve this?
Would you ever have a bundle which exports its api and includes the implementation in the same bundle. As far as I can see any give bundle would either export all its classes or no classes. What am I missing?
It is definitely a best practice to separate API bundles from their implementations in OSGi. If you do this, then any bundle that uses the API only needs to import classes from the API bundle, which can allow you to change implementations at runtime without restarting your dependent bundles.
Ideally your implementation bundle would implement the interface and export implementation as a service on the API provided interface. This allows the client bundles to utilize the service without referencing the implementation bundle.
In Apache Sling we do both: major APIs are in their own bundles, but for smaller things like extensions or optional components we often provide the default implementation in the same bundle as the API.
In the latter case, you can still allow for those default services to be replaceable, for example using service ranking values when you want to override them.
A bundle does not have to export all its classes, our bundles which include default services export just the API packages (and the default implementations are in different packages, obviously).
Unless there is a hard requirement to be able to replace implementation at runtime, without restarting client bundles, I would personally advocate keeping the explicit dependency link between API and implementation (either by including impl classes in the API bundle, or by having the API bundle import implementation packages from the impl. bundle).
The pb with the patterns suggested above is that they break the dependency chain. The benefits of dependency management go far beyond simple API compatibility, they also include ensuring predictable, consistent runtime behavior, as well as compatibility with the deployment ecosystem, and all of those require managing the implementation dependencies.

Resources