private int runCommandLine(final Map<String, Object> options, final String[] commandLine)
      throws IOException {
    // initialize the startup log starting with a fresh log file (where all startup messages are
    // printed)
    final File startLogFile =
        IOUtils.tryGetCanonicalFileElseGetAbsoluteFile(
            new File(workingDirectory, startLogFileName));

    if (startLogFile.exists() && !startLogFile.delete()) {
      throw new IOException(
          LocalizedStrings.AgentLauncher_UNABLE_TO_DELETE_FILE_0.toLocalizedString(
              startLogFile.getAbsolutePath()));
    }

    Map<String, String> env = (Map<String, String>) options.get(ENVARGS);
    if (env == null) {
      env = new HashMap<String, String>();
    }
    // read the passwords from command line
    SocketCreator.readSSLProperties(env, true);

    printCommandLine(commandLine);

    final int pid = OSProcess.bgexec(commandLine, workingDirectory, startLogFile, false, env);

    System.out.println(
        LocalizedStrings.AgentLauncher_STARTING_JMX_AGENT_WITH_PID_0.toLocalizedString(pid));

    return pid;
  }
 public static void init() throws Exception {
   Properties props = new Properties();
   int pid = OSProcess.getId();
   String path = File.createTempFile("dunit-cachejta_", ".xml").getAbsolutePath();
   /** * Return file as string and then modify the string accordingly ** */
   String file_as_str = readFile(TestUtil.getResourcePath(CacheUtils.class, "cachejta.xml"));
   file_as_str = file_as_str.replaceAll("newDB", "newDB_" + pid);
   String modified_file_str = modifyFile(file_as_str);
   FileOutputStream fos = new FileOutputStream(path);
   BufferedWriter wr = new BufferedWriter(new OutputStreamWriter(fos));
   wr.write(modified_file_str);
   wr.flush();
   wr.close();
   props.setProperty("cache-xml-file", path);
   //    String tableName = "";
   //		  props.setProperty("mcast-port", "10339");
   try {
     //			   ds = DistributedSystem.connect(props);
     ds = (new ExceptionsDUnitTest("temp")).getSystem(props);
     cache = CacheFactory.create(ds);
   } catch (Exception e) {
     e.printStackTrace(System.err);
     throw new Exception("" + e);
   }
 }
 private static String modifyFile(String str) throws IOException {
   String search = "<jndi-binding type=\"XAPooledDataSource\"";
   String last_search = "</jndi-binding>";
   String newDB = "newDB_" + OSProcess.getId();
   String jndi_str =
       "<jndi-binding type=\"XAPooledDataSource\" jndi-name=\"XAPooledDataSource\"          jdbc-driver-class=\"org.apache.derby.jdbc.EmbeddedDriver\" init-pool-size=\"5\" max-pool-size=\"5\" idle-timeout-seconds=\"600\" blocking-timeout-seconds=\"6\" login-timeout-seconds=\"2\" conn-pooled-datasource-class=\"org.apache.derby.jdbc.EmbeddedConnectionPoolDataSource\" xa-datasource-class=\"org.apache.derby.jdbc.EmbeddedXADataSource\" user-name=\"mitul\" password=\"83f0069202c571faf1ae6c42b4ad46030e4e31c17409e19a\" connection-url=\"jdbc:derby:"
           + newDB
           + ";create=true\" >";
   String config_prop =
       "<config-property>"
           + "<config-property-name>description</config-property-name>"
           + "<config-property-type>java.lang.String</config-property-type>"
           + "<config-property-value>hi</config-property-value>"
           + "</config-property>"
           + "<config-property>"
           + "<config-property-name>user</config-property-name>"
           + "<config-property-type>java.lang.String</config-property-type>"
           + "<config-property-value>jeeves</config-property-value>"
           + "</config-property>"
           + "<config-property>"
           + "<config-property-name>password</config-property-name>"
           + "<config-property-type>java.lang.String</config-property-type>"
           + "<config-property-value>83f0069202c571faf1ae6c42b4ad46030e4e31c17409e19a</config-property-value>        "
           + "</config-property>"
           + "<config-property>"
           + "<config-property-name>databaseName</config-property-name>"
           + "<config-property-type>java.lang.String</config-property-type>"
           + "<config-property-value>"
           + newDB
           + "</config-property-value>"
           + "</config-property>\n";
   String new_str = jndi_str + config_prop;
   /*
    * String new_str = " <jndi-binding type=\"XAPooledDataSource\"
    * jndi-name=\"XAPooledDataSource\"
    * jdbc-driver-class=\"org.apache.derby.jdbc.EmbeddedDriver\"
    * init-pool-size=\"5\" max-pool-size=\"5\" idle-timeout-seconds=\"600\"
    * blocking-timeout-seconds=\"6\" login-timeout-seconds=\"2\"
    * conn-pooled-datasource-class=\"org.apache.derby.jdbc.EmbeddedConnectionPoolDataSource\"
    * xa-datasource-class=\"org.apache.derby.jdbc.EmbeddedXADataSource\"
    * user-name=\"mitul\"
    * password=\"83f0069202c571faf1ae6c42b4ad46030e4e31c17409e19a\"
    * connection-url=\"jdbc:derby:"+newDB+";create=true\" > <property
    * key=\"description\" value=\"hi\"/> <property key=\"databaseName\"
    * value=\""+newDB+"\"/> <property key=\"user\" value=\"mitul\"/> <property
    * key=\"password\"
    * value=\"83f0069202c571faf1ae6c42b4ad46030e4e31c17409e19a\"/>";
    */
   int n1 = str.indexOf(search);
   getLogWriter().fine("Start Index = " + n1);
   int n2 = str.indexOf(last_search, n1);
   StringBuffer sbuff = new StringBuffer(str);
   getLogWriter().fine("END Index = " + n2);
   String modified_str = sbuff.replace(n1, n2, new_str).toString();
   return modified_str;
 }
 protected RegionAttributes getDiskRegionAttributes() {
   AttributesFactory factory = new AttributesFactory(getRegionAttributes());
   File[] diskDirs = new File[1];
   diskDirs[0] = new File("diskRegionDirs/" + OSProcess.getId());
   diskDirs[0].mkdirs();
   factory.setDiskStoreName(
       getCache()
           .createDiskStoreFactory()
           .setDiskDirs(diskDirs)
           .setTimeInterval(1000)
           .setQueueSize(0)
           .create("TXRestrictionsDUnitTest")
           .getName());
   factory.setDataPolicy(DataPolicy.PERSISTENT_REPLICATE);
   return factory.create();
 }
  private Agent createAgent(final Properties props) throws IOException, AdminException {
    DistributionManager.isDedicatedAdminVM = true;
    SystemFailure.setExitOK(true);

    final AgentConfigImpl config = createAgentConfig(props);

    // see bug 43760
    if (config.getLogFile() == null || "".equals(config.getLogFile().trim())) {
      config.setLogFile(AgentConfigImpl.DEFAULT_LOG_FILE);
    }

    logger = config.getLogWriter();
    OSProcess.redirectOutput(
        new File(config.getLogFile())); // redirect output to the configured log file

    return AgentFactory.getAgent(config);
  }
  /** Starts the GemFire JMX Agent "server" process with the given command line arguments. */
  public void server(final String[] args) throws Exception {
    final Map<String, Object> options = getServerOptions(args);

    // make the process a UNIX daemon if possible
    String errMsg = makeDaemon();

    workingDirectory = IOUtils.tryGetCanonicalFileElseGetAbsoluteFile((File) options.get(DIR));

    Status status = createStatus(this.basename, STARTING, OSProcess.getId());
    status.msg = errMsg;
    writeStatus(status);

    Agent agent = startAgentVM((Properties) options.get(AGENT_PROPS), status);

    // periodically check and see if the JMX Agent has been told to stop
    pollAgentForPendingShutdown(agent);
  }
 /** Notes that an error has occurred in the agent and that it has shut down because of it. */
 private void setServerError(final String message, final Throwable cause) {
   try {
     writeStatus(
         createStatus(
             this.basename,
             SHUTDOWN_PENDING_AFTER_FAILED_STARTUP,
             OSProcess.getId(),
             message,
             cause));
   } catch (Exception e) {
     if (logger != null) {
       logger.severe(e);
     } else {
       e.printStackTrace();
     }
     System.exit(1);
   }
 }
  /**
   * Creates the log writer appender for a distributed system based on the system's parsed
   * configuration. The initial banner and messages are also entered into the log by this method.
   *
   * @param isLoner Whether the distributed system is a loner or not
   * @param isSecurity Whether a log for security related messages has to be created
   * @param config The DistributionConfig for the target distributed system
   * @param logConfig if true log the configuration
   * @throws GemFireIOException if the log file can't be opened for writing
   */
  static LogWriterAppender createLogWriterAppender(
      final boolean appendToFile,
      final boolean isLoner,
      final boolean isSecurity,
      final LogConfig config,
      final boolean logConfig) {

    final boolean isDistributionConfig = config instanceof DistributionConfig;
    final DistributionConfig dsConfig = isDistributionConfig ? (DistributionConfig) config : null;
    File logFile = config.getLogFile();
    String firstMsg = null;
    boolean firstMsgWarning = false;

    AlertAppender.getInstance().setAlertingDisabled(isLoner);

    // security-log-file is specified in DistributionConfig
    if (isSecurity) {
      if (isDistributionConfig) {
        File tmpLogFile = dsConfig.getSecurityLogFile();
        if (tmpLogFile != null && !tmpLogFile.equals(new File(""))) {
          logFile = tmpLogFile;
        }
      } else {
        throw new IllegalArgumentException("DistributionConfig is expected for SecurityLogWriter");
      }
    }

    // log-file is NOT specified in DistributionConfig
    if (logFile == null || logFile.equals(new File(""))) {
      // out = System.out;
      return null;
    }

    // log-file is specified in DistributionConfig

    // if logFile exists attempt to rename it for rolling
    if (logFile.exists()) {
      final boolean useChildLogging =
          config.getLogFile() != null
              && !config.getLogFile().equals(new File(""))
              && config.getLogFileSizeLimit() != 0;
      final boolean statArchivesRolling =
          isDistributionConfig
              && dsConfig.getStatisticArchiveFile() != null
              && !dsConfig.getStatisticArchiveFile().equals(new File(""))
              && dsConfig.getArchiveFileSizeLimit() != 0
              && dsConfig.getStatisticSamplingEnabled();

      if (!appendToFile
          || useChildLogging
          || statArchivesRolling) { // check useChildLogging for bug 50659
        final File oldMain =
            ManagerLogWriter.getLogNameForOldMainLog(
                logFile, isSecurity || useChildLogging || statArchivesRolling);
        final boolean succeeded = LogFileUtils.renameAggressively(logFile, oldMain);

        if (succeeded) {
          firstMsg =
              LocalizedStrings.InternalDistributedSystem_RENAMED_OLD_LOG_FILE_TO_0
                  .toLocalizedString(oldMain);
        } else {
          firstMsgWarning = true;
          firstMsg =
              LocalizedStrings.InternalDistributedSystem_COULD_NOT_RENAME_0_TO_1.toLocalizedString(
                  new Object[] {logFile, oldMain});
        }
      }
    }

    // create a FileOutputStream to the logFile
    FileOutputStream fos;
    try {
      fos = new FileOutputStream(logFile, true);
    } catch (FileNotFoundException ex) {
      String s =
          LocalizedStrings.InternalDistributedSystem_COULD_NOT_OPEN_LOG_FILE_0.toLocalizedString(
              logFile);
      throw new GemFireIOException(s, ex);
    }
    final PrintStream out = new PrintStream(fos);

    // create the ManagerLogWriter that LogWriterAppender will wrap
    ManagerLogWriter mlw = null;
    String logWriterLoggerName = null;
    if (isSecurity) {
      mlw = new SecurityManagerLogWriter(dsConfig.getSecurityLogLevel(), out, config.getName());
      logWriterLoggerName = LogService.SECURITY_LOGGER_NAME;
    } else {
      mlw = new ManagerLogWriter(config.getLogLevel(), out, config.getName());
      logWriterLoggerName = LogService.MAIN_LOGGER_NAME;
    }

    mlw.setConfig(config);
    //    if (mlw.infoEnabled()) { -- skip here and instead do this in LogWriterFactory when
    // creating the LogWriterLogger
    //      if (!isLoner /* do this on a loner to fix bug 35602 */
    //          || !Boolean.getBoolean(InternalLocator.INHIBIT_DM_BANNER)) {
    //        mlw.info(Banner.getString(null));
    //      }
    //    }

    AppenderContext[] appenderContext = new AppenderContext[1];
    if (isSecurity) {
      appenderContext[0] = LogService.getAppenderContext(LogService.SECURITY_LOGGER_NAME);
    } else {
      appenderContext[0] =
          LogService.getAppenderContext(); // ROOT or gemfire.logging.appenders.LOGGER
    }

    // create the LogWriterAppender that delegates to ManagerLogWriter;
    final LogWriterAppender appender =
        LogWriterAppender.create(appenderContext, logWriterLoggerName, mlw, fos);

    // remove stdout appender from MAIN_LOGGER_NAME only if isUsingGemFireDefaultConfig -- see
    // #51819
    if (!isSecurity
        && LogService.MAIN_LOGGER_NAME.equals(logWriterLoggerName)
        && LogService.isUsingGemFireDefaultConfig()) {
      LogService.removeConsoleAppender();
    }

    // log the first msg about renaming logFile for rolling if it pre-existed
    final InternalLogWriter logWriter = mlw;
    if (firstMsg != null) {
      if (firstMsgWarning) {
        logWriter.warning(firstMsg);
      } else {
        logWriter.info(firstMsg);
      }
    }

    // log the config
    if (logConfig) {
      if (isLoner) {
        logWriter.info(
            LocalizedStrings
                .InternalDistributedSystem_RUNNING_IN_LOCAL_MODE_SINCE_MCASTPORT_WAS_0_AND_LOCATORS_WAS_EMPTY);
      } else {
        // LOG:CONFIG: changed from config to info
        logWriter.info(
            LocalizedStrings.InternalDistributedSystem_STARTUP_CONFIGURATIONN_0,
            config.toLoggerString());
      }
    }

    // LOG: do NOT allow redirectOutput
    if (ALLOW_REDIRECT) {
      // fix #46493 by moving redirectOutput invocation here
      if (ProcessLauncherContext.isRedirectingOutput()) {
        try {
          OSProcess.redirectOutput(config.getLogFile());
        } catch (IOException e) {
          logWriter.error(e);
          // throw new GemFireIOException("Unable to redirect output to " + config.getLogFile(), e);
        }
      }
    }

    return appender;
  }