aboutsummaryrefslogtreecommitdiffstats
path: root/aai-resources/src/main
diff options
context:
space:
mode:
authorFiete Ostkamp <Fiete.Ostkamp@telekom.de>2024-11-22 13:53:42 +0100
committerFiete Ostkamp <Fiete.Ostkamp@telekom.de>2025-01-07 09:58:46 +0100
commitdd4a7968d539a958b2ddccb77d00fcb68eb177b7 (patch)
tree7cba2ac4c6b414c35dc57f255cceb849f6cebe05 /aai-resources/src/main
parentcd19e26cd9fd7f74662053c06d0cde4513faddf5 (diff)
Use GraphChecker from aai-common
Issue-ID: AAI-4069 Signed-off-by: Fiete Ostkamp <Fiete.Ostkamp@telekom.de> Change-Id: I52e5d412d038dd3e89091cbbcb4e0b23fefc6541
Diffstat (limited to 'aai-resources/src/main')
-rw-r--r--aai-resources/src/main/java/org/onap/aai/rest/util/EchoHealthIndicator.java21
-rw-r--r--aai-resources/src/main/java/org/onap/aai/rest/util/EchoResponse.java40
-rw-r--r--aai-resources/src/main/java/org/onap/aai/tasks/AaiGraphChecker.java203
3 files changed, 20 insertions, 244 deletions
diff --git a/aai-resources/src/main/java/org/onap/aai/rest/util/EchoHealthIndicator.java b/aai-resources/src/main/java/org/onap/aai/rest/util/EchoHealthIndicator.java
index fd5dbcf8..e685be07 100644
--- a/aai-resources/src/main/java/org/onap/aai/rest/util/EchoHealthIndicator.java
+++ b/aai-resources/src/main/java/org/onap/aai/rest/util/EchoHealthIndicator.java
@@ -20,8 +20,7 @@
package org.onap.aai.rest.util;
-import org.onap.aai.tasks.AaiGraphChecker;
-import org.onap.aai.tasks.AaiGraphChecker.CheckerType;
+import org.onap.aai.util.GraphChecker;
import org.springframework.boot.actuate.health.Health;
import org.springframework.boot.actuate.health.HealthIndicator;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
@@ -34,17 +33,17 @@ import lombok.RequiredArgsConstructor;
@ConditionalOnProperty(name = "aai.actuator.echo.enabled", havingValue = "true")
public class EchoHealthIndicator implements HealthIndicator {
- private final AaiGraphChecker aaiGraphChecker;
+ private final GraphChecker graphChecker;
- @Override
- public Health health() {
+ @Override
+ public Health health() {
return healthy()
- ? Health.up().build()
- : Health.down().build();
- }
+ ? Health.up().build()
+ : Health.down().build();
+ }
- private boolean healthy() {
- return aaiGraphChecker.isAaiGraphDbAvailable(CheckerType.ACTUAL);
- }
+ private boolean healthy() {
+ return graphChecker.isAaiGraphDbAvailable();
+ }
}
diff --git a/aai-resources/src/main/java/org/onap/aai/rest/util/EchoResponse.java b/aai-resources/src/main/java/org/onap/aai/rest/util/EchoResponse.java
index 0e44a631..1c14ff02 100644
--- a/aai-resources/src/main/java/org/onap/aai/rest/util/EchoResponse.java
+++ b/aai-resources/src/main/java/org/onap/aai/rest/util/EchoResponse.java
@@ -26,42 +26,35 @@ import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
-import javax.ws.rs.QueryParam;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.HttpHeaders;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;
-import org.apache.commons.lang3.BooleanUtils;
import org.onap.aai.exceptions.AAIException;
import org.onap.aai.logging.ErrorLogHelper;
import org.onap.aai.restcore.RESTAPI;
-import org.onap.aai.tasks.AaiGraphChecker;
+import org.onap.aai.util.GraphChecker;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
+import lombok.RequiredArgsConstructor;
+
/**
* The Class EchoResponse.
*/
@Component
@Path("/util")
+@RequiredArgsConstructor
public class EchoResponse extends RESTAPI {
private static final Logger LOGGER = LoggerFactory.getLogger(EchoResponse.class);
- private static final String CHECK_DB_STATUS_ACTION = "checkDB";
-
- private static final String CHECK_DB_STATUS_NOW_ACTION = "checkDBNow";
-
private static final String UP_RESPONSE="{\"status\":\"UP\",\"groups\":[\"liveness\",\"readiness\"]}";
- private final AaiGraphChecker aaiGraphChecker;
-
- public EchoResponse(AaiGraphChecker aaiGraphChecker) {
- this.aaiGraphChecker = aaiGraphChecker;
- }
+ private final GraphChecker graphChecker;
/**
* Simple health-check API that echos back the X-FromAppId and X-TransactionId to clients.
@@ -77,8 +70,7 @@ public class EchoResponse extends RESTAPI {
@GET
@Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
@Path("/echo")
- public Response echoResult(@Context HttpHeaders headers, @Context HttpServletRequest req,
- @QueryParam("action") String myAction) {
+ public Response echoResult(@Context HttpHeaders headers, @Context HttpServletRequest req) {
String fromAppId;
String transId;
@@ -98,10 +90,7 @@ public class EchoResponse extends RESTAPI {
templateVars.add(transId);
try {
- if (CHECK_DB_STATUS_ACTION.equalsIgnoreCase(myAction)
- || CHECK_DB_STATUS_NOW_ACTION.equalsIgnoreCase(myAction)) {
- validateDBStatus(myAction);
- }
+ validateDBStatus();
return generateSuccessResponse();
} catch (AAIException aaiException) {
@@ -120,18 +109,9 @@ public class EchoResponse extends RESTAPI {
* @param action expected input values 'checkDB' 'checkDBNow'
* @throws AAIException exception thrown if DB is not available
*/
- private void validateDBStatus(String action) throws AAIException {
-
- Boolean dbAvailable = null;
- if (CHECK_DB_STATUS_ACTION.equalsIgnoreCase(action)) {
- dbAvailable = aaiGraphChecker.isAaiGraphDbAvailable(AaiGraphChecker.CheckerType.CACHED);
- } else if (CHECK_DB_STATUS_NOW_ACTION.equalsIgnoreCase(action)) {
- dbAvailable = aaiGraphChecker.isAaiGraphDbAvailable(AaiGraphChecker.CheckerType.ACTUAL);
- } else {
- LOGGER.error("Invalid check db action specified to generate echo response: '{}'", action);
- }
-
- if (BooleanUtils.isFalse(dbAvailable)) {
+ private void validateDBStatus() throws AAIException {
+ boolean dbAvailable = graphChecker.isAaiGraphDbAvailable();
+ if (!dbAvailable) {
throw new AAIException("AAI_5105", "Error establishing a database connection");
}
diff --git a/aai-resources/src/main/java/org/onap/aai/tasks/AaiGraphChecker.java b/aai-resources/src/main/java/org/onap/aai/tasks/AaiGraphChecker.java
deleted file mode 100644
index 3c07a529..00000000
--- a/aai-resources/src/main/java/org/onap/aai/tasks/AaiGraphChecker.java
+++ /dev/null
@@ -1,203 +0,0 @@
-/*
- * ============LICENSE_START=======================================================
- * Copyright (C) 2022 Bell Canada
- * ================================================================================
- * 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.
- * ============LICENSE_END=========================================================
- */
-
-package org.onap.aai.tasks;
-
-import com.google.common.collect.Iterators;
-
-import java.util.Iterator;
-import java.util.Timer;
-import java.util.TimerTask;
-
-import javax.annotation.PostConstruct;
-import javax.annotation.PreDestroy;
-
-import org.apache.commons.lang3.BooleanUtils;
-import org.apache.commons.lang3.Validate;
-import org.janusgraph.core.JanusGraphException;
-import org.janusgraph.core.JanusGraphTransaction;
-import org.janusgraph.core.JanusGraphVertex;
-import org.onap.aai.dbmap.AAIGraph;
-import org.onap.aai.exceptions.AAIException;
-import org.onap.aai.logging.ErrorLogHelper;
-import org.onap.aai.util.AAIConfig;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.springframework.beans.factory.config.ConfigurableBeanFactory;
-import org.springframework.context.annotation.Scope;
-import org.springframework.stereotype.Component;
-
-/**
- * Singleton class responsible to check that AAI service is able to connect to its back-end database.
- * The check can run as a scheduled task or on demand.
- */
-@Component
-@Scope(ConfigurableBeanFactory.SCOPE_SINGLETON)
-public class AaiGraphChecker extends TimerTask {
-
- private static final Logger LOGGER = LoggerFactory.getLogger(AaiGraphChecker.class);
-
- // Default indicator to enable or disable scheduled task
- private static final String DEFAULT_SCHEDULE_ENABLED_VALUE = "false";
- // Default delay, in seconds, before the scheduled task is started, if enabled
- private static final String DEFAULT_SCHEDULE_DELAY_VALUE = "5";
- // Default period, in seconds, between two consecutive executions of the scheduled task, if enabled
- private static final String DEFAULT_SCHEDULE_PERIOD_VALUE = "60";
-
- // Database availability cached indicator
- private volatile Boolean isAaiGraphDbAvailableCache = null;
-
- private Timer timer = null;
-
- /**
- * Enumeration of check type that can be made.
- */
- public enum CheckerType {
- ACTUAL, CACHED
- }
-
- private AaiGraphChecker() {
- }
-
- @PostConstruct
- private void setupTimer() {
-
- boolean scheduleEnabled = Boolean.parseBoolean(
- getConfigurationValueOrDefault("aai.graph.checker.task.enabled", DEFAULT_SCHEDULE_ENABLED_VALUE));
- long scheduleDelay = Long.parseLong(
- getConfigurationValueOrDefault("aai.graph.checker.task.delay", DEFAULT_SCHEDULE_DELAY_VALUE));
- long schedulePeriod = Long.parseLong(
- getConfigurationValueOrDefault("aai.graph.checker.task.period", DEFAULT_SCHEDULE_PERIOD_VALUE));
- LOGGER.debug("Setting up AaiGraphChecker with scheduleEnabled={}, scheduleDelay={}, schedulePeriod={} ",
- scheduleEnabled, scheduleDelay, schedulePeriod);
-
- if (scheduleEnabled) {
- timer = new Timer();
- timer.schedule(this, scheduleDelay * 1000, schedulePeriod * 1000);
- }
- }
-
- @PreDestroy
- private void tearDownTimer() {
- LOGGER.debug("Tear down AaiGraphChecker");
- if (timer != null) {
- timer.cancel();
- timer = null;
- }
- }
-
- @Override
- public void run() {
- isAaiGraphDbAvailable(CheckerType.ACTUAL);
- }
-
- /**
- * Clear database availability cached indicator.
- */
- public void clearDbAvailabilityCachedIndicator() {
- isAaiGraphDbAvailableCache = null;
- }
-
- /**
- * Indicate if AAI Graph database is available either from actual db connection or from cached property state.
- *
- * @param checkerType the type of check to be made (actual or cached). Null is not supported.
- * @return
- * <li>true, if database is available</li>
- * <li>false, if database is NOT available</li>
- * <li>null, if database availability can not be determined</li>
- */
- public Boolean isAaiGraphDbAvailable(CheckerType checkerType) {
- Validate.notNull(checkerType);
- if (CheckerType.ACTUAL.equals(checkerType)) {
- isAaiGraphDbAvailableCache = isAaiGraphDbAvailableActual();
- }
- logDbState(checkerType);
- return isAaiGraphDbAvailableCache;
- }
-
- private Boolean isAaiGraphDbAvailableActual() {
- Boolean dbAvailable;
- JanusGraphTransaction transaction = null;
- try {
- transaction = AAIGraph.getInstance().getGraph().newTransaction();
- final Iterator<JanusGraphVertex> vertexIterator = transaction.query().limit(1).vertices().iterator();
- if (LOGGER.isDebugEnabled()) {
- LOGGER.debug("Number of vertices retrieved while checking db: {}", Iterators.size(vertexIterator));
- }
- vertexIterator.hasNext();
- LOGGER.debug("Actual database availability is true");
- dbAvailable = Boolean.TRUE;
- } catch (JanusGraphException e) {
- String message = "Actual database availability is false (after JanusGraph exception)";
- ErrorLogHelper.logError("500", message + ": " + e.getMessage());
- LOGGER.error(message, e);
- dbAvailable = Boolean.FALSE;
- } catch (Error e) {
- // Following error occurs when aai resources is starting:
- // - UnsatisfiedLinkError (for org.onap.aai.dbmap.AAIGraph$Helper instantiation)
- // Following errors are raised when aai resources is starting and cassandra is not running:
- // - ExceptionInInitializerError
- // - NoClassDefFoundError (definition for org.onap.aai.dbmap.AAIGraph$Helper is not found)
- String message = "Actual database availability is false (after error)";
- ErrorLogHelper.logError("500", message + ": " + e.getMessage());
- LOGGER.error(message, e);
- dbAvailable = Boolean.FALSE;
- } catch (Exception e) {
- String message = "Actual database availability can not be determined";
- ErrorLogHelper.logError("500", message + ": " + e.getMessage());
- LOGGER.error(message, e);
- dbAvailable = null;
- } finally {
- if (transaction != null && !transaction.isClosed()) {
- // check if transaction is open then close instead of flag
- try {
- transaction.rollback();
- } catch (Exception e) {
- String message = "Exception occurred while closing transaction";
- LOGGER.error(message, e);
- ErrorLogHelper.logError("500", message + ": " + e.getMessage());
- }
- }
- }
- return dbAvailable;
- }
-
- private void logDbState(CheckerType type) {
- if (BooleanUtils.isTrue(isAaiGraphDbAvailableCache)) {
- LOGGER.debug("Database is available from {} check.", type);
- } else if (BooleanUtils.isFalse(isAaiGraphDbAvailableCache)) {
- LOGGER.error("Database is NOT available from {} check.", type);
- } else {
- LOGGER.error("Database availability is UNKNOWN from {} check.", type);
- }
- }
-
- private String getConfigurationValueOrDefault(String property, String defaultValue) {
- String result;
- try {
- result = AAIConfig.get(property);
- } catch (AAIException e) {
- LOGGER.error("Unable to get defined configuration value for '{}' property, then default '{}' value is used",
- property, defaultValue);
- result = defaultValue;
- }
- return result;
- }
-
-}