com.newrelic.metrics.publish.configuration.ConfigurationException Java Examples

The following examples show how to use com.newrelic.metrics.publish.configuration.ConfigurationException. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: AgentFactory.java    From metrics_publish_java with MIT License 6 votes vote down vote up
void createConfiguredAgents(Runner runner) throws ConfigurationException {
    if (Config.getValue("agents") != null) {
        if ( !(Config.getValue("agents") instanceof JSONArray) ) {
            throw new ConfigurationException("Plugin 'agents' JSON configuration must be an array");
        }
        
        JSONArray json = Config.getValue("agents");
        for (int i = 0; i < json.size(); i++) {
            JSONObject obj = (JSONObject) json.get(i);
            @SuppressWarnings("unchecked")
            Map<String, Object> map = obj;
            createAndRegister(runner, map);
        }
    } else {
        createAndRegister(runner, new HashMap<String, Object>());
    }
}
 
Example #2
Source File: AgentFactory.java    From metrics_publish_java with MIT License 6 votes vote down vote up
/**
 * Read in JSON file from the provided filename.
 * Now deprecated and will be removed in a future release.
 * <p>
 * See {@link Config#getValue(String)} for using the new {@code plugin.json} configuration file.
 * @param filename the filename to read in
 * @return JSONArray the JSONArray that represents the JSON file
 * @throws ConfigurationException if an error occurs reading in or parsing the JSON file
 */
@Deprecated
public JSONArray readJSONFile(String filename) throws ConfigurationException {
    Object parseResult = null;

    File file = getConfigurationFile(filename);

    try {
        FileReader reader = new FileReader(file);
        JSONParser parser = new JSONParser();

        try {
            parseResult = parser.parse(reader);
        } catch (ParseException e) {
            throw logAndThrow("Error parsing config file " + file.getAbsolutePath());
        }
    } catch(IOException ioEx) {
        throw logAndThrow("Error reading config file " + file.getAbsolutePath());
    }
    
    JSONArray json = (JSONArray) parseResult;
    return json;
}
 
Example #3
Source File: Runner.java    From metrics_publish_java with MIT License 6 votes vote down vote up
/**
 * Constructs a {@code Runner}
 * @throws ConfigurationException if there is a configuration issue
 */
public Runner() throws ConfigurationException {
    super();
    componentAgents = new LinkedList<Agent>();

    try {
        Config.init();
        Logger.init(Config.getValue("log_level", "info"),
                    Config.getValue("log_file_path", "logs"),
                    Config.getValue("log_file_name", "newrelic_plugin.log"),
                    getLogLimitInKilobytes());
        logger = Logger.getLogger(Runner.class);
        config = new SDKConfiguration();
    } catch (Exception e) {
        throw new ConfigurationException(e.getMessage());
    }
}
 
Example #4
Source File: MySQLAgentFactory.java    From newrelic_mysql_java_plugin with MIT License 5 votes vote down vote up
/**
 * Configure an agent based on an entry in the properties file. There may be
 * multiple agents per plugin
 */
@Override
public Agent createConfiguredAgent(Map<String, Object> properties) throws ConfigurationException {
    String name = (String) properties.get("name");
    String host = (String) properties.get("host");
    String user = (String) properties.get("user");
    String passwd = (String) properties.get("passwd");
    String conn_properties = (String) properties.get("properties");
    String metrics = (String) properties.get("metrics");

    if (name == null || EMPTY_STRING.equals(name)) {
        throw new ConfigurationException("The 'name' attribute is required. Have you configured the 'config/plugin.json' file?");
    }
    
    /**
     * Use pre-defined defaults to simplify configuration
     */
    if (host == null || EMPTY_STRING.equals(host)) {
        host = MySQLAgent.AGENT_DEFAULT_HOST;
    }
    if (user == null || EMPTY_STRING.equals(user)) {
        user = MySQLAgent.AGENT_DEFAULT_USER;
    }
    if (passwd == null) {
        passwd = MySQLAgent.AGENT_DEFAULT_PASSWD;
    }
    if (conn_properties == null || EMPTY_STRING.equals(conn_properties)) {
        conn_properties = MySQLAgent.AGENT_DEFAULT_PROPERTIES;
    }
    if (metrics == null || EMPTY_STRING.equals(metrics)) {
        metrics = MySQLAgent.AGENT_DEFAULT_METRICS;
    }

    return new MySQLAgent(name, host, user, passwd, conn_properties,
            processMetricCategories(metrics), readCategoryConfiguration());
}
 
