Micro Kernel

  • November 2019
  • PDF

This document was uploaded by user and they confirmed that they have the permission to share it. If you are author or own the copyright of this book, please report to us by using this DMCA report form. Report DMCA


Overview

Download & View Micro Kernel as PDF for free.

More details

  • Words: 3,612
  • Pages: 24
Professional Open Source™

Microkernel The microkernel approach, deployers and classloading

© JBoss, Inc. 2003-2005.

8/2/2005

1

JMX Microkernel Professional Open Source™

We will see the creation of services in JBoss – Every service is an MBean in JBoss

The SAR format and the DTD – The SAR or Service Archive is the basic unit of deployment for services

We will study the ClassLoader architecture of the microkernel – Achieving transparent class visibility in the core

How to write your own service – Service API and packaging

© JBoss, Inc. 2003-2005.

2

1

What is a SAR? Professional Open Source™

SAR stands for Service Archive – Equivalent of the JAR for EJBs

They can be DYNAMICALLY deployed and redeployed – System infrastructure cycles class-loaders – Hot-deploy for services – USE IN DEVELOPMENT, rebuilding or touching -> redeploy

Contains everything the service needs – The classes (optional, can be referenced with URL) – The configuration of the service in a jboss-service.xml

If you don’t use the classes you can use a standalone myname-service.xml To deploy just drop the SAR or service.xml in the deploy directory – Just like applications.

REMOVE A SAR YOU REMOVE THE SERVICE

3

© JBoss, Inc. 2003-2005.

What is in a SAR Professional Open Source™

myService.sar

META-INF must be capitalized

META-INF

org

interfaces

Java package structure

implementation

jboss-service.xml

Embedded deployment descriptor

MyServiceMBean

MyServiceIMPL

OR myService-service.xml

Standalone deployment descriptor

© JBoss, Inc. 2003-2005.

4

2

Service.xml Professional Open Source™

5

© JBoss, Inc. 2003-2005.

Service.xml Professional Open Source™

Loader-repository – Alternate class loading scoping to isolate a deployment classes

Classpath – A service.xml can optionally reference external classes • Codebase and archives attributes define location and may contain system property references – Will be deployed as package by Unified Deployer – Base for class-less SAR

Depends – How to order independent services? – By MBean name – Inversion of Control injection of type dependencies

XMBeans

© JBoss, Inc. 2003-2005.

6

3

jboss-service.xml: JRMPInvoker Example Professional Open Source™

<server> <server> dot.com:loader=my.sar dot.com:loader=my.sar /> <mbean <mbeancode=“com.dot.TestBean” code=“com.dot.TestBean”name=“dot.com:service=Test”> name=“dot.com:service=Test”> <arg <argtype=“int” type=“int”value=“10” value=“10”/>/> <arg <argtype=“com.dot.Array” type=“com.dot.Array”value=“1,2,3” value=“1,2,3”/>/> dot.com:name=a,type=b name=“SomeObjectName”>dot.com:name=a,type=b name=“Config”> Exposed Exposed as as org.w3c.dom.Element org.w3c.dom.Element port=“123”> attribute attribute type type name=“gateway”/> <depends <dependsoptional-attribute-name=“TxManager”>jboss.system:service=TransactionMgr optional-attribute-name=“TxManager”>jboss.system:service=TransactionMgr

7

© JBoss, Inc. 2003-2005.

jboss-service.xml: XMBean Example Professional Open Source™

<server> <server> <mbean <mbeancode="org.jboss.naming.JNDIView" code="org.jboss.naming.JNDIView"name="jboss:service=JNDIView“ name="jboss:service=JNDIView“ xmbean-dd="resource:xmdesc/JNDIView-xmbean.xml"> xmbean-dd="resource:xmdesc/JNDIView-xmbean.xml"> Reference Reference the the service service interface interface description. description. <mbean> <mbean> <description>JNDIView <description>JNDIViewService. Service. org.jboss.naming.JNDIView org.jboss.naming.JNDIView &defaultAttributes; &defaultAttributes; <description>Output <description>OutputJNDI JNDIinfo infoas astext text list list <parameter> <parameter> <description>If <description>Iftrue, true,list listthe theclass classof ofeach eachobject objectin inaddition additionto toits itsname name verbose verbose boolean boolean java.lang.String java.lang.String Automatically Automatically declares declares JBoss JBoss service service lifecycle lifecycle operations. operations. &defaultOperations; &defaultOperations; © JBoss, Inc. 2003-2005.

