embrace osgi apache con europe2009

78
Embrace Change Carsten Ziegeler [email protected] OSGi A Developer's Quickstart

Upload: day

Post on 18-May-2015

1.292 views

Category:

Technology


5 download

TRANSCRIPT

Page 1: Embrace OSGi Apache Con Europe2009

Embrace Change

Carsten [email protected]

OSGi

A Developer's Quickstart

Page 2: Embrace OSGi Apache Con Europe2009

About• Member of the ASF

– Sling, Felix, Cocoon, Portals, Sanselan, Excalibur, Incubator

– PMC: Felix, Portals, Cocoon, Incubator, Excalibur (Chair)

• RnD Team at Day Software• Article/Book Author, Technical Reviewer• JSR 286 Spec Group (Portlet API 2.0)

2

Page 3: Embrace OSGi Apache Con Europe2009

Agenda1 Motivation2 And Action...3 Why OSGi?4 Apache Felix 5-7 Bundles, Services, Dynamics8 Famous Final Words

3

Page 4: Embrace OSGi Apache Con Europe2009

Example Application

1 Motivation1 Motivation

4

Page 5: Embrace OSGi Apache Con Europe2009

Motivation• Modularity is key

– Manage growing complexity– Support dynamic extensibility

• No solution in standard Java– OSGi: tried and trusted

• Embrace change – Embrace OSGi– Only a few concepts – easy to get started

5

Page 6: Embrace OSGi Apache Con Europe2009

Example Application

2 And Action...2 And Action...

6

Page 7: Embrace OSGi Apache Con Europe2009

Paint Program• Swing-based paint program• Interface SimpleShape for drawing

– Different implementations– Each shape has name and icon properties– Available shapes are displayed in tool bar

• Select shape and then select location– Shapes can be dragged, but not resized

• Support dynamic deployment of shapes

7

Page 8: Embrace OSGi Apache Con Europe2009

Shape Abstraction• Conceptual SimpleShape interface

public interface SimpleShape{ /** * Method to draw the shape of the service. * @param g2 The graphics object used for * painting. * @param p The position to paint the shape. **/ public void draw(Graphics2D g2, Point p);}

8

Page 9: Embrace OSGi Apache Con Europe2009

Paint Program Mock Up

9

Page 10: Embrace OSGi Apache Con Europe2009

High-Level Architecture

DrawingFrame

ShapeComponent

DefaultShape

SimpleShape

1 1ShapeTracker

1 *

1

1 1

* 1

1

10

Page 11: Embrace OSGi Apache Con Europe2009

High-Level Architecture

DrawingFrame

ShapeComponent

DefaultShape

SimpleShape

1 1 1 *

1

1 1

* 1

1

ShapeTracker

Best practice – Try to centralize interaction with OSGi API so that

other components remain POJOs...only Shape Tracker will

interact with OSGi API.

11

Page 12: Embrace OSGi Apache Con Europe2009

High-Level Architecture

ShapeComponent

DefaultShape

SimpleShape

1 1 1 *

1

1 1

* 1

1

ShapeTracker

DrawingFrame

Main application window – gets

dynamically injected with available shapes

from the Shape Tracker.

12

Page 13: Embrace OSGi Apache Con Europe2009

DrawingFrame

High-Level Architecture

ShapeComponent

1 1 1 *

1

1 1

* 1

1

ShapeTracker

DefaultShape

SimpleShapeActual shape

implementation.

13

Page 14: Embrace OSGi Apache Con Europe2009

DrawingFrame

High-Level Architecture

ShapeComponent

1 1 1 *

1

1 1

* 1

1

ShapeTracker

DefaultShape

SimpleShape

Injected “proxied” shape implementation to hide aspects of dynamism and provide a default

implementation.

Actual shape implementation.

14

Page 15: Embrace OSGi Apache Con Europe2009

SimpleShape

DefaultShape

DrawingFrame

High-Level Architecture

1 1 1 *

1

1 1

* 1

1

ShapeTracker

ShapeComponent

Component that draws the shape in parent frame; looks up shape via Drawing Frame

