/** Returns last line of output from the command */
  public SampleResult sample(Entry e) {
    SampleResult res = new SampleResult();
    res.setSampleLabel(
        getName() + ":(" + getUsername() + "@" + getHostname() + ":" + getPort() + ")");

    // Set up sampler return types
    res.setSamplerData(action + " " + source);

    res.setDataType(SampleResult.TEXT);
    res.setContentType("text/plain");

    String response;
    if (getSession() == null) {
      connect();
    }

    try {
      if (getSession() == null) {
        log.error(
            "Failed to connect to server with credentials "
                + getUsername()
                + "@"
                + getHostname()
                + ":"
                + getPort()
                + " pw="
                + getPassword());
        throw new NullPointerException("Failed to connect to server: " + getFailureReason());
      }

      response = doFileTransfer(getSession(), source, destination, res);
      res.setResponseData(response.getBytes());

      res.setSuccessful(true);

      res.setResponseMessageOK();
    } catch (JSchException e1) {
      res.setSuccessful(false);
      res.setResponseCode("JSchException");
      res.setResponseMessage(e1.getMessage());
    } catch (SftpException e1) {
      res.setSuccessful(false);
      res.setResponseCode("SftpException");
      res.setResponseMessage(e1.getMessage());
    } catch (IOException e1) {
      res.setSuccessful(false);
      res.setResponseCode("IOException");
      res.setResponseMessage(e1.getMessage());
    } catch (NullPointerException e1) {
      res.setSuccessful(false);
      res.setResponseCode("Connection Failed");
      res.setResponseMessage(e1.getMessage());
    } finally {
      // Try a disconnect/sesson = null here instead of in finalize.
      disconnect();
      setSession(null);
    }
    return res;
  }
