final boolean requestClusterState(final boolean display) {
    try {
      Settings settings = ElasticsearchPreferences.getInstance().toSettings();

      ClusterStatsResponse stats = new Elasticsearch(settings).stats();

      String desiredCluster = this.clusterName.getStringValue();
      String receivedCluster = stats.getClusterNameAsString();

      String message;

      if (!desiredCluster.equals(receivedCluster)) {
        message = "Connected to cluster " + desiredCluster;
        message += " instead of " + receivedCluster + ". ";
        message += "Please correct the Cluster name setting.";

        throw new IllegalStateException(message);
      }

      if (display) {
        message = "Cluster " + receivedCluster + ", ";
        message += "status " + stats.getStatus() + ".";

        MessageDialog.openInformation(this.getShell(), "Elasticsearch status", message.toString());
      }

      return true;
    } catch (Exception failure) {
      String title, message, toggle;

      if (failure instanceof ElasticsearchException) {
        ElasticsearchException exception = (ElasticsearchException) failure;

        title = "Elasticsearch error";
        message = exception.getDetailedMessage() + ", status " + exception.status();
      } else {
        title = failure instanceof IllegalStateException ? "Elasticsearch error" : "Unknown error";
        message = failure.getMessage();
      }

      toggle = "Always request cluster status on confirmation";

      Preference preference =
          Preference.usingToggleState(
              this.getPreferenceStore(), this.requestClusterState.getPreferenceName());

      boolean state =
          MessageDialogWithPreference.openError(this.getShell(), title, message, toggle, preference)
              .getToggleState();

      this.requestClusterState.getChangeControl().setSelection(state);

      return false;
    }
  }
 public void testOnModuleExceptionsArePropagated() {
   Settings settings = Settings.builder().put("path.home", createTempDir()).build();
   PluginsService service = newPluginsService(settings, FailOnModule.class);
   try {
     service.processModule(new BrokenModule());
     fail("boom");
   } catch (ElasticsearchException ex) {
     assertEquals("failed to invoke onModule", ex.getMessage());
     assertEquals("boom", ex.getCause().getCause().getMessage());
   }
 }
Example #3
0
 public final boolean open() {
   if (client == null) {
     client = createClient();
   }
   try {
     connect();
   } catch (ElasticsearchException e) {
     logger.error(
         "Failed to connect to " + getClusterName() + ", reason='" + e.getMessage() + "'");
     close();
     return false;
   }
   return true;
 }
Example #4
0
 @Override
 FlushResponse onParticularError(ElasticsearchException e) {
   String message =
       String.format("ES translog flush failed. index[%s] cause[%s]", indexName, e.toString());
   log.debug(message);
   return null;
 }
  @Before
  public void init() {

    if (client == null) {
      synchronized (ElasticNodeClient.class) {
        if (client == null) {

          try {
            client =
                new TransportClient()
                    .addTransportAddress(new InetSocketTransportAddress("192.168.1.202", 9300));
          } catch (ElasticsearchException e) {
            e.printStackTrace();
            throw new RuntimeException(e);
          }
        }
      }
    }
  }
 public static void renderException(XContentBuilder builder, Params params, Exception e)
     throws IOException {
   builder.startObject("error");
   final ElasticsearchException[] rootCauses = ElasticsearchException.guessRootCauses(e);
   builder.field("root_cause");
   builder.startArray();
   for (ElasticsearchException rootCause : rootCauses) {
     builder.startObject();
     rootCause.toXContent(
         builder,
         new ToXContent.DelegatingMapParams(
             Collections.singletonMap(ElasticsearchException.REST_EXCEPTION_SKIP_CAUSE, "true"),
             params));
     builder.endObject();
   }
   builder.endArray();
   ElasticsearchException.toXContent(builder, params, e);
   builder.endObject();
 }
 @Override
 public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException {
   builder.startObject();
   if (processorTag != null) {
     builder.field(ConfigurationUtils.TAG_KEY, processorTag);
   }
   if (failure == null) {
     ingestDocument.toXContent(builder, params);
   } else {
     ElasticsearchException.renderException(builder, params, failure);
   }
   builder.endObject();
   return builder;
 }
 /**
  * Statis toXContent helper method that also renders non {@link
  * org.elasticsearch.ElasticsearchException} instances as XContent.
  */
 public static void toXContent(XContentBuilder builder, Params params, Throwable ex)
     throws IOException {
   ex = ExceptionsHelper.unwrapCause(ex);
   if (ex instanceof ElasticsearchException) {
     ((ElasticsearchException) ex).toXContent(builder, params);
   } else {
     builder.field("type", getExceptionName(ex));
     builder.field("reason", ex.getMessage());
     if (ex.getCause() != null) {
       builder.field("caused_by");
       builder.startObject();
       toXContent(builder, params, ex.getCause());
       builder.endObject();
     }
     if (params.paramAsBoolean(
             REST_EXCEPTION_SKIP_STACK_TRACE, REST_EXCEPTION_SKIP_STACK_TRACE_DEFAULT)
         == false) {
       builder.field("stack_trace", ExceptionsHelper.stackTrace(ex));
     }
   }
 }
  @Test
  public void testRequiredRoutingWithPathMapping() throws Exception {
    client()
        .admin()
        .indices()
        .prepareCreate("test")
        .addAlias(new Alias("alias"))
        .addMapping(
            "type1",
            XContentFactory.jsonBuilder()
                .startObject()
                .startObject("type1")
                .startObject("_routing")
                .field("required", true)
                .field("path", "routing_field")
                .endObject()
                .startObject("properties")
                .startObject("routing_field")
                .field("type", "string")
                .field("index", randomBoolean() ? "no" : "not_analyzed")
                .field("doc_values", randomBoolean() ? "yes" : "no")
                .endObject()
                .endObject()
                .endObject()
                .endObject())
        .execute()
        .actionGet();
    ensureGreen();

    logger.info("--> indexing with id [1], and routing [0]");
    client()
        .prepareIndex(indexOrAlias(), "type1", "1")
        .setSource("field", "value1", "routing_field", "0")
        .setRefresh(true)
        .execute()
        .actionGet();

    logger.info("--> check failure with different routing");
    try {
      client()
          .prepareIndex(indexOrAlias(), "type1", "1")
          .setRouting("1")
          .setSource("field", "value1", "routing_field", "0")
          .setRefresh(true)
          .execute()
          .actionGet();
      fail();
    } catch (ElasticsearchException e) {
      assertThat(e.unwrapCause(), instanceOf(MapperParsingException.class));
    }

    logger.info("--> verifying get with no routing, should fail");
    for (int i = 0; i < 5; i++) {
      try {
        client().prepareGet(indexOrAlias(), "type1", "1").execute().actionGet().isExists();
        fail();
      } catch (RoutingMissingException e) {
        assertThat(e.status(), equalTo(RestStatus.BAD_REQUEST));
        assertThat(e.getMessage(), equalTo("routing is required for [test]/[type1]/[1]"));
      }
    }
    logger.info("--> verifying get with routing, should find");
    for (int i = 0; i < 5; i++) {
      assertThat(
          client()
              .prepareGet(indexOrAlias(), "type1", "1")
              .setRouting("0")
              .execute()
              .actionGet()
              .isExists(),
          equalTo(true));
    }
  }
