La présentation est en train de télécharger. S'il vous plaît, attendez

La présentation est en train de télécharger. S'il vous plaît, attendez

NSY102 1 NSY102 Conception de logiciels Intranet JMX Java Management eXtension API Architecture à base de composants Cnam Paris jean-michel Douin, douin.

Présentations similaires


Présentation au sujet: "NSY102 1 NSY102 Conception de logiciels Intranet JMX Java Management eXtension API Architecture à base de composants Cnam Paris jean-michel Douin, douin."— Transcription de la présentation:

1 NSY102 1 NSY102 Conception de logiciels Intranet JMX Java Management eXtension API Architecture à base de composants Cnam Paris jean-michel Douin, douin au cnam point fr version 25 Mai 2009

2 NSY102 2 Sommaire Objectifs –Supervision d’une JVM, locale ou distante Une Première approche –Un exemple simple Un Managed Bean (MBean) Un agent Une supervision comme démonstration De plus près : 3 niveaux –Instrumentation Standard, dynamic, open, model Beans et MXBeans. –Agent / serveur Installation et accès aux « MBeans » –Distribué Connecteurs et adaptateurs –Applette et JMX, Plug-in et JMX En conclusion –Tout est ou deviendra MBean ? …

3 NSY102 3 Bibliographie utilisée La présentation de Christophe Ebro –http://rangiroa.essi.fr/cours/internet/02-JMX-partie2.pdfhttp://rangiroa.essi.fr/cours/internet/02-JMX-partie2.pdf L’indispensable tutoriel de Sun –http://java.sun.com/docs/books/tutorial/jmx/index.htmlhttp://java.sun.com/docs/books/tutorial/jmx/index.html –http://java.sun.com/javase/technologies/core/mntr-mgmt/javamanagement/http://java.sun.com/javase/technologies/core/mntr-mgmt/javamanagement/ Hello world –http://java.sun.com/j2se/1.5.0/docs/guide/jmx/examples.htmlhttp://java.sun.com/j2se/1.5.0/docs/guide/jmx/examples.html Le blog de Daniel Fuchs et celui de Luis-Miguel Alventosa –http://blogs.sun.com/jmxetc/ http://blogs.sun.com/lmalventosa/http://blogs.sun.com/jmxetc/http://blogs.sun.com/lmalventosa/ JMX et Design Patterns chez hp –http://devresource.hp.com/drc/resources/jmxbestp_dp_pres/index.jsphttp://devresource.hp.com/drc/resources/jmxbestp_dp_pres/index.jsp Côté développeur ibm –http://www-128.ibm.com/developerworks/java/library/j-jmx2/http://www-128.ibm.com/developerworks/java/library/j-jmx2/ Orienté MX4j, « date un peu » http://admc.com/blaine/howtos/jmx/http://admc.com/blaine/howtos/jmx/ http://www.xmojo.org/products/xmojo/index.html Spécialisé MXBean / accès à la JVM –http://www-128.ibm.com/developerworks/java/library/j-mxbeans/ Divers –http://www-adele.imag.fr/users/Didier.Donsez/ujf/sujet/jmx.html

4 NSY102 4 Pré-requis Notions de –Introspection En tant qu’utilisateur –Client/serveur, Protocole JRMP( rmi) et HTTP –Patrons Factory, Publish-Subscribe, DynamicProxy

5 NSY102 5 JMX : Objectifs Supervision de JVM locales ou distantes –En cours d’exécution Gestion/administration de Ressources –Matérielles comme logicielles Configuration/déploiement/mise à jour –Statique et dynamique Contrôle –Du Cycle de vie : start/stop/suspend/resume –De la Charge en vue d’une meilleure répartition Supervision –Performance –Des erreurs/ exceptions –De l’état (cf. cycle de vie)

6 NSY102 6 Supervision : mouture fine… Détection de la mémoire utilisée Déclenchement du ramasse-miettes, ou bien son arrêt Chargement de classe en mode verbose Détection d’un interblocage Accès aux ressources de l’OS Gestion d’application de type MBean Gestion de serveurs Gestion d’applettes ! –Au sein d’un navigateur …

7 NSY102 7 JMX API Hypothèse : tout est JAVA-JVM –Ressources matérielles –Ressources logicielles Depuis J2SE 1.5, mais 1.6 sera préféré, et JMX >= 1.4 Adoptée par de nombreuses entreprises –http://java.sun.com/javase/technologies/core/mntr-mgmt/javamanagement/jmxadoption.jsphttp://java.sun.com/javase/technologies/core/mntr-mgmt/javamanagement/jmxadoption.jsp –Déjà présent au sein de plate-formes commerciales … JBoss, Apache, GlassFish, Outils prédéfinis –jconsole, jvisualvm(1.6 update11), interface vers rmi/http/snmp/jini … –JDMK en open source Java Dynamic Management Kit http://java.sun.com/products/jdmk/