rather than having a direct reference.

15

Page 16: Embrace OSGi Apache Con Europe2009

Example Application

LIVE DEMO

16

Page 17: Embrace OSGi Apache Con Europe2009

Example Application

3 Why OSGi?3 Why OSGi?

17

Page 18: Embrace OSGi Apache Con Europe2009

Class Path Hell

• Can you spot some potential problems?

18

Page 19: Embrace OSGi Apache Con Europe2009

Class Path Hell

• What libs are used? Versions?• Which jar is used? Version?• No difference between private and public

classes

19

Page 20: Embrace OSGi Apache Con Europe2009

Java's Shortcomings• Simplistic version handling

– “First” class from class path– JAR files assume backwards compatibility at

best• Implicit dependencies

– Dependencies are implicit in class path ordering

– JAR files add improvements for extensions, but cannot control visibility

20

Page 21: Embrace OSGi Apache Con Europe2009

Java's Shortcomings• Split packages by default

– Class path approach searches until it finds, which leads to shadowing or version mixing

• Limited scoping mechanisms– No module access modifier– Impossible to declare all private stuff as

private• Missing module concept

– Classes are too fine grained, packages are too simplistic, class loaders are too low level

• No deployment/lifecycle support21

Page 22: Embrace OSGi Apache Con Europe2009

Java Dynamism Limitations• Low-level support for dynamics

– Class loaders are complicated to use and error prone

• Support for dynamics is still purely manual– Must be completely managed by the

programmer– Leads to many ad hoc, incompatible

solutions• Limited deployment support

22

Page 23: Embrace OSGi Apache Con Europe2009

OSGi Technology• Adds modularity and dynamics

– Module concept• Explicit sharing (importing and exporting)

– Automatic management of code dependencies

• Enforces sophisticated consistency rules for class loading

– Life-cycle management• Manages dynamic deployment and configuration

• Service Registry– Publish/find/bind

23

Page 24: Embrace OSGi Apache Con Europe2009

Example Application

4 Apache Felix4 Apache Felix

24

Page 25: Embrace OSGi Apache Con Europe2009

OSGi Alliance• Industry consortium• OSGi Service Platform specification

– Framework specification for hosting dynamically downloadable services

– Standard service specifications• Several expert groups define the

specifications– Core Platform Expert Group (CPEG)– Mobile Expert Group (MEG)– Vehicle Expert Group (VEG)– Enterprise Expert Group (EEG)

25

Page 26: Embrace OSGi Apache Con Europe2009

Apache Felix• Top-level project (March 2007)• Healthy and diverse community• OSGi R4 (R4.1) implementation

– Framework (frequent releases)– Services (continued development)

• Log, Package Admin, Event Admin,Configuration Admin, Declarative Services,Meta Type, Deployment Admin (and more)

– Moving towards upcoming R4.2• Tools

– Maven Plugins, Web Console, iPojo26

Page 27: Embrace OSGi Apache Con Europe2009

Apache Felix• Growing community

– Several code grants and contributions– Various (Apache) projects use Felix / have

expressed interest in Felix and/or OSGi• e.g., ServiceMix, Directory, Sling, Tuscany

• Roadmap– Continue toward R4 and R4.1 compliance

• some parts consider pre R4.2 already

27

Page 28: Embrace OSGi Apache Con Europe2009

Example Application

5 OSGi – Part 15 OSGi – Part 1 BundlesBundles

28

Page 29: Embrace OSGi Apache Con Europe2009

OSGi Architectural Overview

HardwareDriver Driver Driver

Operating SystemJava

OSGi

Framew

ork

Bundle

29

Page 30: Embrace OSGi Apache Con Europe2009

OSGi Framework Layering

CDCCDC

ExecutionEnvironment

L0 - •OSGi Minimum Execution Environment•CDC/Foundation•JavaSE

MODULEL1 - Creates the concept of modules (aka. bundles) that use classes from each other in a controlled way according to system and bundle constraints

LIFECYCLEL2 - Manages the life cycle of bundle in a bundle repository without requiring the VM be restarted