Example #10
0
  @Test
  public void testRequiredRoutingMapping() throws Exception {
    client()
        .admin()
        .indices()
        .prepareCreate("test")
        .addAlias(new Alias("alias"))
        .addMapping(
            "type1",
            XContentFactory.jsonBuilder()
                .startObject()
                .startObject("type1")
                .startObject("_routing")
                .field("required", true)
                .endObject()
                .endObject()
                .endObject())
        .execute()
        .actionGet();
    ensureGreen();

    logger.info("--> indexing with id [1], and routing [0]");
    client()
        .prepareIndex(indexOrAlias(), "type1", "1")
        .setRouting("0")
        .setSource("field", "value1")
        .setRefresh(true)
        .execute()
        .actionGet();
    logger.info("--> verifying get with no routing, should fail");

    logger.info("--> indexing with id [1], with no routing, should fail");
    try {
      client()
          .prepareIndex(indexOrAlias(), "type1", "1")
          .setSource("field", "value1")
          .setRefresh(true)
          .execute()
          .actionGet();
      fail();
    } catch (ElasticsearchException e) {
      assertThat(e.unwrapCause(), instanceOf(RoutingMissingException.class));
    }

    logger.info("--> verifying get with routing, should find");
    for (int i = 0; i < 5; i++) {
      assertThat(
          client()
              .prepareGet(indexOrAlias(), "type1", "1")
              .setRouting("0")
              .execute()
              .actionGet()
              .isExists(),
          equalTo(true));
    }

    logger.info(
        "--> deleting with no routing, should broadcast the delete since _routing is required");
    client().prepareDelete(indexOrAlias(), "type1", "1").setRefresh(true).execute().actionGet();
    for (int i = 0; i < 5; i++) {
      try {
        client().prepareGet(indexOrAlias(), "type1", "1").execute().actionGet().isExists();
        fail();
      } catch (RoutingMissingException e) {
        assertThat(e.status(), equalTo(RestStatus.BAD_REQUEST));
        assertThat(e.getMessage(), equalTo("routing is required for [test]/[type1]/[1]"));
      }
      assertThat(
          client()
              .prepareGet(indexOrAlias(), "type1", "1")
              .setRouting("0")
              .execute()
              .actionGet()
              .isExists(),
          equalTo(false));
    }

    logger.info("--> indexing with id [1], and routing [0]");
    client()
        .prepareIndex(indexOrAlias(), "type1", "1")
        .setRouting("0")
        .setSource("field", "value1")
        .setRefresh(true)
        .execute()
        .actionGet();
    logger.info("--> verifying get with no routing, should not find anything");

    logger.info(
        "--> bulk deleting with no routing, should broadcast the delete since _routing is required");
    client()
        .prepareBulk()
        .add(Requests.deleteRequest(indexOrAlias()).type("type1").id("1"))
        .execute()
        .actionGet();
    client().admin().indices().prepareRefresh().execute().actionGet();
    for (int i = 0; i < 5; i++) {
      try {
        client().prepareGet(indexOrAlias(), "type1", "1").execute().actionGet().isExists();
        fail();
      } catch (RoutingMissingException e) {
        assertThat(e.status(), equalTo(RestStatus.BAD_REQUEST));
        assertThat(e.getMessage(), equalTo("routing is required for [test]/[type1]/[1]"));
      }
      assertThat(
          client()
              .prepareGet(indexOrAlias(), "type1", "1")
              .setRouting("0")
              .execute()
              .actionGet()
              .isExists(),
          equalTo(false));
    }
  }
  public void testExceptionRegistration()
      throws ClassNotFoundException, IOException, URISyntaxException {
    final Set<Class> notRegistered = new HashSet<>();
    final Set<Class> hasDedicatedWrite = new HashSet<>();
    final Set<String> registered = new HashSet<>();
    final String path = "/org/elasticsearch";
    final Path startPath =
        PathUtils.get(
                ElasticsearchException.class
                    .getProtectionDomain()
                    .getCodeSource()
                    .getLocation()
                    .toURI())
            .resolve("org")
            .resolve("elasticsearch");
    final Set<? extends Class> ignore =
        Sets.newHashSet(
            org.elasticsearch.test.rest.parser.RestTestParseException.class,
            org.elasticsearch.index.query.TestQueryParsingException.class,
            org.elasticsearch.test.rest.client.RestException.class,
            org.elasticsearch.common.util.CancellableThreadsTest.CustomException.class,
            org.elasticsearch.rest.BytesRestResponseTests.WithHeadersException.class,
            org.elasticsearch.client.AbstractClientHeadersTests.InternalException.class);
    FileVisitor<Path> visitor =
        new FileVisitor<Path>() {
          private Path pkgPrefix = PathUtils.get(path).getParent();

          @Override
          public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs)
              throws IOException {
            Path next = pkgPrefix.resolve(dir.getFileName());
            if (ignore.contains(next)) {
              return FileVisitResult.SKIP_SUBTREE;
            }
            pkgPrefix = next;
            return FileVisitResult.CONTINUE;
          }

          @Override
          public FileVisitResult visitFile(Path file, BasicFileAttributes attrs)
              throws IOException {
            try {
              String filename = file.getFileName().toString();
              if (filename.endsWith(".class")) {
                Class<?> clazz = loadClass(filename);
                if (ignore.contains(clazz) == false) {
                  if (Modifier.isAbstract(clazz.getModifiers()) == false
                      && Modifier.isInterface(clazz.getModifiers()) == false
                      && isEsException(clazz)) {
                    if (ElasticsearchException.isRegistered(clazz.getName()) == false
                        && ElasticsearchException.class.equals(clazz.getEnclosingClass())
                            == false) {
                      notRegistered.add(clazz);
                    } else if (ElasticsearchException.isRegistered(clazz.getName())) {
                      registered.add(clazz.getName());
                      try {
                        if (clazz.getDeclaredMethod("writeTo", StreamOutput.class) != null) {
                          hasDedicatedWrite.add(clazz);
                        }
                      } catch (Exception e) {
                        // fair enough
                      }
                    }
                  }
                }
              }
            } catch (ClassNotFoundException e) {
              throw new RuntimeException(e);
            }
            return FileVisitResult.CONTINUE;
          }

          private boolean isEsException(Class<?> clazz) {
            return ElasticsearchException.class.isAssignableFrom(clazz);
          }

          private Class<?> loadClass(String filename) throws ClassNotFoundException {
            StringBuilder pkg = new StringBuilder();
            for (Path p : pkgPrefix) {
              pkg.append(p.getFileName().toString()).append(".");
            }
            pkg.append(filename.substring(0, filename.length() - 6));
            return Thread.currentThread().getContextClassLoader().loadClass(pkg.toString());
          }

          @Override
          public FileVisitResult visitFileFailed(Path file, IOException exc) throws IOException {
            throw exc;
          }

          @Override
          public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException {
            pkgPrefix = pkgPrefix.getParent();
            return FileVisitResult.CONTINUE;
          }
        };

    Files.walkFileTree(startPath, visitor);
    final Path testStartPath =
        PathUtils.get(ExceptionSerializationTests.class.getResource(path).toURI());
    Files.walkFileTree(testStartPath, visitor);
    assertTrue(notRegistered.remove(TestException.class));
    assertTrue(notRegistered.remove(UnknownHeaderException.class));
    assertTrue(
        "Classes subclassing ElasticsearchException must be registered \n"
            + notRegistered.toString(),
        notRegistered.isEmpty());
    assertTrue(registered.removeAll(ElasticsearchException.getRegisteredKeys())); // check
    assertEquals(registered.toString(), 0, registered.size());
  }
 @Override
 public void writeTo(StreamOutput out) throws IOException {
   super.writeTo(out);
   out.writeBoolean(isExecutorShutdown);
 }