8 NSY102 8 Architecture 3 niveaux –Instrumentation Gestion de la ressource par un composant (MBean, Managed Bean) –Agents Initialisation, installation et contrôle des MBean –Distribué/intégration Adaptateurs de Protocoles RMI/HTTP/SNMP-CMIP Sécurité Common Management Information Protocol (CMIP), protocole ISO Simple Network Management Protocol (SNMP)

9 NSY102 9 Schéma de Christophe Ebro de Sun 3 niveaux instrumentation, serveur, distribué

10 NSY102 10 Objectifs rappel contexte JVM Accès à une JVM « de l’extérieur » –Supervicion d’une JVM en cours d’exécution … Gestion d’objets Java déjà en place…MBean –Accès aux attributs (introspection) Lecture/écriture –Appels de méthodes (introspection) Passage de paramètres / retour de résultat –Notifications, (publish-subscribe) évènements Ajout dynamique de nouveaux objets MBean –Code des classes en place spécialisé –Code « hors-place » à télécharger Retrait dynamique d’objets MBean Un exemple vite …

11 NSY102 11 Par l’exemple : un capteur… SensorMBeanInstrumentation SensorAgentServeur –Installation du service Outil jconsoleDistribué –Un client en standard (j2SE)

12 NSY102 12 Un exemple comme présentation SensorMBean Sensor Instrumentation SensorAgent Serveur Outil de Sun jconsole Distribué

13 NSY102 13 Instrumentation, Standard MBean // un capteur comme ressource public interface Sensor MBean { // getter/setter public int getValue(); public void setValue(int val); // operations public void reset(); } MBean suffixe imposé … syntaxe à respecter

14 NSY102 14 Remarques d’introspecteur … getter/setter selon Sun, une convention public int getValue(); public void setValue(int val); Un outil peut donc en déduire qu’il existe un attribut int value; accessible en lecture et en écriture

