jean-michel Douin, douin au cnam point fr

Slides:



Advertisements
Présentations similaires
Mais vous comprenez qu’il s’agit d’une « tromperie ».
Advertisements

ORTHOGRAM PM 3 ou 4 Ecrire: « a » ou « à » Référentiel page 6
Reporting de la Cellule Nationale Droit dOption Situation au 31 décembre 2011.
[number 1-100] There is no rule to the way to remember the names for the numbers 1 to 10 in French so we recommend that you simply practice!
CHAPITRE 8 LES ALIMENTS 3/25/2017 Des fruits Madame Craven.
Additions soustractions
Distance inter-locuteur
1 Plus loin dans lutilisation de Windows Vista ©Yves Roger Cornil - 2 août
Les numéros 70 –
Les numéros
Les identités remarquables
Le, la, les words Possessive Adjectives MINE!!. 2 My in french is mon, ma,mes... Le word/ begins with a vowel: Mon La word: Ma Les word: Mes.
Xavier Mouranche Registre e-MUST Evaluation en Médecine dUrgence des Stratégies Thérapeutiques de lInfarctus du Myocarde.
Cours MIAGE « Architectures Orientées Services » Henry Boccon-Gibod 1 Orchestration de Web Services Module 5 Exercice Pratique à l'usage de l'environnement.
Cours MIAGE « Architectures Orientées Services » Henry Boccon-Gibod 1 Architectures Orientées Services Composants de Service Exemple pratique de développement.
Algorithme et structure de données
LICENCE MIAGE Introduction Programmation Orientée Objet JAVA philippe
LES TRIANGLES 1. Définitions 2. Constructions 3. Propriétés.
Données statistiques sur le droit doption au 31/01 8 février 2012.
Correspondances en Onco-Urologie - Vol. III - n° 3 – juillet-août-septembre VESSIE Daprès James ND et al., N Engl J Med 2012;366:16:
Technologies et pédagogie actives en FGA. Plan de latelier 1.Introduction 2.Les technologies en éducation 3.iPads 4.TNI 5.Ordinateurs portables 6.Téléphones.
User management pour les entreprises et les organisations Auteur / section: Gestion des accès.
Révision (p. 130, texte) Nombres (1-100).
La législation formation, les aides des pouvoirs publics
Connexion base de données
Injection de dépendances
Initiation et perfectionnement à lutilisation de la micro-informatique Créer un blog avec Windows Live Spaces sur un Mac ou sur un PC ©Yves Roger Cornil.
La méthodologie………………………………………………………….. p3 Les résultats
Structure(djs)TéléphoneFax ADRA R049,96,03,21 CHLEF027,77,22,66 /77,49, LAGHOUAT029,90,41,08029,90,42,47 OUM EL BOUAGHI032,42,16,26032,42,45,32.
BlueJ_XI 1 Java, les objets : tout de suite ! Gestion des erreurs : les exceptions Notes de cours associées au chapitre 11 tutorial BlueJ
Le soccer & les turbans Sondage mené par lAssociation détudes canadiennes 14 juin 2013.
ESIEE 1 JMX Java Management eXtension API Architecture à base de composants Cnam Paris jean-michel Douin, douin au cnam point fr version 19 Février 2008.
Présentation générale
1 Guide de lenseignant-concepteur Vincent Riff 27 mai 2003.
Les nombres.
Les quartiers Villeray – La Petite-Patrie et les voisinages
Fierté envers les symboles et institutions canadiens Jack Jedwab Association détudes canadiennes 26 novembre 2012.
TortoiseSVN N°. Subversion : pour quoi faire ? Avoir un espace de stockage commun – Tous les étudiants du SIGLIS ont un espace svn commun Partager vos.
Conseil Administration AFRAC – 2 décembre Toulouse 1 Fermes de références Palmipèdes à foie gras Synthèse régionale – Midi Pyrénées Exercice
Projet poker 1/56. Introduction Présentation de léquipe Cadre du projet Enjeux Choix du sujet 2.
NSY102 1 Concurrence compléments Notes de cours Cnam Paris jean-michel Douin, douin au cnam point fr 19 Mars 2007.
7 décembre 2011 Evolution des projets : les services web, le site RRNADMIN et lévolution du RN vers une base de données relationnelles.
Logiciel gratuit à télécharger à cette adresse :
Les chiffres & les nombres
Les Monnaies et billets du FRANC Les Monnaies Euro.
DUMP GAUCHE INTERFERENCES AVEC BOITIERS IFS D.G. – Le – 1/56.
1 CSI 2532 Lab5 Installation de JDBC Février 13, 2012.
Les maths en francais 7ième année.
Multi-Thread Jian-Yun Nie
Année universitaire Réalisé par: Dr. Aymen Ayari Cours Réseaux étendus LATRI 3 1.
Cours 11 Threads. Chapitre X threads threadPOO-L3 H. Fauconnier3 Threads threads: plusieurs activités qui coexistent et partagent des données exemples:
Jean-Marc Léger Président Léger Marketing Léger Marketing Les élections présidentielles américaines.
COURS DE PROGRAMMATION ORIENTEE OBJET :
Introduction au Langage C
Android UIThread, Thread, Handler et AsyncTask
Proxy et plus Cnam Paris jean-michel Douin, douin au cnam point fr
MAGIE Réalisé par Mons. RITTER J-P Le 24 octobre 2004.
Les Nombres 0 – 100 en français.
Aire d’une figure par encadrement
Les fondements constitutionnels
MAGIE Réalisé par Mons. RITTER J-P Le 24 octobre 2004.
Première CTP le 4 décembre Nouvelle CTP depuis le 1 er février RTM milieu de cette année.
1/65 微距摄影 美丽的微距摄影 Encore une belle leçon de Macrophotographies venant du Soleil Levant Louis.
Certains droits réservés pour plus d’infos, cliquer sur l’icône.
Annexe Résultats provinciaux comparés à la moyenne canadienne
La formation des maîtres et la manifestation de la compétence professionnelle à intégrer les technologies de l'information et des communications (TIC)
Bienvenue.
NSY102 1 NSY102 Conception de logiciels Intranet JMX Java Management eXtension API Architecture à base de composants Cnam Paris jean-michel Douin, douin.
© - Last update: Sunday, 31 January Master « Technologies de l’Internet » - UPPA.
jean-michel Douin, douin au cnam point fr
Transcription de la présentation:

jean-michel Douin, douin au cnam point fr NSY102 Conception de logiciels Intranet JMX Java Management eXtension API Cnam Paris jean-michel Douin, douin au cnam point fr version 08 Avril 2011 Architecture à base de composants

Sommaire Objectifs Une Première approche De plus près : 3 niveaux Supervision d’une JVM, locale ou distante Lecture/écriture/mise à jour/téléchargement/… 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

Bibliographie utilisée La présentation de Christophe Ebro http://rangiroa.essi.fr/cours/internet/02-JMX-partie2.pdf L’indispensable tutoriel de Sun http://java.sun.com/docs/books/tutorial/jmx/index.html http://java.sun.com/javase/technologies/core/mntr-mgmt/javamanagement/ Hello world http://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/ JMX et Design Patterns chez hp http://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/ JMX in Action, ed. Manning Benjamin G.Sullins et Mark B. Whipple http://java.sun.com/developer/Books/javaprogramming/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

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

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)

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 … …

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.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/

Architecture 3 niveaux Instrumentation Agents Distribué/intégration Gestion de la ressource par un composant (MBean, Managed Bean) Agents Initialisation, installation au sein du serveur de 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)

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

Objectifs rappel contexte JVM Accès à une JVM « de l’extérieur » Supervision 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 premier exemple …

Par l’exemple : un capteur… SensorMBean Instrumentation Un capteur / une mesure SensorAgent Serveur Installation du service Outil jconsole Distribué Un client en standard (j2SE)

Un exemple en introduction Outil de Sun jconsole Distribué SensorMBean Sensor Instrumentation SensorAgent Serveur

Les classes en présence Outil de Sun jconsole SensorMBean Sensor SensorAgent SensorMBean.java Une interface, les méthodes proposées Sensor.java Une implémentation de l’interface SensorAgent Inscription auprès du serveur de MBean (prédéfini) Les méthodes deviennent des services, accesibles via le serveur de MBean jconsole Une application prédéfinie Instrumentation Serveur Distribué

Instrumentation, Standard MBean public interface SensorMBean { // getter/setter public int getValue(); public void setValue(int val); // operations public void reset(); } MBean suffixe imposé … syntaxe à respecter

Remarques de l’introspecteur … getter/setter selon Sun, une convention d’écriture 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

Sensor implements SensorMBean public class Sensor implements SensorMBean{ private final int PERIOD; private int value; // Acquisition est une classe interne // une simulation du capteur, page suivante private Acquisition local; 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; public void reset(){… page suivante Classe Sensor imposée …

Sensor suite public void reset(){ local.interrupt(); try{local.join();}catch(InterruptedException ie){} System.out.println("reset ...."); local = this.new Acquisition(); } 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); System.out.println("." + value);} // cf page suivante }catch(InterruptedException ie){}