Example #5
Source File: MySQLAgentFactory.java    From newrelic_mysql_java_plugin with MIT License 5 votes vote down vote up
/**
 * Read metric category information that enables the dynamic definition of
 * MySQL metrics that can be collected.
 * 
 * @return Map Categories and the meta data about the categories
 * @throws ConfigurationException
 */
public Map<String, Object> readCategoryConfiguration() throws ConfigurationException {
    Map<String, Object> metricCategories = new HashMap<String, Object>();
    try {
        JSONArray json = readJSONFile(CATEGORY_CONFIG_FILE);
        for (int i = 0; i < json.size(); i++) {
            JSONObject obj = (JSONObject) json.get(i);
            String category = (String) obj.get("category");
            metricCategories.put(category, obj);
        }
    } catch (ConfigurationException e) {
        throw new ConfigurationException("'metric_categories' could not be found in the 'plugin.json' configuration file");
    }
    return metricCategories;
}
 
Example #6
Source File: Main.java    From newrelic_mysql_java_plugin with MIT License 5 votes vote down vote up
public static void main(String[] args) {
    try {
        Runner runner = new Runner();
        runner.add(new MySQLAgentFactory());
        runner.setupAndRun(); // Never returns
    } catch (ConfigurationException e) {
        System.err.println("ERROR: " + e.getMessage());
        System.exit(1);
    }
}
 
Example #7
Source File: TestMySQLAgentFactory.java    From newrelic_mysql_java_plugin with MIT License 5 votes vote down vote up
@SuppressWarnings("unchecked")
@Test
public void verifyMetricCategoryConfiguration() {

    MySQLAgentFactory factory = new MySQLAgentFactory();
    Map<String, Object> categories = null;
    try {
        categories = factory.readCategoryConfiguration();
    } catch (ConfigurationException e) {
        fail(e.getMessage());
    }
    assertEquals(7, categories.size());
    Object status = categories.get("status");
    assertNotNull(status);
    Map<String, String> map = (Map<String, String>) status;
    assertEquals("SHOW GLOBAL STATUS", map.get("SQL"));
    assertEquals("set", map.get("result"));

    Object slave = categories.get("slave");
    assertNotNull(slave);
    map = (Map<String, String>) slave;
    assertEquals("SHOW SLAVE STATUS", map.get("SQL"));
    assertEquals("row", map.get("result"));

    Object mutex = categories.get("innodb_mutex");
    assertNotNull(mutex);
    map = (Map<String, String>) mutex;
    assertEquals("SHOW ENGINE INNODB MUTEX", map.get("SQL"));
    assertEquals("special", map.get("result"));

    Object doesnotexist = categories.get("doesnotexist");
    assertNull(doesnotexist);

}
 
Example #8
Source File: TestMySQLAgentFactory.java    From newrelic_mysql_java_plugin with MIT License 5 votes vote down vote up
@Ignore
@Test
public void verifyMetricCategoryValueAttribute() {
    MySQLAgentFactory factory = new MySQLAgentFactory();
    Map<String, Object> categories = null;
    try {
        categories = factory.readCategoryConfiguration();
    } catch (ConfigurationException e) {
        fail(e.getMessage());
    }
    assertEquals(7, categories.size());

    Object status = categories.get("status");
    assertNotNull(status);
    @SuppressWarnings("unchecked")
    Map<String, String> map = (Map<String, String>) status;
    String valueMetrics = map.get("value_metrics");
    assertNotNull(valueMetrics);
    Set<String> metrics = new HashSet<String>(Arrays.asList(valueMetrics.toLowerCase().split(COMMA)));
    assertEquals(19, metrics.size());
    assertTrue(metrics.contains("uptime"));
    assertFalse(metrics.contains("com_select"));
    String counterMetrics = map.get("counter_metrics");
    assertNotNull(counterMetrics);
    metrics = new HashSet<String>(Arrays.asList(counterMetrics.toLowerCase().split(COMMA)));
    assertEquals(196, metrics.size());

}
 
Example #9
Source File: Main.java    From newrelic-elasticsearch with MIT License 5 votes vote down vote up
public static void main(String[] args) {
    try {
        Runner runner = new Runner();
        runner.add(new ElasticsearchAgentFactory());
        runner.setupAndRun(); // Never returns
    } catch (ConfigurationException e) {
        System.err.println("ERROR: " + e.getMessage());
        System.exit(-1);
    }
}
 
