ElasticsearchController.java

/*
 * Copyright 2020 Global Crop Diversity Trust
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.gringlobal.mvc.admin;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import java.util.concurrent.BlockingQueue;

import javax.annotation.Resource;

import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.cluster.metadata.AliasMetaData;
import org.gringlobal.component.elastic.ElasticReindex;
import org.gringlobal.service.ElasticsearchService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.task.TaskExecutor;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

@Controller
@RequestMapping("/admin/elastic")
@PreAuthorize("hasAuthority('GROUP_ADMINS')")
@Slf4j
public class ElasticsearchController {

	@Autowired(required = false)
	private ElasticsearchService elasticsearchService;

	@Resource
	private BlockingQueue<ElasticReindex> elasticReindexQueue;

	@Autowired
	private TaskExecutor taskExecutor;

	/**
	 * Renders view where indexes and their aliases are displayed.
	 *
	 * @param model
	 * @return
	 */
	@GetMapping("/")
	public String viewIndexesAndAliases(Model model) throws IOException {
		var listIndicesResponse = elasticsearchService.listIndices();

		Map<String, List<AliasMetaData>> aliases = new HashMap<>();
		if (listIndicesResponse != null) {
			aliases = listIndicesResponse.getAliases();
		}
		model.addAttribute("indexes", new TreeMap<>(aliases));
		model.addAttribute("reindexTypes", createReindexTypesMap());
		model.addAttribute("updateQueueSize", elasticReindexQueue.size());

		return "/admin/elastic/index";
	}

	/**
	 * This method refreshes data in the currently active index. It is very handy
	 * when having to refresh part of ES after direct database update.
	 *
	 * @param type
	 */
	@RequestMapping(method = RequestMethod.POST, value = "/action", params = { "reindex=content", "type" })
	public String reindexElasticContent(@RequestParam(value = "type", required = true) String type) {

		if (elasticReindexQueue.size() > 0) {
			throw new RuntimeException("Reindex queue not empty or operation is locked! Unable to run new indexing.");
		}

		if (type.equals("All")) {
			taskExecutor.execute(() -> {
				try {
					log.warn("Reindexing EVERYTHING!!!");
					elasticsearchService.reindexAll();
				} catch (Throwable e) {
					log.error("Error executing reindexAll", e);
				}
			});
		} else {
			taskExecutor.execute(() -> {
				try {
					log.warn("Reindexing {}", type);
					elasticsearchService.reindex(Class.forName(type));
				} catch (Throwable e) {
					log.error("Error executing reindex of " + type, e);
				}
			});
		}

		return "redirect:/admin/elastic/";
	}

	@RequestMapping(method = RequestMethod.POST, value = "/action", params = { "action=realias" })
	public String moveAlias(@RequestParam(name = "aliasName") String aliasName, @RequestParam(name = "indexName") String indexName) {
		elasticsearchService.realias(aliasName, null, indexName);
		return "redirect:/admin/elastic/";
	}

	@RequestMapping(method = RequestMethod.POST, value = "/action", params = { "action=delete-alias" })
	public String deleteAlias(@RequestParam(name = "aliasName") String aliasName) {
		elasticsearchService.deleteAlias(aliasName);
		return "redirect:/admin/elastic/";
	}

	@RequestMapping(method = RequestMethod.POST, value = "/action", params = { "action=delete-index", "indexName" })
	public String deleteIndex(@RequestParam(name = "indexName") String indexName) {
		elasticsearchService.deleteIndex(indexName);
		return "redirect:/admin/elastic/";
	}

	private Map<String, String> createReindexTypesMap() {
		Map<String, String> reindexTypesMap = new TreeMap<>();
		for (Class<?> clazz : elasticsearchService.getIndexedEntities()) {
			reindexTypesMap.put(clazz.getSimpleName(), clazz.getName());
		}
		return reindexTypesMap;
	}

}