8

4

JBoss Configuration Services Professional Open Source™

JMX does not define any life cycle or dependency management It is common for an MBean to depend on the services of other MBeans – – – –

JNDI Transactions Logging Invokers

JBoss provides – Deployment to JMX • All deployments have a UnifiedClassLoader – Configuration – Lifecycle management – Dependency management • Start a service you start those that depend on him if complete • Stop a service you stop those that depend on him

9

© JBoss, Inc. 2003-2005.

The Service Interface Professional Open Source™

– MBeans that need to be notified when they should start and stop need to implement a Service interface – Start and stop are done in steps on a given deployment package packageorg.jboss.system; org.jboss.system; public publicinterface interfaceService Service {{ public publicvoid voidcreate() create()throws throwsException; Exception; public publicvoid voidstart() start()throws throwsException; Exception; public publicvoid voidstop(); stop(); public publicvoid voiddestroy(); destroy(); }}

© JBoss, Inc. 2003-2005.

10

5

org.jboss.system.ServiceController Professional Open Source™

Create is called when all bean I depend on are “created” When a service's create method is called – This gives an MBean an opportunity to check that required MBeans or resources exist. – The service typically cannot utilize other MBean services at this point, as most JBoss MBean services do not become fully functional until they have been started via their start method. – Because of this, service implementations often do not implement create in favor of just the start method because that is the first point at which the service can be fully functional.

11

© JBoss, Inc. 2003-2005.

org.jboss.system.ServiceController Professional Open Source™

– start method is called after the create method has returned – start is called when all beans a service depends on are started – Receipt of a start method invocation signals a service to become fully operational • since all services upon which the service depends have been created and started if possible.

© JBoss, Inc. 2003-2005.

12

6

org.jboss.system.ServiceController Professional Open Source™

The stop method is invoked by the by the JBoss server shutdown process – Shutdown is managed by the org.jboss.util.Shutdown MBean

The stop method invokes the stop method on each Service in reverse order from that of the create and start methods – Services that were last to start are the first to be stopped

13

© JBoss, Inc. 2003-2005.

org.jboss.system.ServiceController Professional Open Source™

– The destroy method is invoked by the JBoss server shutdown process after the stop method. – The destroy method invokes the destroy method on each Service in reverse order from that of the init and start methods. • Service implementations often do not implement destroy in favor of simply implementing the stop method, or neither stop nor destroy if the service has no state or resources that need cleanup.

© JBoss, Inc. 2003-2005.

14

7

Writing a Custom Service MBean Professional Open Source™

Writing a custom MBean service that integrates into the JBoss server requires the use of the org.jboss.system.Service interface pattern if the custom service is dependent on other JBoss services. – When a custom MBean depends on other MBean services you cannot perform any JBoss service dependent initialization in any of the javax.management.MBeanRegistration interface methods.

Instead, you must do this in the Service interface create and/or start methods by: – Add any of the Service methods that you want called on your MBean to your MBean interface. • This allows your MBean implementation to avoid dependencies on JBoss specific interfaces. – Extend the org.jboss.system.ServiceMBeanSupport class

15

© JBoss, Inc. 2003-2005.

Professional Open Source™

Booting Size 42.

© JBoss, Inc. 2003-2005.

8/2/2005

16

8

jboss-service.xml Professional Open Source™

There is a jboss-service.xml that we use to boot – It is a static configuration – It resides under the conf directory of your server fileset

Use the jboss-service.xml static file – When you are done developing – When you want to put all configuration in one static file – Central “locked” version

17

© JBoss, Inc. 2003-2005.

Package org.jboss.system Professional Open Source™

Startup sequence – Create an MBeanServer JBossMX – JBoss at birth is nothing but an MBeanServer

It contains core server and deployers, • org.jboss.system.server • org.jboss.system.deployment