Exemplo n.º 2
0
  /**
   * Perform a single sample.<br>
   * In this case, this method will simply sleep for some amount of time.
   *
   * <p>This method returns a <code>SampleResult</code> object.
   *
   * <pre>
   *
   *  The following fields are always set:
   *  - responseCode (default &quot;&quot;)
   *  - responseMessage (default &quot;&quot;)
   *  - label (set from LABEL_NAME parameter if it exists, else element name)
   *  - success (default true)
   *
   * </pre>
   *
   * The following fields are set from the user-defined parameters, if supplied:
   *
   * <pre>
   * -samplerData - responseData
   * </pre>
   *
   * @see org.apache.jmeter.samplers.SampleResult#sampleStart()
   * @see org.apache.jmeter.samplers.SampleResult#sampleEnd()
   * @see org.apache.jmeter.samplers.SampleResult#setSuccessful(boolean)
   * @see org.apache.jmeter.samplers.SampleResult#setSampleLabel(String)
   * @see org.apache.jmeter.samplers.SampleResult#setResponseCode(String)
   * @see org.apache.jmeter.samplers.SampleResult#setResponseMessage(String)
   * @see org.apache.jmeter.samplers.SampleResult#setResponseData(byte [])
   * @see org.apache.jmeter.samplers.SampleResult#setDataType(String)
   * @param context the context to run with. This provides access to initialization parameters.
   * @return a SampleResult giving the results of this sample.
   */
  @Override
  public SampleResult runTest(JavaSamplerContext context) {
    setupValues(context);

    SampleResult results = new SampleResult();

    results.setResponseCode(responseCode);
    results.setResponseMessage(responseMessage);
    results.setSampleLabel(label);

    if (samplerData != null && samplerData.length() > 0) {
      results.setSamplerData(samplerData);
    }

    if (resultData != null && resultData.length() > 0) {
      results.setResponseData(resultData, null);
      results.setDataType(SampleResult.TEXT);
    }

    // Record sample start time.
    results.sampleStart();

    long sleep = sleepTime;
    if (sleepTime > 0 && sleepMask > 0) { // / Only do the calculation if
      // it is needed
      long start = System.currentTimeMillis();
      // Generate a random-ish offset value using the current time.
      sleep = sleepTime + (start % sleepMask);
    }

    try {
      // Execute the sample. In this case sleep for the
      // specified time, if any
      if (sleep > 0) {
        TimeUnit.MILLISECONDS.sleep(sleep);
      }
      results.setSuccessful(success);
    } catch (InterruptedException e) {
      LOG.warn("JavaTest: interrupted.");
      results.setSuccessful(true);
    } catch (Exception e) {
      LOG.error("JavaTest: error during sample", e);
      results.setSuccessful(false);
    } finally {
      // Record end time and populate the results.
      results.sampleEnd();
    }

    if (LOG.isDebugEnabled()) {
      LOG.debug(whoAmI() + "\trunTest()" + "\tTime:\t" + results.getTime());
      listParameters(context);
    }

    return results;
  }
  @Override
  public SampleResult sample(Entry entry) {
    ServiceSocket socket = null;
    SampleResult sampleResult = new SampleResult();
    sampleResult.setSampleLabel(getName());
    sampleResult.setDataEncoding(getContentEncoding());

    StringBuilder errorList = new StringBuilder();
    errorList.append("\n\n[Problems]\n");

    boolean isOK = false;

    String payloadMessage = getRequestPayload();
    sampleResult.setSamplerData(payloadMessage);
    sampleResult.sampleStart();

    try {
      socket = getConnectionSocket();
      if (socket == null) {
        sampleResult.setResponseCode("500");
        sampleResult.setSuccessful(false);
        sampleResult.sampleEnd();
        sampleResult.setResponseMessage(errorList.toString());
        errorList.append(" - Connection couldn't be opened").append("\n");
        return sampleResult;
      }

      if (!payloadMessage.isEmpty()) {
        socket.sendMessage(payloadMessage);
      }

      int responseTimeout = Integer.parseInt(getResponseTimeout());
      socket.awaitClose(responseTimeout, TimeUnit.MILLISECONDS);

      if (socket.getResponseMessage() == null || socket.getResponseMessage().isEmpty()) {
        sampleResult.setResponseCode("204");
      }

      if (socket.getError() != 0) {
        isOK = false;
        sampleResult.setResponseCode(socket.getError().toString());
      } else {
        sampleResult.setResponseCodeOK();
        isOK = true;
      }

      sampleResult.setResponseData(socket.getResponseMessage(), getContentEncoding());

    } catch (URISyntaxException e) {
      errorList
          .append(" - Invalid URI syntax: ")
          .append(e.getMessage())
          .append("\n")
          .append(StringUtils.join(e.getStackTrace(), "\n"))
          .append("\n");
    } catch (IOException e) {
      errorList
          .append(" - IO Exception: ")
          .append(e.getMessage())
          .append("\n")
          .append(StringUtils.join(e.getStackTrace(), "\n"))
          .append("\n");
    } catch (NumberFormatException e) {
      errorList
          .append(" - Cannot parse number: ")
          .append(e.getMessage())
          .append("\n")
          .append(StringUtils.join(e.getStackTrace(), "\n"))
          .append("\n");
    } catch (InterruptedException e) {
      errorList
          .append(" - Execution interrupted: ")
          .append(e.getMessage())
          .append("\n")
          .append(StringUtils.join(e.getStackTrace(), "\n"))
          .append("\n");
    } catch (Exception e) {
      errorList
          .append(" - Unexpected error: ")
          .append(e.getMessage())
          .append("\n")
          .append(StringUtils.join(e.getStackTrace(), "\n"))
          .append("\n");
    }

    sampleResult.sampleEnd();
    sampleResult.setSuccessful(isOK);

    String logMessage = (socket != null) ? socket.getLogMessage() : "";
    sampleResult.setResponseMessage(logMessage + errorList);
    return sampleResult;
  }
  public SampleResult runTest(JavaSamplerContext runTestContext) {
    String indexFileSystemPath = runTestContext.getParameter("indexfilesystem.path");

    String timeStamp =
        new SimpleDateFormat("yyyy/MM/dd HH:mm:ss").format(Calendar.getInstance().getTime());
    resultObj.put("Date and Execution Time", timeStamp);

    resultObj.put("Execution Plan", "Sequential Performance of Indexes FS");
    try {
      resultObj.put("Host", InetAddress.getLocalHost().getHostAddress());
    } catch (UnknownHostException e) {
      e.printStackTrace();
    }

    SampleResult result = new SampleResult();

    try {
      result.sampleStart();
      preallocateTestFile(FILE_NAME);

      for (final PerfTestCase testCase : testCases) {
        JSONArray readDuration = new JSONArray();
        JSONArray bytesRead = new JSONArray();
        JSONArray bytesWrite = new JSONArray();
        for (int i = 0; i < 5; i++) {
          System.gc();
          long writeDurationMs = testCase.test(PerfTestCase.Type.WRITE, FILE_NAME);
          System.gc();
          long readDurationMs = testCase.test(PerfTestCase.Type.READ, FILE_NAME);
          long bytesReadPerSec = (FILE_SIZE * 1000L) / readDurationMs;
          long bytesWrittenPerSec = (FILE_SIZE * 1000L) / writeDurationMs;
          readDuration.add(readDurationMs);
          bytesRead.add(bytesReadPerSec);
          bytesWrite.add(bytesWrittenPerSec);

          out.format(
              "%s\twrite=%,d\tread=%,d bytes/sec\n",
              testCase.getName(), bytesWrittenPerSec, bytesReadPerSec);

          String output =
              out.format(
                      "%s\twrite=%,d\tread=%,d bytes/sec\n",
                      testCase.getName(), bytesWrittenPerSec, bytesReadPerSec)
                  .toString();
          result.setSamplerData(testCase.getName() + "-- IO RESULTS --- " + output);
          // resultIo.setSamplerData(testCase.getName() + "-- Writen Bytes per second:" +
          // bytesWrittenPerSec + "-- Read Bytes per second:" + bytesReadPerSec);
          result.addSubResult(result);
        }

        resultObj.put(testCase.getName(), readDuration);
        resultObj.put(testCase.getName(), bytesRead);
        resultObj.put(testCase.getName(), bytesWrite);
      }

      deleteFile(indexFileSystemPath + "/" + FILE_NAME);

      try {

        FileWriter file = new FileWriter(resultsDirectory + "/" + OUTPUT_JSON_FILE_NAME);
        file.write(resultObj.toJSONString());
        file.flush();
        file.close();

      } catch (IOException e) {
        e.printStackTrace();
      }

      result.sampleEnd();
      result.setSuccessful(true);
      logger.info("Successfully Tested Index Disk IO  at path: " + indexFileSystemPath);
      result.setResponseMessage("Successfully Tested IO at  Indexes Disk");
      result.setResponseCodeOK();
    } catch (Exception e) {
      result.sampleEnd();
      result.setSuccessful(false);
      result.setResponseMessage("Failed to TestIO: " + e);
      StringWriter stringWriter = new StringWriter();
      e.printStackTrace(new PrintWriter(stringWriter));
      result.setResponseData(stringWriter.toString().getBytes());
      result.setDataType(SampleResult.TEXT);
      result.setResponseCode("500");
    }
    return result;
  }
  /** {@inheritDoc} */
  @Override
  public SampleResult sample(Entry entry) {
    SampleResult result = new SampleResult();
    result.setSampleLabel(getName());
    result.setSuccessful(false);
    result.setResponseCode("500");

    QueueingConsumer consumer;
    String consumerTag;

    trace("AMQPConsumer.sample()");

    try {
      initChannel();

      consumer = new QueueingConsumer(channel);
      channel.basicQos(1); // TODO: make prefetchCount configurable?
      consumerTag = channel.basicConsume(getQueue(), autoAck(), consumer);
    } catch (IOException ex) {
      log.error("Failed to initialize channel", ex);
      return result;
    }

    result.setSampleLabel(getTitle());
    /*
     * Perform the sampling
     */
    result.sampleStart(); // Start timing
    try {
      QueueingConsumer.Delivery delivery = consumer.nextDelivery(getReceiveTimeoutAsInt());

      if (delivery == null) {
        log.warn("nextDelivery timed out");
        return result;
      }

      /*
       * Set up the sample result details
       */
      result.setSamplerData(new String(delivery.getBody()));

      result.setResponseData("OK", null);
      result.setDataType(SampleResult.TEXT);

      result.setResponseCodeOK();
      result.setResponseMessage("OK");
      result.setSuccessful(true);

      if (!autoAck()) channel.basicAck(delivery.getEnvelope().getDeliveryTag(), false);

    } catch (ShutdownSignalException e) {
      log.warn("AMQP consumer failed to consume", e);
      result.setResponseCode("400");
      result.setResponseMessage(e.toString());
      interrupt();
    } catch (ConsumerCancelledException e) {
      log.warn("AMQP consumer failed to consume", e);
      result.setResponseCode("300");
      result.setResponseMessage(e.toString());
      interrupt();
    } catch (InterruptedException e) {
      log.info("interuppted while attempting to consume");
      result.setResponseCode("200");
      result.setResponseMessage(e.toString());
    } catch (IOException e) {
      log.warn("AMQP consumer failed to consume", e);
      result.setResponseCode("100");
      result.setResponseMessage(e.toString());
    } finally {
      try {
        channel.basicCancel(consumerTag);
      } catch (IOException e) {
        log.error("Couldn't safely cancel the sample's consumer", e);
      }
    }

    result.sampleEnd(); // End timimg
    trace("AMQPConsumer.sample ended");

    return result;
  }