Successfully reported this slideshow.
We use your LinkedIn profile and activity data to personalize ads and to show you more relevant ads. You can change your ad preferences anytime.
OSGi Service Platformcore specification v4.2   Ilya Katsov, Grid Dynamics              2010                                1
Agenda                              OSGi motivationOSGi technology overview                              Basics of OSGi ar...
Part IOSGi Technology Overview                           3
OSGi :: 1J2ME – Java in every pocketOSGi – Java server in every pocketDesigned by Open Services Gateway Initiative Allianc...
OSGi :: 2              Remote manager                     bundles                                     Bundles andInitial r...
Challenges :: 1                Presentation                Business logicWeb container        Persistence   Libs          ...
Challenges :: 2  content               controller        checkout          signup  domain                 common          ...
Challenges :: 3  content         controller        checkout       signup       content         controller        checkout ...
Photo by shutterberry (http://www.flickr.com/photos/shutterberry/) ofAutumn Rhythm (Number 30), 1950 by Jackson Pollack.  ...
OSGi motivationThe following drawbacks of Java are crucial for the automaticallydistributable and manageable system:    Li...
OSGi motivationThe following drawbacks of Java are crucial for the automaticallydistributable and manageable system:    Li...
OSGi Service Platform Architecture                                        Bundles      execute                            ...
OSGi specifications                                                           R4 CoreR1 Specification   R2 Specification  ...
What’s up?“OSGi Alliance Publishes Enterprise Specification. Enterprise-tailored specification addresses use cases in ente...
Implementations and usagesOSGi implementations:        Equinox OSGi               Knopflerfish OSGi               Apache F...
Part II     Bundles           Service Layer                           Security    Life Cycle LayerModule Layer OSGi framew...
BundlesA bundle is comprised of Java classes and other resources,which together can provide functions to end users.A bundl...
Class loaders :: 1                               Boot class                                loader  System              Bun...
Class loaders :: 2A class space must be consistent, such that it never contains twoclasses with the same fully qualified n...
Manifest :: format notesHeader is an item of manifest. Common header syntax:                               package-name | ...
Manifest :: version                          2.0.5.GD_v2-patch              major        minor       micro          qualif...
Manifest :: general declarations :: 1Bundle-ManifestVersion The Framework version 1.3 (or later) bundle manifest version m...
Manifest :: general declarations :: 2Bundle-RequiredExecutionEnvironment A bundle can require that a Framework provides a ...
Bundles wiring                 24
Versions   A: Import-Package: p; version="[1,2)"   B: Export-Package: p; version=1.5.1         A                          ...
Package constraints :: 1Package s from B depends on particular version of package p from D(for example s is a service and ...
Package constraints :: 2     A                  B          A: Import-Package: p;t                                   B: Exp...
Class filteringAn exporter can limit the visibility of the classes in a package withthe include and exclude directives on ...
Provider selectionSpecification defines the following headers which may be used[in particular] for wiring:        Bundle-S...
Custom attributes :: 1 We already know that the Import-Package header may be used with the following attributes: version, ...
Custom attributes :: 2The mandatory directive may be used to declare attributes whichmust occur in the import definition. ...
Optional packagesA bundle can indicate that it does not require a package to resolvecorrectly, but it may use the package ...
Resolution directiveThe resolution directive can take the following values:        mandatory        optionalA: Import-Pack...
Dynamic importDynamicImport-Package: org.foo.*Dynamic imports apply only to packages for which no wire has beenestablished...
Fragment bundles :: 1Fragments are bundles that can be attached to one or more hostbundles by the Framework. Attaching is ...
Fragment bundles :: 2Fragment-Host: BundleA-Symbolic-NameThe bundle-version of the host bundle may be specified as an attr...
Fragment bundles :: 3Fragments must remain attached to a host as long as the host remainsresolved. When a host bundle beco...
Fragment bundles :: 3Fragments must remain attached to a host as long as the host remainsresolved. When a host bundle beco...
Fragment bundles :: 3Fragments must remain attached to a host as long as the host remainsresolved. When a host bundle beco...
Fragment bundles :: 3Fragments must remain attached to a host as long as the host remainsresolved. When a host bundle beco...
Extension bundles :: 1Extension bundles can deliver optional parts of the Frameworkimplementation or provide functionality...
Extension bundles :: 2An extension bundle must throw a BundleException if it isinstalled or updated and it specifies any o...
Requiring bundles :: 1The Require-Bundle manifest header contains a list of bundlesymbolic names that need to be searched ...
Requiring bundles :: 2Requiring bundles is quite dangerous and error-prone way to wire bundles.Specification underlines th...
System bundle exportsThe system property       org.osgi.framework.system.packagescontains the export packages descriptions...
Resolving process                    46
Bundle class path :: 1          Bundle JAR     Fragment (id=1) JAR                                Entry path     Fragment ...
Bundle class path :: 2A: Bundle-ClassPath:.,resource.jarB: Fragment-Host: AThe effective class path is A:/, resource.jar, ...
Bundle class path :: 3Fragments can never unilaterally insert code ahead of their host’sbundle class path. Nevertheless ho...
Search order :: 1                    50
Search order :: 2                    51
Search order :: 3                    52
Activation PolicyBundle may specify activation policy in its manifest. Activationmeans triggering of Bundle Activator. The...
Manifest Headers :: 1Bundle-ActivationPolicy: lazyThe Bundle-ActivationPolicy specifies how the framework should activate ...
Manifest Headers :: 2Bundle-DocURL: http:/www.acme.com/Firewall/docThe Bundle-DocURL headers must contain a URL pointing t...
Manifest Headers :: 3Bundle-NativeCode: /lib/http.DLL; osname = QNX; osversion =3.1The Bundle-NativeCode header contains a...
Manifest Headers :: 4DynamicImport-Package: com.acme.plugin.*The DynamicImport-Package header contains a comma-separated l...
Part III     Bundles           Service Layer                           Security    Life Cycle LayerModule Layer OSGi frame...
Interfaces overview    An optional part of a bundle.                          An optional part of a bundle. Initializes   ...
Launching Framework :: 1void launch( String factoryName, File[] bundles )throws Exception {         Map p = new HashMap();...
Launching properties :: 1Map p = new HashMap();...Framework framework = factory.newFramework(p);The Map object given as a ...
Launching properties :: 2org.osgi.framework.executionenvironmentorg.osgi.framework.storage - The framework is free to use ...
Framework Lifecycle     newFramework                                 update                                 stop          ...
Bundle context                 64
BundleContext :: 1A bundles execution context within the Framework. The context isused to grant access to other methods so...
BundleContext :: 2A BundleContext object will be created and provided to the bundleassociated with this context when it is...
Getting bundle informationThe BundleContext interface defines methods to retrieveinformation about bundles installed in th...
Persistent storage and propertiesThe Framework should provide a private persistent storage areafor each installed bundle o...
The bundle object                    69
The Bundle ObjectFor each bundle installed in the OSGi Service Platform, there isan associated Bundle object. The Bundle o...
Bundle Lifecycle :: 1               install                                      update                                   ...
Bundle Lifecycle :: 2When a bundle is installed, it is stored in the persistentstorage of the Framework and remains there ...
Installing and resolving bundlesThe BundleContext defines the following methods forinstalling a bundle:Bundle installBundl...
Starting bundlesThe Bundle defines the following methods:                                 Is used to specify activation po...
ActivationA bundle is activated by calling its Bundle Activator object, if oneexists. The start(BundleContext) method will...
Stopping bundlesThe Bundle defines the following methods:                                 May simply deactivate bundle or ...
Updating bundlesThe Bundle defines the following methods: void update() void update(InputStream input)The update process s...
Uninstalling bundlesThe Bundle defines the following methods: void uninstall()Once this method returns, the state of the O...
Detecting bundle changesThe Framework must keep the time that a bundle is changed byany of the life cycle operations. The ...
Loading classes    One bundle can load classes directly form foreign class loader.           Load plugins from another bun...
Resources    The Bundle interface defines two methods to return manifest    header information:           Dictionary getHe...
The System BundleIn addition to normal bundles, the Framework itself is representedas a bundle. The bundle representing th...
Events         83
EventsBundleEvent        Reports changes in the life cycle of bundles.                   Reports that the Framework is sta...
Bundle listeners         <<interface>>        BundleListener                                   INSTALLED              STOP...
Performance and memory footprintThe OSGi is said to have very little performance overheadStandard java uses linear class p...
Part IV     Bundles           Service Layer                           Security    Life Cycle LayerModule Layer OSGi framew...
Interfaces overview     <<interface>>            Is used to manage service  ServiceRegistration         account           ...
Example of workflow1. Provider bundle contains service implementation and/or interfaces.   Service implementation may opti...
Registering ServicesBundleContext declares the following methods for service registering:ServiceRegistration registerServi...
Service properties :: 1Service properties are used to specify meta information about services.This information may be used...
Service properties :: 2  The Framework supports the following standard properties:Property          Type       Description...
Locating servicesBundle context declares the following methods for service locating:    ServiceReference getServiceReferen...
Getting and releasing service objectBundleContext declares the following methods for service clients:  Object getService(S...
Service FactoryOften, the service object that is registered by a bundle is returneddirectly. If, however, the service obje...
Unregistering Services :: 1The ServiceRegistration interface defines the unregister()method to unregister the service obje...
Unregistering Services :: 2Framework invalidates all ServiceReferences after unregistering, butpointers to service objects...
Service Events BundleContext declares the following methods for listeners registration:void addServiceListener(ServiceList...
Part VBasic Services                 99
Package Admin Service                        100
Packages :: 1The PackageAdmin class provides the following methods:getExportedPackage(String) – Returns an ExportedPackage...
Packages :: 2refreshPackages(Bundle[]) – The management agent may call thismethod to refresh the exported packages of the ...
Packages :: 34. Each bundle in the graph that is in the UNINSTALLED state isremoved from the graph and is now completely r...
BundlesgetBundle(Class) – Answer the bundle with the class loader thatloaded the given class.getBundles(String,String)– Fi...
Fragments and hostsgetFragments(Bundle) – Return an array of bundles that currently actas fragment to the given bundle. If...
Start Level Service                      106
Start levelA start level is defined as a non-negative integer. A start level of 0 isthe state in which the Framework has e...
Start level serviceThe Framework has an active start level that is used to decide whichbundles can be started. All bundles...
Active start levelA Management Agent can influence the active start level with thesetStartLevel(int) method. The Framework...
Start up and shut downAt startup, the Framework must have an active start level of zero. Itmust then move the active start...
Part VIBeyond this presentation                           111
Beyond this presentationSecurity. Platform has powerful mechanisms for security management(roles, permissions, security-re...
Q&A      113
Upcoming SlideShare
Loading in …5
×

OSGi Service Platform 4.2

3,224 views

Published on

Published in: Technology, Business
  • Be the first to comment

OSGi Service Platform 4.2

  1. 1. OSGi Service Platformcore specification v4.2 Ilya Katsov, Grid Dynamics 2010 1
  2. 2. Agenda OSGi motivationOSGi technology overview Basics of OSGi architecture Bundles and ManifestsModule Layer Bundles wiring Class loaders Framework lifecycleLife Cycle Layer Bundle lifecycle Events Registering servicesService Layer Locating services Service events, filters, factories Package Admin serviceStandard services and tools Start Level service 2
  3. 3. Part IOSGi Technology Overview 3
  4. 4. OSGi :: 1J2ME – Java in every pocketOSGi – Java server in every pocketDesigned by Open Services Gateway Initiative Alliance for Digital mobile phones Vehicles Embedded appliances Industrial computers Desktop PCsThe scope of the OSGi Service Platform is: A powerful model for co-existence of different components/applications in a single JVM. A secure environment that executes applications in a sandbox so that these applications cannot harm the environment, nor interfere with other resident applications. A flexible remote management architecture that allows platform operators (the organization that manages the platform) and enterprises to manage thousands or even millions of Service Platforms from a single management domain. A number of standardized, optional services: Logging, Configuration, HTTP, XML, Wiring, IO, Event Handling, Device Discovery and driver loading and many more 4
  5. 5. OSGi :: 2 Remote manager bundles Bundles andInitial request configuration Management agent OSGicontainer container OSGicontainer OSGicontainer OSGicontainer OSGicontainer OSGicontainer OSGi 5
  6. 6. Challenges :: 1 Presentation Business logicWeb container Persistence Libs JRE 6
  7. 7. Challenges :: 2 content controller checkout signup domain common service utils dao messaging gateway assemblercatalina jasper-api hibernate log4j spring xerces el-api servlet-api persistence-api lucenejsp-api tomcat-coyote jdo xstream rt jce jsse javaws charsets dnsns sunmscapi localedata sunpkcs11 plugin 7
  8. 8. Challenges :: 3 content controller checkout signup content controller checkout signup domain common service utils domain common service utils dao messaging gateway assembler dao messaging gateway assemblercatalina jasper-api hibernate log4j catalina jasper-api hibernate log4j spring xerces spring xerces el-api servlet-api el-api servlet-api persistence-api lucene persistence-api lucenejsp-api tomcat-coyote jdo xstream jsp-api tomcat-coyote jdo xstream rt jce jsse javaws charsets dnsns rt jce jsse javaws charsets dnsns sunmscapi localedata sunpkcs11 plugin sunmscapi localedata sunpkcs11 plugin content controller checkout signup content controller checkout signup domain common service utils domain common service utils dao messaging gateway assembler dao messaging gateway assemblercatalina jasper-api hibernate log4j catalina jasper-api hibernate log4j spring xerces spring xerces el-api servlet-api el-api servlet-api persistence-api lucene persistence-api lucenejsp-api tomcat-coyote jdo xstream jsp-api tomcat-coyote jdo xstream rt jce jsse javaws charsets dnsns rt jce jsse javaws charsets dnsns sunmscapi localedata sunpkcs11 plugin sunmscapi localedata sunpkcs11 plugin content controller checkout signup content controller checkout signup domain common service utils domain common service utils dao messaging gateway assembler dao messaging gateway assemblercatalina jasper-api hibernate log4j catalina jasper-api hibernate log4j spring xerces spring xerces el-api servlet-api el-api servlet-api persistence-api lucene persistence-api lucenejsp-api tomcat-coyote jdo xstream jsp-api tomcat-coyote jdo xstream rt jce jsse javaws charsets dnsns rt jce jsse javaws charsets dnsns sunmscapi localedata sunpkcs11 plugin sunmscapi localedata sunpkcs11 plugin 8
  9. 9. Photo by shutterberry (http://www.flickr.com/photos/shutterberry/) ofAutumn Rhythm (Number 30), 1950 by Jackson Pollack. 9
  10. 10. OSGi motivationThe following drawbacks of Java are crucial for the automaticallydistributable and manageable system: Limited deployment and management support Poor support of logical system partitioning Error-prone class path concept Unreliable dynamic updates No versioning in runtime 10
  11. 11. OSGi motivationThe following drawbacks of Java are crucial for the automaticallydistributable and manageable system: Limited deployment and management support Poor support of logical system partitioning Error-prone class path concept Unreliable dynamic updates No versioning in runtime 11
  12. 12. OSGi Service Platform Architecture Bundles execute register, unregister, get, unget class load Security start, stop Service Layer manage Life Cycle Layer install, uninstall Module layer OSGi framework Execution environmentNative libraries OS Hardware 12
  13. 13. OSGi specifications R4 CoreR1 Specification R2 Specification R3 Specification Specification Core Core Core Core Services Services Permission Admin R4 Service Updated R2 Compendium Log services Specification Http Services XML Parser IO Connector Updated R3 services Wiring Admin Event Admin … Monitor Admin … 13
  14. 14. What’s up?“OSGi Alliance Publishes Enterprise Specification. Enterprise-tailored specification addresses use cases in enterprise scenarios. ” OSGi press release 23 Mar 2010“OSGi Cloud Computing Workshop. The Eclipse Foundation andthe OSGi Alliance are organizing a Cloud Workshop at ThursdayMarch 25 during the OSGi DevCon/EclipseCon in Santa Clara…” OSGi press release“In my famous company innoQ I currently have the opportunity towork on a real cool tool: Bundle-Bee. It claims to be able to take anyOSGi bundle and distribute the computational load to an ad-hoc grid(e.g. all machines in an office) without special setup orconfiguration.” Joerg Plewe 28 Jan 2010 14
  15. 15. Implementations and usagesOSGi implementations: Equinox OSGi Knopflerfish OSGi Apache FelixIndustry leading servers moves towards OSGi: Glassfish v3 WebSphere V7 WebLogicMore OSGi projects:“The Spring Dynamic Modules for OSGi(tm) Service Platforms project makes it easy to buildSpring applications that run in an OSGi framework…”“Apache ACE is a software distribution framework that allows you to centrally manage anddistribute software components, configuration data and other artifacts to target systems…”“Apache Sling is an innovative web framework that is intended to bring back the fun to webdevelopment… The embedded Apache Felix…”“The Chameleon project aims to provide a simple way to lay out specific OSGi runtimes fittingyour requirements. The strategy is to provide a layered stack…”“The Apache CXF Distributed OSGi subproject provides the Reference Implementation of theDistribution Provider component of the OSGi Remote Services Specification…” 15
  16. 16. Part II Bundles Service Layer Security Life Cycle LayerModule Layer OSGi framework 16
  17. 17. BundlesA bundle is comprised of Java classes and other resources,which together can provide functions to end users.A bundle is a JAR file that:Contains the resources necessary to provide some functionality.These resources may be class files for the Java programminglanguage, as well as other data such as HTML files, help files,icons, other JRAs, and so on.Contains a manifest file describing the contents of the JAR fileand providing information about the bundle.Can contain optional documentation in the OSGI-OPT directory ofthe JAR file or one of its sub-directories. Management systemsmay remove this information to save storage space in the OSGiService Platform. 17
  18. 18. Class loaders :: 1 Boot class loader System Bundle Bundle Bundlebundle class class class class loader loader loader loaderA class space is then all classes reachable from a given bundle’s classloader. Thus, a class space for a given bundle can contain classes from: The parent class loader (normally java.* packages from the boot class path) Imported packages Required bundles The bundles class path (private packages) Attached fragments 18
  19. 19. Class loaders :: 2A class space must be consistent, such that it never contains twoclasses with the same fully qualified name (to prevent Class CastExceptions). However, separate class spaces in an OSGi Platformmay contain classes with the same fully qualified name.One bundle can access to class loader of other bundle in runtimeunder control of Framework.The Framework must always delegate any package that starts withjava.* to the parent class loader. Other packages that must beloaded from the boot class loader can therefore be specified with theSystem property org.osgi.framework.bootdelegationorg.osgi.framework.bootdelegation=sun.*,com.sun.* 19
  20. 20. Manifest :: format notesHeader is an item of manifest. Common header syntax: package-name | pathImport-Package: com.acme.foo;com.acme.bar;version="[1.23,1.24]";resolution:=mandatory,com.acme.next attribute directiveparameter ::= directive | attributeA Framework implementation must ignore unrecognized manifestheaders, unknown attributes and directives. The bundledeveloper can define additional manifest headers as needed.Organizations that want to use headers that do not clash withOSGi Alliance defined names or bundle header names from otherorganizations should prefix custom headers with x-, forexample x-LazyStart. Organizations external to the OSGi canrequest header names in the OSGi namespace. 20
  21. 21. Manifest :: version 2.0.5.GD_v2-patch major minor micro qualifierSpecification doesn’t define version compatibility policy. However itrecommends the following: major – An incompatible update minor – A backward compatible update micro – A change that does not affect the interface: for example, a bug fix.Version interval is specified using standard mathematical notation:Import-package: com.acme.foo;version=“[1.2, 2)” com.acme.bar;version=7.5.1Single version is interpreted as [version, ∞)Exact version should be specified as [1.5.1, 1.5.1]Default version is 0.0.0Default range is [0.0.0, ∞) 21
  22. 22. Manifest :: general declarations :: 1Bundle-ManifestVersion The Framework version 1.3 (or later) bundle manifest version must be’2’. Bundle manifests written to previous specifications’ manifest syntax are taken to have a bundle manifest version of 1, although there is no way to express this in such manifests.Bundle-SymbolicName The Bundle-SymbolicName manifest header is a mandatory header. The bundle symbolic name and bundle version allow a bundle to be uniquely identified in the Framework. Directive singleton may be specified: Bundle-SymbolicName: com.acme.foo;singleton:=true This directive indicates that the bundle can only have a single version resolved. A value of true indicates that the bundle is a singleton bundle. The default value is false. The Framework must resolve at most one bundle when multiple versions of a singleton bundle with the same symbolic name are installed. Singleton bundles do not affect the resolution of non-singleton bundles with the same symbolic name. 22
  23. 23. Manifest :: general declarations :: 2Bundle-RequiredExecutionEnvironment A bundle can require that a Framework provides a certain execution environment before it is resolved. This header contains comma separated list of the following values: CDC-1.1/Foundation-1.1 Equal to J2ME Foundation Profile OSGi/Minimum-1.2 OSGi EE that is a minimal set that allows the implementation of an OSGi Framework. J2SE-1.2 Java 2 SE 1.2.x J2SE-1.3 Java 2 SE 1.3.x J2SE-1.4 Java 2 SE 1.4.x J2SE-1.5 Java 2 SE 1.5.x JavaSE-1.6 Java SE 1.6.xBundle-Version 23
  24. 24. Bundles wiring 24
  25. 25. Versions A: Import-Package: p; version="[1,2)" B: Export-Package: p; version=1.5.1 A B version=[1,2) p p-1.5.1 C p-2.4.1import export 25
  26. 26. Package constraints :: 1Package s from B depends on particular version of package p from D(for example s is a service and p is a domain object). Client A shouldnot import package p from the arbitrary location: A B s s p p This route is dictated uses by uses directive This route will cause directive ClassCastException C D p-2.1 p-2.4 26
  27. 27. Package constraints :: 2 A B A: Import-Package: p;t B: Export-Package: p;uses:=“q”p p Import-Package: qt q C: Export-Package: q;uses:=“r,s” Import-Package: r;s D: Export-Package: s,t C E: Export-Package: r;uses:=“t” q Import-Package: t r s D E s r t t To maintain class space consistency, the Framework must ensure that none of its bundle imports conflicts with any of that bundle’s implied packages. 27
  28. 28. Class filteringAn exporter can limit the visibility of the classes in a package withthe include and exclude directives on the export definition. Thevalue of each of these directives is a comma-separated list of classnames.Class names must not include their package name and do not endwith .class. That is, the class com.acme.foo.Daffy is named Daffyin either list. The class name can include multiple wildcards (’*’).The ordering of include and exclude is not significant. The defaultfor the include directive is ’*’.Export-Package: com.acme.foo;exclude:=“*Impl” 28
  29. 29. Provider selectionSpecification defines the following headers which may be used[in particular] for wiring: Bundle-SymbolicName Bundle-Version bundle-symbolic-name andThe following definitions will match: bundle-version must not be A: Bundle-SymbolicName: A declared in Export-Package explicitly. The Framework will Import-Package: com.acme.foo; automatically associate this bundle-symbolic-name=B; information. bundle-version="[1.41,2.0)" B: Bundle-SymbolicName: B Bundle-Version: 1.41 Export-Package: com.acme.fooThe following definitions not match because B does notspecify a version and thus defaults to 0.0.0: A: Bundle-SymbolicName: A Import-Package: com.acme.foo; bundle-symbolic-name=B; bundle-version="[1.41,2.0)" B: Bundle-SymbolicName: B Export-Package: com.acme.foo;version=1.42 29
  30. 30. Custom attributes :: 1 We already know that the Import-Package header may be used with the following attributes: version, bundle-symbolic-name, bundle- version. The Export-Package header may be used with the version attribute (bundle-symbolic-name and bundle-version will be added automatically). In accordance with the specification developer may declare custom attributes in the Export-Package and check these attributes in Import-Package. Attributes are compared as strings. The following statements will match because a match is not prevented if the export definition contains attributes that do not occur in the import definition:A: Import-Package: com.acme.foo;company=“ACME”B: Export-Package: com.acme.foo;company="ACME";security=false 30
  31. 31. Custom attributes :: 2The mandatory directive may be used to declare attributes whichmust occur in the import definition. The following statements willnot match because import definition doesn’t specify mandatorysecurity attribute: A: Import-Package: com.acme.foo;company=“ACME” B: Export-Package: com.acme.foo;company="ACME"; security=false;mandatory:=security 31
  32. 32. Optional packagesA bundle can indicate that it does not require a package to resolvecorrectly, but it may use the package if it is available. For example,logging is important, but the absence of a log service should notprevent a bundle from running.Optional imports can be specified in the following ways: Resolution Directive – The resolution directive on an import definition specifying the value optional. A bundle may successfully resolve if a suitable optional package is not present. Dynamic Imports – The DynamicImport-Package header is intended to look for an exported package when that package is needed. The key use case for dynamic import is the Class.forName method when a bundle does not know in advance the class name it may be requested to load.An attempt is made to establish a wire for a dynamic import every timethere is an attempt to load a class in that package, whereas the wirefor a resolution optional package may only be established when thebundle is resolved. 32
  33. 33. Resolution directiveThe resolution directive can take the following values: mandatory optionalA: Import-Package: p; resolution:=optional; version=1.6B: Export-Package: p; q; version=1.5.0The implementation of a bundle that uses optional packages mustbe prepared to handle the fact that the packages may not beavailable: that is, an exception can be thrown when there is areference to a class from a missing package.When an optional package cannot be resolved, any attempts by thebundle to load classes from it will follow normal bundle classloading search order as if the import never existed. 33
  34. 34. Dynamic importDynamicImport-Package: org.foo.*Dynamic imports apply only to packages for which no wire has beenestablished and no definition could be found in any other way. Dynamicimport is used as last resort. This will be discussed later.No directives are architected by the Framework for DynamicImport-Package. Arbitrary matching attributes may be specified. The followingarbitrary matching attributes are architected by the Framework: version – A version range to select the version of an export definition. The default value is 0.0.0. bundle-symbolic-name – The bundle symbolic name of the exporting bundle. bundle-version – a version range to select the bundle version of the exporting bundle. The default value is 0.0.0.Dynamic imports must be searched in the order in which they arespecified. The order is particularly important when package names withwildcards are used. The order will then determine the order in whichmatching occurs. This means that the more specific packagespecifications should appear before the broader specifications. 34
  35. 35. Fragment bundles :: 1Fragments are bundles that can be attached to one or more hostbundles by the Framework. Attaching is done as part of resolving: theFramework appends the relevant definitions of the fragment bundles tothe host’s definitions before the host is resolved.A key use case for fragments is providing translation files for differentlocales. This allows the translation files to be treated and shippedindependently from the main application bundle.All class or resource loading of a fragment is handled through the host’sclass loader or Bundle object, a fragment must never have its own classloader. Fragment bundles are treated as if they are an intrinsic part oftheir hosts. Fragment can’t declare Bundle-Activator header.Fragment can’t declare Bundle-Activator header. A B <<host>> <<fragment>> 35
  36. 36. Fragment bundles :: 2Fragment-Host: BundleA-Symbolic-NameThe bundle-version of the host bundle may be specified as an attribute.Fragments can never unilaterally insert code ahead of their host’sbundle class path. Nevertheless host bundle can allow to insert codeahead of its own code – this will be discussed later. 36
  37. 37. Fragment bundles :: 3Fragments must remain attached to a host as long as the host remainsresolved. When a host bundle becomes unresolved, then all its attachedFragment bundles must be detached from the host bundle. When afragment bundle becomes unresolved the Framework must: 1. Detach it from the host 2. Re-resolve the host bundles 3. Reattach the remaining attached fragment bundles.A Fragment bundle can become unresolved by calling therefreshPackages method. C A B<<fragment>> <<host>> <<fragment>> 37
  38. 38. Fragment bundles :: 3Fragments must remain attached to a host as long as the host remainsresolved. When a host bundle becomes unresolved, then all its attachedFragment bundles must be detached from the host bundle. When afragment bundle becomes unresolved the Framework must: 1. Detach it from the host 2. Re-resolve the host bundles 3. Reattach the remaining attached fragment bundles.A Fragment bundle can become unresolved by calling therefreshPackages method. C A B<<fragment>> <<host>> <<fragment>> 38
  39. 39. Fragment bundles :: 3Fragments must remain attached to a host as long as the host remainsresolved. When a host bundle becomes unresolved, then all its attachedFragment bundles must be detached from the host bundle. When afragment bundle becomes unresolved the Framework must: 1. Detach it from the host 2. Re-resolve the host bundles 3. Reattach the remaining attached fragment bundles.A Fragment bundle can become unresolved by calling therefreshPackages method. C A B<<fragment>> <<host>> <<fragment>> 39
  40. 40. Fragment bundles :: 3Fragments must remain attached to a host as long as the host remainsresolved. When a host bundle becomes unresolved, then all its attachedFragment bundles must be detached from the host bundle. When afragment bundle becomes unresolved the Framework must: 1. Detach it from the host 2. Re-resolve the host bundles 3. Reattach the remaining attached fragment bundles.A Fragment bundle can become unresolved by calling therefreshPackages method. C A B<<fragment>> <<host>> <<fragment>> 40
  41. 41. Extension bundles :: 1Extension bundles can deliver optional parts of the Frameworkimplementation or provide functionality that must reside on the bootclass path. These packages cannot be provided by the normalimport/export mechanisms.Fragment-Host: com.acme.impl.framework; extension:=frameworkDirective extension is only applicable when the Fragment-Host is theSystem Bundle. The following values are supported: framework – The fragment bundle is a Framework extension bundle. Framework extensions are necessary to provide implementation aspects of the Framework. For example, a Framework vendor could supply the optional services like Permission Admin service and Start Level service with Framework extension bundles. bootclasspath – The fragment bundle is a boot class path extension bundle. Boot class path extensions are necessary because certain package implementations assume that they are on the boot class path or are required to be available to all clients. 41
  42. 42. Extension bundles :: 2An extension bundle must throw a BundleException if it isinstalled or updated and it specifies any of the following headers: Import-Package Require-Bundle Bundle-NativeCode DynamicImport-Package Bundle-Activator 42
  43. 43. Requiring bundles :: 1The Require-Bundle manifest header contains a list of bundlesymbolic names that need to be searched after the imports aresearched but before the bundle’s class path is searched. Fragment orextension bundles can not be required.The framework must take all exported packages from a requiredbundle, including any packages exported by attached fragments, andwire these packages to the requiring bundle.The following directives can be used in the Require-Bundle header: visibility – If the value is private (default), then all visible packages from the required bundles are not re-exported. If the value is reexport then bundles that require this bundle will transitively have access to these required bundle’s exported packages. resolution – If the value is mandatory (default) then the required bundle must exist for this bundle to resolve. If the value is optional, the bundle will resolve even if the required bundle does not exist. 43
  44. 44. Requiring bundles :: 2Requiring bundles is quite dangerous and error-prone way to wire bundles.Specification underlines the following drawbacks of this approach: Split Packages – Classes from the same package can come from different bundles with Require bundle, such a package is called a split package. Completeness – Split packages are open ended, it is difficult to guarantee that all the intended pieces of a split package have actually been included. Ordering – If the same classes are present in more than one required bundle, then the ordering of Require-Bundle is significant. A wrong ordering can cause hard to trace errors, similar to the traditional class path model of Java. Performance – A class must be searched in all providers when packages are split. This potentially increases the number of times that a ClassNotFoundException must be thrown which can potentially introduce a significant overhead. Mutable Exports – The feature of visibility:=reexport that the export signature of the requiring bundle can unexpectedly change depending on the export signature of the required bundle. Shadowing – The classes in the requiring bundle that are shadowed by those in a required bundle depend on the export signature of the required bundle and the classes the required bundle contains. 44
  45. 45. System bundle exportsThe system property org.osgi.framework.system.packagescontains the export packages descriptions for the system bundle.Framework implementations should attempt to load these classesfrom the boot class path. 45
  46. 46. Resolving process 46
  47. 47. Bundle class path :: 1 Bundle JAR Fragment (id=1) JAR Entry path Fragment (id=2) JAR Fragment (id=3) JARThe Bundle-ClassPath header may be declared in manifest in order tomanage class path.The content of the effective bundle class path is constructed from thebundle’s Bundle-Classpath header, concatenated with the Bundle-Classpath headers of any fragments, in ascending bundle id order. 47
  48. 48. Bundle class path :: 2A: Bundle-ClassPath:.,resource.jarB: Fragment-Host: AThe effective class path is A:/, resource.jar, B:/resource.jar is first looked up in the host bundle’s container, and ifnot found, the entry is looked up in the container of B. 48
  49. 49. Bundle class path :: 3Fragments can never unilaterally insert code ahead of their host’sbundle class path. Nevertheless host bundle can allow to insert codeahead of its own code.A: Bundle-SymbolicName: A Bundle-ClassPath:.,required.jar,optional,default.jarB: Bundle-SymbolicName: B Fragment-Host: A A B required.jar optional/.. default.jar fragment.jarThe effective class path is:A:/A: required.jarB: optionalA: default.jarB: fragment.jar 49
  50. 50. Search order :: 1 50
  51. 51. Search order :: 2 51
  52. 52. Search order :: 3 52
  53. 53. Activation PolicyBundle may specify activation policy in its manifest. Activationmeans triggering of Bundle Activator. The only policy defined is thelazy activation policy. If no Bundle-ActivationPolicyheader is specified, the bundle will use eager activation.By default, any class load can trigger the lazy activation, however,resource loads must not trigger the activation. The lazy activationpolicy can define which classes cause the activation with thefollowing directives:include – A list of package names that must trigger the activationwhen a class is loaded from any of these packages. The default is allpackage names present in the bundle.exclude – A list of package names that must not trigger theactivation of the bundle when a class is loaded from any of thesepackages. The default is no package names.Bundle-ActivationPolicy: lazy;include:="com.acme.service.base,com.acme.service.help" 53
  54. 54. Manifest Headers :: 1Bundle-ActivationPolicy: lazyThe Bundle-ActivationPolicy specifies how the framework should activate the bundle once started.Bundle-Activator: com.acme.fw.ActivatorThe Bundle-Activator header specifies the name of the class used to start and stop the bundle.Bundle-Category: osgi, test, nurseryThe Bundle-Category header holds a comma-separated list of category names.Bundle-ClassPath: /jar/http.jar,.The Bundle-ClassPath header defines a comma-separated list of JAR file path names or directories(inside the bundle) containing classes and resources. The period (’.’) specifies the root directory ofthe bundle’s JAR. The period is also the default.Bundle-ContactAddress: 2400 Oswego Road, Austin, TX 74563The Bundle-ContactAddress header provides the contact address of the vendor.Bundle-Copyright: OSGi (c) 2002The Bundle-Copyright header contains the copyright specification for thisbundle.Bundle-Description: Network FirewallThe Bundle-Description header defines a short description of this bundle. 54
  55. 55. Manifest Headers :: 2Bundle-DocURL: http:/www.acme.com/Firewall/docThe Bundle-DocURL headers must contain a URL pointing to documentationabout this bundle.Bundle-Icon: /icons/acme-logo.pngThe optional Bundle-Icon header provides a list of URLs to icons representingthis bundle in different sizes.Bundle-License:http://www.opensource.org/licenses/jabberpl.phpThe Bundle-License header provides an optional machine readable form of license information.Bundle-Localization: OSGI-INF/l10n/bundleThe Bundle-Localization header contains the location in the bundle where localization files can befound. The default value is OSGI-INF/l10n/bundle. Translations are by default therefore OSGI-INF/l10n/bundle_de.properties, OSGI-INF/l10n/bundle_nl.propertiesBundle-ManifestVersion: 2The Bundle-ManifestVersion header defines that the bundle follows the rules of this specification.The Bundle-ManifestVersion header determines whether the bundle follows the rules of thisspecification. It is 1 (the default) for Release 3 Bundles, 2 for Release 4 and later.Bundle-Name: FirewallThe Bundle-Name header defines a readable name for this bundle. This should be a short, human-readable name that can contain spaces. 55
  56. 56. Manifest Headers :: 3Bundle-NativeCode: /lib/http.DLL; osname = QNX; osversion =3.1The Bundle-NativeCode header contains a specification of native codelibraries contained in this bundle.Bundle-RequiredExecutionEnvironment: CDC-1.0/Foundation-1.0The Bundle-RequiredExecutionEnvironment contains a comma-separated list of executionenvironments that must be present on the Service Platform.Bundle-SymbolicName: com.acme.daffyThe Bundle-SymbolicName header specifies a non-localizable name for this bundle. The bundlesymbolic name together with a version must identify a unique bundle.Bundle-UpdateLocation:http://www.acme.com/Firewall/bundle.jarThe Bundle-UpdateLocation header specifies a URL where an update for this bundle should comefrom. If the bundle is updated, this location should be used, if present, to retrieve the updated JARfile.Bundle-Vendor: OSGi AllianceThe Bundle-Vendor header contains a human-readable description of the bundle vendor.Bundle-Version: 1.1The Bundle-Version header specifies the version of this bundle. 56
  57. 57. Manifest Headers :: 4DynamicImport-Package: com.acme.plugin.*The DynamicImport-Package header contains a comma-separated list ofpackage names that should be dynamically imported when needed.Export-Package: org.osgi.util.tracker;version=1.3The Export-Package header contains a declaration of exported packages.Export-Service: org.osgi.service.log.LogServiceDeprecated.Fragment-Host: org.eclipse.swt; bundle-version="[3.0.0,4.0.0)"The Fragment-Host header defines the host bundles for this fragment.Import-Package:org.osgi.util.tracker,org.osgi.service.io;version=1.4The Import-Package header declares the imported packages for this bundle.Import-Service: org.osgi.service.log.LogServiceDeprecatedRequire-Bundle: com.acme.chessThe Require-Bundle header specifies that all exported packages fromanother bundle must be imported, effectively requiring the public interfaceof another bundle. 57
  58. 58. Part III Bundles Service Layer Security Life Cycle LayerModule Layer OSGi framework 58
  59. 59. Interfaces overview An optional part of a bundle. An optional part of a bundle. Initializes Enables bundle to listen events bundle. Framework passes personal BundleContext to each activator <<interface>> <<register>> <<interface>> BundleListener BundleActivator <<create>> <<interface>> <<register>> FrameworkListener <<receive>> Is used tostart, stop, <<install new>> update <<interface>> <<interface>>bundle and Bundle BundleContext control its <<association>> state andparameters Each bundle has its own instance of context and each context has a context bundleFramework <<interface>> <<create>> <<interface>> Is used tois a bundle Framework FrameworkFactory instantiate the Framework 59
  60. 60. Launching Framework :: 1void launch( String factoryName, File[] bundles )throws Exception { Map p = new HashMap(); p.put( "org.osgi.framework.storage", System.getProperties("user.home")+File.separator+"osgi"); FrameworkFactory factory = (FrameworkFactory) Class.forName( factoryName ).newInstance(); Framework framework = factory.newFramework(p); framework.init(); // Framework state is STARTING, context is available, bundles are in // INSTALLED state BundleContext context = framework.getBundleContext(); for ( File bundle : bundles ) context.installBundle( bundle.toURL().toString() ); framework.start(); // Framework and bundles are in ACTIVE state, services may be // obtained via getService framework.waitForStop(); // Framework releases any resources and goes to RESOLVED state, may // be started again} 60
  61. 61. Launching properties :: 1Map p = new HashMap();...Framework framework = factory.newFramework(p);The Map object given as a parameter to the newFrameworkmethod provides the initialization properties to the framework.The framework must not look in the System properties, thegiven Map is complete. 61
  62. 62. Launching properties :: 2org.osgi.framework.executionenvironmentorg.osgi.framework.storage - The framework is free to use thisdirectory as it sees fit, for example, completely erase all files anddirectories in it.org.osgi.framework.system.packages - The packages that should beexported from the System Bundle.org.osgi.framework.system.packages.extra - Packages specified inthis property are added to the org.osgi.framework.system.packagesproperty and therefore have the same syntax. This allows theconfigurator to only define the additional packages and leave thestandard VM packages to be defined by the framework.org.osgi.framework.trust.repositories - This property is used toconfigure trust repositories for the framework. The value is path of files. 62
  63. 63. Framework Lifecycle newFramework update stop init INSTALLED STARTING init startupdate start start initstop init start RESOLVED ACTIVE stop update stop update stop update start STOPPING init update stops the Framework and restarts to its previous state 63
  64. 64. Bundle context 64
  65. 65. BundleContext :: 1A bundles execution context within the Framework. The context isused to grant access to other methods so that this bundle can interactwith the Framework.BundleContext methods allow a bundle to: Subscribe to events published by the Framework. Register service objects with the Framework service registry. Retrieve ServiceReferences from the Framework service registry. Get and release service objects for a referenced service. Install new bundles in the Framework. Get the list of bundles installed in the Framework. Get the Bundle object for a bundle. Create File objects for files in a persistent storage area provided for the bundle by the Framework. 65
  66. 66. BundleContext :: 2A BundleContext object will be created and provided to the bundleassociated with this context when it is started using theBundleActivator.start(org.osgi.framework.BundleContext)method. The same BundleContext object will be passed to thebundle associated with this context when it is stopped using theBundleActivator.stop(org.osgi.framework.BundleContext)method. A BundleContext object is generally for the private use ofits associated bundle and is not meant to be shared with otherbundles in the OSGi environment.The Bundle object associated with a BundleContext object iscalled the context bundle.The BundleContext object is only valid during the execution of itscontext bundle. The BundleContext object must never be reusedafter its context bundle is stopped. 66
  67. 67. Getting bundle informationThe BundleContext interface defines methods to retrieveinformation about bundles installed in the OSGi Service Platform: getBundle() – Returns the single Bundle object associated with the BundleContext object. getBundles() – Returns an array of the bundles currently installed in the Framework. getBundle(long) – Returns the Bundle object specified by the unique identifier, or null if no matching bundle is found. 67
  68. 68. Persistent storage and propertiesThe Framework should provide a private persistent storage areafor each installed bundle on platforms with some form of filesystem support. BundleContext interface defines the followingmethod: File getDataFile(String filename)The BundleContext interface defines a method for returninginformation pertaining to Framework properties:getProperty(String). In particular the following properties aresupported: org.osgi.framework.version org.osgi.framework.processor org.osgi.framework.os.name 68
  69. 69. The bundle object 69
  70. 70. The Bundle ObjectFor each bundle installed in the OSGi Service Platform, there isan associated Bundle object. The Bundle object for a bundle canbe used to manage the bundle’s life cycle.Bundle is identified by: Bundle Identifier - A long that is a Framework assigned unique identifier for the full lifetime of a bundle, even if it is updated or the Framework is restarted. Bundle location – A name assigned by the management agent (Operator) to a bundle during the installation. This string is normally interpreted as a URL to the JAR file but this is not mandatory. Within a particular Framework, a location must be unique. Bundle Symbolic Name and Bundle Version – A name and version assigned by the developer. The combination of Bundle Version and Bundle Symbolic Name is a globally unique identifier for a bundle. 70
  71. 71. Bundle Lifecycle :: 1 install update refresh INSTALLED STARTING refresh resolve update start RESOLVED ACTIVEuninstall uninstall stop UNINSTALLED STOPPING 71
  72. 72. Bundle Lifecycle :: 2When a bundle is installed, it is stored in the persistentstorage of the Framework and remains there until it isexplicitly uninstalled. Whether a bundle has been started orstopped must be recorded in the persistent storage of theFramework. A bundle that has been persistently recorded asstarted must be started whenever the Framework starts untilthe bundle is explicitly stopped. 72
  73. 73. Installing and resolving bundlesThe BundleContext defines the following methods forinstalling a bundle:Bundle installBundle(String location)Bundle installBundle(String location, InputStream input) Will be used as identifierEvery bundle is uniquely identified by its location string. If aninstalled bundle is using the specified location, theinstallBundle methods must return the Bundle object forthat installed bundle and not install a new bundle.The returned bundle may be in INSTALLED or RESOLVED state.The Framework decides when to resolve bundle, resolvingcan’t be triggered via Bundle or BundleContext API. 73
  74. 74. Starting bundlesThe Bundle defines the following methods: Is used to specify activation policy for void start() current start and/or alter persistent void start(int options) autostart settingEach bundle is associated with persistent autostart setting.This setting can have the following values: Stopped – The bundle should not be started. Started with eager activation – The bundle must be started once it is ready and it must then be eagerly activated. Started with declared activation – The bundle must be started once it is ready and it must then be activated according to its declared activation policy (Bundle- ActivationPolicy). 74
  75. 75. ActivationA bundle is activated by calling its Bundle Activator object, if oneexists. The start(BundleContext) method will be called.Fragment bundles must not have a Bundle Activator specified.Activation policy: Bundle may specify activation policy in its manifest. The only policy defined is the lazy activation policy. If no Bundle- ActivationPolicy header is specified, the bundle will use eager activation A lazy activation policy indicates that the bundle, once started, must not be activated until a class is loaded from it; either during normal class loading or via the Bundle loadClass method. The lazy activation policy allows a Framework implementation to defer the creation of the bundle class loader and activation of the bundle until the bundle is first used; potentially saving resources and initialization time during startup. Started bundle has state STARTING until activation. After successful activation state is ACTIVE. 75
  76. 76. Stopping bundlesThe Bundle defines the following methods: May simply deactivate bundle or set void stop() autostart setting to Stopped void stop(int options)A bundle is deactivated by calling its Bundle Activator object, ifone exists. The stop(BundleContext) method will be called. 76
  77. 77. Updating bundlesThe Bundle defines the following methods: void update() void update(InputStream input)The update process supports migration from one version of abundle to a newer version of the same bundle. The exports of anupdated bundle must be immediately available to theFramework. If none of the old exports are used, then the oldexports must be removed. Otherwise, all old exports mustremain available for existing bundles and future resolves untilthe refreshPackages method is called or the Framework isrestarted. The refreshPackages method will be discussed later.After the update operation is complete, the framework mustattempt to move the bundle to the same state as it was beforethe operation taking the activation policy into account, withoutchanging the autostart setting. 77
  78. 78. Uninstalling bundlesThe Bundle defines the following methods: void uninstall()Once this method returns, the state of the OSGi Service Platformmust be the same as if the bundle had never been installed,unless bundle exports packages or bundle was selected by theFramework as the exporter of packages. If none of the oldexports are used, then the old exports must be removed.Otherwise, all old exports must remain available for existingbundles and future resolves until the refreshPackages methodis called or the Framework is restarted. 78
  79. 79. Detecting bundle changesThe Framework must keep the time that a bundle is changed byany of the life cycle operations. The getLastModified() methodwill return the last time the bundle was installed, updated, oruninstalled. This last modified time must be stored persistently. 79
  80. 80. Loading classes One bundle can load classes directly form foreign class loader. Load plugins from another bundle Start an application model activator Interact with legacy codeBundleContext A 1: Bundle getBundle(long id) 2: Class loadClass(String name) Bundle A Bundle B Class Loader B Class X 80
  81. 81. Resources The Bundle interface defines two methods to return manifest header information: Dictionary getHeaders() Dictionary getHeaders(String locale) The resources from a bundle can come from different sources. They can come from the raw JAR file, Fragment bundles, imported packages, or the bundle class path. The Bundle interface provides a number of methods that access resources but use different strategies:java.net.URL getResource(java.lang.String name)- provideaccess to resources that is consistent with the class space asdescribed in Overall Search Order.findEntries(String path, String filePattern, booleanrecurse) - Returns entries in this bundle and its attached fragments(scans JARs). Required bundles will not be scaned.getEntry(String path) - Returns a URL to the entry at thespecified path in this bundle (scan JAR). 81
  82. 82. The System BundleIn addition to normal bundles, the Framework itself is representedas a bundle. The bundle representing the Framework is referred toas the system bundle.The system bundle is listed in the set of installed bundles returnedby BundleContext.getBundles()The system bundle is always assigned a bundle identifier of zero.The system bundle’s life cycle cannot be managed like normalbundles. Its life cycle methods must behave as follows:start – Does nothing because the system bundle is already started.stop – Returns immediately and shuts down the Framework onanother thread.update – Returns immediately, then stops and restarts theFramework on another thread.uninstall – The Framework must throw a BundleExceptionindicating that the system bundle cannot be uninstalled. 82
  83. 83. Events 83
  84. 84. EventsBundleEvent Reports changes in the life cycle of bundles. Reports that the Framework is started, start levelFrameworkEvent has changed, packages have been refreshed, or that an error has been encountered.BundleContext defines the following methods: void addBundleListener(BundleListener listener) void addFrameworkListener(FrameworkListener listener) void removeBundleListener(BundleListener listener) void removeFrameworkListener(FrameworkListener listener)Bundle listeners may be synchronous or asynchronous, frameworklisteners are asynchronous. 84
  85. 85. Bundle listeners <<interface>> BundleListener INSTALLED STOPPEDbundleChanged(BundleEvent event) LAZY_ACTIVATION STOPPING RESOLVED UNINSTALLED STARTED UNRESOLVED <<interface>> STARTING UPDATED SynchronousBundleListener SynchronousBundleListener objects are called synchronously during the processing of the event and must be called before any BundleListener object is called. Asynchronous delivery: The Framework may use one or more threads to hit listeners but each handler must receive the events in the same order as the events were posted. Synchronous delivery: In rare cases, events can be delivered out of order to a listener. One pathological case is when a service listener unregisters a service that it receives in the REGISTERED event for. If there are listeners queued behind the pathological listener then they see the unregistering before they see the registration. 85
  86. 86. Performance and memory footprintThe OSGi is said to have very little performance overheadStandard java uses linear class path. OSGi supports fast classloading because information about classes and class loaders isusually indexed in a hash table. Nevertheless initialization is saidto be a bottleneck: 1 second per bundle is an extra minute boot time for a system with 60 bundles Don’t use name lookups and network access in the bundle activators Initialization process should be spread in time by means of lazy initializationEach bundle has its own class loader and class loaders are said tobe expensive. Don’t start to many bundles; stop unused bundles. 86
  87. 87. Part IV Bundles Service Layer Security Life Cycle LayerModule Layer OSGi framework 87
  88. 88. Interfaces overview <<interface>> Is used to manage service ServiceRegistration account <<interface>> ServiceFactory <<create>> <<may implement>> <<interface>> <<register/unregister, get/unget>> BundleContext Service <<locate>> <<register>> <<interface>> Is used to obtain service, its ServiceReference <<interface>> properties and providing bundle ServiceListener<<navigate>> <<navigate>> <<interface>> Provides information about Bundle <<create>> exported and used services 88
  89. 89. Example of workflow1. Provider bundle contains service implementation and/or interfaces. Service implementation may optionally implement ServiceFactory interface.2. Provider bundle registers new service via BundleContext and stores returned ServiceRegistration.3. Client bundle locates ServiceReference by service name and filters via BundleContext.4. Client obtains actual service object by ServiceReference via BundleContext.5. Client works with service.6. Client releases service object via BundleContext.7. Provider unregisters service via ServiceRegistration.8. The Framework publishes unregistering event. All clients must clear references to service object. 89
  90. 90. Registering ServicesBundleContext declares the following methods for service registering:ServiceRegistration registerService(String clazz, Object service, Dictionary properties)ServiceRegistration registerService(String[] clazz, Object service, Dictionary properties) clazz – Interface name(s) service – Service implementation properties – Service propertiesEvery successful service object registration must yield a uniqueServiceRegistration object even if the same service object is registeredmultiple times. 90
  91. 91. Service properties :: 1Service properties are used to specify meta information about services.This information may be used to filter services during location. The values of properties should be limited to primitive or standard Java types to prevent unwanted inter bundle dependencies. Key must be a String and value should be a type recognized by Filter objects (if value is not a String, it should implement Comparable and have constructor taking single String object). The key of a property is not case sensitive. When a Dictionary object that contains keys that only differ in case is passed, the Framework must raise an exception. All properties share a single name space in the Framework service registry. The service properties are intended to provide information about the service object. The properties should not be used to participate in the actual function of the service. Modifying the properties for the service registration is a potentially expensive operation. 91
  92. 92. Service properties :: 2 The Framework supports the following standard properties:Property Type Descriptionservice.id Long The Framework assigns a unique value to every registered service object that is larger than values provided to all previously registered service objects.service.pid Long The purpose of a Persistent Identifier (PID) is to identify a service across Framework restarts. If the bundle is stopped and later started, the same PID must always be used.service.ranking Integer When registering a service object, a bundle may optionally specify a service.ranking number as one of the service object’s properties. If multiple qualifying service interfaces exist, a service with the highest SERVICE_RANKING number determines which service object is returned by the Framework.objectClass String[] The objectClass property contains the set of interface names under which a service object is registered with the Framework. The Framework must set this property automatically. 92
  93. 93. Locating servicesBundle context declares the following methods for service locating: ServiceReference getServiceReference(String clazz) If multiple such services exist, the service with the highest ranking is returned. If there is a tie in ranking, the service with the lowest service ID; that is, the service that was registered first is returned. ServiceReference[] getServiceReferences(String clazz, String filter) The returned array of ServiceReference objects contains services that were registered under the specified class, match the specified filter criteria, and the packages for the class names under which the services were registered match the context bundles packages. ServiceReference[] getAllServiceReferences(String clazz, String filter) As previous but doesn’t check that package under which the services were registered are assignable to the context bundle’s packages. This method is infrastructural, it shouldn’t be used for ordinal service location. 93
  94. 94. Getting and releasing service objectBundleContext declares the following methods for service clients: Object getService(ServiceReference reference) boolean ungetService(ServiceReference reference) true if actually unregistered, false if service is not [already] associated with bundle 94
  95. 95. Service FactoryOften, the service object that is registered by a bundle is returneddirectly. If, however, the service object that is registered implementsthe ServiceFactory interface, the Framework must call methods on thisobject to create a unique service object for each distinct bundle thatgets the service. Object getService(Bundle bundle, ServiceRegistration registration) void ungetService(Bundle bundle, ServiceRegistration registration, Object service) The Framework calls getService if the bundle’s usage count of that service object is zero. After this the Framework must cache the mapping of the bundle-to-service request, and return the cached service object.The Framework must check the service object returned by this method.If it is not an instance of all the classes named when the service factorywas registered, null is returned to the caller that called getService.The Framework calls ungetService if the bundle’s usage count for thatservice object must drop to zero after this call returns; that is, thebundle is about to release its last dependency on the service object. 95
  96. 96. Unregistering Services :: 1The ServiceRegistration interface defines the unregister()method to unregister the service object. This must remove theservice object from the Framework service registry.ServiceEvent.UNREGISTERING will be published.The bundle that unregisters a service object might not be the samebundle that registered it. 96
  97. 97. Unregistering Services :: 2Framework invalidates all ServiceReferences after unregistering, butpointers to service objects can not be cleared by framework. Bundlesmust listen to events generated by the Framework to clean up andremove stale references.Service developers can minimize the consequences of (but notcompletely prevent) stale references by using the followingmechanisms: Implement service objects using the ServiceFactory interface. The methods in the ServiceFactory interface simplify tracking bundles that use their service objects. Use indirection in the service object implementations. Service objects handed out to other bundles should use a pointer to the actual service object implementation. When the service object becomes invalid, the pointer is set to null, effectively removing the reference to the actual service object. 97
  98. 98. Service Events BundleContext declares the following methods for listeners registration:void addServiceListener(ServiceListener listener)void addServiceListener(ServiceListener listener, String filter)void removeServiceListener(ServiceListener listener) REGISTERED – A service has been registered. MODIFIED – The properties of a service have been modified. MODIFIED_ENDMATCH – Listeners registered with a filter can not see the MODIFIED event when a modification makes this filter no longer match. The lack of this notification complicates tracking a service with a filter. The MODIFIED_ENDMATCH event is therefore delivered if the old service properties matched the given filter but the modified properties do not. UNREGISTERING – A service is in the process of being unregistered. This event is synchronously delivered before the service has completed unregistering. That is, the service object is still valid. The bundle receiving this event must release all references to this service before this method returns. 98
  99. 99. Part VBasic Services 99
  100. 100. Package Admin Service 100
  101. 101. Packages :: 1The PackageAdmin class provides the following methods:getExportedPackage(String) – Returns an ExportedPackage objectthat provides information about the requested package. Thisinformation can be used to make the decision to refresh the package.getExportedPackages(Bundle) – Returns a list of ExportedPackageobjects for each package that the given bundle exports.resolveBundles(Bundle[]) – The Framework must attempt to resolvethe given bundles. 101
  102. 102. Packages :: 2refreshPackages(Bundle[]) – The management agent may call thismethod to refresh the exported packages of the specified bundles. 1. Compute a graph of bundles starting with the specified bundles. If no bundles are specified, compute a graph of bundles starting with bundle updated or uninstalled since the last call to this method. Add to the graph any bundle that is wired to a package that is currently exported by a bundle in the graph. The graph is fully constructed when there is no bundle outside the graph that is wired to a bundle in the graph. The graph may contain UNINSTALLED bundles that are currently still exporting packages. 2. Each bundle in the graph that is in the ACTIVE state will be stopped as described in the Bundle.stop method. 3. Each bundle in the graph that is in the RESOLVED state is unresolved and thus moved to the INSTALLED state. The effect of this step is that bundles in the graph are no longer RESOLVED. 102
  103. 103. Packages :: 34. Each bundle in the graph that is in the UNINSTALLED state isremoved from the graph and is now completely removed fromthe Framework.5. Each bundle in the graph that was in the ACTIVE state prior toStep 2 is started as described in the Bundle.start method,causing all bundles required for the restart to be resolved.6. A framework event of typeFrameworkEvent.PACKAGES_REFRESHED is fired. 103
  104. 104. BundlesgetBundle(Class) – Answer the bundle with the class loader thatloaded the given class.getBundles(String,String)– Find a the set of bundles with the givenbundle symbolic name and that fall within the given version. If theversion is null, all bundles with the given bundle symbolic name arereturned.getBundleType(Bundle) – Answer the type of the bundle. This is abitmap of the different types. 104
  105. 105. Fragments and hostsgetFragments(Bundle) – Return an array of bundles that currently actas fragment to the given bundle. If there are no fragments attached,null must be returned.getHosts(Bundle) – Return the bundles that acts as host to thisfragment bundle. The given bundle should be an attached fragmentbundle, otherwise null is returned.getRequiredBundles(String) – Return an array of RequiredBundleobjects that match the given name (or all of the given name is null).The RequiredBundle object provides structural information about arequired bundle. 105
  106. 106. Start Level Service 106
  107. 107. Start levelA start level is defined as a non-negative integer. A start level of 0 isthe state in which the Framework has either not been launched orhas completed shutdown (these two states are consideredequivalent). In this state, no bundles are running. Progressivelyhigher integral values represent progressively higher start levels.For example, 2 is a higher start level than 1. The Framework mustsupport all positive int values (Integer.MAX_VALUE) for start levels.The System Bundle is defined to have a start level of zero. The startlevel of the System Bundle cannot be changed. 107
  108. 108. Start level serviceThe Framework has an active start level that is used to decide whichbundles can be started. All bundles must be assigned a bundle startlevel. This is the minimum start level to start a bundle.The bundle start level can be set with thesetBundleStartLevel(Bundle, int) method.When a bundle is installed, it is initially assigned the bundle startlevel returned by getInitialBundleStartLevel(). The initial bundlestart level to be used when bundles are installed can be set withsetInitialBundleStartLevel(int). 108
  109. 109. Active start levelA Management Agent can influence the active start level with thesetStartLevel(int) method. The Framework must then increase ordecrease the active start level by 1 until the requested start level isreached. The process of starting or stopping bundles, which isinitiated by the setStartLevel(int) method, must take placeasynchronously. 109
  110. 110. Start up and shut downAt startup, the Framework must have an active start level of zero. Itmust then move the active start level to the beginning start level. Thebeginning start level is specified with an argument when starting theFramework or through some other means, which is left undefined inthe specification. If no beginning start level is given, the Frameworkmust assume a beginning start level of one.When the Framework shuts down, the requested start level must beset to zero. The Framework must then follow the described processto make the active start level equal to zero. 110
  111. 111. Part VIBeyond this presentation 111
  112. 112. Beyond this presentationSecurity. Platform has powerful mechanisms for security management(roles, permissions, security-related services etc).Special services and mechanisms. Specification describes severalauxiliary mechanisms like OSGi-specific URL handling or serviceproxying.Standard services. OSGi platform contains many standard services. Inparticular: Admin services. These services enables Management Agent to control wiring strategies, deployment process, configuration, monitoring etc. Application services. Services for logging, IO, XML parsing. Enterprise specification declares services for JTA, JMX, JPA, and Web utilization. Remote services. OSGi R4 introduces a distribution providers. 112
  113. 113. Q&A 113

×