JBoss uses the SAR format with XML to deploy services in a more advanced fashion (through the deployers) Support for ISV embeddable JBoss – Have your external application control this boot sequence – Or have your application be a part of the JBoss services

© JBoss, Inc. 2003-2005.

18

9

The ServerConfig URL Locations Professional Open Source™

19

© JBoss, Inc. 2003-2005.

Server Boot Professional Open Source™

package packageorg.jboss.system.server; org.jboss.system.server; import importjava.io.File; java.io.File; import importjava.net.URL; java.net.URL; import importjavax.management.MBeanServer; javax.management.MBeanServer; import importjavax.management.MBeanServerFactory; javax.management.MBeanServerFactory; import importjavax.management.ObjectName; javax.management.ObjectName; import importjavax.management.MBeanException; javax.management.MBeanException; import importorg.jboss.mx.loading.UnifiedClassLoader; org.jboss.mx.loading.UnifiedClassLoader; /** /** **The Themain maincontainer containercomponent componentof ofaaJBoss JBossserver serverinstance. instance. */*/ public publicclass classServerImpl ServerImplimplements implementsServer, Server,ServerImplMBean ServerImplMBean{{ /** /**The TheJMX JMXMBeanServer MBeanServerwhich whichwill willserve serveas asour ourcommunication communicationbus. bus.*/*/ private privateMBeanServer MBeanServerserver; server; /** /**The Themain maindeployer deployerobject objectname, name,replace replacewith withproxy proxyonce oncedeployment deploymentmoved movedto toJBoss/System JBoss/System*/*/ private privateObjectName ObjectNamemainDeployer; mainDeployer;

© JBoss, Inc. 2003-2005.

20

10

Server Boot Professional Open Source™

private privatevoid voiddoStart() doStart()throws throwsException Exception {{ log.info("Starting log.info("StartingGeneral GeneralPurpose PurposeArchitecture Architecture(GPA)..."); (GPA)..."); ////Create Createthe theMBeanServer MBeanServer server server==MBeanServerFactory.createMBeanServer("jboss"); MBeanServerFactory.createMBeanServer("jboss"); log.debug("Created log.debug("CreatedMBeanServer: MBeanServer:""++server); server); ////Register Registerserver servercomponents components server.registerMBean(this, server.registerMBean(this,ServerImplMBean.OBJECT_NAME); ServerImplMBean.OBJECT_NAME); server.registerMBean(config, server.registerMBean(config,ServerConfigImplMBean.OBJECT_NAME); ServerConfigImplMBean.OBJECT_NAME); ////Initialize Initializespine spineboot bootlibraries libraries UnifiedClassLoader UnifiedClassLoaderucl ucl==initBootLibraries(); initBootLibraries(); ////Set SetServiceClassLoader ServiceClassLoaderas asclassloader classloaderfor forthe theconstruction constructionof of ////the thebasic basicsystem system Thread.currentThread().setContextClassLoader(ucl); Thread.currentThread().setContextClassLoader(ucl);

21

© JBoss, Inc. 2003-2005.

Server Boot Professional Open Source™

////Service ServiceController Controller ObjectName null).getObjectName(); ObjectNamecontrollerName controllerName==server.createMBean("org.jboss.system.ServiceController", server.createMBean("org.jboss.system.ServiceController",null).getObjectName(); log.debug("Registered log.debug("Registeredservice servicecontroller: controller:""++controllerName); controllerName); ////Main MainDeployer Deployer mainDeployer mainDeployer==server.createMBean("org.jboss.deployment.MainDeployer", server.createMBean("org.jboss.deployment.MainDeployer",null).getObjectName(); null).getObjectName(); ////Jar JarDeployer Deployer objectName objectName==server.createMBean("org.jboss.deployment.JARDeployer", server.createMBean("org.jboss.deployment.JARDeployer",null).getObjectName(); null).getObjectName(); initService(controllerName, initService(controllerName,objectName); objectName); ////SAR SARDeployer Deployer objectName objectName==server.createMBean("org.jboss.deployment.SARDeployer", server.createMBean("org.jboss.deployment.SARDeployer",null).getObjectName(); null).getObjectName(); initService(controllerName, initService(controllerName,objectName); objectName); log.info("Core log.info("Coresystem systeminitialized"); initialized");

© JBoss, Inc. 2003-2005.

22

11

Server Boot Professional Open Source™

jboss-service.xml jboss-service.xml is is aa static static configuration configuration

////Ok, Ok,now nowdo doaafirst firstdeploy deployof ofJBoss' JBoss'jboss-service.xml jboss-service.xml server.invoke(mainDeployer, server.invoke(mainDeployer, "deploy", "deploy", new newObject[] Object[]{{config.getServerConfigURL() config.getServerConfigURL()++config.getRootDeploymentFilename() config.getRootDeploymentFilename()},}, new newString[] String[]{{String.class.getName() String.class.getName()}); }); ////Calculate Calculatehow howlong longitittook took long longlapsedTime lapsedTime==System.currentTimeMillis() System.currentTimeMillis()--startDate.getTime(); startDate.getTime(); long longminutes minutes==lapsedTime lapsedTime//60000; 60000; long longseconds seconds==(lapsedTime (lapsedTime--60000 60000**minutes) minutes)//1000; 1000; long longmilliseconds milliseconds==(lapsedTime (lapsedTime--60000 60000**minutes minutes--1000 1000**seconds); seconds); ////Tell Tellthe theworld worldhow howfast fastititwas was=) =) log.info("JBoss log.info("JBoss(MX (MXMicroKernel) MicroKernel)["["++jbossPackage.getImplementationVersion() jbossPackage.getImplementationVersion()++ "]"]Started Startedin in""++minutes minutes ++"m:" "m:"++seconds seconds ++"s:" "s:"++milliseconds milliseconds+"ms"); +"ms"); started started==true; true; }}

23

© JBoss, Inc. 2003-2005.

SAR Format and XML configuration Professional Open Source™

Instantiation and configuration of all MBeans via XML 6 server.instantiate() :name=MyService :name=MyService 7 server.createMBean() 8 server.setAttributes() 10 createService() 12 startService()

Service Service Controller Controller

5 install(objectname) 9 create(service) 11 start(service)

2 Deploy(URL) DeploymentScanner DeploymentScanner 1 Scan URL

XML

MainDeployer MainDeployer

SARDeployer SARDeployer

3 accepts(DeploymentInfo) 4 parseDocument(DeploymentInfo)

*-service.xml © JBoss, Inc. 2003-2005.

24

12

org.jboss.deployment.MainDeployer Professional Open Source™

– The deploy() operation starts the deployment process /** /**The Thedeploy deploymethod methoddeploys deploysaapackage packagerepresented representedby byaaDeploymentInfo DeploymentInfoobject. object. ** **@param @paramdeployment deploymentaaDeploymentInfo DeploymentInfovalue value */*/ public publicvoid voiddeploy(DeploymentInfo deploy(DeploymentInfodeployment) deployment) throws throwsDeploymentException DeploymentException{{ ////IfIfwe weare arealready alreadydeployed deployedreturn return ifif(isDeployed(deployment.url)) (isDeployed(deployment.url)) {{return;} return;} boolean booleaninited inited==false; false; try try {{ inited inited==init(deployment); init(deployment); }} catch catch(Throwable (Throwablet)t){{ DeploymentException.rethrowAsDeploymentException("Could DeploymentException.rethrowAsDeploymentException("Couldnot notinitialise initialisedeployment: deployment:““… …);); }} ifif((inited inited)){{ create(deployment); create(deployment); start(deployment); start(deployment); }}else else{{ … …

25

© JBoss, Inc. 2003-2005.

org.jboss.deployment.SARDeployer Professional Open Source™

– SARDeployer accepts the deployment, and parses deployment specific configuration public publicboolean booleanaccepts(DeploymentInfo accepts(DeploymentInfodi) di){{ String StringurlStr urlStr==di.url.toString(); di.url.toString(); return returnurlStr.endsWith("sar") urlStr.endsWith("sar")||||urlStr.endsWith("sar/") urlStr.endsWith("sar/")|||| urlStr.endsWith("deployer") urlStr.endsWith("deployer")||||urlStr.endsWith("deployer/") urlStr.endsWith("deployer/")|||| urlStr.endsWith("service.xml") urlStr.endsWith("service.xml")||||urlStr.endsWith("deployer.xml"); urlStr.endsWith("deployer.xml"); }} /** /**Parse Parsethe theMETA-INF/jboss-service.xml META-INF/jboss-service.xmldescriptor descriptor */*/ protected protectedvoid voidparseDocument(DeploymentInfo parseDocument(DeploymentInfodi) di)throws throwsException Exception{{ try try{{ ifif(di.document (di.document== ==null) null){{ DocumentBuilder DocumentBuilderparser parser==DocumentBuilderFactory.newInstance().newDocumentBuilder(); DocumentBuilderFactory.newInstance().newDocumentBuilder(); URL URLdocURL docURL==di.localUrl; di.localUrl; URLClassLoader URLClassLoaderlocalCL localCL==di.localCl; di.localCl; ////Load Loadjboss-service.xml jboss-service.xmlfrom fromthe thejar jaror ordirectory directory ifif(di.isXML (di.isXML== ==false) false) docURL = localCL.findResource("META-INF/jboss-service.xml"); docURL = localCL.findResource("META-INF/jboss-service.xml"); ////Validate Validatethat thatthe thedescriptor descriptorwas wasfound found ifif(docURL (docURL== ==null) null) throw thrownew newDeploymentException("Failed DeploymentException("Failedto tofind findMETA-INF/jboss-service.xml"); META-INF/jboss-service.xml");

© JBoss, Inc. 2003-2005.

26

13

org.jboss.system.ServiceController Professional Open Source™

– ServiceController manages the dependencies and service life cycle management public publicsynchronized synchronizedvoid voidstart(ObjectName start(ObjectNameserviceName) serviceName)throws throwsException Exception{{ ...... try try{{ ifif(!installedServices.contains(ctx)) (!installedServices.contains(ctx)) installedServices.add(ctx); installedServices.add(ctx); ////IfIfwe weare arealready alreadystarted started(can (canhappen happenin independencies) dependencies)just justreturn return ifif(ctx.state (ctx.state== ==ServiceContext.RUNNING ServiceContext.RUNNING||||ctx.state ctx.state== ==ServiceContext.FAILED) ServiceContext.FAILED){{return; return;}} ...... ////Are Areall allthe thembeans mbeansIIdepend dependon onstarted? started? ififnot notjust justreturn return for for(Iterator (Iteratoriterator iterator==ctx.iDependOn.iterator(); ctx.iDependOn.iterator();iterator.hasNext();) iterator.hasNext();){{ ServiceContext ServiceContextsctx sctx==(ServiceContext) (ServiceContext)iterator.next(); iterator.next(); int intstate state==sctx.state; sctx.state; ////AAdependent dependentisisnot notrunning running ifif(!(state (!(state== ==ServiceContext.RUNNING)) ServiceContext.RUNNING)){{ ctx.state ctx.state==oldState; oldState; return; return; }} }}

27

© JBoss, Inc. 2003-2005.

ServiceCreator and ServiceConfigurator Professional Open Source™

Helper classes to ServiceController – ServiceCreator initializes and registers the JMX MBean • MBeanServer.instantiate() • MBeanServer.createMBean() – ServiceConfigurator injects default attribute values from descriptor • MBeanServer.setAttributes()

© JBoss, Inc. 2003-2005.

28

14

Professional Open Source™

Deployment Ordering And other party tricks.

© JBoss, Inc. 2003-2005.

8/2/2005

29

xAR Deployment Ordering (1/3) Professional Open Source™

conf/jboss-service.xml (at boot time) – Deployed in order definition of the MBeans

Within the deploy folder – – – – – – –

SAR xxx-service.xml RAR JAR WAR EAR ZIP

© JBoss, Inc. 2003-2005.

30

15

xAR Deployment Ordering (2/3) Professional Open Source™

Russian Dolls ordering: – Any xAR can be contained in any other xAR other than WARs • Since WARs are often used for content loading and have their own class loading model we do not look into them for deployments – The corresponding deployer will be used to deploy the xAR – The order: INNER-first, OUTER-last (depth first search)

Name Based Ordering – org.jboss.deployment.DeploymentSorter • Implements the standard ordering described previously – org.jboss.deployment.scanner.PrefixDeploymentSorter • Orders deployed based on their numeric prefix – nnn-whatever.xAR – App.sar, stuff.ear, 1foo.ear, 2bar.sar

• Used after standard ordering

31

© JBoss, Inc. 2003-2005.

xAR Deployment Ordering (3/3) Professional Open Source™

– You can explicitly set service ordering by using the <depends> tag – If a required service is not available, the deployment is suspended – Once available, the deployment is resumed <mbean <mbeancode="org.jboss.deployment.cache.DeploymentCache" code="org.jboss.deployment.cache.DeploymentCache" name="jboss.deployment:type=DeploymentCache"> name="jboss.deployment:type=DeploymentCache"> <depends>jboss.system:service=MainDeployer <depends>jboss.system:service=MainDeployer … …

© JBoss, Inc. 2003-2005.

32

16

jboss-service.xml: Dependency Injection Example Professional Open Source™

The depends element can be used for dependency injection – The proxy-type attribute specifies the interface name that should be exposed on an dynamic proxy pointing at the dependent MBean specified by the JMX ObjectName – The special value proxy-type="attribute" will use the attribute’s type as an interface to the proxy <mbean code="org.jboss.example.Helper" name="domain:name=helper"/> <mbean code="myBean" name="domain:name=x"> <depends optional-attribute-name="Helper" proxy-type="org.jboss.example.HelperMBean“> domain:name=helper <mbean code="myBean" name="domain:name=y"> <depends optional-attribute-name="Helper“ proxy-type="attribute"> domain:name=helper

33

© JBoss, Inc. 2003-2005.

Professional Open Source™

Classloading in JBoss Microkernel What is a class in Java?

© JBoss, Inc. 2003-2005.

8/2/2005

34

17

Java Class Definition and Runtime Type System Professional Open Source™

Class definition in Java runtime – Class is identified by its fully qualified class name and the defining classloader (JVM spec change introduced in 1.2)

Same package and class name defined by two different classloaders are not the same types to the Java runtime – Although the Java developer (and compiler) still thinks they’re the same type – Java developers and compilers work with the fully qualified name as the class identity, classloaders are not explicit in the Java language

Java Class

What defines my identity?

35

© JBoss, Inc. 2003-2005.

Java Class Definition and Runtime System Professional Open Source™

Two classloaders both defining MyClass class – Reference “value” is a reference to an instance of MyClass defined by CL1 – CL2 does not recognize type MyClass as defined by CL1, it has its own definition of MyClass (even if they have identical bytecodes) – An attempt to assign a reference of type <MyClass, CL1> to type <MyClass, CL2> fails at runtime due to type mismatch

Class MyClass

Class MyClass

CL1 CL1

Class Foo class class Foo Foo {{ public public void void doStuff() doStuff() {{ MyClass MyClass value value == new new MyClass(); MyClass(); bar.setField(value); bar.setField(value); }} }}

CL2 CL2

Class Bar

setField(value) (pass-by-reference)

class class Bar Bar {{ MyClass MyClass value; value; public public void void setField(MyClass setField(MyClass value) value) {{ this.value this.value == value; value; }} }}

CLASS CAST EXCEPTION! © JBoss, Inc. 2003-2005.

36

18

JBoss 4.x Classloader Repository Professional Open Source™

JBoss defines classloading domains Within a classloading domain a class is identified by its fully qualified class name – Any given class can have only one defining classloader within the domain – We return to the intuitive Java notion that class is identified by its name

Within a classloading domain we can safely use references – We know that a given class name can only have one defining loader – Essential for performance!

Loader Loader Repository Repository Class is identified Java Java Class Class by its name in the classloading domain

37

© JBoss, Inc. 2003-2005.

JBoss 4.x Classloader Repository Professional Open Source™

In the default configuration, all deployment classloaders are added to a single classloader repository – Duplicate class definitions are handled with a “first one wins” policy; later attempts to add duplicate class definitions are discarded

defineClass(“Foo”) CL d

Default Loader Repository

– Initiating classloaders find the class definitions from the loader repository classloader set

Class Foo CL i

loadClass(“Foo”)

WAR SAR EJB-JAR

© JBoss, Inc. 2003-2005.

38

19

JBoss 4.x Classloader Repository Professional Open Source™

Classloading domains can be configured into hierarchical tree structure – Children have visibility to their parent but not to their siblings

Parent Repository Shared JARs

Child Repository

Child Repository 010010110101110101000

Util Class 1.0

EJB-JAR

Must serialize instances between domains to avoid type mismatch (versions 1.0 and 1.1 must be serialization compatible)

Util Class 1.1

EJB-JAR

39

© JBoss, Inc. 2003-2005.

A UnifiedClassLoader per Deployment Professional Open Source™

Deployment Deployment Archive Archive

Top Top Level Level Deployer Deployer

Top Top Level Level UCL UCL

There is one UCL per top-level deployment archive – Any nested components archives are added as jars to the top-level UCL – WARs are the exception to this • Only the war archive itself is added • Any nested archives are not added to the UCL • WEB-INF/lib/jars and WEB-INF/classes are not added to the UCL – Can be changed via UseJBossWebLoader setting in web container © JBoss, Inc. 2003-2005.

40

20

mx.loading.UnifiedClassLoader Professional Open Source™

public publicclass classUnifiedClassLoader UnifiedClassLoaderextends extendsURLClassLoader URLClassLoader{{

The The UCL UCL delegates delegates to to aa central central repository repository of of classes classes and and stores stores in in that that repository repository

/** /**Reference Referenceto tothe theunified unifiedrepository. repository.*/*/ private null; privateUnifiedLoaderRepository UnifiedLoaderRepositoryrepository repository==null; public publicClass ClassloadClassLocally(String loadClassLocally(Stringname, name,boolean booleanresolve) resolve) throws throwsClassNotFoundException ClassNotFoundException {{ return returnsuper.loadClass(name, super.loadClass(name,resolve); resolve); }} This This is is called called by by the the repository repository /** /** to to ask ask the the UCL UCL to to really really look look for for **We Weintercept interceptthe theload loadclass classto toknow knowexactly exactlythe thedependencies dependencies the the class class without without looping looping **of ofthe theunderlying underlyingjar. jar. **Forwards Forwardsrequest requestto to{@link {@linkUnifiedLoaderRepository} UnifiedLoaderRepository}.. */*/ public publicClass ClassloadClass(String loadClass(Stringname, name,boolean booleanresolve) resolve) throws throwsClassNotFoundException ClassNotFoundException {{ return returnrepository.loadClass(name, repository.loadClass(name,resolve, resolve,this); this); }}

41

© JBoss, Inc. 2003-2005.

mx.loading.UnifiedLoaderRepository3 Professional Open Source™

public publicclass classUnifiedLoaderRepository3 UnifiedLoaderRepository3 {{ public name,boolean booleanresolve, resolve,ClassLoader ClassLoaderscl) scl) publicClass ClassloadClass(String loadClass(Stringname, throws throwsClassNotFoundException ClassNotFoundException {{ ////Try Trythe thecache cachebefore beforeanything anythingelse. else. Class Classcls cls==this.loadClassFromCache(task.classname); this.loadClassFromCache(task.classname); if( if(cls cls!= !=null null)) return returncls; cls; IfIf itit is is already already present present return return itit

© JBoss, Inc. 2003-2005.

42

21

mx.loading.UnifiedLoaderRepository3 (Cont) Professional Open Source™

////Get Getthe theset setof ofclass classloaders loadersfrom fromthe thepackages packagesmap map HashSet HashSetpkgSet pkgSet==this.getPackageClassLoaders(name); this.getPackageClassLoaders(name); if( if(pkgSet pkgSet== ==null null||||pkgSet.size() pkgSet.size()== ==00)) {{ ////Next Nexttry trythe theclass classloader loaderitself itself cls cls==this.loadClassFromClassLoader(task.classname, this.loadClassFromClassLoader(task.classname,false, false, task.requestingClassLoader); task.requestingClassLoader); if( if(cls cls!= !=null null)) return returncls; cls;

IfIf no no loader loader in in the the repository repository has has the the class class pkg pkg try try the the class class loader loader

////IfIfno nopkg pkgmatch matchwas wasfound foundthere thereisisno nopoint pointlooking lookingany anyfurther further String Stringmsg msg=="No "NoClassLoaders ClassLoadersfound foundfor: for:"+name; "+name; throw thrownew newClassNotFoundException(msg); ClassNotFoundException(msg); }} Else Else load load class class from from one one of ////Query of the the loaders loaders in in the the Querythe theclass classloaders loadersthat thathave haveclasses classesin inthe therequested requestedpackage package repository Iterator repository Iteratoriter iter==pkgSet.iterator(); pkgSet.iterator(); while( while(iter.hasNext() iter.hasNext())) {{ UnifiedClassLoader3 UnifiedClassLoader3ucl ucl(UnifiedClassLoader3) (UnifiedClassLoader3)iter.next(); iter.next(); ////Details Detailsof ofthe thechoice choiceof ofwhich whichclass classloader loaderisischosen chosenare arehidden hiddenin inscheduleTask scheduleTask scheduleTask(ucl, scheduleTask(ucl,name, name,…); …); }}

43

© JBoss, Inc. 2003-2005.

JBoss Shared Repository Professional Open Source™

22 Service Service A A asks asks for for aa class, class, class class is is added added to to repository repository by by finding finding UCL UCL

11 Deployer Deployer creates creates the the UCL UCL for for the the SAR SAR

Deployer REPOSITORY

JBossMX

IT IT WORKS! WORKS! Services Services that that didn’t didn’t know know each each other other are are sharing sharing their their classes classes

© JBoss, Inc. 2003-2005.

33 Service Service B B asks asks for for the the class, class, get get the the same same class class through through its its Classloader/repository Classloader/repository

44

22

Configuration Professional Open Source™

<jboss> <jboss> Unique Unique JMX JMX loaderRepositoryClass=‘…’> Name Name jboss.test:ejb-jar=log4j113-ejb.jar jboss.test:ejb-jar=log4j113-ejb.jar java2ParentDelegation=false java2ParentDelegation=false Parent Parent first/Child first/Child

first first

– loaderRepositoryClass: defines the name of the UnifiedLoaderRepository to create • org.jboss.mx.loading.HeirarchicalLoaderRepository3 – Required loader-repository content is the JMX ObjectName of the scoped repository – Optional loader-repository-config depends on loaderRepositoryClass

45

© JBoss, Inc. 2003-2005.

Integration Professional Open Source™

How does integration work? – How can a stack that wasn’t develop for JBoss work with the UCL?

Use the parent delegation model – It says “when asked for a class first ask my parent” – This is the default behavior, if the parent knows the class you use it. – SET THE PARENT TO BE THE CONTEXT CLASSLOADER

Setting parent is done at create time – (We can avoid this since JDK 1.4) The The context context CL CL is is aa JBoss JBoss one one (the (the creation creation call call comes comes from from JBoss) JBoss) ClassLoader ClassLoaderjbossClassLoader jbossClassLoader==Thread.currentThread().getContextClassLoader(); Thread.currentThread().getContextClassLoader(); Classloader ClassloadermyOwnClassLoader myOwnClassLoader==new newMyOwnClassLoader(jbossClassLoader); MyOwnClassLoader(jbossClassLoader);

© JBoss, Inc. 2003-2005.

46

23

JMX: J2EE a service based world Professional Open Source™

By and large the J2EE world is a service based world – – – – – –

All J2EE APIs are really services to the applications JMX buys us a way to manage it in a standard fashion JMX puts minimal, standard, requirements on module builders Complexity of the code base grows with APIs Few vendors can do all the stacks Those that do, do so in a monolithic fashion

© JBoss, Inc. 2003-2005.

47

24

Related Documents

Micro Kernel
November 2019 22
Kernel
May 2020 12
Kernel
October 2019 31
Kernel
May 2020 20
Kernel Thread
November 2019 26
Linux Kernel
November 2019 30