Java tutorial
/* 1: */ package com.newrelic.agent; /* 2: */ /* 3: */ import com.newrelic.agent.command.XmlInstrumentOptions; /* 4: */ import com.newrelic.agent.command.XmlInstrumentValidator; /* 5: */ import com.newrelic.agent.deps.org.apache.commons.cli.CommandLine; /* 6: */ import com.newrelic.agent.deps.org.apache.commons.cli.CommandLineParser; /* 7: */ import com.newrelic.agent.deps.org.apache.commons.cli.HelpFormatter; /* 8: */ import com.newrelic.agent.deps.org.apache.commons.cli.Option; /* 9: */ import com.newrelic.agent.deps.org.apache.commons.cli.Options; /* 10: */ import com.newrelic.agent.deps.org.apache.commons.cli.ParseException; /* 11: */ import com.newrelic.agent.deps.org.apache.commons.cli.PosixParser; /* 12: */ import com.newrelic.agent.install.AppServerIdentifier; /* 13: */ import com.newrelic.agent.install.AppServerIdentifier.AppServerType; /* 14: */ import com.newrelic.agent.install.ConfigInstaller; /* 15: */ import com.newrelic.agent.install.SelfInstaller; /* 16: */ import com.newrelic.agent.install.SelfInstallerFactory; /* 17: */ import com.newrelic.agent.instrumentation.verifier.InstrumentationVerifier; /* 18: */ import com.newrelic.agent.instrumentation.verifier.VerificationLogger; /* 19: */ import com.newrelic.agent.logging.IAgentLogger; /* 20: */ import com.newrelic.agent.service.ServiceFactory; /* 21: */ import java.io.File; /* 22: */ import java.io.IOException; /* 23: */ import java.io.PrintStream; /* 24: */ import java.net.URL; /* 25: */ import java.security.CodeSource; /* 26: */ import java.security.ProtectionDomain; /* 27: */ import java.text.MessageFormat; /* 28: */ import java.util.ArrayList; /* 29: */ import java.util.Collection; /* 30: */ import java.util.Collections; /* 31: */ import java.util.HashMap; /* 32: */ import java.util.List; /* 33: */ import java.util.Map; /* 34: */ import java.util.Map.Entry; /* 35: */ import java.util.logging.Level; /* 36: */ /* 37: */ class AgentCommandLineParser /* 38: */ { /* 39: */ private static final String INSTALL_COMMAND = "install"; /* 40: */ private static final String DEPLOYMENT_COMMAND = "deployment"; /* 41: */ private static final String VERIFY_INSTRUMENTATION_COMMAND = "verifyInstrumentation"; /* 42: */ private static final String INSTRUMENT_COMMAND = "instrument"; /* 43: 39 */ private static final Map<String, Options> commandOptionsMap = new HashMap(); /* 44: */ private static final Map<String, String> commandDescriptions; /* 45: */ /* 46: */ static /* 47: */ { /* 48: 40 */ commandOptionsMap.put("deployment", getDeploymentOptions()); /* 49: 41 */ commandOptionsMap.put("install", getInstallOptions()); /* 50: 42 */ commandOptionsMap.put("instrument", getInstrumentOptions()); /* 51: 43 */ commandOptionsMap.put("verifyInstrumentation", getVerifyInstrumentationOptions()); /* 52: */ /* 53: 45 */ commandDescriptions = new HashMap(); /* 54: 46 */ commandDescriptions.put("deployment", "[OPTIONS] [description] Records a deployment"); /* 55: 47 */ commandDescriptions.put("install", "[OPTIONS] Generates a newrelic.yml configuration with the given license key and attempts to integrate with app server"); /* 56: */ /* 57: */ /* 58: 50 */ commandDescriptions.put("instrument", "[OPTIONS] Validates a custom instrumentation xml configuration file."); /* 59: */ } /* 60: */ /* 61: */ public void parseCommand(String[] args) /* 62: */ { /* 63: 61 */ CommandLineParser parser = new PosixParser(); /* 64: */ try /* 65: */ { /* 66: 63 */ CommandLine cmd = parser.parse(getCommandLineOptions(), args); /* 67: */ /* 68: */ /* 69: 66 */ List<String> argList = cmd.getArgList(); /* 70: 67 */ String command = argList.size() > 0 ? (String) argList.get(0) : null; /* 71: 69 */ if (cmd.hasOption('h')) /* 72: */ { /* 73: 70 */ printHelp(command); /* 74: 71 */ return; /* 75: */ } /* 76: 73 */ if (command != null) /* 77: */ { /* 78: 74 */ Options commandOptions = (Options) commandOptionsMap.get(command); /* 79: 75 */ if (commandOptions == null) /* 80: */ { /* 81: 76 */ printHelp(); /* 82: 77 */ System.err.println("\nInvalid command - " + command); /* 83: 78 */ System.exit(1); /* 84: */ } /* 85: 80 */ cmd = parser.parse(commandOptions, args); /* 86: */ } /* 87: 83 */ if ("deployment".equals(command)) /* 88: */ { /* 89: 84 */ deploymentCommand(cmd); /* 90: */ } /* 91: 85 */ else if ("install".equals(command)) /* 92: */ { /* 93: 86 */ installCommand(cmd); /* 94: */ } /* 95: 87 */ else if ("instrument".equals(command)) /* 96: */ { /* 97: 88 */ instrumentCommand(cmd); /* 98: */ } /* 99: 89 */ else if ("verifyInstrumentation".equals(command)) /* 100: */ { /* 101: 90 */ verifyInstrumentation(cmd); /* 102: */ } /* 103: 91 */ else if ((cmd.hasOption('v')) || (cmd.hasOption("version"))) /* 104: */ { /* 105: 92 */ System.out.println(Agent.getVersion()); /* 106: */ } /* 107: */ else /* 108: */ { /* 109: 94 */ printHelp(); /* 110: 95 */ System.exit(1); /* 111: */ } /* 112: */ } /* 113: */ catch (ParseException e) /* 114: */ { /* 115: 98 */ System.err.println("Error parsing arguments"); /* 116: 99 */ printHelp(); /* 117:100 */ System.exit(1); /* 118: */ } /* 119: */ catch (Exception e) /* 120: */ { /* 121:102 */ System.err.println("Error executing command"); /* 122:103 */ e.printStackTrace(); /* 123:104 */ System.exit(1); /* 124: */ } /* 125: */ } /* 126: */ /* 127: */ private void instrumentCommand(CommandLine cmd)/* 128: */ throws Exception /* 129: */ { /* 130:115 */ XmlInstrumentValidator.validateInstrumentation(cmd); /* 131: */ } /* 132: */ /* 133: */ private void deploymentCommand(CommandLine cmd)/* 134: */ throws Exception /* 135: */ { /* 136:119 */ Deployments.recordDeployment(cmd); /* 137: */ } /* 138: */ /* 139: */ private void installCommand(CommandLine cmd)/* 140: */ throws Exception /* 141: */ { /* 142:124 */ System.out.println("***** ( ( o)) New Relic Java Agent Installer"); /* 143:125 */ System.out.println("***** Installing version " + Agent.getVersion() + " ..."); /* 144: */ /* 145:127 */ File newRelicDir = new File( getClass().getProtectionDomain().getCodeSource().getLocation().toURI()).getParentFile(); /* 146: */ /* 147:129 */ File appServerDir = null; /* 148:130 */ if (cmd.getOptionValue('s') != null) { /* 149:131 */ appServerDir = new File(cmd.getOptionValue('s')); /* 150: */ } /* 151:132 */ if ((appServerDir == null) || (!appServerDir.exists()) || (!appServerDir.isDirectory())) { /* 152:133 */ appServerDir = newRelicDir.getParentFile(); /* 153: */ } /* 154:134 */ appServerDir = appServerDir.getCanonicalFile(); /* 155: */ /* 156:136 */ boolean startup_patched = false; /* 157:137 */ boolean config_installed = false; /* 158:138 */ AppServerIdentifier.AppServerType type = AppServerIdentifier.getAppServerType(appServerDir); /* 159:141 */ if ((type == null) || (type == AppServerIdentifier.AppServerType.UNKNOWN)) /* 160: */ { /* 161:142 */ printUnknownAppServer(appServerDir); /* 162: */ } /* 163: */ else /* 164: */ { /* 165:144 */ SelfInstaller installer = SelfInstallerFactory.getSelfInstaller(type); /* 166:145 */ if (installer != null) { /* 167:146 */ startup_patched = installer.backupAndEditStartScript(appServerDir.toString()); /* 168: */ } /* 169: */ } /* 170:150 */ if ((newRelicDir.exists()) && (newRelicDir.isDirectory())) /* 171: */ { /* 172:151 */ if (ConfigInstaller.isConfigInstalled(newRelicDir)) /* 173: */ { /* 174:152 */ System.out.println("No need to create New Relic configuration file because:"); /* 175:153 */ System.out.println(MessageFormat.format(" .:. A config file already exists: {0}", new Object[] { ConfigInstaller.configPath(newRelicDir) })); /* 176: */ /* 177:155 */ config_installed = true; /* 178: */ } /* 179: */ else /* 180: */ { /* 181: */ try /* 182: */ { /* 183:158 */ ConfigInstaller.install(cmd.getOptionValue('l'), newRelicDir); /* 184:159 */ config_installed = true; /* 185:160 */ System.out.println( "Generated New Relic configuration file " + ConfigInstaller.configPath(newRelicDir)); /* 186: */ } /* 187: */ catch (IOException e) /* 188: */ { /* 189:163 */ System.err.println( MessageFormat.format("An error occurred generating the configuration file {0} : {1}", new Object[] { ConfigInstaller.configPath(newRelicDir), e.toString() })); /* 190: */ /* 191: */ /* 192:166 */ Agent.LOG.log(Level.FINE, "Config file generation error", e); /* 193: */ } /* 194: */ } /* 195: */ } /* 196: */ else /* 197: */ { /* 198:170 */ System.err.println("Could not create New Relic configuration file because:"); /* 199:171 */ System.err.println(MessageFormat.format(" .:. {0} does not exist or is not a directory", new Object[] { newRelicDir.getAbsolutePath() })); /* 200: */ } /* 201:176 */ if ((startup_patched) && (config_installed)) /* 202: */ { /* 203:177 */ printInstallSuccess(); /* 204:178 */ System.exit(0); /* 205: */ } /* 206: */ else /* 207: */ { /* 208:180 */ printInstallIncomplete(); /* 209:181 */ System.exit(1); /* 210: */ } /* 211: */ } /* 212: */ /* 213: */ private void printInstallSuccess() /* 214: */ { /* 215:187 */ System.out.println("***** Install successful"); /* 216:188 */ System.out.println("***** Next steps:"); /* 217:189 */ System.out .println("You're almost done! To see performance data for your app:" + SelfInstaller.lineSep + " .:. Restart your app server" + SelfInstaller.lineSep + " .:. Exercise your app" + SelfInstaller.lineSep + " .:. Log into http://rpm.newrelic.com" + SelfInstaller.lineSep + "Within two minutes, your app should show up, ready to monitor and troubleshoot." + SelfInstaller.lineSep + "If app data doesn't appear, check newrelic/logs/newrelic_agent.log for errors."); /* 218: */ } /* 219: */ /* 220: */ private void printInstallIncomplete() /* 221: */ { /* 222:198 */ System.out.println("***** Install incomplete"); /* 223:199 */ System.out.println("***** Next steps:"); /* 224:200 */ System.out .println("For help completing the install, see https://newrelic.com/docs/java/new-relic-for-java"); /* 225: */ } /* 226: */ /* 227: */ private void printUnknownAppServer(File appServerLoc) /* 228: */ { /* 229:205 */ StringBuilder knownAppServers = new StringBuilder(); /* 230:206 */ for (int i = 0; i < AppServerIdentifier.AppServerType.values().length - 1; i++) /* 231: */ { /* 232:207 */ AppServerIdentifier.AppServerType type = AppServerIdentifier.AppServerType.values()[i]; /* 233:208 */ knownAppServers.append(type.getName()); /* 234:209 */ if (i < AppServerIdentifier.AppServerType.values().length - 3) { /* 235:210 */ knownAppServers.append(", "); /* 236:211 */ } else if (i == AppServerIdentifier.AppServerType.values().length - 3) { /* 237:212 */ knownAppServers.append(" or "); /* 238: */ } /* 239: */ } /* 240:216 */ System.out.println("Could not edit start script because:"); /* 241:217 */ System.out.println(" .:. Could not locate a " + knownAppServers.toString() + " instance in " + appServerLoc.toString()); /* 242: */ /* 243:219 */ System.out.println( "Try re-running the install command with the -s <AppServerRootDirectory> option or from <AppServerRootDirectory>" + SelfInstaller.fileSep + "newrelic."); /* 244: */ /* 245:221 */ System.out.println("If that doesn't work, locate and edit the start script manually."); /* 246: */ } /* 247: */ /* 248: */ private void printHelp() /* 249: */ { /* 250:225 */ HelpFormatter formatter = new HelpFormatter(); /* 251:226 */ System.out .println(MessageFormat.format("New Relic Agent Version {0}", new Object[] { Agent.getVersion() })); /* 252:227 */ formatter.printHelp("java -jar newrelic.jar", "", getBasicOptions(), getCommandLineFooter()); /* 253: */ } /* 254: */ /* 255: */ private void printHelp(String command) /* 256: */ { /* 257:231 */ if (command == null) /* 258: */ { /* 259:232 */ printHelp(); /* 260:233 */ return; /* 261: */ } /* 262:235 */ HelpFormatter formatter = new HelpFormatter(); /* 263:236 */ System.out .println(MessageFormat.format("New Relic Agent Version {0}", new Object[] { Agent.getVersion() })); /* 264:237 */ String footer = "\n " + command + ' ' + (String) commandDescriptions.get(command); /* 265:238 */ formatter.printHelp("java -jar newrelic.jar " + command, "", (Options) commandOptionsMap.get(command), footer); /* 266: */ } /* 267: */ /* 268: */ private void verifyInstrumentation(CommandLine cmd) /* 269: */ { /* 270:243 */ List<String> args = cmd.getArgList().subList(1, cmd.getArgList().size()); /* 271: */ /* 272:245 */ String instrumentationJar = (String) args.get(0); /* 273:246 */ boolean expectedVerificationResult = Boolean.valueOf((String) args.get(1)).booleanValue(); /* 274:247 */ List<String> userJars = new ArrayList(); /* 275:248 */ if (args.size() > 2) { /* 276:249 */ userJars = args.subList(2, args.size()); /* 277: */ } /* 278: */ try /* 279: */ { /* 280:254 */ ServiceFactory.setServiceManager(null); /* 281: */ /* 282:256 */ VerificationLogger logger = new VerificationLogger(); /* 283:257 */ InstrumentationVerifier instrumentationVerifier = new InstrumentationVerifier(logger); /* 284:258 */ boolean passed = instrumentationVerifier.verify(instrumentationJar, userJars); /* 285:259 */ List<String> output = logger.getOutput(); /* 286:260 */ logger.flush(); /* 287:261 */ if (passed == expectedVerificationResult) /* 288: */ { /* 289:262 */ instrumentationVerifier.printVerificationResults(System.out, output); /* 290: */ } /* 291: */ else /* 292: */ { /* 293:264 */ instrumentationVerifier.printVerificationResults(System.err, output); /* 294:265 */ System.exit(1); /* 295: */ } /* 296: */ } /* 297: */ catch (Exception e) /* 298: */ { /* 299:268 */ System.err.println("Unexpected error while verifying"); /* 300:269 */ e.printStackTrace(); /* 301:270 */ System.exit(1); /* 302: */ } /* 303: */ } /* 304: */ /* 305: */ private String getCommandLineFooter() /* 306: */ { /* 307:275 */ int maxCommandLength = getMaxCommandLength(); /* 308:276 */ String minSpaces = " "; /* 309: */ /* 310:278 */ StringBuilder builder = new StringBuilder("\nCommands:"); /* 311:279 */ for (Map.Entry<String, String> entry : commandDescriptions.entrySet()) /* 312: */ { /* 313:280 */ String extraSpaces = new String( new char[maxCommandLength - ((String) entry.getKey()).length()]).replace('\000', ' '); /* 314:281 */ builder.append("\n ").append((String) entry.getKey()).append(extraSpaces) .append(minSpaces).append((String) entry.getValue()); /* 315: */ } /* 316:283 */ return builder.toString(); /* 317: */ } /* 318: */ /* 319: */ private int getMaxCommandLength() /* 320: */ { /* 321:287 */ int max = 0; /* 322:288 */ for (String command : commandDescriptions.keySet()) { /* 323:289 */ max = Math.max(max, command.length()); /* 324: */ } /* 325:291 */ return max; /* 326: */ } /* 327: */ /* 328: */ static Options getCommandLineOptions() /* 329: */ { /* 330:295 */ Collection<Options> values = new ArrayList(Collections.singletonList(getBasicOptions())); /* 331:296 */ values.addAll(commandOptionsMap.values()); /* 332:297 */ return combineOptions(values); /* 333: */ } /* 334: */ /* 335: */ private static Options combineOptions(Collection<Options> optionsList) /* 336: */ { /* 337:302 */ Options newOptions = new Options(); /* 338:303 */ for (Options options : optionsList) { /* 339:304 */ for (Option option : options.getOptions()) { /* 340:305 */ newOptions.addOption(option); /* 341: */ } /* 342: */ } /* 343:308 */ return newOptions; /* 344: */ } /* 345: */ /* 346: */ private static Options getBasicOptions() /* 347: */ { /* 348:312 */ Options options = new Options(); /* 349:313 */ options.addOption("v", false, "Prints the agent version"); /* 350:314 */ options.addOption("version", false, "Prints the agent version"); /* 351:315 */ options.addOption("h", false, "Prints help"); /* 352: */ /* 353:317 */ return options; /* 354: */ } /* 355: */ /* 356: */ private static Options getInstallOptions() /* 357: */ { /* 358:321 */ Options options = new Options(); /* 359:322 */ options.addOption("l", true, "Use the given license key"); /* 360:323 */ options.addOption("s", true, "Path to application server"); /* 361: */ /* 362:325 */ return options; /* 363: */ } /* 364: */ /* 365: */ private static Options getDeploymentOptions() /* 366: */ { /* 367:329 */ Options options = new Options(); /* 368: */ /* 369:331 */ options.addOption("appname", true, "Set the application name. Default is app_name setting in newrelic.yml"); /* 370: */ /* 371:333 */ options.addOption("environment", true, "Set the environment (staging, production, test, development)"); /* 372: */ /* 373:335 */ options.addOption("user", true, "Specify the user deploying"); /* 374:336 */ options.addOption("revision", true, "Specify the revision being deployed"); /* 375:337 */ options.addOption("changes", false, "Reads the change log for a deployment from standard input"); /* 376: */ /* 377:339 */ return options; /* 378: */ } /* 379: */ /* 380: */ private static Options getInstrumentOptions() /* 381: */ { /* 382:348 */ Options options = new Options(); /* 383:349 */ XmlInstrumentOptions[] instrumentOps = XmlInstrumentOptions.values(); /* 384:350 */ for (XmlInstrumentOptions op : instrumentOps) { /* 385:351 */ options.addOption(op.getFlagName(), op.isArgRequired(), op.getDescription()); /* 386: */ } /* 387:353 */ return options; /* 388: */ } /* 389: */ /* 390: */ private static Options getVerifyInstrumentationOptions() /* 391: */ { /* 392:357 */ Options options = new Options(); /* 393: */ /* 394:359 */ return options; /* 395: */ } /* 396: */ } /* Location: E:\tmp\newrelic\newrelic.jar * Qualified Name: com.newrelic.agent.AgentCommandLineParser * JD-Core Version: 0.7.0.1 */