15 NSY102 15 Sensor implements SensorMBean public class Sensor implements SensorMBean{ private final int PERIOD; private int value; private Acquisition local; // un thread interne source en annexe public Sensor(int period){ this.PERIOD = period; local = this.new Acquisition(); } public synchronized int getValue(){ return value; } public synchronized void setValue(int value){ this.value = value; } // operations public void reset(){… Class Sensor imposée …

16 NSY102 16 Agent ou impresario L’agent du bean se charge de –L’installation (instanciation) du MBean –L’enregistrement auprès du serveur de MBeans MBeanServer Un nom unique lui est attribué –en général par l’utilisateur, –selon une convention de nommage Apparenté Properties exemple : SensorAgent:name=Sensor1 »name la clé, Sensor1 la valeur Cet agent est ici installé sur la même JVM –D’autres peuvent le faire : un autre MBean, le serveur, de l’extérieur …

17 NSY102 17 Agent : SensorAgent public class SensorAgent{ private MBeanServer mbs; public SensorAgent(){ try{ mbs = ManagementFactory.getPlatformMBeanServer(); ObjectName name = new ObjectName("SensorAgent:name=Sensor1"); Sensor mbean = new Sensor(2000); // création du mbean mbs.registerMBean(mbean, name); // enregistrement }catch(Exception e){ …} } public static void main(String[] args)throws Exception{ … new SensorAgent(); Thread.sleep(Long.MAX_VALUE); // la JVM reste active

18 NSY102 18 Commentaires mbs = ManagementFactory.getPlatformMBeanServer(); Le gestionnaire de MBean inclus dans la JVM ObjectName name = new ObjectName("SensorAgent:name=Sensor1"); Un nom, éventuellement suivi de propriétés Sensor mbean = new Sensor(2000); Création du mbean mbs.registerMBean(mbean, name); Enregistrement auprès du gestionnaire

19 NSY102 19 Distribué : jconsole Accès à l’une des JVM, –Déjà équipée de son MBeanServer* LocalProcess SensorAgent (ici numérotation « windows ») Les PID des JVM : console> jps * Plusieurs MBeanServer Peuvent co-exister

20 NSY102 20 Distribué : jconsole name=Sensor1 –Accès aux attributs getter/setter, par introspection

21 NSY102 21 Distribué : jconsole name=Sensor1 –Opération reset()

22 NSY102 22 Distribué : jconsole Onglet Threads, un MXBean abordé par la suite –SensorAgent est bien endormi…

23 NSY102 23 Java VisualVM visualVM –https://visualvm.dev.java.net/download.htmlhttps://visualvm.dev.java.net/download.html https://visualvm.dev.java.net/docindex.html – jconsole global

24 NSY102 24 Résumé, Pause … MBean –Un composant Agent –Chargé du dialogue avec l’infrastructure(canevas/framework) jconsole un outil prédéfini –C‘est une application Java –Accès aux MBean depuis n’importe quelle application Locale ou distante

25 NSY102 25 Jconsole comme SensorClient SensorMBean Sensor Instrumentation SensorAgent SensorClient Outil de Sun jconsole SensorClient ou comment accéder au bean Depuis une application java ordinaire ?

26 NSY102 26 Client : SensorClient public class SensorClient{ // même JVM // SensorAgent a = new SensorAgent(); préalable MBeanServer mbs = …… // à la recherche du MBean ObjectName name = new ObjectName("SensorAgent:name=Sensor1"); // accès aux attributs par leur nom // accès à l’attribut, getValue() System.out.println(mbs.getAttribute(name, "Value")); …

27 NSY102 27 SensorClient & DynamicProxy // ou bien à l’aide d’un dynamicProxy // un mandataire généré dynamiquement, du byte-code à la volée SensorMBean sensor = (SensorMBean) MBeanServerInvocationHandler.newProxyInstance( mbs, // MBeanServer name, // ObjectName SensorMBean.class, // interface false); // détaillé par la suite System.out.println(sensor.getValue()); sensor.reset(); DynamicProxy encore …

28 NSY102 28 Résumé Instrumentation un MBean Serveur un agent qui pourrait devenir un MBean… Client même JVM, à l’aide d’un mandataire dynamique Distribué jconsole

29 NSY102 29 Notifications Réveil, alarmes, pannes … –Ou bien Notifications, évènements asynchrones, réseau ? Patron Observateur distribué … –Publish-subscribe : filtre d’évènements possible –Notifications Vers des JVM installées sur la même machine Vers des JVM distantes Notification  NotificationBroadcaster  NotificationListener

30 NSY102 30 Réveil & notifications À la suite d’un changement d’état –Patron publish/subscribe, mode pull (pull : inscription à la demande du client)

31 NSY102 31 Comment ? notify Une classe prédéfinie –NotificationBroadcasterSupport sendNotification(Notification notification) Ajout/retrait d’un observateur/écouteur addNotificationListener( NotificationListener listener, NotificationFilter filter, Object handback) … removeNotificationListener( …

32 NSY102 32 Comment : Listener L’interface NotificationListener handleNotification(Notification notification, Object handback)

33 NSY102 33 Comment ? A chaque changement d’état une notification est effectuée –sendNotification (new Notification(….,….,….)); Éventuellement filtrée –Interface NotificationFilter boolean isNotificationEnabled(Notification notification) isNotificationEnabled – Exécutée avant chaque notification Une notification : classe Notification –Constructeurs –Notification(String type, Object source, long sequenceNumber) –Notification(String type, Object source, long sequenceNumber, long timeStamp, String message)

34 NSY102 34 Avec SensorMBean public interface SensorMBean extends NotificationBroadcaster { // getter/setter public int getValue(); public void setValue(int val); // operations public void reset(); }

35 NSY102 35 Sensor A chaque modification de la valeur du capteur –Une notification est engendrée –Notifications distantes sur le réseau Arrivée possible dans le désordre  estampille

36 NSY102 36 Instrumentation & Notifications public class Sensor extends NotificationBroadcasterSupport implements SensorMBean{ public synchronized void setValue(int value){ this.value = value; this.sequenceNumber++; sendNotification( new Notification( "setValue", // un nom this, sequenceNumber, // un numéro System.currentTimeMillis(), // une estampille Integer.toString(value))); // un message }

37 NSY102 37 L’ Agent & notifications L’agent est un ici observateur de « son » MBean public class SensorAgent implements NotificationListener{ private MBeanServer mbs; public SensorAgent(){ try{ … mbean.addNotificationListener(this,null,null); }catch(Exception e){ e.printStackTrace(); } public void handleNotification( Notification notification, Object handback){ System.out.print(notification.getMessage()); System.out.println(" number : " + notification.getSequenceNumber()); }

38 NSY102 38 Client : jconsole & notifications jconsole a souscrit

39 NSY102 39 SensorClient est un écouteur public class SensorClient implements NotificationListener{ public void handleNotification( Notification notification, Object handback){ …. } public static void main(String[] args) throws Exception { SensorAgent a = new SensorAgent(); // même JVM ici MBeanServer mbs = ManagementFactory.getPlatformMBeanServer(); ObjectName name = new ObjectName("SensorAgent:name=Sensor"); NotificationListener nl = new SensorClient(); SensorMBean sensor = (SensorMBean) MBeanServerInvocationHandler.newProxyInstance(mbs, name, SensorMBean.class, false); sensor.addNotificationListener(nl, null,null);

40 NSY102 40 SensorClient : le mandataire encore lui SensorMBean sensor = (SensorMBean) MBeanServerInvocationHandler.newProxyInstance(mbs, name, SensorMBean.class, true); true retourne un proxy qui impléménte l’interface NotificationEmitter, soit la possibilité de retirer un écouteur de ce MBean (par procuration …) SensorMBean sensor = (SensorMBean) MBeanServerInvocationHandler.newProxyInstance( mbs, name, SensorMBean.class, true); … ((NotificationEmitter)sensor).removeNotificationListener(nl, null, null) ;

41 NSY102 41 Petite conclusion À la mode des Bean-Java –Getter/setter, opérations –Standard MBean comme suffixe … Instrumentation –Enregistrement de ce MBean … Agent –Supervision jconsole, clients visualVM –Notifications jconsole, clients Simple ! À suivre…

42 NSY102 42 Sommaire Maintenant d’un peu plus près

43 NSY102 43 Instrumentation MBeans 5 types Standard : engendré depuis une interface xxxMBean –Voir l’exemple de présentation Dynamic : n’importe quel objet, –fonctionnalités découvertes à l’exécution Model : configurable, une template à instancier Open : limité à un ensemble de type Java –Inhibe les téléchargements de code MXBean 1.6 : accès aux ressources de la JVM

44 NSY102 44 DynamicMBean Interface connue à l’exécution –Liste des attributs construite au démarrage du MBean Une description de ces attributs par exemple dans un fichier XML Tout simplement un Proxy d’accès au MBean

45 NSY102 45 DynamicMBean Par introspection … – c’est un mandataire String/JVM

46 NSY102 46 Dynamic Accès de l’extérieur … –possible avec des noms d’attributs ou d’opérations –Il sera possible de les télécharger …

47 NSY102 47 Exemple du capteur, il faut tout écrire… public class SensorDynamic extends NotificationBroadcasterSupport implements DynamicMBean { public SensorDynamic() { buildDynamicMBeanInfo(); } public Object getAttribute(String attributeName) throws AttributeNotFoundException, MBeanException, ReflectionException { if (attributeName.equals("Value")) { return getValue(); } … Voir http://java.sun.com/j2se/1.5.0/docs/guide/jmx/examples.html

48 NSY102 48 DynamicMBean Proposer une « signature » du composant –getMBeanInfo() retourne cette signature –Les méta-données MBeanInfo décrivent les attributs, opérations et notifications Utilisation ad’hoc –Un adaptateur d’objets Java existants afin de les rendre « compatibles MBean »

49 NSY102 49 Instrumentation MBeans 5 types Standard : engendré depuis une interface xxxMBean Dynamic : n’importe quel objet, –fonctionalités découvertes à l’exécution Model : configurable, une template à instancier Open : limité à un ensemble de type Java –Inhibe les téléchargements de code MXBean 1.6 : accès aux ressources de la JVM

50 NSY102 50 ModelMBean Avertissement : –Model MBeans are a particularly advanced feature of the JMX API. It is perfectly possible to produce an entirely adequate set of MBeans without ever using Model MBeans. –Model MBeans are harder to program so they should only be used when there is a clear benefit. Donc … À lire : The Jakarta Commons Modeler from the Apache Software Foundation builds on the Model MBean framework to allow you to specify MBean interfaces, including descriptors etc, using XML. The attributes and operations mentioned in XML are forwarded to an instance of a Java class that does not have to be an MBean class. The main advantage of this approach is perhaps that the entire information model can be contained in a single XML file. The main disadvantage is that there is no Java interface corresponding to the management interface of a given MBean, which means that clients cannot construct proxies.Jakarta Commons Modeler

51 NSY102 51 Model configurable, une template à instancier lors de l’exécution Extrait de http://www-128.ibm.com/developerworks/java/library/j-jmx2/

52 NSY102 52 ModelMBeanInfo private ModelMBeanInfo createMBeanInfo() { Descriptor atDesc = new DescriptorSupport( new String[] { "name=Value", "descriptorType=attribute", "default=0", "displayName=Value of the Sensor", "getMethod=getValue", "setMethod=setValue" } ); ModelMBeanAttributeInfo [] mmbai = new ModelMBeanAttributeInfo[1]; mmbai[0] = new ModelMBeanAttributeInfo("Value","java.lang.Integer", "The Sensor Value", true,true, false, atDesc); …

53 NSY102 53 RequiredMBeanInfo ObjectName name; name = new ObjectName("MBean:name=Sensor"); RequiredModelMBean modelmbean; modelmbean = new RequiredModelMBean(createMBeanInfo()); server.registerMBean(modelmbean, name); Model MBeans are harder to program …

54 NSY102 54 Instrumentation MBeans 5 types Standard : engendré depuis une interface xxxMBean Dynamic : n’importe quel objet, –fonctionalités découvertes à l’exécution Model : configurable, une template à instancier Open : limité à un ensemble de type Java –Inhibe les téléchargements de code MXBean 1.6 : accès aux ressources de la JVM

55 NSY102 55 OpenMBean Limité à un sous-ensemble –Optimisé en espace et temps d’exécution –Seulement des types primitifs java –Et ne nécessite pas de recompilation, téléchargement de.class Voir OpenMBeanInfo

56 NSY102 56 Instrumentation MBeans 5 types Standard : engendré depuis une interface xxxMBean Dynamic : n’importe quel objet, –fonctionalités découvertes à l’exécution Model : configurable, une template à instancier Open : limité à un ensemble de type Java MXBean : accès aux ressources de la JVM

57 NSY102 57 MXBean Compilation CompilationMXBean Garbage collection system GarbageCollectorMXBean Memory MemoryMXBean Memory managers MemoryManagerMXBean Threading ThreadMXBean Operating system OperatingSystemMXBean Runtime system RuntimeMXBean Class loading system ClassLoadingMXBean Memory resources MemoryPoolMXBean

58 NSY102 58 Un exemple : ThreadAgent, ThreadMXBean public class ThreadAgent{ private MBeanServer mbs; public ThreadAgent(){ try{ ThreadMXBean mbean = ManagementFactory.getThreadMXBean(); mbs = ManagementFactory.getPlatformMBeanServer(); ObjectName name = new ObjectName("ThreadAgent:name=thread1"); mbs.registerMBean(mbean, name); }catch(Exception e){ e.printStackTrace(); } public static void main(String[] args)throws Exception{ … new ThreadAgent(); … Thread.sleep(Long.MAX_VALUE);

59 NSY102 59 Distribué : jconsole (ThreadAgent==MemoryAgent … de la syntaxe)

60 NSY102 60 Sommaire Agents

61 NSY102 61 Agents Adaptateurs et connecteurs MBean server Interrogation et listage Chargement dynamique Agent de services

62 NSY102 62 Distribué, Connector, Adapter Un connector –Est un MBean, –Est enregistré auprès du “MBean server”, –Communique avec une machine (paire) –Exemple Un rmi connecteur Un adapter –Est un MBean, –Est enregistré auprès du “MBean server”, –Ecoute sur un port et respecte un certain protocole. –Exemple Un adapter HTML accepte des requêtes au protocole HTTP Un client type est un navigateur

63 NSY102 63 Les connecteurs RMI TCP dédié

64 NSY102 64 Rmi connecteur, SensorAgent try { MBeanServer mbs …. name = new ObjectName("SensorAgent:name=Sensor2"); mbs.registerMBean(sensorBean, name); // Création et démarrage du connecteur côté serveur JMXServiceURL url = new JMXServiceURL("service:jmx:rmi:///jndi/rmi://localhost:9999/server"); // Création JMXConnectorServer cs = JMXConnectorServerFactory.newJMXConnectorServer(url, null, mbs); // Démarrage cs.start(); } catch(Exception e) { }

65 NSY102 65 java/rmi + jconsole start rmiregistry 9999 l’annuaire –Côté MBeanServer

66 NSY102 66 RmiClient public class RMIClient{ public static void main(String[] args) throws Exception{ // à la recherche du connecteur, via l’annuaire JMXServiceURL url = new JMXServiceURL("service:jmx:rmi:///jndi/rmi://localhost:9999/server"); JMXConnector cs = JMXConnectorFactory.connect(url); MBeanServerConnection mbs = cs.getMBeanServerConnection(); ObjectName name = new ObjectName("SensorAgent:name=Sensor2"); System.out.println(" value : " + mbs.getAttribute(name, "Value")); // à l’aide d’un dynamic proxy … SensorMBean sensor = (SensorMBean) MBeanServerInvocationHandler.newProxyInstance(mbs, name, SensorMBean.class, false); System.out.println(sensor.getValue()); }}

67 NSY102 67 Notification distante… import javax.management.NotificationEmitter; public interface SensorMBean extends NotificationEmitter { // getter/setter public int getValue(); public void setValue(int val); // operations public void reset(); }

68 NSY102 68 Souscription locale auprès du MBean distant url = new JMXServiceURL("service:jmx:rmi:///jndi/rmi://163.173.228.92:9999/server"); connector = JMXConnectorFactory.connect(url); mbean = new ObjectName("SensorAgent:name=Sensor2"); // le mandataire, décidément SensorMBean sensor = ( SensorMBean ) MBeanServerInvocationHandler.newProxyInstance( connector.getMBeanServerConnection(), mbean, SensorMBean.class, false); sensor.addNotificationListener(this,null,null);

69 NSY102 69 Notification, déjà vue public void addNotificationListener (ObjectName, NotificationListener, NotificationFilter, handback) public void removeNotificationListener (ObjectName name, NotificationListener listener) Voir NotificationEmitter

70 NSY102 70 Les adaptateurs Navigateur  html adaptateur

71 NSY102 71 Html adaptateur, SensorAgent try { MBeanServer mbs …. name = new ObjectName("SensorAgent:name=Sensor2"); mbs.registerMBean(sensorBean, name); // Creation et démarrage de l’adaptateur HtmlAdaptorServer adapter = new HtmlAdaptorServer();//* adapter.setPort(8088); name = new ObjectName("HtmlAdaptorServer:name=html,port=8088"); mbs.registerMBean(adapter, name); adapter.start(); * import com.sun.jdmk.comm.*; // 5.0.1 jdmkrt.jar

72 NSY102 72 Le Client est un navigateur

73 NSY102 73 Client, navigateur Sans oublier, jdmkrt.jar dans le classpath –Bluej voir le répertoire lib/userlib/ ou./+libs/ –java -cp.;../JMX/jdmkrt.jar ThreadAgent

74 NSY102 74 A la recherche du MBean ? MBean en connaissant son nom : ok Tous les MBean d’un certain type ? Tous les MBean dont l’attribut « Counter » == 10 Tous les MBean dont l’attribut « Counter » >= 10 et dont l’estampille < X « QL » pour les MBean ? MQL ? –QueryExp –Expression booléenne

75 NSY102 75 QueryExp, comme composite… QueryExp exp = Query.gt(Query.attr("count"), Query.value(10)) QueryExp prob1 = Query.eq(Query.attr("inkLevel"), Query.value("LOW")); QueryExp prob2 = Query.lt(Query.attr("paperCount"), Query.value(50)); QueryExp exp = Query.or(prob1, prob2); "(inkLevel = LOW) or (paperCount < 50)"

76 NSY102 76 Chargement dynamique de MBean Agent M-Let Description XML

77 NSY102 77 M-Let Comment –M-Let agent

78 NSY102 78 Chargement dynamique de MBean M-Let –« URLClassLoader » Associé à un descripteur en XML Descripteur XML, nommé sensor.mlet, à cette URL http://jfod.cnam.fr/NSY102/jmx/sensor.mlet

79 NSY102 79 Mlet en séquence

80 NSY102 80 Agent M-let public MLetAgent(){ try{ mbs = ManagementFactory.getPlatformMBeanServer(); ObjectName name = new ObjectName("Services:name=mlet"); mbs.createMBean("javax.management.loading.MLet", name); JMXServiceURL url = new JMXServiceURL("service:jmx:rmi:///jndi/rmi://localhost:9999/server"); JMXConnectorServer cs = JMXConnectorServerFactory.newJMXConnectorServer(url, null, mbs); cs.start(); }catch(Exception e){ e.printStackTrace(); }

81 NSY102 81 Agent M-Let Téléchargement dynamique du MBean Sensor –Appel de getMBeansFromURL( " http://jfod.cnam.fr/NSY102/jmx/sensor.mlet " ) Sensor À la volée!

82 NSY102 82 MLetBean public interface MLetMBean { public Set getMBeansFromURL(String url) throws ServiceNotFoundException; public Set getMBeansFromURL(URL url) throws ServiceNotFoundException; public void addURL(URL url); public void addURL(String url) throws ServiceNotFoundException; public URL[] getURLs(); public URL getResource(String name); public InputStream getResourceAsStream(String name); public Enumeration getResources(String name) throws IOException; public String getLibraryDirectory(); public void setLibraryDirectory(String libdir); }

83 NSY102 83 M-Let File [ ] [ ] –Adaptés au constructeurs avec paramètres –Exemple

84 NSY102 84 Retrait dynamique de MBean mbs = ManagementFactory.getPlatformMBeanServer(); ObjectName name=… mbs.unregister(name) –À faire avec jconsole …

85 NSY102 85 Sommaire

86 NSY102 86 Interrogations au sujet des MBeans MBeanInfo meta-data: mbs.getMBeanInfo(objName); –Dynamic comme Standard MBeans And you can also run a type-check: mbs.isInstanceOf(objName, className)

87 NSY102 87 Accès au MBean : MBeanInfo Interface respectée par un Mbean –Les attributs et les opérations disponibles –Ces instances sont immutables getClassName() –Le nom de la classe getConstructors() –La liste des constructeurs getAttributes() –La liste des attributs Syntaxe getName() et setName() Name est l’attribut getOperations() –Opérations accessibles Syntaxe autre qu’un attribut getNotifications() –À la condition que ce Mbean implémente l’interface NotificationBroadcaster NotificationBroadcaster ( Ce sera NotificationBroadcaster.getNotificationInfo() qui sera déclenchée) NotificationBroadcaster.getNotificationInfo()

88 NSY102 88 MBeanInfo et plus …

89 NSY102 89 Un petit dernier, une applette Comment intervenir sur une applette de navigateur … Est-ce bien utile ? –Supervision chez le client à son insu ? Ou comment intervenir sur une application téléchargée –Par exemple avec java web start –Toujours à son insu … –Un petit et dernier exemple en 4 transparents Une applette incluant serveur web supervisée chez le client

90 NSY102 90 JConsole et Applet Extrait de http://blogs.sun.com/lmalventosa/ Développer 1.une interface AppletteXXXXXMBean 2.une classe AppletteXXXXX extends JApplet implements AppletteXXXXXMBean 3.Puis générer l’archive AppletteXXXXX.jar Générer un certificat keytool -genkey -alias nsy -keypass PWD -keystore nsystore -storepass PWD Signer l’archive jarsigner -keystore nsystore AppletteXXXXX.jar nsy Exemple : ici http://jfod.cnam.fr/NSY102/AppletteServeurWeb.html C’est une page html standard <applet code="AppletteServeurWeb.class" width=500 height=200 archive="AppletteServeurWeb.jar" >

91 NSY102 91 JConsole et Applet démo Un client : http://localhost:8100/test/?param1=applette

92 NSY102 92 Jconsole et Applet : un exemple en images Cliquer sur valider engendre une nouvelle fenêtre avec le résultat de la requête effectuée en http://localhost:8100/test/?test=essai

93 NSY102 93 Jconsole et applet suite Un scenario : –1) arreterServeurWeb –2) demarrerServeurWeb port 8200 –3) ouvrir un nouvel onglet sur le navigateur puis recharger la page initiale 2 serveurs en cours d’exécution 8100 et 8200 –4) applet_i_2 est apparu dans l’onglet MBeans de jconsole –…

94 NSY102 94 L’interface « Mbean » de l’applette public interface AppletteServeurWebMBean{ // opérations public void demarrerServeurWeb(int port); public void arreterServeurWeb(); // lectures, getter public int getPort(); public boolean getServeurActif(); public String getHostCodeBase(); public String getDerniereRequete(); }

95 NSY102 95 L’applette, un extrait du code source private static AtomicInteger applet_id = new AtomicInteger(1); private MBeanServer mbs; private ObjectName name; public void init(){ // initialisation de l’applette // et de son MBean... mbs = ManagementFactory.getPlatformMBeanServer(); name = new ObjectName("AppletteMBean: type=AppletteServeurWeb, "+ "name=applet_id_" + applet_id.getAndIncrement()); mbs.registerMBean(this, name); } public synchronized void stop(){ // terminaison de l’applette // et de son MBean... mbs.unregisterMBean(name); } source complet ici http://jfod.cnam.fr/NSY102/appletteServeurWebMBean/

96 NSY102 96 Conclusion JMX est bien un framework/canevas –MBean –Plug-in Plug-in et JMX installer pour voir celui-ci : http://blog.luminis.nl/luminis/entry/top_threads_plugin_for_jconsole voir également http://blogs.sun.com/jmxetc/entry/ingo_rockel_thread_dump_plugin jconsole et jvisualVM deux utiles outils de supervision, et simples d’utilisation

97 NSY102 97 jconsole Les sources de sun : https://jdk6.dev.java.net/https://jdk6.dev.java.net/ sun/tools/jconsole/ sun/tools/jconsole/inspector/ sun/tools/jconsole/resources/ com/sun/tools/jconsole/

98 NSY102 98 Luis-Miguel Alventosa’s Blog http://blogs.sun.com/lmalventosa/ Luis-Miguel Alventosa show how to use JMX Monitoring & Management with both Applets and Web Start Applications. [July 6, 2006]AppletsWeb Start Applications –http://blogs.sun.com/lmalventosa/entry/per_thread_cpu_usage_jconsole Voir aussi jconsole -pluginpath topthreads.jar –http://blog.luminis.nl/luminis/entry/top_threads_plugin_for_jconsole

99 NSY102 99 http://blog.luminis.nl/luminis/entry/top_threads_plugin_for_jconsole jconsole -pluginpath topthreads.jar –Onglet Top threads

100 NSY102 100 MBean Cycle de vie Extrait de ce livre, –chapitre 9 : Designing with JMX Paragraphe 3 MBean Registration and Lifecycle

101 NSY102 101 Création locale et enregistrement

102 NSY102 102 Création du MBean et enregistrement

103 NSY102 103 Création depuis une application externe

104 NSY102 104 Création par un adaptateur

105 NSY102 105 Création au démarrage

106 NSY102 106 M-let et notifications Être prévenu d’un téléchargement Voir l’adaptateur livre page 241

107 NSY102 107 MXBean JMX 1.4 et les annotations L’exemple de sun http://java.sun.com/javase/6/docs/technotes/guides/jmx/tutorial/essential.html#wp1054551 http://java.sun.com/javase/6/docs/technotes/guides/jmx/tutorial/essential.html#wp1054551 public interface QueueSamplerMXBean { public QueueSample getQueueSample(); public void clearQueue(); } public class QueueSampler implements QueueSamplerMXBean { private Queue queue; public QueueSampler(Queue queue) { this.queue = queue; } public QueueSample getQueueSample() { synchronized (queue) { return new QueueSample(new Date(), queue.size(), queue.peek()); } public void clearQueue() { synchronized (queue) { queue.clear(); }

108 NSY102 108 MXBean 1.4 public class QueueSample { private final Date date; private final int size; private final String head; @ConstructorProperties({"date", "size", "head"}) public QueueSample(Date date, int size, String head){ this.date = date; this.size = size; this.head = head; } public Date getDate() { return date; } public int getSize() { return size; } public String getHead() { return head; } }

109 NSY102 109 CompositeData MBeanServer mbs =...whatever...; ObjectName name = new ObjectName("com.example.mxbeans:type=QueueSampler"); CompositeData queueSample = (CompositeData) mbs.getAttribute(name, "QueueSample"); int size = (Integer) queueSample.get("size"); MBeanServer mbs =...whatever...; ObjectName name = new ObjectName("com.example.mxbeans:type=QueueSampler"); QueueSamplerMXBean proxy = JMX.newMXBeanProxy(mbs, name, QueueSamplerMXBean.class); QueueSample queueSample = proxy.getQueueSample(); int size = queueSample.getSize();

110 NSY102 110 JMX-JBoss http://www.openknowledge.de/pdf/jax2003/JMX_2003_05_10.pdf

111 NSY102 111 Sécurisé les accès Extrait de http://blogs.sun.com/jmxnetbeans/date/20070816http://blogs.sun.com/jmxnetbeans/date/20070816 http://jfod.cnam.fr/NSY102/jmx/TestSSLContext.java Securing the ConnectorServer Your agent code looks something like : JMXConnectorServer server = JMXConnectorServerFactory. newJMXConnectorServer(new JMXServiceURL("service:jmx:ws:" + "//localhost:8080/jmxws"), null, ManagementFactory.getPlatformMBeanServer()); server.start(); So how do you enable HTTPS? Simply by changing the protocol name when creating the JMXServiceURL to be ws-secure instead of ws. So now your code looks like : JMXConnectorServer server = JMXConnectorServerFactory. newJMXConnectorServer(new JMXServiceURL("service:jmx:ws- secure:" + "//localhost:8080/jmxws"), null, ManagementFactory.getPlatformMBeanServer()); server.start();

112 NSY102 112 Sécurisé les accès Are you done? Not yet, you need to provide a KeyStore location and a KeyStore password for SSL to find the certificates. You don't have a KeyStore or a certificate? Not a big deal, use keytool! For example call : keytool -genkey -keystore jsr262Keystore -keyalg RSA java -classpath... - Djavax.net.ssl.keyStore=jsr262Keystore - Djavax.net.ssl.keyStorePassword=123456 MyJMXAgent // Create the SSLContext SSLContext ctx = TestSSLContext.getInstance("SSLv3"); // Create an env map Map env = new HashMap(1); // Provide the SSLContext env.put("jmx.remote.ws.sslcontext", ctx); // Create the ConnectorServer providing the env map JMXConnectorServer server = JMXConnectorServerFactory. newJMXConnectorServer(new JMXServiceURL("service:jmx:ws-secure:" + "//localhost:8080/jmxws"), env, ManagementFactory.getPlatformMBeanServer()); server.start();

113 NSY102 113 Source Sensor.Acquisition public class Sensor implements SensorMBean{ …. private class Acquisition extends Thread implements java.io.Serializable{ private Random random= new Random(); public Acquisition(){ random= new Random(); start(); } public void run(){ int valeur = 0; try{ while(!isInterrupted()){ Thread.sleep(PERIOD/2); //int value = random.nextInt(100); Sensor.this.setValue(valeur); Thread.sleep(PERIOD/2); System.out.println("." + valeur); valeur++; } }catch(InterruptedException ie){} }


Télécharger ppt "NSY102 1 NSY102 Conception de logiciels Intranet JMX Java Management eXtension API Architecture à base de composants Cnam Paris jean-michel Douin, douin."

Présentations similaires


Annonces Google