SERVICE MODEL L3 – Provides a publish/find/bind service model to decouple bundles

30

Page 31: Embrace OSGi Apache Con Europe2009

OSGi Framework• Component-oriented framework• Module concept: Bundles

– Separate class loader -> graph– Package sharing and version management– Life-cycle management and notification

• Dynamic!– Install, update, and uninstall at runtime

• Runs multiple applications and services in a single VM

31

Page 32: Embrace OSGi Apache Con Europe2009

OSGi Modularity• Explicit code boundaries and

dependencies– Package imports and exports

• Multi-version support– Version ranges for dependencies

• Class space is managed by OSGi• Managed life cycle

– Dynamic install, update, uninstall

32

Page 33: Embrace OSGi Apache Con Europe2009

OSGi Modularity - Example• Dynamic module deployment and

dependency resolution

OSGi framework

Provided package

existingbundle

33

Page 34: Embrace OSGi Apache Con Europe2009

OSGi Modularity - Example• Dynamic module deployment and

dependency resolution

OSGi framework

existingbundle

installbundle.jar

34

Page 35: Embrace OSGi Apache Con Europe2009

OSGi Modularity - Example• Dynamic module deployment and

dependency resolution

OSGi framework

existingbundleresolve

bundle

35

Page 36: Embrace OSGi Apache Con Europe2009

OSGi Modularity - Example• Dynamic module deployment and

dependency resolution

OSGi framework

existingbundle

automatic packagedependency resolution

36

Page 37: Embrace OSGi Apache Con Europe2009

Creating a Bundle• Plain old JAR with additional metadata in

the manifest– Bundle identifier, version, exports, imports

• Tools– Text editor (Manifest)– Eclipse (PDE)– Bundle packaging tools

• BND from Peter Kriens• Apache Felix maven-bundle-plugin based on

BND

37

Page 38: Embrace OSGi Apache Con Europe2009

Maven is Your Friend• Apache Felix Maven Bundle Plugin• Creates metadata based on POM

– Automatically: import packages– Manually: export and private packages

• Analyses classes for consistency• Allows to include dependencies• Creates final bundle JAR file

38

Page 39: Embrace OSGi Apache Con Europe2009

Maven Bundle Plugin Sample <artifactId>org.apache.sling.engine</artifactId> <packaging>bundle</packaging> <version>2.0.3-incubator-SNAPSHOT</version> <build> <plugins> <plugin> <groupId>org.apache.felix</groupId> <artifactId>maven-bundle-plugin</artifactId> <extensions>true</extensions> <configuration> <instructions> <Export-Package> org.apache.sling.engine;version=${pom.version} </Export-Package> <Private-Package> org.apache.sling.engine.impl </Private-Package> <Embed-Dependency> commons-fileupload </Embed-Dependency> </instructions>

39

Page 40: Embrace OSGi Apache Con Europe2009

Maven Bundle Plugin Sample <artifactId>org.apache.sling.engine</artifactId> <packaging>bundle</packaging> <version>2.0.3-incubator-SNAPSHOT</version> <build> <plugins> <plugin> <groupId>org.apache.felix</groupId> <artifactId>maven-bundle-plugin</artifactId> <extensions>true</extensions> <configuration> <instructions> <Export-Package> org.apache.sling.engine;version=${pom.version} </Export-Package> <Private-Package> org.apache.sling.engine.impl </Private-Package> <Embed-Dependency> commons-fileupload </Embed-Dependency> </instructions>

40

Page 41: Embrace OSGi Apache Con Europe2009

Maven Bundle Plugin Sample <artifactId>org.apache.sling.engine</artifactId> <packaging>bundle</packaging> <version>2.0.3-incubator-SNAPSHOT</version> <build> <plugins> <plugin> <groupId>org.apache.felix</groupId> <artifactId>maven-bundle-plugin</artifactId> <extensions>true</extensions> <configuration> <instructions> <Export-Package> org.apache.sling.engine;version=${pom.version} </Export-Package> <Private-Package> org.apache.sling.engine.impl </Private-Package> <Embed-Dependency> commons-fileupload </Embed-Dependency> </instructions>

