1 /*
   2  * Copyright (c) 2018, Oracle and/or its affiliates. All rights reserved.
   3  * 
   4  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   5  *
   6  * The contents of this file are subject to the terms of either the Universal Permissive License
   7  * v 1.0 as shown at http://oss.oracle.com/licenses/upl
   8  *
   9  * or the following license:
  10  *
  11  * Redistribution and use in source and binary forms, with or without modification, are permitted
  12  * provided that the following conditions are met:
  13  * 
  14  * 1. Redistributions of source code must retain the above copyright notice, this list of conditions
  15  * and the following disclaimer.
  16  * 
  17  * 2. Redistributions in binary form must reproduce the above copyright notice, this list of
  18  * conditions and the following disclaimer in the documentation and/or other materials provided with
  19  * the distribution.
  20  * 
  21  * 3. Neither the name of the copyright holder nor the names of its contributors may be used to
  22  * endorse or promote products derived from this software without specific prior written permission.
  23  * 
  24  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR
  25  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
  26  * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
  27  * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
  28  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  29  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
  30  * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY
  31  * WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  32  */
  33 package org.openjdk.jmc.agent;
  34 
  35 import java.io.File;
  36 import java.io.FileInputStream;
  37 import java.io.FileNotFoundException;
  38 import java.io.InputStream;
  39 import java.lang.instrument.Instrumentation;
  40 import java.util.logging.Level;
  41 import java.util.logging.Logger;
  42 
  43 import javax.xml.stream.XMLStreamException;
  44 
  45 import org.openjdk.jmc.agent.impl.DefaultTransformRegistry;
  46 import org.openjdk.jmc.agent.jmx.AgentManagementFactory;
  47 
  48 /**
  49  * Small ASM based byte code instrumentation agent for declaratively adding logging and JFR events.
  50  * Note: This agent is currently work in progress, and it is not supported for production use yet.
  51  */
  52 public class Agent {
  53         /**
  54          * This should be generated as part of the build later.
  55          */
  56         public final static String VERSION = "0.0.1"; //$NON-NLS-1$
  57         private final static String DEFAULT_CONFIG = "jfrprobes.xml"; //$NON-NLS-1$
  58 
  59         @SuppressWarnings("unused")
  60         private static Instrumentation instrumentationInstance;
  61 
  62         /**
  63          * This method is run when the agent is started from the command line.
  64          *
  65          * @param agentArguments
  66          *            the arguments to the agent, in this case the path to the config file.
  67          * @param instrumentation
  68          *            the {@link Instrumentation} instance, provided to us by the kind JVM.
  69          */
  70         public static void premain(String agentArguments, Instrumentation instrumentation) {
  71                 printVersion();
  72                 getLogger().fine("Starting from premain"); //$NON-NLS-1$
  73                 initializeAgent(agentArguments, instrumentation);
  74         }
  75 
  76         /**
  77          * This method is run when the agent is loaded dynamically.
  78          *
  79          * @param agentArguments
  80          *            the arguments to the agent, in this case the path to the config file.
  81          * @param instrumentation
  82          *            the {@link Instrumentation} instance, provided to us by the kind JVM.
  83          */
  84         public static void agentmain(String agentArguments, Instrumentation instrumentation) {
  85                 printVersion();
  86                 getLogger().fine("Starting from agentmain"); //$NON-NLS-1$
  87                 initializeAgent(agentArguments, instrumentation);
  88         }
  89 
  90         /**
  91          * This method can be used to initialize the BCI agent when using it as a stand alone library.
  92          *
  93          * @param configuration
  94          *            the configuration options, as XML. The stream will be fully read, but not closed.
  95          * @param instrumentation
  96          *            the {@link Instrumentation} instance.
  97          * @throws XMLStreamException
  98          *             if the configuration could not be read.
  99          */
 100         public static void initializeAgent(InputStream configuration, Instrumentation instrumentation)
 101                         throws XMLStreamException {
 102                 TransformRegistry registry = DefaultTransformRegistry.from(configuration);
 103                 instrumentationInstance = instrumentation;
 104                 instrumentation.addTransformer(new Transformer(registry));
 105                 AgentManagementFactory.createAndRegisterAgentControllerMBean(instrumentation, registry);
 106         }
 107 
 108         /**
 109          * @return the Logger to use for agent related status information.
 110          */
 111         public static Logger getLogger() {
 112                 return Logger.getLogger(Agent.class.getName());
 113         }
 114 
 115         /**
 116          * Loads the configuration from the file specified in the agentArguments, and initializes the
 117          * agent.
 118          *
 119          * @param agentArguments
 120          *            the file to load from.
 121          * @param instrumentation
 122          *            the {@link Instrumentation} instance.
 123          */
 124         private static void initializeAgent(String agentArguments, Instrumentation instrumentation) {
 125                 if (agentArguments == null || agentArguments.trim().length() == 0) {
 126                         agentArguments = DEFAULT_CONFIG;
 127                 }
 128                 File file = new File(agentArguments);
 129                 try {
 130                         InputStream stream = new FileInputStream(file);
 131                         initializeAgent(stream, instrumentation);
 132                 } catch (FileNotFoundException | XMLStreamException e) {
 133                         getLogger().log(Level.SEVERE, "Failed to read jfr probe definitions from " + file.getPath(), e); //$NON-NLS-1$
 134                 }
 135         }
 136 
 137         private static void printVersion() {
 138                 Logger.getLogger(Agent.class.getName()).info(String.format("JMC BCI agent v%s", VERSION)); //$NON-NLS-1$
 139         }
 140 }