osgi training for carbon developers

47
OSGi Training Aruna Karunarathna Senior Software Engineer

Upload: aruna-karunarathna

Post on 06-Jan-2017

167 views

Category:

Software


0 download

TRANSCRIPT

Page 1: OSGi Training for Carbon Developers

OSGi Training

Aruna KarunarathnaSenior Software Engineer

Page 2: OSGi Training for Carbon Developers

Modularity in Java

Page 3: OSGi Training for Carbon Developers

Why Modularity

o Ease of development (interactions are clearly defined)

o Pluggable modules

o Reusable modules

Page 4: OSGi Training for Carbon Developers

Is Java providing the modularity?

o Compile time vs Runtime difference

o Compiled and run under single/flat classpath

o Alternatives

o Write custom classloaders / non standard way to handle

Page 5: OSGi Training for Carbon Developers

Java Classloading...

http://www.techjava.de/topics/2008/01/java-class-loading/

Page 6: OSGi Training for Carbon Developers

Java Compile Time vs Runtime...

axiom-1.2.0.jar axis2-1.4.5.jar log4j.1.4.1..jar saxon.14.1..jar algpr.1.3.2..jar spring.0.2.1..jar

spring-core.0.34.1..jar abdera_1.0.0..jar ajaxtags_1.3.0.beta-rc7-.jar annogen_0.1.0..jar antlr_3.2.0..jar apache-zookeeper_3.3.4..jar

Page 7: OSGi Training for Carbon Developers

JAR (Java Archive)

o Development units in java

o Application contains several jar files

o At runtime there is no real meaning for a jar file

o All the developed Jar files treated as a single, ordered, global list which is called the classpath.

Page 8: OSGi Training for Carbon Developers

JAR (Java Archive) cntd..

o Problems with JAR Files

- Multiple versions of JAR files cannot be loaded at same time

- A JAR cannot declare dependencies on other JARs.

- No mechanism for information hiding

- Jars cannot be treated as modules.

