Successfully reported this slideshow.
We use your LinkedIn profile and activity data to personalize ads and to show you more relevant ads. You can change your ad preferences anytime.

Jopr Plugin Development

2,299 views

Published on

Published in: Technology, Art & Photos
  • Be the first to comment

Jopr Plugin Development

  1. 1. JON Plugins
  2. 2. Conceitos Serviços Servidores Plataformas 2
  3. 3. Serviços Recursos Servidores Plataformas 3
  4. 4. Hierarquia entre Recursos 4
  5. 5. 5
  6. 6. EJB, WebApp, Recursos Filhos Datasource JBoss App Server Recurso iMac Recurso Pai 6
  7. 7. Service BuscadorBean Server JBoss EAP 4.3 Plataform Mac OS X Recurso Categoria Tipo 7
  8. 8. ? Por que cada tipo de recurso tem métricas e operações distintos? 8
  9. 9. Métricas da Métricas do plataforma servidor 9
  10. 10. Operações da plataforma Operações do servidor 10
  11. 11. ? Por que alguns recursos são automaticamente descobertos e outros não? 11
  12. 12. É tudo culpa do agente! 12
  13. 13. Arquitetura do RHQ/Jopr/JON http://www.redhat.com/f/pdf/Write_A_Plugin_WP_web.pdf 13
  14. 14. 14
  15. 15. Arquitetura do jon-agent http://www.redhat.com/f/pdf/Write_A_Plugin_WP_web.pdf 15
  16. 16. Serviços só são descobertos e monitorados pelo JON devido à existência de plugins específicos jon-agent plugins ... 16
  17. 17. Mas e se houver um serviço cuja monitoração é desejada mas para o qual ainda não existam plugins? jon-agent plugins ... 17
  18. 18. Agora sim! jon-agent plugins 18
  19. 19. B AM u c o s t n i i i n v t e i o s t r s y i n g 19
  20. 20. business intelligence? 20
  21. 21. Desenvolva seus próprios plugins! http://www.jboss.org/community/docs/DOC-12824 http://support.rhq-project.org/display/RHQ/RHQ+Plugin+Community 21
  22. 22. a ert cob des mé tric as op er aç ões 22
  23. 23. facets 23
  24. 24. Step-by-Step 1. descoberta 2. métricas 3. operações 24
  25. 25. plugin descriptor discovery plugin component component 25
  26. 26. App Package Descriptor WebApp WAR web.xml Portlet WAR portlet.xml EJB JAR ejb-jar.xml MIDlet JAR MANIFEST Enterprise App EAR application.xml MBeans SAR *-service.xml Connectors RAR JON Plugin JAR rhq-plugin.xml 26
  27. 27. http://viewvc.rhq-project.org/cgi-bin/viewvc.cgi/rhq/trunk/modules/core/client-api/src/main/resources/rhq-plugin.xsd?view=log 27
  28. 28. Discovery Component public class BuscadorDiscovery implements ResourceDiscoveryComponent { public Set discoverResources(ResourceDiscoveryContext discoveryContext) { // Implementa a regra de descoberta do Buscador // (via tabela de processos, arquivo em disco, porta TCP/IP, etc) // Monta e retorna colecao com os recursos descobertos. } } 28
  29. 29. Plugin Component public class BuscadorComponent implements ResourceComponent { public AvailabilityType getAvailability() { // Regra para verificar se o recurso esta disponivel ou nao. } public void start(ResourceContext context) { // Inicializa conexao com o rescurso } public void stop() { // Finaliza conexao com o recurso } } 29
  30. 30. Plugin Component public class BuscadorComponent implements ResourceComponent, MeasurementFacet { public void getValues(MeasurementReport report, Set metrics) { // Recuperar e armazenar em ‘report’ o valor de // cada metrica presente em ‘metrics’ } } 30
  31. 31. Primeiro Plugin ...a gente nunca esquece... 31
  32. 32. $ svn co http://anonsvn.jboss.org/repos/jopr/trunk A trunk/.classpath A trunk/LICENSE_LGPL A trunk/LICENSE A trunk/.project A trunk/LICENSE_GPL é preciso obter o A trunk/modules código fonte do Jopr ou A trunk/modules/plugins do RHQ Project A trunk/modules/plugins/hibernate A trunk/modules/plugins/hibernate/src A trunk/modules/plugins/hibernate/src/test A trunk/modules/plugins/hibernate/src/test/java A trunk/modules/plugins/hibernate/src/test/java/org A trunk/modules/plugins/hibernate/src/test/java/org/rhq A trunk/modules/plugins/hibernate/src/test/java/org/rhq/plugins A trunk/modules/plugins/hibernate/src/test/java/org/rhq/plugins/hibernate ... A trunk/etc/jbas5-ejb-client/src/main/java A trunk/etc/jbas5-ejb-client/src/main/java/test A trunk/etc/jbas5-ejb-client/src/main/java/test/EjbClient.java A trunk/etc/jbas5-ejb-client/pom.xml A trunk/.settings A trunk/.settings/org.eclipse.jdt.core.prefs A trunk/.settings/org.maven.ide.eclipse.prefs U trunk Checked out revision 673. 32
  33. 33. existe um gerador de plugins! download 33
  34. 34. execute o gerador de plugins $ java -jar rhq-pluginGen-1.2.2-jar-with-dependencies.jar Please specify the plugin root category PLATFORM(P), SERVER(S), SERVICE(I), i Please specify its PackagePrefix: br.com.seatecnologia.monitoring.buscador Please specify its FileSystemRoot: /Users/alegomes/Code/jboss.org/jopr/trunk/modules/plugins Please specify its ComponentClass: BuscadorComponent Please specify its DiscoveryClass: BuscadorDiscovery Please specify if it should support Events (y/N): Please specify its ParentType: Please specify if it should support Monitoring (y/N): y Please specify if it should support Operations (y/N): Please specify if it should support Singleton (y/N): Please specify if it should support ResourceConfiguration (y/N): Please specify if it should support CreateChildren (y/N): Please specify if it should support UsesExternalJarsInPlugin (y/N): Please specify if it should support DeleteChildren (y/N): Please specify if it should support ManualAddOfChildren (y/N): Please specify if it should support UsePluginLifecycleListenerApi (y/N): Please specify its Name: buscador Please specify its Description: Plugin para acompanhamento da execucao do aplicativo de simulacao de memory leaks Do you want to add a child to buscador? (y/N) Don't forget to add your plugin to the parent pom.xml responda as questões 34
  35. 35. $ ls -1 /Users/alegomes/Code/jboss.org/jopr/trunk/modules/plugins JBossOSGi buscador hibernate jboss-as jboss-as-5 plugin gerado já na pasta jboss-cache de plugins do Jopr pluginGen.log pom.xml rhq-server tomcat $ ls -1 /Users/alegomes/Code/jboss.org/jopr/trunk/modules/plugins/buscador pom.xml src plugin gerado como projeto Maven 35
  36. 36. .deb apt-get .rpm yum .jar maven 36
  37. 37. arquivo de configuração do Maven 37
  38. 38. código fonte do plugin 37
  39. 39. arquivos de configuração do plugin 37
  40. 40. Discovery e Plugin Components 38
  41. 41. descritor do plugin 39
  42. 42. 40
  43. 43. src/main/resources/META-INF/rhq-plugin.xml <plugin-configuration> <!-- TODO add your own here --> </plugin-configuration> comente isto por enquanto para testarmos apenas o build e deploy do plugin <!-- plugin-configuration> <!- TODO add your own here -> </plugin-configuration --> 41
  44. 44. mvn compile mvn package mvn clean ... http://maven.apache.org/guides/introduction/introduction-to-the-lifecycle.html 42
  45. 45. mvn package [INFO] Failed to resolve artifact. GroupId: org.rhq erro ao ArtifactId: rhq-plugins-parent executar o Version: 1.2.0-SNAPSHOT ‘mvn package’ Reason: Unable to download the artifact from any repository <parent> <groupId>org.rhq</groupId> <artifactId>rhq-plugins-parent</artifactId> <version>1.2.0-SNAPSHOT</version><!-- TODO adjust RHQ version --> </parent> pom.xml lib requerida pelo plugin gerado 43
  46. 46. Repositórios JBoss http://repository.jboss.org/maven2 Releases oficiais de libs JBoss e.g. 1.2.0.GA http://snapshots.jboss.org/maven2 Libs JBoss ainda em desenvolvimento e.g. 1.3.0-SNAPSHOT 44
  47. 47. repositório oficial não possui a versão 1.2.0-SNAPSHOT repositório de snapshots até possui a versão 1.2.0-SNAPSHOT, mas já estão desenvolvendo a 1.3.0-SNAPSHOT 45
  48. 48. pom.xml alteração da versão da lib <parent> <groupId>org.rhq</groupId> <artifactId>rhq-plugins-parent</artifactId> <version>1.2.0.GA</version><!-- TODO adjust RHQ version --> </parent> ... <repositories> <repository> <id>jboss</id> <name>JBoss Repository</name> <url>http://repository.jboss.org/maven2/</url> </repository> </repositories> inclusão de um dos repositórios do JBoss 46
  49. 49. jopr/modules/plugins/buscador$ mvn package [INFO] Scanning for projects... Downloading: http://repository.jboss.org/maven2//org/rhq/rhq-plugins- parent/1.2.0.GA/rhq-plugins-parent-1.2.0.GA.pom 3K downloaded Downloading: http://repository.jboss.org/maven2//org/rhq/rhq-parent/ 1.2.0.GA/rhq-parent-1.2.0.GA.pom 19K downloaded Downloading: http://repository.jboss.org/maven2//org/apache/maven/wagon/ wagon-scm/1.0-beta-4/wagon-scm-1.0-beta-4.pom ... Downloading: http://repository.jboss.org/maven2//commons-lang/commons- lang/2.1/commons-lang-2.1.jar 202K downloaded [INFO] [jar:jar] [INFO] Building jar: /Volumes/Data/Code/jboss.org/jopr/modules/plugins/ buscador/target/buscador-plugin-1.2.0.GA.jar [INFO] ------------------------------------------------------------------------ [INFO] BUILD SUCCESSFUL [INFO] ------------------------------------------------------------------------ [INFO] Total time: 8 minutes 16 seconds [INFO] Finished at: Fri May 29 00:45:29 BRT 2009 [INFO] Final Memory: 16M/126M [INFO] ------------------------------------------------------------------------ 47
  50. 50. Deploy jopr/trunk/modules/plugins/buscador alegomes$ cp target/buscador-plugin-1.2.0.GA.jar ~/JavaTools/jon-server-2.2.0.GA/jbossas/server/ default/deploy/rhq.ear/rhq-downloads/rhq-plugins/ 06:05:33,763 INFO [ProductPluginDeployer] Discovered agent plugin [buscador] 06:05:34,406 INFO [ProductPluginDeployer] Deploying [1] new or updated agent plugins: [buscador] log do jon-server 48
  51. 51. ./rhq-server.sh console ... 07:22:52,375 INFO [EARDeployer] Init J2EE application: file:/Volumes/Data/Applications/JavaTools/ jon-server-2.2.0.GA/jbossas/server/default/deploy/rhq.ear/ 07:23:01,581 INFO [SchedulerService] Scheduler has a default operation timeout of [600] seconds. 07:23:03,094 INFO [CoreServer] Version=[1.2.0.GA], Build Number=[3862], Build Date=[27.Apr.2009 16.56.25 EDT] 07:23:20,790 INFO [ProductPluginDeployer] Discovered agent plugin [buscador] 07:23:22,726 INFO [ProductPluginDeployer] Discovered agent plugin [Hibernate] 07:23:24,821 INFO [ProductPluginDeployer] Discovered agent plugin [JBossAS] 07:23:25,988 INFO [ProductPluginDeployer] Discovered agent plugin [RHQServer] 07:23:27,329 INFO [ProductPluginDeployer] Discovered agent plugin [RHQAgent] 07:23:28,437 INFO [ProductPluginDeployer] Discovered agent plugin [Apache] 07:23:29,579 INFO [ProductPluginDeployer] Discovered agent plugin [Database] 07:23:30,776 INFO [ProductPluginDeployer] Discovered agent plugin [IIS] 07:23:31,938 INFO [ProductPluginDeployer] Discovered agent plugin [JMX] 07:23:32,947 INFO [ProductPluginDeployer] Discovered agent plugin [Platforms] 07:23:33,940 INFO [ProductPluginDeployer] Discovered agent plugin [Postgres] 07:23:34,366 INFO [PersistenceUnitDeployment] Starting persistence unit persistence.units:ear=rhq.ear,unitName=rhqpu 07:23:34,786 INFO [Version] Hibernate EntityManager 3.2.1.GA ... 49
  52. 52. sudo ./rhq-agent.sh rhq-agent-jon-2.2.0/bin alegomes$ sudo ./rhq-agent.sh RHQ 1.2.0.GA [3862] (Mon Apr 27 17:55:22 BRT 2009) > > plugins info Plugins that are currently installed: jopr-hibernate-plugin-2.2.0.GA.jar Plugin Name: Hibernate Last Updated: May 27, 2009 6:38:29 PM BRT File Size: 11,008 bytes MD5 Hashcode: d8540d9ff5e15867f7e19bd755fe1afe ... rhq-postgres-plugin-1.2.0.GA.jar Plugin Name: Postgres Last Updated: May 27, 2009 6:38:26 PM BRT File Size: 475,851 bytes MD5 Hashcode: 7049b7b7d33ec5f5ebb903ffdb9f5e85 Total number of plugins currently installed: [10] > 50
  53. 53. sudo ./rhq-agent.sh > plugins update The plugin container has been stopped. Updating plugins to their latest versions. The plugin [buscador-plugin-1.2.0.GA.jar] has been updated. Completed updating the plugins to their latest versions. The plugin container has been started. > 51
  54. 54. sudo ./rhq-agent.sh > plugins info Plugins that are currently installed: buscador-plugin-1.2.0.GA.jar Plugin Name: buscador Last Updated: May 29, 2009 7:29:26 AM BRT File Size: 6,567 bytes MD5 Hashcode: 2bd7e8dcbd206ee56a9aec9f6b9b6e6d jopr-hibernate-plugin-2.2.0.GA.jar Plugin Name: Hibernate Last Updated: May 27, 2009 6:38:29 PM BRT File Size: 11,008 bytes MD5 Hashcode: d8540d9ff5e15867f7e19bd755fe1afe ... rhq-postgres-plugin-1.2.0.GA.jar Plugin Name: Postgres Last Updated: May 27, 2009 6:38:26 PM BRT File Size: 475,851 bytes MD5 Hashcode: 7049b7b7d33ec5f5ebb903ffdb9f5e85 Total number of plugins currently installed: [11] 52
  55. 55. Auto-Discovery 53
  56. 56. Discovery Component import org.rhq.core.pluginapi.inventory.ResourceDiscoveryComponent; public class BuscadorDiscovery implements ResourceDiscoveryComponent { public Set discoverResources(ResourceDiscoveryContext discoveryContext) throws Exception { // Todos os recursos descobertos serao agrupados neste conjunto Set discoveredResources = new HashSet(); // Implementa a regra de descoberta do Buscador // (via tabela de processos, arquivo em disco, porta TCP/IP, etc) // Cria objeto que represente o recurso descoberto DiscoveredResourceDetails detail = .....; // Adicione cada um dos recursos descobertos ao resultado discoveredResources.add(detail); return discoveredResources; } 54
  57. 57. Process Scan Process Info Query Language Process|basename|match=^java.*,arg|org.jboss.Main|match=.* process|pidfile|match=/etc/product/lock.pid List<ProcessScanResult> autoDiscoveryResults = context.getAutoDiscoveredProcesses(); for (ProcessScanResult result : autoDiscoveryResults) { ProcessInfo procInfo = result.getProcessInfo(); ... DiscoveredResourceDetails detail = new DiscoveredResourceDetails( resourceType, key, name, null, description, childConfig, procInfo ); result.add(detail); } Discovery Component 55
  58. 58. 56
  59. 59. Plugin Component public class BuscadorComponent implements ResourceComponent { public AvailabilityType getAvailability() { // Regra para verificar se o recurso esta disponivel ou nao. return AvailabilityType.UP; } public void start(ResourceContext context) throws Exception { // Inicializa conexao com o rescurso } public void stop() { // Finaliza conexao com o recurso } } 57
  60. 60. Plugin Component public class BuscadorComponent implements ResourceComponent, MeasurementFacet { /** * Coleta valores das metricas mapeadas no descritor */ public void getValues(MeasurementReport report, Set metrics) throws Exception { for (MeasurementScheduleRequest metrica : metrics) { if (metrica.getName().equals("umaMetricaQualquer")) { MeasurementDataNumeric valor = null; valor = new MeasurementDataNumeric(metrica, Double.valueOf(VALOR_QUALQUER)); report.addData(valor); } // Fazer a mesma coisa para as outras metricas } } 58
  61. 61. plugin-configuration <plugin-configuration> </plugin-configuration> 59
  62. 62. plugin-configuration 60
  63. 63. plugin-configuration <plugin-configuration> <c:simple-property name="contexto" type="string" required="true" /> </plugin-configuration> 61
  64. 64. plugin-configuration 62
  65. 65. Measurement Facet <!-- jboss.web:name=http-0.0.0.0-8080,type=ThreadPool:currentThreadsBusy --> <metric property="jboss.web:name=%schema%%dash%%address%-%port%,type=ThreadPool:currentThreadsBusy" displayName="Threads Active" defaultOn="true" category="utilization" displayType="summary"/> public void getValues(MeasurementReport report, Set<MeasurementScheduleRequest> requests) { ... } 63
  66. 66. Configuration Facet <resource-configuration> <c:group name="connection" displayName="Connection Information"> <c:simple-property name="type"> <c:property-options> <c:option value="no-tx-datasource" name="No TX Datasource"/> <c:option value="local-tx-datasource" name="Local TX Datasource" default="true"/> <c:option value="xa-datasource" name="XA Datasource"/> </c:property-options> </c:simple-property> ... </resource-configuration> 64
  67. 67. Operation Facet <operation name="start" displayName="Start" description="Start this application server. The script used is specified in the Operations group of connection properties."> <results> <c:simple-property name="operationResult" description="Outcome of starting the server."/> </results> </operation> public OperationResult invokeOperation(String name, Configuration configuration) throws InterruptedException { JBossASServerSupportedOperations operation = Enum.valueOf(JBossASServerSupportedOperations.class, name.toUpperCase()); return operationsDelegate.invoke(operation, configuration); } 65
  68. 68. Content Facet <content name="cumulativePatch" displayName="Cumulative Patch" category="deployable" description="Automatically installable application server patches"> <configuration> <c:simple-property name="jiraId"/> <c:simple-property name="distributionStatus"/> <c:simple-property name="downloadUrl"/> <c:simple-property name="instructionCompatibilityVersion"/> </configuration> </content> // ContentFacet Implementation -------------------------------------------- public List<DeployPackageStep> generateInstallationSteps(ResourcePackageDetails packageDetails) { return contentFacetDelegate.generateInstallationSteps(packageDetails); } public DeployPackagesResponse deployPackages(Set<ResourcePackageDetails> packages, ContentServices contentServices) { return contentFacetDelegate.deployPackages(packages, contentServices); } public RemovePackagesResponse removePackages(Set<ResourcePackageDetails> packages) { return contentFacetDelegate.removePackages(packages); } public Set<ResourcePackageDetails> discoverDeployedPackages(PackageType type) { return contentFacetDelegate.discoverDeployedPackages(type); } public InputStream retrievePackageBits(ResourcePackageDetails packageDetails) { return contentFacetDelegate.retrievePackageBits(packageDetails); } 66
  69. 69. Event Facet <event name="logEntry" description="an entry in a log file"/> public void start(ResourceContext context) throws Exception { ... this.logFileEventDelegate = new LogFileEventResourceComponentHelper(this.resourceContext); this.logFileEventDelegate.startLogFileEventPollers(); } public void stop() { this.logFileEventDelegate.stopLogFileEventPollers(); ... } 67
  70. 70. Baixe, instale e configure o Maven Baixe e descompacte o código fonte do Jopr Baixe e execute o gerador de plugins Faça o deploy do plugin gerado Experimente a PIQL Explore suas facetas 68
  71. 71. JUST DO IT 69 Sugestão: inspire-se no exemplo RHQ_httptest2.zip, disponível no servidor.
  72. 72. Q&A

×