41

Page 42: Embrace OSGi Apache Con Europe2009

Maven Bundle Plugin Sample <artifactId>org.apache.sling.engine</artifactId> <packaging>bundle</packaging> <version>2.0.3-incubator-SNAPSHOT</version> <build> <plugins> <plugin> <groupId>org.apache.felix</groupId> <artifactId>maven-bundle-plugin</artifactId> <extensions>true</extensions> <configuration> <instructions> <Export-Package> org.apache.sling.engine;version=${pom.version} </Export-Package> <Private-Package> org.apache.sling.engine.impl </Private-Package> <Embed-Dependency> commons-fileupload </Embed-Dependency> </instructions>

42

Page 43: Embrace OSGi Apache Con Europe2009

Be Modular!• Create clean package spaces

– public vs private• Provide Bundles

– Add manifest information• Think about dependencies

– Additional bundle vs include– Optional– Version ranges

• Benefits even without OSGi

43

Page 44: Embrace OSGi Apache Con Europe2009

Example Application

6 OSGi – Part 26 OSGi – Part 2 ServicesServices

44

Page 45: Embrace OSGi Apache Con Europe2009

OSGi Services (1/3)• Service-oriented architecture

– Publish/find/bind– Possible to use modules without services

Publish Find

Interact

ServiceRegistry

ServiceProvider

ServiceRequester

ServiceDescription

45

Page 46: Embrace OSGi Apache Con Europe2009

OSGi Services (2/3)• An OSGi application is...

– A collection of bundles that interact via service interfaces

– Bundles may be independently developed and deployed

– Bundles and their associated services may appear or disappear at any time

• Resulting application follows a Service-Oriented Component Model approach

46

Page 47: Embrace OSGi Apache Con Europe2009

OSGi Services (3/3)• Dynamic service lookup

OSGi framework

Provided service

Provided package

existingbundle

component

47

Page 48: Embrace OSGi Apache Con Europe2009

OSGi Services (3/3)• Dynamic service lookup

OSGi framework

existingbundle

componentinstallbundle.jar

48

Page 49: Embrace OSGi Apache Con Europe2009

OSGi Services (3/3)• Dynamic service lookup

OSGi framework

existingbundle

componentactivatebundle

49

Page 50: Embrace OSGi Apache Con Europe2009

OSGi Services (3/3)• Dynamic service lookup

OSGi framework

existingbundle

component

automatic packagedependency resolution

50

Page 51: Embrace OSGi Apache Con Europe2009

OSGi Services (3/3)• Dynamic service lookup

OSGi framework

existingbundle

component

manual servicedependency resolution

51

Page 52: Embrace OSGi Apache Con Europe2009

OSGi Services Advantages• Lightweight services

– Lookup is based on interface name– Direct method invocation

• Good design practice– Separates interface from implementation– Enables reuse, substitutability, loose coupling,

and late binding

52

Page 53: Embrace OSGi Apache Con Europe2009

OSGi Services Advantages• Dynamic

– Loose coupling and late binding• Application's configuration is simply the set of

deployed bundles– Deploy only the bundles that you need

53

Page 54: Embrace OSGi Apache Con Europe2009

OSGi Services Issues• More sophisticated, but more complicated

– Requires a different way of thinking• Things might appear/disappear at any moment

– Must manually resolve and track services• There is help

– Service Tracker• Still somewhat of a manual approach

– Declarative Services, Spring DM, iPOJO• Sophisticated service-oriented component

frameworks• Automated dependency injection and more• More modern, POJO-oriented approaches

54

Page 55: Embrace OSGi Apache Con Europe2009

Example Application

7 OSGi – Part 37 OSGi – Part 3 DynamicsDynamics

55

Page 56: Embrace OSGi Apache Con Europe2009

Everything is a Bundle• How to structure bundles?

– API vs implementation bundle– Fine-grained vs coarse-grained– No “One Size Fits All”

• Simple Rules– Stable code vs changing code– Optional parts

56

Page 57: Embrace OSGi Apache Con Europe2009

