Upload
argus
View
41
Download
0
Embed Size (px)
DESCRIPTION
NPRG044: OSGi framework. Michal Malohlava & Pavel Parízek parizek @d3s.mff.cuni.cz. Step #1: Download Eclipse 4.2 RCP http://www.eclipse.org/downloads/. Do you use JARs?. JAR advantages and disadvantages. + Includes class files and additional resources + Deployment - PowerPoint PPT Presentation
Citation preview
CHARLES UNIVERSITY IN PRAGUE
http://d3s.mff.cuni.cz
faculty of mathematics and physics
NPRG044:OSGi framework
Michal Malohlava & Pavel Parí[email protected]
2
Step #1:Download Eclipse 4.2 RCP
http://www.eclipse.org/downloads/
3
Do you use JARs?
4
JAR advantages and disadvantages
Michal Malohlava & Pavel Parízek, NPRG044, OSGi framework
+ Includes class files and additional resources+ Deployment
- No information hiding- No runtime meaning- Cannot specify required JARs- No versioning
OK, it’s not completely true, but JARs classpath
is almost entirely useless
5
Common Java classloading
Michal Malohlava & Pavel Parízek, NPRG044, OSGi framework
Cannot handle different versions of the same class
The picture was taken from the book “OSGi in Practice” written by Neil Bartlett See http://njbartlett.name/osgibook.html
6
J2EE classloading
Michal Malohlava & Pavel Parízek, NPRG044, OSGi framework
The classloader has precedence over all classloaders below =>
all applications have to use the same version of the core library
The picture was taken from the book “OSGi in Practice” written by Neil Bartlett See http://njbartlett.name/osgibook.html
7
OSGi
Michal Malohlava & Pavel Parízek, NPRG044, OSGi framework
OSGi is a specificationOpen Service Gateway InitiativeCurrent version R5 (see http://www.osgi.org/)Three parts + Java API + execution environment specification
CoreCompendiumEnterprise
SpecifiesFrameworkModulesProvided servicesAdditional functionality
8
OSGi framework
Michal Malohlava & Pavel Parízek, NPRG044, OSGi framework
Framework to build modular applications“LEGO principle”Fine-grained modules which are
ReusableScalableIsolated
Bringing separation of concepts Modules should be “easily” testable,manageable, maintainable, repairable, exchangeable
Bringing abstraction
9
OSGi framework conceptual architecture
Michal Malohlava & Pavel Parízek, NPRG044, OSGi framework
The picture was taken from the book “OSGi in Practice” written by Neil Bartlett See http://njbartlett.name/osgibook.html
10
OSGi basic concepts
Michal Malohlava & Pavel Parízek, NPRG044, OSGi framework
BundleModuleUnit of deployment
ServiceCommunication between components
11
Bundle
Michal Malohlava & Pavel Parízek, NPRG044, OSGi framework
Unit of deploymentClassical JAR with meta-information
Class filesAdditional resources (images, videos, source code, …)Directories containing meta-information (META-INF, OSGI-INF)
Bundle is versionedMajor, minor, micro, qualifier (1.0.3_rc2)Multiple versions at runtime are allowed
Bundle can export/hide packagesRecommended practice: ”Exposing only API not implementation”
Declarative dependenciesBundlesPackages
Range of version [1.0, 2.0)
12
Bundle meta-information
Michal Malohlava & Pavel Parízek, NPRG044, OSGi framework
Manifest META-INF/MANIFEST.MFManifest-Version: 1.0Bundle-ManifestVersion: 2Bundle-Name: LogTargetBundleBundle-Activator: LogTargetActivatorBundle-SymbolicName: cz.cuni.mff.d3s.LogTargetBundleBundle-Version: 1.0.0.qualifierBundle-Vendor: D3S MFF UKBundle-RequiredExecutionEnvironment: JavaSE-1.6Import-Package: cz.mff.cuni.d3s.nprg044.tut1.test01.api, org.osgi.framework;version="1.5.0", org.osgi.service.component;version="1.1.0", org.osgi.service.log;version="1.3.0“Service-Component: OSGI-INF/componentOne.xml, OSGI-INF/factory.xml
The length of each line is limited to 72 bytes by the design of JVM
13
Bundle dependencies
Michal Malohlava & Pavel Parízek, NPRG044, OSGi framework
Export packagesList all of packages + versions + attributesFine-grained package filtering
exclude, include, parameters
Import packageRequire specific version(s)
e.g. [1.0, 2.0)
Resolution: optional/mandatory
Require bundleNot recommended because it restricts further changes in the API
Export-Package: cz.*;exclude=”*Impl”
Import-Package: cz.mff.*;version=”[1.0,1.3.1)”;resolution=optional
Require-Bundle: logger-api-bundle
14
MANIFEST.MF headers
Michal Malohlava & Pavel Parízek, NPRG044, OSGi framework
Bundle-ClassPathWay to bundle third-party JAR libraries
Bundle-ActivatorName of the class implementing BundleActivatorThe class is called when the bundle is activated
Bundle-SymbolicNameBundle ID
Bundle-Version1.0.3.qualifier (qualifier corresponds to timestamp)
Bundle-RequiredExecutionEnvironmentEnforces the execution context
DynamicImport-PackageOn-the-fly import
Bundle-NativeCodeImport .so, .dll
15
Bundle lifecycle
Michal Malohlava & Pavel Parízek, NPRG044, OSGi framework
The picture was taken from the book “OSGi in Practice” written by Neil Bartlett See http://njbartlett.name/osgibook.html
16
Bundle lifecycle - activation
Michal Malohlava & Pavel Parízek, NPRG044, OSGi framework
Manage the bundle lifecycle
class BundleActivatorvoid start(BundleContext ctx)
Register services and listeners, look for servicesvoid stop(BundleContext ctx)
Stop trackers and listeners, …
class BundleContextPropertiesServicesBundlesFiltersListeners
public class SimpleLogTargetActivator extends Activator {
@Override public void start(BundleContext ctx){ /* ... */ }
@Override public void stop(BundleContext ctx) { /* ... */ }}
17
OSGi classloading
Michal Malohlava & Pavel Parízek, NPRG044, OSGi framework
The picture was taken from the OSGi wikiSee http://wiki.osgi.org/wiki/Main_Page
18
OSGi classloading
Michal Malohlava & Pavel Parízek, NPRG044, OSGi framework
Separated classloader per bundleClassloaders do not compose a tree, but a general graph
Lookup orderParent
only for classes from the java.* packages
Imported packagesRequired bundlesLocal bundleclasspath
The picture was taken from the book “OSGi in Practice” written by Neil Bartlett See http://njbartlett.name/osgibook.html
19
Bundle classpath
Michal Malohlava & Pavel Parízek, NPRG044, OSGi framework
Bundle classpath is composed of classes fromImported packagesProvisions of required bundlesLocal classpath specified via Bundle-Classpath
20
OSGi Console
Michal Malohlava & Pavel Parízek, NPRG044, OSGi framework
Important commandshelpss
Displays installed bundlesservices
Displays published servicesstatusexit
Shutdown the OSGi frameworkstart/stop <bundle-id>update <bundle-id>packages
Shows exported packagesdiag
Run diagnostic
21
Demo #01
Michal Malohlava & Pavel Parízek, NPRG044, OSGi framework
Download Eclipse 4.2 RCPhttp://www.eclipse.org/downloads/
Create a simple bundle with activatorVia wizard in “New > Project > …”
Run the bundleCreate new OSGi launch configuration & launch it
Package org.eclipse.osgi is required to be selectedUse “Add required bundles”
Observe its state in the console
22
Service
Michal Malohlava & Pavel Parízek, NPRG044, OSGi framework
Communication layer for bundlesWell-defined communication pointsInherent dynamic nature
Can appear/disappear any time at runtime
Multiple providers can provide the same serviceThe service has additional properties (e.g., priority)
ServiceService is an object registered by a bundle in a ServiceRegistry
ProgrammaticallyDeclaratively
Service has associated propertiesE.g., service.ranking
23
Registering service (1)
Michal Malohlava & Pavel Parízek, NPRG044, OSGi framework
Programmatically in BundleActivator
ProblemsSemantics spread over the code
dependencies, properties, implementation versus interface
public void start(BundleContext context) { SimpleLogTargetImpl logTargetImpl = new SimpleLogTargetImpl();
registration = context.registerService(ILogTarget.class.getName(),logTargetImpl,null);
}
24
Registering service (2)
Michal Malohlava & Pavel Parízek, NPRG044, OSGi framework
Declarative services (DS)
DeclarativelyServices provided by components
Automated service management by DS frameworkDependency injection of required servicesLife-cycle management
<scr:component name="logger-component“ enable=“true”
activate=“activate”> <implementation class="cz.cuni...LoggerImpl"/> <service> <provide interface="cz...ILogger"/> </service></scr:component>
25
Service components
Michal Malohlava & Pavel Parízek, NPRG044, OSGi framework
Component is a normal Java class contained within a bundle
Defined in a separate XML file in the OSGI-INF directory
MANIFEST.FM has to contain component file reference: Service-Component: OSGI-INF/component.xml
ActivationDeclared method
Parameters: ComponentContext, BundleContext, Map
Service providerSpecify name of the provided service
<scr:component name="logger-component“ activate=“activate”> <implementation class="cz.cuni...LoggerImpl"/> <service> <provide interface="cz...ILogger"/> </service></scr:component>
26
Component factories
Michal Malohlava & Pavel Parízek, NPRG044, OSGi framework
A component can be declared as a factoryComponentFactory service is registered
newInstance(Dictionary d) method
The user tracks for the ComponentFactory service and creates a new instance
A component factory can provide a serviceRegistered for each created instance
27
Demo #02
Michal Malohlava & Pavel Parízek, NPRG044, OSGi framework
Create a bundle that defines some API API: a set of Java interfaces
Implement two bundles implementing the API
Register API servicesProgrammaticallyDeclaratively
Launch configuration has to contain the bundle ‘org.eclipse.equinox.ds’
Observe provided services in console (command services)
28
Service consumption (1)
Michal Malohlava & Pavel Parízek, NPRG044, OSGi framework
Bundle can search for a service that implements a specific interfaceSeveral bad solutions
context.getService(...)Nasty code with active waiting
Service registry listeners
Recommended solutions (thread-safe)Service trackerComponents
ServiceReference ref =
context.getServiceReference(“cz.bar”);if (ref!=null) { Bar bar = (Bar) context.getService(ref); if (bar != null) { ... context.ungetService(ref) }}
29
Service tracker – white board pattern
Michal Malohlava & Pavel Parízek, NPRG044, OSGi framework
Service dependenciesContent provider versus consumers
e.g., consume a new service if and only if the specified service appears
“Don't look for content providers, let them to register as services and track for the services”
ServiceTracker captures the service life-cyclevia ServiceTrackerCustomizer
Captures the process of adding/removing/modifying services
30
Service tracker
Michal Malohlava & Pavel Parízek, NPRG044, OSGi framework
Service TrackerTracking for services
Filters (name, id, property, owning bundle, ...)LDAP syntax (e.g. (&(objectName=”foo”)(property1=”Xyz”)) )
//In Bundle Activator - starttracker = new ServiceTracker(context, ILogger.class.getName(), null);
tracker.open();
// get the service(s)ILogger log = (ILogger) tracker.getService();ILogger log = (Ilogger) tracker.waitForService(1000);
// stop trackingtracker.close();
31
Service tracker
Michal Malohlava & Pavel Parízek, NPRG044, OSGi framework
Construction determines attributes
ServiceTracker methodsopen()/close() – start/stop tracking for a servicegetService()addingService/removedService/modifiedService
Parameter: ServiceReference rfInterface ServiceTrackerCustomizerCan be overridden by the user
ServiceTracker(BundleContext context,
java.lang.String clazz, ServiceTrackerCustomizer customizer)
32
Service consumption (2)
Michal Malohlava & Pavel Parízek, NPRG044, OSGi framework
Declaratively via service components
Service referenceNameInterfacesBind/unbind methodsTargetPolicy: static/dynamicCardinality: M..N
1..1 – if multiple services are accessible then the one with the highest service.ranking is used
<scr:component name=”getServiceComp”> <implementation class=”GetLoggerService”> <reference name=”log” interface=”org.osgi...LogService” bind=”setLog” unbind=”unsetLog”</scr:component>
33
Service lookup
Michal Malohlava & Pavel Parízek, NPRG044, OSGi framework
Lookup strategyLook for the service during component activation
Event strategyLet the DS framework inject the service via defined methodsBind/unbind attributes of the reference declaration
<?xml version="1.0" encoding="UTF-8"?><scr:component name="example.listen" xmlns:scr="http://www.osgi.org/xmlns/scr/v1.1.0"> <implementation class="com.acme.LogLookupImpl"/> <reference name="LOG" interface="org.osgi.service.log.LogService"/></scr:component>
public class LogLookupImpl { private void activate(ComponentContext ctxt) { LogService log = (LogService) ctxt.locateService("LOG"); }}
34
Demo #03
Michal Malohlava & Pavel Parízek, NPRG044, OSGi framework
Write a new bundle with a tester component consuming declared services
Possiblescenario
Try to call the update commandin the console
35
OSGi services
Michal Malohlava & Pavel Parízek, NPRG044, OSGi framework
Logging (LogService)Http (HttpService)
Exposing registered servletsEvent
Messaging Producer <-> ConsumerDevice managerDiagnostics/Monitoring
JMXApplication manager
Application package – set of resources (bundles, data,...)Can be deployed/installed
Location/measurement servicesRemote services
36
Demo #04
Michal Malohlava & Pavel Parízek, NPRG044, OSGi framework
Use HttpService as an additional implementation of ILogTargetIntroduce a new bundle with a component exposing ILogTarget and requiring HttpService
Register HTTP servlet
Launch configuration has to introduce web-server bundlesDon’t forget on
javax.servletorg.eclipse.equinox.http.servletorg.eclipse.equinox.http.jettyorg.eclipse.jetty.*... and few others (check the error messages)
Specify JVM property: -Dorg.osgi.service.http.port=8080
37
OSGi 4.2 features
Michal Malohlava & Pavel Parízek, NPRG044, OSGi framework
Framework launchingRemote servicesBlueprint servicesBundle trackerService hooksConditional permissions
Enterprise features Bundling (WAR), JPA, JNDI, JDBC integration
38
OSGi 4.3 features
Michal Malohlava & Pavel Parízek, NPRG044, OSGi framework
Introduction of generics into the OSGi APICapabilitiesWeaving hook
Bytecode modification
and many others
39
OSGi 5 features
Michal Malohlava & Pavel Parízek, NPRG044, OSGi framework
OSGi Bundle Repository (OBR)Integration with Java ServiceLoader
40
OSGi applications
Michal Malohlava & Pavel Parízek, NPRG044, OSGi framework
Existing applicationsBMW service platformEclipseVirgo server (Spring dm Server)GlassFish J2EE application serverIBM WebSphere J2EE application serverNewtonJBoss, JOnASApache Karaf
UsersBombardier, Volvo, Siemens, BMW, IBM, Red Hat, Siemens AG, NEC, Oracle
41
OSGi implementations
Michal Malohlava & Pavel Parízek, NPRG044, OSGi framework
Open sourceEclipse Equinox
Many extensions of OSGi (bundle aspects, extension points)
Apache FelixBased on Oscar (implementation of OSGi R3)Compliant to OSGi specification R4.2
KnopflerfishConcierge
Implementation of OSGi R3, optimized for embedded devices
CommercialProSyst, Knopflerfish Pro
42
Bundles repositories
Michal Malohlava & Pavel Parízek, NPRG044, OSGi framework
OBRhttp://bundles.osgi.orgOSGi compendium implementation
Springhttp://sigil.codecauldron.org/spring-external.obrhttp://sigil.codecauldron.org/spring-release.obr
Knopflerfishhttp://www.knopflerfish.org/repo/bindex.xml
43
Resources
Michal Malohlava & Pavel Parízek, NPRG044, OSGi framework
OSGi specificationhttp://www.osgi.org/
Wikipedia http://en.wikipedia.org/wiki/OSGi
NPRG044 source codehttp://code.google.com/a/eclipselabs.org/p/nprg044-eclipse-platform/