Démonstration SensorMBean s = new Sensor(2000); Une « mesure » toutes les deux secondes

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 …

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{ SensorAgent agent = new SensorAgent();

Commentaires sur l’agent mbs = ManagementFactory.getPlatformMBeanServer(); Le gestionnaire de MBean prédéfini ObjectName name = new ObjectName("SensorAgent:name=Sensor1"); Un nom, éventuellement suivi de propriétés SensorMBean mbean = new Sensor(2000); Création du mbean, même JVM mbs.registerMBean(mbean, name); Enregistrement auprès du gestionnaire

Supervisions prédéfinies Outils jconsole jvisualVM jps

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

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

Distribué : jconsole name=Sensor1 opération reset()

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

Java VisualVM jvisualVM https://visualvm.dev.java.net/download.html https://visualvm.dev.java.net/docindex.html jconsole global

jvisualVM, puissant …

jvisualVM, à essayer

Résumé, Pause … MBean Agent Jconsole, jvisualvm deux outils prédéfinis Un composant Agent Chargé du dialogue avec l’infrastructure(canevas/framework) Jconsole, jvisualvm deux outils prédéfinis Ce sont des applications écrites en Java… À suivre : Accès aux MBean depuis n’importe quelle application Locale ou distante

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

Client : SensorClient, même JVM 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")); // exécuter une opération Object[] paramètres = new Object[]{}; String[] signature = new String[]{}; mbs.invoke(name, "reset", paramètres, signature);

Remarques // même JVM // SensorAgent a = new SensorAgent(); au préalable // SensorAgent et le client ont accès au même MBeanServer MBeanServer mbs = ManagementFactory.getPlatformMBeanServer(); // à la recherche du MBean ObjectName name = new ObjectName("SensorAgent:name=Sensor1"); // depuis une autre JVM, ce capteur n’est pas accessible (pour le moment)

SensorClient & DynamicProxy // accès à l’aide d’un dynamicProxy 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 cf le cours Proxy … attention ici même JVM

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, jvisualvm

Notifications Réveil, alarmes, pannes … Patron Observateur distribué … 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

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

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

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

Comment ? A chaque changement d’état une notification est effectuée sendNotification (new Notification(….,….,….)); Éventuellement filtrée Interface NotificationFilter boolean isNotificationEnabled(Notification notification) 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)

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

jconsole a tout compris … L’item Notifications apparaît Souscription possible depuis une autre JVM …

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

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 }

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());

Client : jconsole & notifications jconsole a souscrit

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);

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 …) MBeanServerInvocationHandler.newProxyInstance( mbs, name, SensorMBean.class, true); … ((NotificationEmitter)sensor).removeNotificationListener(nl, null, null) ;

Cycle de vie, pre, prede, post, postde interface MBeanRegistration Méthodes déclenchées à l’installation du MBean pre… à la désinstallation post Pour Lire une configuration globale ou d’un autre MBean S’enquérir d’une valeur Mise à jour d’un journal …

interface MBeanRegistration public void postDeregister(); public void postRegister(Boolean done); public void preDeregister(); // le MBeanServer est transmis  accès aux autres MBean public ObjectName preRegister(MBeanServer server, ObjectName name); } Un exemple : obtenir la valeur courante du capteur via le MBean Sensor préalablement installé