Third Party Libraries• Use as bundles

– Project delivers already a bundle• Apache Commons, Apache Sling etc.

– Use special bundle repositories• Felix Commons, Spring etc.• But check included metadata!

– Create your own wrapper• Easy with the Felix maven bundle plugin

• Include in your bundle– Again: easy with the Felix maven bundle

plugin

57

Page 58: Embrace OSGi Apache Con Europe2009

Everything is Dynamic• Bundles can come and go!

– Packages– Services

• Services can come and go!• Be prepaired!

– Application code must handle dynamics!

58

Page 59: Embrace OSGi Apache Con Europe2009

Dynamic Services• OSGi Declarative Services Specification

– XML Configuration • Contained in bundle• Manifest entry pointing to config(s)

– Publishing services– Consuming services

• Policy (static,dynamic), cardinality (0..1, 1..1, 0..n)– Default configuration– Service Lifecycle management

• Various Implementations– Apache Felix SCR

59

Page 60: Embrace OSGi Apache Con Europe2009

Dynamic Services Configuration<scr:component enabled="true" name="org.apache.sling.event.impl.DistributingEventHandler">

<implementation class="org.apache.sling.event.impl.DistributingEventHandler"/>

<service servicefactory="false"> <provide interface="org.osgi.service.event.EventHandler"/> </service>

<property name="repository.path" value="/var/eventing/distribution"/> <property name="cleanup.period" type="Integer" value="15"/>

<reference name="threadPool" interface="org.apache.sling.event.ThreadPool" cardinality="1..1" policy="static" bind="bindThreadPool" unbind="unbindThreadPool"/>

60

Page 61: Embrace OSGi Apache Con Europe2009

Dynamic Services Configuration<scr:component enabled="true" name="org.apache.sling.event.impl.DistributingEventHandler">

<implementation class="org.apache.sling.event.impl.DistributingEventHandler"/>

<service servicefactory="false"> <provide interface="org.osgi.service.event.EventHandler"/> </service>

<property name="repository.path" value="/var/eventing/distribution"/> <property name="cleanup.period" type="Integer" value="15"/>

<reference name="threadPool" interface="org.apache.sling.event.ThreadPool" cardinality="1..1" policy="static" bind="bindThreadPool" unbind="unbindThreadPool"/>

61

Page 62: Embrace OSGi Apache Con Europe2009

Dynamic Services Configuration<scr:component enabled="true" name="org.apache.sling.event.impl.DistributingEventHandler">

<implementation class="org.apache.sling.event.impl.DistributingEventHandler"/>

<service servicefactory="false"> <provide interface="org.osgi.service.event.EventHandler"/> </service>

<property name="repository.path" value="/var/eventing/distribution"/> <property name="cleanup.period" type="Integer" value="15"/>

<reference name="threadPool" interface="org.apache.sling.event.ThreadPool" cardinality="1..1" policy="static" bind="bindThreadPool" unbind="unbindThreadPool"/>

62

Page 63: Embrace OSGi Apache Con Europe2009

Dynamic Services Configuration<scr:component enabled="true" name="org.apache.sling.event.impl.DistributingEventHandler">

<implementation class="org.apache.sling.event.impl.DistributingEventHandler"/>

<service servicefactory="false"> <provide interface="org.osgi.service.event.EventHandler"/> </service>

<property name="repository.path" value="/var/eventing/distribution"/> <property name="cleanup.period" type="Integer" value="15"/>

<reference name="threadPool" interface="org.apache.sling.event.ThreadPool" cardinality="1..1" policy="static" bind="bindThreadPool" unbind="unbindThreadPool"/>

63

Page 64: Embrace OSGi Apache Con Europe2009

Declarative Services• Reads XML configs on bundle start• Registers services• Keeps track of dependencies

– Starts/stops services• Invokes optional activation and

deactivation method– Provides access to configuration

• Caution: A service is by default only started if someone else uses it!– Immediate flag forces a service start

64

Page 65: Embrace OSGi Apache Con Europe2009

Example Service protected ThreadPool threadPool;

