CacheController.java

/*
 * Copyright 2022 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.genesys.server.api.admin.v1;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

import org.genesys.server.api.ApiBaseController;
import org.genesys.server.mvc.admin.AdminController;
import org.genesys.server.service.MappingService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.Cache;
import org.springframework.cache.CacheManager;
import org.springframework.http.MediaType;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.hazelcast.core.DistributedObject;
import com.hazelcast.core.Hazelcast;
import com.hazelcast.core.HazelcastInstance;
import com.hazelcast.map.IMap;
import com.hazelcast.map.LocalMapStats;

import io.swagger.annotations.Api;

/**
 * Manage caches
 *
 * @author mobreza
 */
@RestController("cacheApi1")
@PreAuthorize("hasRole('ADMINISTRATOR')")
@RequestMapping(CacheController.CONTROLLER_URL)
@Api(tags = { "cachev1" })
public class CacheController {

	/** The Constant CONTROLLER_URL. */
	public static final String CONTROLLER_URL = ApiBaseController.APIv1_BASE + "/admin/cache";

	public static final Logger LOG = LoggerFactory.getLogger(AdminController.class);

	@Autowired
	private MappingService mappingService;

	@Autowired
	private CacheManager cacheManager;

	@PostMapping(value = "/clearCache/clearAll")
	public void clearCacheAll() {
		for (String cacheName : cacheManager.getCacheNames()) {
			clearCache(cacheName);
		}
	}

	@PostMapping(value = "/clearCache/clearTiles")
	public void clearTilesCache() {
		final Cache tileServerCache = cacheManager.getCache("tileserver");
		if (LOG.isDebugEnabled()) {
			LOG.debug("tileServerCache={}", tileServerCache.getNativeCache());
		}

		@SuppressWarnings("rawtypes") final IMap hazelCache = (IMap) tileServerCache.getNativeCache();

		LOG.info("Tiles cache size={}", hazelCache.size());
		int count = 0;
		for (final Object key : hazelCache.keySet()) {
			LOG.info("\tkey={}", key);
			if (++count > 20) {
				break;
			}
		}
		mappingService.clearCache();
		LOG.info("Tiles cache size={}", hazelCache.size());
	}

	@PostMapping(value = "/clearCaches")
	public void clearCaches(@RequestBody final List<String> cacheNames) {
		for (String cacheName: cacheNames) {
			clearCache(cacheName);
		}
	}

	@PostMapping(value = "/clearCache/{name}")
	public void clearCache(@PathVariable("name") String cacheName) {
		final Cache cache = cacheManager.getCache(cacheName);
		if (cache != null) {
			LOG.info("Clearing cache {}", cacheName);
			cache.clear();
		} else {
			LOG.info("No such cache: {}", cacheName);
		}
	}

	@GetMapping(value = "", produces = { MediaType.APPLICATION_JSON_VALUE })
	public CacheStatsResponse cacheStats() {
		List<CacheStats> cacheMaps = new ArrayList<CacheStats>();
		List<Object> cacheOther = new ArrayList<Object>();

		Set<HazelcastInstance> instances = Hazelcast.getAllHazelcastInstances();
		for (HazelcastInstance hz : instances) {
			if (LOG.isDebugEnabled())
				LOG.debug("\n\nCache stats Instance: {}", hz.getName());

			for (DistributedObject o : hz.getDistributedObjects()) {
				if (o instanceof IMap) {
					IMap<?, ?> imap = (IMap<?, ?>) o;
					cacheMaps.add(new CacheStats(imap));

					if (LOG.isDebugEnabled()) {
						LOG.debug("{}: {} {}", imap.getServiceName(), imap.getName(), imap.getPartitionKey());
						LocalMapStats localMapStats = imap.getLocalMapStats();
						LOG.debug("created: {}", localMapStats.getCreationTime());
						LOG.debug("owned entries: {}", localMapStats.getOwnedEntryCount());
						LOG.debug("backup entries: {}", localMapStats.getBackupEntryCount());
						LOG.debug("locked entries: {}", localMapStats.getLockedEntryCount());
						LOG.debug("dirty entries: {}", localMapStats.getDirtyEntryCount());
						LOG.debug("hits: {}", localMapStats.getHits());
						LOG.debug("puts: {}", localMapStats.getPutOperationCount());
						LOG.debug("last update: {}", localMapStats.getLastUpdateTime());
						LOG.debug("last access: {}", localMapStats.getLastAccessTime());
					}
				} else {
					if (LOG.isDebugEnabled())
						LOG.debug("{} {}", o.getClass(), o);
					cacheOther.add(o);
				}
			}
		}

		return new CacheStatsResponse(cacheMaps, cacheOther);
	}

	public static class CacheStatsResponse {
		public List<CacheStats> cacheMaps;
		public List<String> cacheOther;

		public CacheStatsResponse(List<CacheStats> cacheMaps, List<Object> cacheOther) {
			this.cacheMaps = cacheMaps;
			this.cacheOther = cacheOther.stream().map(Object::toString).collect(Collectors.toList());
		}
	}

	public static class CacheStats {
		public String serviceName;
		public String name;
		public String statsOwnedEntryCount;
		public String statsLockedEntryCount;
		public String statsPutOperationCount;
		public String statsHits;

		public CacheStats(IMap<?, ?> imap) {
			this.serviceName = imap.getServiceName();
			this.name = imap.getName();
			LocalMapStats mapStats = imap.getLocalMapStats();
			statsOwnedEntryCount = String.valueOf(mapStats.getOwnedEntryCount());
			statsLockedEntryCount = String.valueOf(mapStats.getLockedEntryCount());
			statsPutOperationCount = String.valueOf(mapStats.getPutOperationCount());
			statsHits = String.valueOf(mapStats.getHits());
		}
	}

}