Example #10
Source File: Main.java    From newrelic-unix-plugin with MIT License 5 votes vote down vote up
private static void checkPluginFile() throws ConfigurationException {
	File pluginConfigFile = new File(Config.getConfigDirectory() + File.separator + "plugin.json");
	if(!pluginConfigFile.exists()) {
		System.err.println("WARNING: " + pluginConfigFile.toString() + " does not exist");
		String thisOS = System.getProperty("os.name").toLowerCase().trim();
		String thisVer = System.getProperty("os.version").trim();
		
		if(thisOS.contains("os x")) {
			thisOS = "osx";
		} else if(thisOS.contains("sunos")) {
			if(thisVer.equals("5.10")) {
				thisOS = "solaris_10";
			} else if(thisVer.equals("5.11")) {
				thisOS = "solaris_11";
			} else {
				throw new ConfigurationException("This version of Solaris isn't supported: " + thisVer);
			}
		}
		
		File specificPluginConfigFile = new File(Config.getConfigDirectory() + File.separator + "plugin.json." + thisOS);
		if(specificPluginConfigFile.exists()) {
			System.err.println("Attempting to copy plugin.json." + thisOS + " to plugin.json");
			try {
				copyFile(specificPluginConfigFile, pluginConfigFile);
				System.err.println("Successfully copied plugin.json." + thisOS + " to plugin.json");
			} catch(IOException ioe) {
				throw new ConfigurationException("Failed to copy plugin.json file for your OS: " + thisOS + "\n" + ioe.getMessage());
			}
		} else {
			throw new ConfigurationException("The plugin.json file for this OS doesn't exist: " + thisOS);
		}
	}
}
 
Example #11
Source File: AgentFactory.java    From metrics_publish_java with MIT License 5 votes vote down vote up
private File getConfigurationFile(String configFileName) throws ConfigurationException {
    String path = Config.getConfigDirectory() + File.separatorChar + configFileName;
    File file = new File(path);
    if (!file.exists()) {
        throw logAndThrow("Cannot find config file " + path);
    }
    return file;
}
 
Example #12
Source File: Main.java    From newrelic-unix-plugin with MIT License 5 votes vote down vote up
public static void main(String[] args) {
	try {
		checkPluginFile();
        Runner runner = new Runner();
        runner.add(new UnixAgentFactory());
        runner.setupAndRun(); // Never returns
    } catch (ConfigurationException e) {
        System.err.println("ERROR: " + e.getMessage());
        System.exit(-1);
    }
}
 
Example #13
Source File: Runner.java    From metrics_publish_java with MIT License 5 votes vote down vote up
private void setupAgents() throws ConfigurationException {
    logger.debug("Setting up agents to be run");

    createAgents();
    if(config.internalGetServiceURI() != null) {
        logger.info("Metric service URI: ", config.internalGetServiceURI());
    }

    context = new Context();

    Iterator<Agent> iterator = componentAgents.iterator();
    while (iterator.hasNext()) {
        Agent agent = iterator.next();

        setupAgentContext(agent);

        agent.prepareToRun();
        agent.setupMetrics();

        //TODO this is a really awkward place to set the license key on the request
        context.licenseKey = config.getLicenseKey();
        if(config.internalGetServiceURI() != null) {
            context.internalSetServiceURI(config.internalGetServiceURI());
        }
        context.internalSetSSLHostVerification(config.isSSLHostVerificationEnabled());
    }
}
 