protected void activate(ComponentContext context) throws Exception { @SuppressWarnings("unchecked") final Dictionary<String, Object> props = context.getProperties(); this.cleanupPeriod = (Integer)props.get("cleanup.period"); super.activate(context); }

protected void bindThreadPool(ThreadPool p) { this.threadPool = p; }

protected void unbindThreadPool(ThreadPool p) { if ( this.threadPool == p ) { this.threadPool = null; } }

65

Page 66: Embrace OSGi Apache Con Europe2009

Config Admin and Metatype• OSGi Config Admin

– Configuration Manager– Persistence storage– API to retrieve/update/remove configs– Works with Declarative Services

• OSGi Metatype Service– Description of bundle metadata– Description of service configurations

• Various Implementations– Apache Felix

66

Page 67: Embrace OSGi Apache Con Europe2009

Maven SCR Plugin• Combines everything (DS, ConfigAdmin,

Metatype, Maven)• Annotation-based (works for 1.4+)• Annotate components

– Properties with default values– Service providers– Services references (policy and cardinality)

• Generates DS XML• Generates Metatype config• Generates Java code

67

Page 68: Embrace OSGi Apache Con Europe2009

SCR Plugin Sample/** * @scr.component * @scr.property name="repository.path" value="/var/eventing/distribution" private="true" * @scr.service interface="EventHandler" */public class DistributingEventHandler implements EventHandler {

protected static final int DEFAULT_CLEANUP_PERIOD = 15;

/** @scr.property valueRef="DEFAULT_CLEANUP_PERIOD" type="Integer" */ protected static final String PROP_CLEANUP_PERIOD = "cleanup.period";

/** @scr.reference */ protected ThreadPool threadPool;

protected void activate(ComponentContext context) throws Exception { final Dictionary<String, Object> props = context.getProperties(); this.cleanupPeriod = (Integer)props.get(PROP_CLEANUP_PERIOD); }

68

Page 69: Embrace OSGi Apache Con Europe2009

Alternatives• Manually through bundle activator• Apache Felix iPojo• Spring Dynamic Modules

69

Page 70: Embrace OSGi Apache Con Europe2009

Handling extensibility• Two basic implementation strategies

– Service-based approach– Extender model

70

Page 71: Embrace OSGi Apache Con Europe2009

Service Whiteboard Pattern• Clients register a service interface• Service tracker for registered services• Simple, more robust, leverages the OSGi

service model• Service whiteboard pattern

– It is an Inversion of Control pattern

71

Page 72: Embrace OSGi Apache Con Europe2009

Externder Model• Bundles contain manifest entries

– Like available service classes• Custom bundle tracker

– Keeps track of bundles– Specifically, STARTED and STOPPED events– Checks bundles manifest data

• Creates/removes services

72

Page 73: Embrace OSGi Apache Con Europe2009

Example Application

8 Famous8 Famous Final WordsFinal Words

73

Page 74: Embrace OSGi Apache Con Europe2009

Conclusion• Modulary and dynamics are required by

todays applications• OSGi technology addresses Java's

limitations in these areas– Available today and growing in importance

• Development is straightforward and provides immediate benefits

• Apache Felix is ready when you are!

74

Page 75: Embrace OSGi Apache Con Europe2009

Suggestions for Development• Think about modularity!

– Clean package space• Think about dynamics!• Consider OSGi• Check out the spec and other projects• Minimize dependencies to OSGi

– but only if it makes sense

75

Page 76: Embrace OSGi Apache Con Europe2009

Suggestions for Using OSGi• Think about dynamics

– Optional bundles– Optional services– Handle these cases

• Use your preferred logging library– LogManager takes care

• Use available tooling• Be part of the community!

76

Page 77: Embrace OSGi Apache Con Europe2009

Check It Out• Read the OSGi spec

– Framework– Config Admin, Metatype, Declarative

Services– Deployment Admin, OBR

• Download Apache Felix– Try tutorials and samples

• Download Apache Sling :)• Explore the web – embrace OSGi

77

Page 78: Embrace OSGi Apache Con Europe2009

Questions?Questions?Embrace Change

OSGi