Exemple … public interface SensorValuesMBean{ public int currentValue(); } public class SensorValues implements SensorValuesMBean, MBeanRegistration{ private MBeanServer server; private int value; public void postDeregister(){} public void postRegister(Boolean done){} public void preDeregister(){} public ObjectName preRegister(MBeanServer server, ObjectName name){ this.server = server; try{ ObjectName name1 = new ObjectName("SensorAgent:name=Sensor1"); if(server.isRegistered(name1)){ this.value = (Integer)server.getAttribute(name1,"Value"); }catch(Exception e){e.printStackTrace(); } return name; public int currentValue(){return this.value;} Avec register, createMBean auprès de MBeanServer

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

Sommaire de plus près

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

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 Soit un mandataire d’accès au MBean

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

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 …

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

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 »

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

ModelMBean Avertissement : Donc … 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.

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

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); …

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

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

OpenMBean Limité à un sous-ensemble Voir OpenMBeanInfo 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

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

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

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);

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

Sommaire Agents

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

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 , Ecoute sur un port et respecte un certain protocole. Un adapter HTML accepte des requêtes au protocole HTTP Un client type est un navigateur

Les connecteurs RMI TCP dédié

Rmi connecteur, SensorAgent try { MBeanServer mbs …. name = new ObjectName("SensorAgent:name=Sensor2"); mbs.registerMBean(sensorBean, name); // Quelle est l’URL, enregistrement auprès de l’annuaire rmi JMXServiceURL url = new JMXServiceURL("service:jmx:rmi:///jndi/rmi://localhost:9999/server"); // Création du connecteur JMXConnectorServer cs = JMXConnectorServerFactory.newJMXConnectorServer(url, null, mbs); // Démarrage du service cs.start(); } catch(Exception e) { }

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

RmiClient enfin public class RMIClient{ public static void main(String[] args) throws Exception{ // à la recherche du connecteur 1) l’URL JMXServiceURL url = new JMXServiceURL("service:jmx:rmi:///jndi/rmi://localhost:9999/server"); // tentaive de connexion, récupération d’un mandataire JMXConnector cs = JMXConnectorFactory.connect(url); MBeanServerConnection mbs = cs.getMBeanServerConnection(); ObjectName name = new ObjectName("SensorAgent:name=Sensor2"); System.out.println(" value : " + mbs.getAttribute(name, "Value")); // … SensorMBean sensor = (SensorMBean) MBeanServerInvocationHandler.newProxyInstance( mbs, name, SensorMBean.class, false); System.out.println(sensor.getValue()); }}

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(); }

Souscription 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);

NotificationEmitter public void addNotificationListener (ObjectName, NotificationListener, NotificationFilter, handback) public void removeNotificationListener (ObjectName name, NotificationListener listener)

Exécution « distante » … «entre deux JVM SensorAgentAndRMI

jconsole « distant » a souscrit En démo : plusieurs clients distants souscrivent Quelles sont les incidences (mémoire,cpu,..) côté services ? jvisualvm pour une première évaluation ? Incidence de jvisualvm ?

Supervision jvisualvm, CPU et où Quel(s) coût(s) à l’exécution du client ?

Les adaptateurs Navigateur HTML  HTTP adaptateur

Html adaptateur, SensorAgent try { MBeanServer mbs …. name = new ObjectName("SensorAgent:name=Sensor2"); mbs.registerMBean(sensorBean, name); // Création 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 http://jfod.cnam.fr/NSY102/jms1.1/jdmkrt.jar

un Client comme peut l’être un navigateur

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

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

QueryExp, comme composite… 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)“ Set s = mBeanServer.queryBeans( new ObjectName(“printer:*"), exp);

Chargement dynamique de MBean Agent M-Let register, unregister Description XML

M-Let Comment M-Let agent

Chargement dynamique de MBean M-Let « URLClassLoader » Associé à un descripteur en XML <MLET CODE=Sensor ARCHIVE=sensor.jar CODEBASE=http://jfod.cnam.fr/NSY102/jmx/ NAME=Sensor:name=Sensor1> </MLET> Descripteur XML, nommé sensor.mlet, à cette URL http://jfod.cnam.fr/NSY102/jmx/sensor.mlet

Mlet en séquence

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(); }

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

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); }

M-Let File <MLET CODE="className" | OBJECT="serializedObjectFileName" ARCHIVE="classOrJarFileName" [CODEBASE="relativePathToArchive"] [NAME="mbeanObjectName"] [VERSION="version"] > [<ARG TYPE="type" VALUE="value">] </MLET> [<ARG TYPE="type" VALUE="value">] Adaptés au constructeurs avec paramètres Exemple <ARG TYPE=int VALUE=3000>

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

Retour au sommaire

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)

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 ( Ce sera NotificationBroadcaster.getNotificationInfo() qui sera déclenchée)

MBeanInfo et plus …

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

JConsole et Applet Extrait de http://blogs.sun.com/lmalventosa/ Développer une interface AppletteXXXXXMBean une classe AppletteXXXXX extends JApplet implements AppletteXXXXXMBean 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" >

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

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

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 …

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(); }

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 mbs.unregisterMBean(name); source complet ici http://jfod.cnam.fr/NSY102/appletteServeurWebMBean/

Conclusion JMX est bien un framework/canevas Plug-in et JMX 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 …

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

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] 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

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

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

Sécuriser les accès Extrait de http://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();

Sécuriser 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();