o Hence Java is suffering from modularity.. :(

Page 9: OSGi Training for Carbon Developers

Dynamism in Java

o Can a Jar file updated while the application is running?

o Can new functionality be added while the application is running? (Update a class file with new version)

o The application (JVM), needs to be restarted.

o Java lacks Dynamism.

Page 10: OSGi Training for Carbon Developers

OSGi for the rescue?

o Widely accepted way (A specification) of developing modular and dynamic systems using Java [1].

o OSGi Framework implementations (Open Source)o Equinoxo Knopflerfisho Apache

[1]. https://www.osgi.org/developer/specifications/

Page 11: OSGi Training for Carbon Developers

Bundles

o Bundles are the development unit of OSGio Typical OSGi application consists with multiple bundleso Bundles can share packages and hide packages in a

consistent manner Most Importantly

o What changes there in bundles, when comparing to JAR files?

o Bundle object persist over the framework executions when the installed bundles are reloaded from the framework’s cache.

Page 12: OSGi Training for Carbon Developers

MANIFEST.MF

o Use some standard MANIFEST Headers. o Defines the bundle’s identityo Specifies the packages on which

this bundle dependso Specifies the packages on which this

bundle exportso Declares additional human-readable

information

o Bundle object persist over the framework executions when the installed bundles are reloaded from the framework’s cache.

Manifest-Version: 1.0Bnd-LastModified: 1405099135557Build-Jdk: 1.7.0_55Built-By: arunaBundle-Activator: org.sample.ActivatorBundle-ManifestVersion: 2Bundle-Name: sampleBundle-SymbolicName: sampleBundle-Vendor: WSO2 IncBundle-Version: 1.0.0Created-By: Apache Maven Bundle PluginExport-Package: org.sample;uses:="org.osgi.framework";version="1.0.0"Import-Package: org.osgi.framework;version="[1.7,2)"Tool: Bnd-2.1.0.20130426-122213

Page 13: OSGi Training for Carbon Developers

Bundles cntd..

o Standard Java - Place Jar files in classpath

o OSGi Framework - Install bundles to framework

Page 14: OSGi Training for Carbon Developers

Java class loading with OSGi...

Page 15: OSGi Training for Carbon Developers

Lifecycle State Diagram

Page 16: OSGi Training for Carbon Developers

DEMO

o OSGi Framework

o First Look at a Sample Bundle

o Try out the lifecycle events of a bundle

http://www.slideshare.net/rossmason/realtime-apis

Page 17: OSGi Training for Carbon Developers

Bundle Activator Manifest Entry

o Bundle Activator Manifest Entry is the hook to the Bundle execution entry point.

o Similar to the Main Method of a Jar file?..o Header value specifies the name of a reachable class

o Either a class in an Imported Packageo A class in the Bundle class path

o This class implements the org.osgi.framework.BundleActivator interface, and implements the following two methods.

o Can use these two methods to customize the behaviours when the bundle is started and stopped.

public interface BundleActivator { void start(org.osgi.framework.BundleContext bundleContext) throws java.lang.Exception; void stop(org.osgi.framework.BundleContext bundleContext) throws java.lang.Exception;}

Page 18: OSGi Training for Carbon Developers

Bundle Activator Manifest Entry cntd...

o When the bundle installed and started, OSGi Framework creates an instance of Bundle Activator class and call the start() method.

o When the bundle stop is initiated, OSGi Framework call the stop()

method.o In practice when the stop is called, you should undo everything you did

in the start method.o The activator instance on which start() is called is the same

instance on which stop() is called.o The activator instance is discarded and isn’t used again, after

stop() is called.o If the bundle is subsequently restarted after being stopped, a new

activator instance is created, and the start() and stop() methods are invoked on it as appropriate.

Page 19: OSGi Training for Carbon Developers

Bundle Context

o Can be accessed via start() and stop() of Bundle Activator classo Bundle context object is its role as the unique execution context of

its associated bundleo Valid while the bundle is active. (The time range from the framework

call start() up until to the stop() is called )

o Gain access to two types of methodso Related to deployment and lifecycle management.o Related to bundle interaction via services.

o They should be treated as sensitive or private objects and not passed freely among bundles

Page 20: OSGi Training for Carbon Developers

Listening for events

o OSGi framework supports two types of events: BundleEvents and

FrameworkEventso The former event type reports changes in the lifecycle of bundles, whereas

the latter reports framework-related changeso The BundleContext object has methods to register BundleListener and

FrameworkListener objects for receiving BundleEvent and FrameworkEvent notifications, respectively

o How to implement BundleListener and FrameworkListener in your code?.a.Create a new class which Implements BundleListener or FrameworkListener b.Implement the bundleChanged(BundleEvent) or

frameworkEvent(FrameworkEvent) methods respectively.c.Register by creating a new Object of the implemented class to the

BundleContext as a Listener using the bundleContext.addBundleListener() or bundleContext.addFrameworkListener() respectively.

o No need to call the removeBundleListener() or removeFrameworkListener(), which will automatically removed when the bundle is stopped.

Page 21: OSGi Training for Carbon Developers

Relationship between carbon & OSGi

Non OSGi Portion OSGi Portion

./carbon.sh org.wso2.carbon.launcher-5.2.0.jar

Equinox + Some Carbon Bundles

Bundles developed by Component

Developers

Page 22: OSGi Training for Carbon Developers

What about Dynamism?

o After the Objects are instantiated, they will tightly coupled with the modules.

o What if we want to change the module or part of the module, dynamically at the runtime?

Page 23: OSGi Training for Carbon Developers

OSGi Services Layer

o Kind of in VM SOA modelo OSGi Registry o OSGi Service is simply a Java Object published to the service registryo Services are published/looked up

Using an exported interface.

OSGi Service Registry

Service Provider Service Consumer

Publish Find

Page 24: OSGi Training for Carbon Developers

Registering an OSGi Service

public class Activator implements BundleActivator { ServiceRegistration serviceRegistration;

public void start(BundleContext bundleContext) throws Exception { HelloWorld helloWorld = new HelloWorld(); serviceRegistration = bundleContext.registerService(Hello.class, helloWorld, null); }

public void stop(BundleContext bundleContext) throws Exception { serviceRegistration.unregister(); }}

Page 25: OSGi Training for Carbon Developers

Using an OSGi Service

public void start(BundleContext bundleContext) throws Exception { ServiceReference reference = bundleContext.getServiceReference(Hello.class.getName()); Hello helloService = null; if (reference != null) { helloService = (Hello) bundleContext.getService(reference); } else { System.out.println("Service reference is null..."); } if (helloService != null) { System.out.println(helloService.sayHello()); } else { System.out.println("Error..."); } }

Page 26: OSGi Training for Carbon Developers

DEMO

o OSGi Services

o Sample Hello Service

o diag command to diagnose

o p command to check exports andimports

http://www.slideshare.net/rossmason/realtime-apis

Page 27: OSGi Training for Carbon Developers

Handle Dynamism?

o Services can register/unregister at anytime.o Service may not be available when tries to use the service

because of the startup order of bundleso Somehow the service was acquired, but service get

unregistered and now we are having a stale service reference?

o Developer has to handle such scenarios?

Page 28: OSGi Training for Carbon Developers

Slate References

o Stale references are a result of an object either,o A bundle which the class loader has stoppedo A service object which the unregisteredo Can be result in significant increase of memoryo Developer should follow the best practices to keep away

from slate references,

HOW?

o Listen to the relevant events and act accordingly.

Page 29: OSGi Training for Carbon Developers

Monitoring OSGi Services

o ServiceListenero Service Trackerso Declarative Services

Page 30: OSGi Training for Carbon Developers

ServiceListener

o A listener interface that can be used to capture service lifecycle events.

public interface ServiceListener{ public void serviceChanged(ServiceEvent event);}

o When an osgi service events are fired; will get a synchronous callback to the serviceChanged(ServiceEvent event)

method

Page 31: OSGi Training for Carbon Developers

ServiceListener cntd...public class SampleServiceListener implements ServiceListener , BundleActivator{ public void start(BundleContext bc) throws Exception { bc.addServiceListener(this); } public void stop(BundleContext bc) throws Exception { bc.removeServiceListener(this); } public void serviceChanged(ServiceEvent event) { switch(event.getType()){

case ServiceEvent.REGISTERED: break; case ServiceEvent.UNREGISTERING: break; case ServiceEvent.MODIFIED: break; } }}

Page 32: OSGi Training for Carbon Developers

DEMO

o OSGi Service Listener

http://www.slideshare.net/rossmason/realtime-apis

Page 33: OSGi Training for Carbon Developers

ServiceListener cntd...

o Any concerns/issues regarding the Service Listener approach?...

https://www.pinterest.com/salenka/meme-faces/

Page 34: OSGi Training for Carbon Developers

ServiceListener cntd...

o What if the service has registered Before the service listener?

o You probably missed the Service Registration event

Now What?....

https://www.pinterest.com/zmeers/meme-faces/

Page 35: OSGi Training for Carbon Developers

Working with OSGi Services

o Some major issues with listeners and trackerso Memory Leakso Race conditions

o Working with OSGI services API complex and error prone

o Bundle developers tend to make optimistic assumptions regarding the availability of services in an attempt to simplify their code.

Page 36: OSGi Training for Carbon Developers

Declarative Services

o Alternative approach for OSGi Services API’so The bundle declare the services; it registers and acquires

in an xml fileo Less effort for developerso Developers can focus more on the business logic, rather

worrying about the OSGi concerns.

Page 37: OSGi Training for Carbon Developers

Declarative Services cntd...

o Additional resources required in a bundleo OSGI-INF/example.xml

o Framework reads the configuration file and enables the dynamism

o A service component contains a description that is interpreted at run time to create and dispose objects

o Maven SCR Plugin to generate the OSGI-INF/example.xml

Page 38: OSGi Training for Carbon Developers

Sample Declarative Service

public class SampleServiceComponent { private Hello hello; protected void activate(ComponentContext context) { }

protected void deactivate(ComponentContext context) { }

public void setHelloService(Hello hello) { this.hello = hello; } public void unsetHelloService(Hello hello) { this.hello = null; }}

Page 39: OSGi Training for Carbon Developers

Sample Declarative Service -scrdescriptor

<?xml version="1.0" encoding="UTF-8"?><components>

<scr:component enabled="true" immediate="true"

name="org.sample.sc.SampleServiceComponent">

<implementation class="org.sample.sl.SampleServiceComponent"/>

<property name="service.pid" value="org.sample.sc.SampleServiceComponent"/>

<reference name="org.sample.api.Hello"

interface="org.sample.api.Hello"

cardinality="1..1"

policy="dynamic" target="(name=impl2)"

bind="setHelloService"

unbind="unsetHelloService"/>

</scr:component></components>

Page 40: OSGi Training for Carbon Developers

SCR Component Lifecycle

o SCR Component become satisfied if the following conditions are satisfied,

o The component should be enabledo All the component’s references are satisfied.

A reference is satisfied when, 1. The reference specifies optional cardinality or 2. There is at least one target service for the reference.

Page 41: OSGi Training for Carbon Developers

References to Services

o Cardinalityo 0..1 –> optional and unaryo 1..1 – mandatory and unary (Default) o 0..n – optional and multipleo 1..n – mandatory and multiple.

o Policyo Statico Dynamic

o Targeto Filter out the necessary services specifying a service

property

Page 42: OSGi Training for Carbon Developers

DEMO

o Sample OSGi Service Component

o SCR JavaDoc Tags

o Maven SCR Plugin

o Troubleshoot issues with,o ls commando comp command

o Target property?

http://www.slideshare.net/rossmason/realtime-apis

Page 43: OSGi Training for Carbon Developers

Jar to Bundle Conversion

o Used to convert a Jar to Bundleo Export all packages in jar fileo Export version is set to 0.0.0o Added the DynamicImport-Package headero No control overo This is just evil :(

Page 44: OSGi Training for Carbon Developers

Jar to Bundle Conversion cntd...

o Hence introduced the WSO2 Orbit Project

o Just a pom.xml file with o Proper dependencieso Proper Information Hidingo Most importantly with proper versions.

o Use the Maven-Bundle-Plugin to create orbit bundles

Page 45: OSGi Training for Carbon Developers

Best Practices

o Dynamism comes with the cost, so handle it properly

o Proper imports and exports

o Proper usage of versioning

o Manage the dependencies

o Use services when and where it requires

Page 47: OSGi Training for Carbon Developers

References

OSGi Alliance Specifications http://www.osgi.org/Specifications/HomePage

OSGI in Action - CREATING MODULAR APPLICATIONS IN JAVA

Carbon Documentation - https://docs.wso2.com/display/Carbon500/WSO2+Carbon+Documentation