Example #14
Source File: UnixAgentFactory.java    From newrelic-unix-plugin with MIT License 4 votes vote down vote up
@Override
public Agent createConfiguredAgent(Map<String, Object> properties) throws ConfigurationException {
	
	String os, command, hostname, iregex, dregex;
	String[] dcommand, icommand;
	
	// Setting agent instance configurations based on plugin.json
	// NOTE: Per-instance properties take precedence over global properties
	
	if (properties.containsKey("debug")) {
		debug = (Boolean) properties.get("debug");
	} else if (global_properties.containsKey("debug")) {
		debug = (Boolean) global_properties.get("debug");
	} else {
		debug = false;
	}
	
	if (properties.containsKey("OS") && !((String) properties.get("OS")).toLowerCase().equals("auto")) {
		os = ((String) properties.get("OS")).toLowerCase();
	} else if (global_properties.containsKey("OS") && !((String) global_properties.get("OS")).toLowerCase().equals("auto")) {
		os = ((String) global_properties.get("OS")).toLowerCase();
	} else {
		os = System.getProperty("os.name").toLowerCase();
	}
	
	if(properties.containsKey("hostname") && !((String)properties.get("hostname")).toLowerCase().equals("auto")) {
		hostname = ((String) properties.get("hostname"));
	} else if (global_properties.containsKey("hostname") && !((String)global_properties.get("hostname")).toLowerCase().equals("auto")) {
		hostname = ((String) global_properties.get("hostname"));
	} else {
		try {
			hostname = java.net.InetAddress.getLocalHost().getHostName(); 
		} catch (Exception e) {
			logger.error("Naming failed: " + e.toString());
			logger.error("Applying default server name (" + kDefaultServerName + ") to this server");
			hostname = kDefaultServerName;
		}
	}
	
	logger.info("Host OS: " + os);
	logger.info("Hostname: " + hostname);
	
	command = ((String) properties.get("command"));
	
	if(os.contains("linux")) {
		umetrics = new LinuxMetrics();
		dcommand = new String[]{};
		dregex = "";
		icommand = new String[]{"ip","link","show"};
		iregex = "\\d+:\\s+(\\w+\\d*):.*";
	} else if (os.contains("aix")) {
		umetrics = new AIXMetrics();
		dcommand = new String[]{};
		dregex = "";
		icommand = new String[]{"/usr/sbin/ifconfig", "-a"};
		iregex = "(\\w+\\d*):\\s+flags.*.*";
	} else if (os.contains("sunos")) {
		umetrics = new SolarisMetrics();
		dcommand = new String[]{};
		dregex = "";
		icommand = new String[]{"/usr/sbin/ifconfig", "-a"};
		iregex = "(\\w+\\d*):\\d*:*\\s+flags.*";
	} else if (os.toLowerCase().contains("os x") || os.toLowerCase().contains("osx")) {
		umetrics = new OSXMetrics();
		dcommand = new String[]{"diskutil", "list"};
		dregex = "\\/dev\\/(\\w+\\d*)\\s+\\([\\w\\s,]+\\):.*";			
		icommand = new String[]{"ifconfig", "-a"};
		iregex = "(\\w+\\d*):\\s+flags.*";
	} else {
		logger.error("Unix Agent could not detect an OS version that it supports.");
		logger.error("Host OS detected: " + os);
		return null;
	}
	
	agentInstanceConfigs.put("os", os);
	agentInstanceConfigs.put("command", command);
	agentInstanceConfigs.put("debug", debug);
	agentInstanceConfigs.put("hostname", hostname);
	agentInstanceConfigs.put("dcommand", dcommand);
	agentInstanceConfigs.put("dregex", dregex);
	agentInstanceConfigs.put("icommand", icommand);
	agentInstanceConfigs.put("iregex", iregex);
	
   	return new UnixAgent(umetrics, agentInstanceConfigs);
}
 
Example #15
Source File: Runner.java    From metrics_publish_java with MIT License 4 votes vote down vote up
private void createAgents() throws ConfigurationException {
    for (Iterator<AgentFactory> iterator = factories.iterator(); iterator.hasNext();) {
        AgentFactory factory = (AgentFactory) iterator.next();
        factory.createConfiguredAgents(this);
    }
}
 
Example #16
Source File: AgentFactory.java    From metrics_publish_java with MIT License 4 votes vote down vote up
private ConfigurationException logAndThrow(String message) {
    logger.error(message);
    return new ConfigurationException(message);
}
 
Example #17
Source File: AgentFactory.java    From metrics_publish_java with MIT License 4 votes vote down vote up
private void createAndRegister(Runner runner, Map<String, Object> map) throws ConfigurationException {
    Agent agent = createConfiguredAgent(map);
    logger.debug("Created agent: ", agent);
    runner.register(agent);
}
 
Example #18
Source File: AgentFactory.java    From metrics_publish_java with MIT License 2 votes vote down vote up
/**
 * Return a new instance of the appropriate {@link Agent} subclass, configured with information
 * extracted from the {@code properties}, a {@code Map} of configuration keys and values.
 * The keys and values are the result of processing the {@code agents} section of the 
 * {@code plugin.json} configuration file. The specific keys and legal values are specific 
 * to the domain of the agent. Since the values come in as {@code Object}, casting and 
 * conversion may be required.
 * @param properties the {@code Map} of properties for creating a configured {@link Agent}
 * @throws ConfigurationException if an error occurs while creating a configured {@link Agent}
 * @see Config
*/
public abstract Agent createConfiguredAgent(Map<String, Object> properties) throws ConfigurationException;