aboutsummaryrefslogtreecommitdiffstats
path: root/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org
diff options
context:
space:
mode:
Diffstat (limited to 'appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org')
-rw-r--r--appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/messageadapter/impl/MessageAdapterImpl.java8
-rw-r--r--appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/requesthandler/constant/Constants.java1
-rw-r--r--appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/requesthandler/conv/Converter.java20
-rw-r--r--appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/requesthandler/exceptions/DGWorkflowNotFoundException.java16
-rw-r--r--appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/requesthandler/exceptions/DuplicateRequestException.java5
-rw-r--r--appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/requesthandler/exceptions/LCMOperationsDisabledException.java8
-rw-r--r--appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/requesthandler/exceptions/MissingVNFDataInAAIException.java12
-rw-r--r--appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/requesthandler/exceptions/MultipleRecordsRetrievedException.java47
-rw-r--r--appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/requesthandler/exceptions/NoRecordsRetrievedException.java49
-rw-r--r--appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/requesthandler/exceptions/RequestExpiredException.java5
-rw-r--r--appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/requesthandler/exceptions/RequestValidationException.java90
-rw-r--r--appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/requesthandler/exceptions/VNFNotFoundException.java16
-rw-r--r--appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/requesthandler/exceptions/WorkflowNotFoundException.java8
-rw-r--r--appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/requesthandler/helper/RequestRegistry.java93
-rw-r--r--appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/requesthandler/helper/RequestValidator.java14
-rw-r--r--appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/requesthandler/impl/AbstractRequestHandlerImpl.java586
-rw-r--r--appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/requesthandler/impl/AbstractRequestValidatorImpl.java258
-rw-r--r--appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/requesthandler/impl/LCMStateManagerImpl.java2
-rw-r--r--appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/requesthandler/impl/LocalRequestHandlerImpl.java208
-rw-r--r--appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/requesthandler/impl/LocalRequestValidatorImpl.java95
-rw-r--r--appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/requesthandler/impl/RequestHandlerImpl.java234
-rw-r--r--appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/requesthandler/impl/RequestValidatorImpl.java477
-rw-r--r--appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/requesthandler/impl/VMRequestValidatorImpl.java81
-rw-r--r--appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/requesthandler/model/ActionIdentifierModel.java (renamed from appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/workingstatemanager/objects/VnfWorkingStateDto.java)73
-rw-r--r--appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/requesthandler/model/Input.java (renamed from appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/workingstatemanager/impl/RequestHandlerMessages.java)20
-rw-r--r--appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/requesthandler/model/Request.java66
-rw-r--r--appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/requesthandler/model/RequestData.java68
-rw-r--r--appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/requesthandler/model/RequestModel.java54
-rw-r--r--appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/requesthandler/model/ScopeOverlapModel.java67
-rw-r--r--appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/validationpolicy/RequestValidationPolicy.java142
-rw-r--r--appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/validationpolicy/executors/ActionInProgressRuleExecutor.java50
-rw-r--r--appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/validationpolicy/executors/RuleExecutor.java44
-rw-r--r--appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/validationpolicy/objects/Policy.java (renamed from appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/requesthandler/impl/VMRequestHandlerImpl.java)32
-rw-r--r--appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/validationpolicy/objects/PolicyNames.java (renamed from appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/workingstatemanager/objects/VNFWorkingState.java)10
-rw-r--r--appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/validationpolicy/objects/Rule.java76
-rw-r--r--appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/validationpolicy/objects/RuleResult.java (renamed from appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/requesthandler/exceptions/InvalidInputException.java)9
-rw-r--r--appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/validationpolicy/objects/ValidationJSON.java (renamed from appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/workingstatemanager/impl/JdbcWorkingStateManager.java)28
-rw-r--r--appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/validationpolicy/rules/AcceptRule.java76
-rw-r--r--appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/validationpolicy/rules/RejectRule.java75
-rw-r--r--appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/validationpolicy/rules/Rule.java51
-rw-r--r--appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/validationpolicy/rules/RuleFactory.java47
-rw-r--r--appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/workingstatemanager/WorkingStateManager.java50
-rw-r--r--appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/workingstatemanager/impl/WorkingStateManagerImpl.java230
43 files changed, 2245 insertions, 1356 deletions
diff --git a/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/messageadapter/impl/MessageAdapterImpl.java b/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/messageadapter/impl/MessageAdapterImpl.java
index 8351f8942..ecc7f729c 100644
--- a/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/messageadapter/impl/MessageAdapterImpl.java
+++ b/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/messageadapter/impl/MessageAdapterImpl.java
@@ -74,10 +74,10 @@ public class MessageAdapterImpl implements MessageAdapter{
BundleContext ctx = FrameworkUtil.getBundle(MessageAdapterImpl.class).getBundleContext();
if (ctx != null) {
- ServiceReference svcRef = ctx.getServiceReference(MessageAdapterFactory.class.getName());
- if (svcRef != null) {
- producer = ((MessageAdapterFactory) ctx.getService(svcRef)).createProducer(pool, writeTopic,apiKey, apiSecret);
- }
+ ServiceReference svcRef = ctx.getServiceReference(MessageAdapterFactory.class.getName());
+ if (svcRef != null) {
+ producer = ((MessageAdapterFactory) ctx.getService(svcRef)).createProducer(pool, writeTopic,apiKey, apiSecret);
+ }
}
return producer;
}
diff --git a/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/requesthandler/constant/Constants.java b/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/requesthandler/constant/Constants.java
index 4015181a1..37fdbcfc3 100644
--- a/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/requesthandler/constant/Constants.java
+++ b/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/requesthandler/constant/Constants.java
@@ -33,4 +33,5 @@ public class Constants {
public static final String FAILURE_MSG="FAILURE";
public static final String DEFAULT_LOGGING_FLAG="true";
public static final long DEFAULT_IDLE_TIMEOUT = TimeUnit.MILLISECONDS.convert(15, TimeUnit.MINUTES);
+ public static final String DEFAULT_TTL_KEY="org.onap.appc.workflow.default.ttl";
}
diff --git a/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/requesthandler/conv/Converter.java b/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/requesthandler/conv/Converter.java
index 5a791711e..406bf620d 100644
--- a/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/requesthandler/conv/Converter.java
+++ b/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/requesthandler/conv/Converter.java
@@ -56,13 +56,9 @@ import java.util.TimeZone;
public class Converter {
- public static final String ISO_FORMAT = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'";
- public static final String MODE_FLAG = "MODE";
- public static final String FORCE_FLAG = "FORCE";
- public static final String TTL_FLAG = "TTL";
- public final static String DMaaP_ROOT_VALUE = "output";
+ private static final String ISO_FORMAT = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'";
+ private final static String DMaaP_ROOT_VALUE = "output";
private static final SimpleDateFormat isoFormatter = new SimpleDateFormat(ISO_FORMAT);
- private static final EELFLogger logger = EELFManager.getInstance().getLogger(Converter.class);
static {
isoFormatter.setTimeZone(TimeZone.getTimeZone("UTC"));
}
@@ -223,6 +219,7 @@ public class Converter {
((StartApplicationOutputBuilder)outObj).setCommonHeader(commonHeader);
((StartApplicationOutputBuilder)outObj).setStatus(status);
return outObj;
+
default:
throw new IllegalArgumentException(action+" action is not supported");
}
@@ -246,7 +243,6 @@ public class Converter {
try {
ObjectMapper objectMapper = new ObjectMapper();
payloadAsString = objectMapper.writeValueAsString(inObj);
-// payloadAsString = objectMapper.writeValueAsString(payloadAsString);
} catch (JsonProcessingException e) {
String errMsg = "Error serialize payload json to string";
throw new ParseException(errMsg + "-" + e.toString(), 0);
@@ -270,7 +266,7 @@ public class Converter {
}
CommonHeaderBuilder commonHeaderBuilder = new CommonHeaderBuilder();
- org.opendaylight.yang.gen.v1.org.onap.appc.lcm.rev160108.common.header.common.header.Flags commonHeaderFlags = null;
+ org.opendaylight.yang.gen.v1.org.onap.appc.lcm.rev160108.common.header.common.header.Flags commonHeaderFlags;
if(inObj.getCommonHeader().getFlags() != null){
commonHeaderFlags = Converter.convFlagsMapTorev160108Flags(inObj.getCommonHeader().getFlags());
commonHeaderBuilder.setFlags(commonHeaderFlags);
@@ -288,7 +284,7 @@ public class Converter {
}
if(inObj.getCommonHeader().getTimeStamp() != null){
- String zuluTimestampStr = Converter.convDateToZuluString(Date.from(inObj.getCommonHeader().getTimeStamp()));
+ String zuluTimestampStr = Converter.convDateToZuluString(inObj.getCommonHeader().getTimeStamp());
ZULU zuluTimestamp = new ZULU(zuluTimestampStr);
commonHeaderBuilder.setTimestamp(zuluTimestamp);
}
@@ -303,7 +299,7 @@ public class Converter {
public static org.opendaylight.yang.gen.v1.org.onap.appc.lcm.rev160108.common.header.common.header.Flags
convFlagsMapTorev160108Flags(org.onap.appc.domainmodel.lcm.Flags flags) {
- Flags rev160108flags = null;
+ Flags rev160108flags;
boolean anyFlag = false;
FlagsBuilder flagsBuilder = new FlagsBuilder();
/*
@@ -346,7 +342,7 @@ public class Converter {
objectMapper.addMixInAnnotations(Payload.class, MixIn.class);
objectMapper.addMixInAnnotations(ZULU.class, MixIn.class);
-// .configure(SerializationConfig.Feature.SORT_PROPERTIES_ALPHABETICALLY,true)
+// .configure(SerializationConfig.Feature.SORT_PROPERTIES_ALPHABETICALLY,true)
ObjectWriter writer = objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL).configure(MapperFeature.SORT_PROPERTIES_ALPHABETICALLY,true)
.writer(SerializationFeature.WRAP_ROOT_VALUE).withRootName(DMaaP_ROOT_VALUE).withoutFeatures(SerializationFeature.ORDER_MAP_ENTRIES_BY_KEYS);
return writer.writeValueAsString(message);
@@ -362,7 +358,7 @@ public class Converter {
objectMapper.addMixInAnnotations(Payload.class, MixIn.class);
objectMapper.addMixInAnnotations(ZULU.class, MixIn.class);
-// .configure(SerializationConfig.Feature.SORT_PROPERTIES_ALPHABETICALLY,true)
+// .configure(SerializationConfig.Feature.SORT_PROPERTIES_ALPHABETICALLY,true)
ObjectWriter writer = objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL).configure(MapperFeature.SORT_PROPERTIES_ALPHABETICALLY,true).writer();
return writer.writeValueAsString(dmaapOutgoingMessage);
}
diff --git a/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/requesthandler/exceptions/DGWorkflowNotFoundException.java b/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/requesthandler/exceptions/DGWorkflowNotFoundException.java
index 5626cfe6f..3ddeea1c4 100644
--- a/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/requesthandler/exceptions/DGWorkflowNotFoundException.java
+++ b/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/requesthandler/exceptions/DGWorkflowNotFoundException.java
@@ -25,14 +25,26 @@
package org.onap.appc.requesthandler.exceptions;
-public class DGWorkflowNotFoundException extends Exception {
+import com.att.eelf.i18n.EELFResourceManager;
+import org.onap.appc.executor.objects.LCMCommandStatus;
+import org.onap.appc.executor.objects.Params;
+import org.onap.appc.i18n.Msg;
+import org.onap.appc.logging.LoggingConstants;
+
+public class DGWorkflowNotFoundException extends RequestValidationException {
public final String workflowModule;
public final String workflowName;
public final String workflowVersion;
- public DGWorkflowNotFoundException(String message,String workflowModule,String workflowName,String workflowVersion){
+ public DGWorkflowNotFoundException(String message,String workflowModule,String workflowName,String workflowVersion,String vnfType,String action){
super(message);
this.workflowModule = workflowModule;
this.workflowName = workflowName;
this.workflowVersion = workflowVersion;
+ super.setLcmCommandStatus(LCMCommandStatus.DG_WORKFLOW_NOT_FOUND);
+ super.setParams(new Params().addParam("actionName", action)
+ .addParam("dgModule", workflowModule).addParam("dgName", workflowName).addParam("dgVersion", workflowVersion));
+ super.setLogMessage(EELFResourceManager.format(Msg.APPC_WORKFLOW_NOT_FOUND, vnfType, action));
+ super.setTargetEntity(LoggingConstants.TargetNames.APPC);
+ super.setTargetService(LoggingConstants.TargetNames.WORKFLOW_MANAGER);
}
}
diff --git a/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/requesthandler/exceptions/DuplicateRequestException.java b/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/requesthandler/exceptions/DuplicateRequestException.java
index b06788a99..8b0f7cbfe 100644
--- a/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/requesthandler/exceptions/DuplicateRequestException.java
+++ b/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/requesthandler/exceptions/DuplicateRequestException.java
@@ -25,8 +25,11 @@
package org.onap.appc.requesthandler.exceptions;
-public class DuplicateRequestException extends Exception {
+import org.onap.appc.executor.objects.LCMCommandStatus;
+
+public class DuplicateRequestException extends RequestValidationException {
public DuplicateRequestException(String message){
super(message);
+ super.setLcmCommandStatus(LCMCommandStatus.DUPLICATE_REQUEST);
}
}
diff --git a/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/requesthandler/exceptions/LCMOperationsDisabledException.java b/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/requesthandler/exceptions/LCMOperationsDisabledException.java
index ca5f72682..730eff67f 100644
--- a/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/requesthandler/exceptions/LCMOperationsDisabledException.java
+++ b/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/requesthandler/exceptions/LCMOperationsDisabledException.java
@@ -24,9 +24,12 @@
package org.onap.appc.requesthandler.exceptions;
+import org.onap.appc.executor.objects.LCMCommandStatus;
+import org.onap.appc.executor.objects.Params;
+
/**
*/
-public class LCMOperationsDisabledException extends Exception {
+public class LCMOperationsDisabledException extends RequestValidationException {
/**
* Constructs a new exception with the specified detail message.
@@ -35,5 +38,8 @@ public class LCMOperationsDisabledException extends Exception {
*/
public LCMOperationsDisabledException(String message) {
super(message);
+ super.setLcmCommandStatus(LCMCommandStatus.REJECTED);
+ super.setParams(new Params().addParam("errorMsg", message));
+
}
}
diff --git a/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/requesthandler/exceptions/MissingVNFDataInAAIException.java b/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/requesthandler/exceptions/MissingVNFDataInAAIException.java
index 219265084..0bd5b8fda 100644
--- a/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/requesthandler/exceptions/MissingVNFDataInAAIException.java
+++ b/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/requesthandler/exceptions/MissingVNFDataInAAIException.java
@@ -24,10 +24,16 @@
package org.onap.appc.requesthandler.exceptions;
-public class MissingVNFDataInAAIException extends Exception {
- String missingAttributeName;
- public MissingVNFDataInAAIException(String attributeName) {
+import org.onap.appc.executor.objects.LCMCommandStatus;
+import org.onap.appc.executor.objects.Params;
+
+public class MissingVNFDataInAAIException extends RequestValidationException {
+ private String missingAttributeName;
+ public MissingVNFDataInAAIException(String attributeName ,String vnfId ) {
+ super("Missing VNF data in AAI");
this.missingAttributeName = attributeName;
+ super.setLcmCommandStatus(LCMCommandStatus.MISSING_VNF_DATA_IN_AAI);
+ super.setParams( new Params().addParam("attributeName", attributeName).addParam("vnfId", vnfId));
}
public String getMissingAttributeName() {
diff --git a/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/requesthandler/exceptions/MultipleRecordsRetrievedException.java b/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/requesthandler/exceptions/MultipleRecordsRetrievedException.java
new file mode 100644
index 000000000..622122e56
--- /dev/null
+++ b/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/requesthandler/exceptions/MultipleRecordsRetrievedException.java
@@ -0,0 +1,47 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * ONAP : APPC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Copyright (C) 2017 Amdocs
+ * =============================================================================
+ * 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.
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.onap.appc.requesthandler.exceptions;
+
+/**
+ * This exception is thrown when more than one record are retrieved from DB
+ */
+public class MultipleRecordsRetrievedException extends Exception {
+ /**
+ * Constructs a new exception with null as its detail message. The cause is not initialized, and may subsequently be
+ * initialized by a call to initCause.
+ */
+ public MultipleRecordsRetrievedException() {
+ }
+
+ /**
+ * Constructs a new exception with the specified detail message. The cause is not initialized, and may subsequently
+ * be initialized by a call to initCause.
+ *
+ * @param message the detail message. The detail message is saved for later retrieval by the getMessage() method.
+ */
+ public MultipleRecordsRetrievedException(String message) {
+ super(message);
+ }
+}
diff --git a/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/requesthandler/exceptions/NoRecordsRetrievedException.java b/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/requesthandler/exceptions/NoRecordsRetrievedException.java
new file mode 100644
index 000000000..d10ca6104
--- /dev/null
+++ b/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/requesthandler/exceptions/NoRecordsRetrievedException.java
@@ -0,0 +1,49 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * ONAP : APPC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Copyright (C) 2017 Amdocs
+ * =============================================================================
+ * 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.
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.onap.appc.requesthandler.exceptions;
+
+/**
+ * This exception is thrown when no record is retrieved from the DB for a
+ * given query parameters.
+ */
+public class NoRecordsRetrievedException extends Exception {
+
+ /**
+ * Constructs a new exception with null as its detail message. The cause is not initialized, and may subsequently be
+ * initialized by a call to initCause.
+ */
+ public NoRecordsRetrievedException() {
+ }
+
+ /**
+ * Constructs a new exception with the specified detail message. The cause is not initialized, and may subsequently
+ * be initialized by a call to initCause.
+ *
+ * @param message the detail message. The detail message is saved for later retrieval by the getMessage() method.
+ */
+ public NoRecordsRetrievedException(String message) {
+ super(message);
+ }
+}
diff --git a/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/requesthandler/exceptions/RequestExpiredException.java b/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/requesthandler/exceptions/RequestExpiredException.java
index 02a130c8b..2657eca0c 100644
--- a/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/requesthandler/exceptions/RequestExpiredException.java
+++ b/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/requesthandler/exceptions/RequestExpiredException.java
@@ -25,8 +25,11 @@
package org.onap.appc.requesthandler.exceptions;
-public class RequestExpiredException extends Exception {
+import org.onap.appc.executor.objects.LCMCommandStatus;
+
+public class RequestExpiredException extends RequestValidationException {
public RequestExpiredException(String message){
super(message);
+ super.setLcmCommandStatus(LCMCommandStatus.EXPIRED_REQUEST);
}
}
diff --git a/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/requesthandler/exceptions/RequestValidationException.java b/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/requesthandler/exceptions/RequestValidationException.java
new file mode 100644
index 000000000..0923b660e
--- /dev/null
+++ b/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/requesthandler/exceptions/RequestValidationException.java
@@ -0,0 +1,90 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * ONAP : APPC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Copyright (C) 2017 Amdocs
+ * =============================================================================
+ * 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.
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.onap.appc.requesthandler.exceptions;
+
+
+import org.onap.appc.executor.objects.LCMCommandStatus;
+import org.onap.appc.executor.objects.Params;
+
+public class RequestValidationException extends Exception {
+ private LCMCommandStatus lcmCommandStatus;
+ private Params params;
+ private String logMessage;
+ private String targetEntity;
+ private String targetService;
+
+ public LCMCommandStatus getLcmCommandStatus() {
+ return lcmCommandStatus;
+ }
+
+ public void setLcmCommandStatus(LCMCommandStatus lcmCommandStatus) {
+ this.lcmCommandStatus = lcmCommandStatus;
+ }
+
+ public Params getParams() {
+ return params;
+ }
+
+ public void setParams(Params params) {
+ this.params = params;
+ }
+
+ public String getLogMessage() {
+ return logMessage;
+ }
+
+ public void setLogMessage(String logMessage) {
+ this.logMessage = logMessage;
+ }
+
+ public RequestValidationException( String message){
+ super(message);
+ }
+
+ public RequestValidationException( String message , LCMCommandStatus lcmCommandStatus, Params params){
+ super(message);
+ this.lcmCommandStatus = lcmCommandStatus;
+ this.params =params;
+ }
+
+ public String getTargetEntity() {
+ return targetEntity;
+ }
+
+ public void setTargetEntity(String targetEntity) {
+ this.targetEntity = targetEntity;
+ }
+
+ public String getTargetService() {
+ return targetService;
+ }
+
+ public void setTargetService(String targetService) {
+ this.targetService = targetService;
+ }
+
+
+
+}
diff --git a/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/requesthandler/exceptions/VNFNotFoundException.java b/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/requesthandler/exceptions/VNFNotFoundException.java
index d1b2759d6..5f452aa27 100644
--- a/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/requesthandler/exceptions/VNFNotFoundException.java
+++ b/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/requesthandler/exceptions/VNFNotFoundException.java
@@ -25,8 +25,20 @@
package org.onap.appc.requesthandler.exceptions;
-public class VNFNotFoundException extends Exception {
- public VNFNotFoundException(String message){
+import com.att.eelf.i18n.EELFResourceManager;
+import org.onap.appc.executor.objects.LCMCommandStatus;
+import org.onap.appc.executor.objects.Params;
+import org.onap.appc.i18n.Msg;
+import org.onap.appc.logging.LoggingConstants;
+
+public class VNFNotFoundException extends RequestValidationException {
+ public VNFNotFoundException(String message, String vnfId){
super(message);
+ super.setLcmCommandStatus(LCMCommandStatus.VNF_NOT_FOUND);
+ Params params = new Params().addParam("vnfId", vnfId);
+ super.setLogMessage(EELFResourceManager.format(Msg.APPC_NO_RESOURCE_FOUND, vnfId));
+ super.setParams(params);
+ super.setTargetEntity(LoggingConstants.TargetNames.AAI);
+ super.setTargetService("");
}
}
diff --git a/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/requesthandler/exceptions/WorkflowNotFoundException.java b/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/requesthandler/exceptions/WorkflowNotFoundException.java
index 85157e32f..498b6a44e 100644
--- a/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/requesthandler/exceptions/WorkflowNotFoundException.java
+++ b/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/requesthandler/exceptions/WorkflowNotFoundException.java
@@ -25,13 +25,19 @@
package org.onap.appc.requesthandler.exceptions;
-public class WorkflowNotFoundException extends Exception {
+import org.onap.appc.executor.objects.LCMCommandStatus;
+import org.onap.appc.executor.objects.Params;
+
+public class WorkflowNotFoundException extends RequestValidationException {
public final String vnfTypeVersion;
public final String command;
public WorkflowNotFoundException(String message,String vnfTypeVersion,String command){
super(message);
this.vnfTypeVersion = vnfTypeVersion;
this.command = command;
+ super.setLcmCommandStatus(LCMCommandStatus.WORKFLOW_NOT_FOUND);
+ Params params = new Params().addParam("actionName", command).addParam("vnfTypeVersion", vnfTypeVersion);
+ super.setParams(params);
}
}
diff --git a/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/requesthandler/helper/RequestRegistry.java b/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/requesthandler/helper/RequestRegistry.java
deleted file mode 100644
index fd1292ff9..000000000
--- a/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/requesthandler/helper/RequestRegistry.java
+++ /dev/null
@@ -1,93 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * ONAP : APPC
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Copyright (C) 2017 Amdocs
- * =============================================================================
- * 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.
- *
- * ECOMP is a trademark and service mark of AT&T Intellectual Property.
- * ============LICENSE_END=========================================================
- */
-
-package org.onap.appc.requesthandler.helper;
-
-import org.apache.commons.lang.ObjectUtils;
-import org.onap.appc.executor.objects.UniqueRequestIdentifier;
-import com.att.eelf.configuration.EELFLogger;
-import com.att.eelf.configuration.EELFManager;
-
-import java.util.Collections;
-import java.util.Set;
-import java.util.concurrent.ConcurrentHashMap;
-
-/**
- *
- * This class serves as Request Registry, which holds the
- * request unique parameters (originatorId,requestId,subRequestId)
- * in memory.
- */
-public class RequestRegistry {
-
- static Set<UniqueRequestIdentifier> set = Collections.newSetFromMap(new ConcurrentHashMap<UniqueRequestIdentifier, Boolean>());
- private static final EELFLogger logger = EELFManager.getInstance().getLogger(RequestRegistry.class);
- public RequestRegistry(){
-
- }
-
- /**
- * This method accepts unique request parameters and adds it to Request Registry
- * if Registry already contains same parameters it returns false,
- * else returns true.
- * @param requestIdentifier
- * @return
- */
- public boolean registerRequest(UniqueRequestIdentifier requestIdentifier){
-
- if (logger.isTraceEnabled()) {
- logger.trace("Entering to registerRequest with UniqueRequestIdentifier = "+ ObjectUtils.toString(requestIdentifier));
- }
- boolean output = set.add(requestIdentifier);
- logger.debug(" Output = " + output);
- if (logger.isTraceEnabled()) {
- logger.trace("Exiting from registerRequest with (output = "+ ObjectUtils.toString(output)+")");
- }
- return output;
- }
-
- /**
- * This method accepts unique request parameters and removes request
- * from the Request Registry
- * @param requestIdentifier
- */
- public void removeRequest(UniqueRequestIdentifier requestIdentifier){
- if (logger.isTraceEnabled()) {
- logger.trace("Entering to removeRequest with UniqueRequestIdentifier = "+ ObjectUtils.toString(requestIdentifier));
- }
- set.remove(requestIdentifier);
- }
-
- /**
- * This method returns the count of currently registered requests
- * in the request registry
- * * @return currently registered requests count
- */
- public int getRegisteredRequestCount() {
- if (logger.isTraceEnabled()) {
- logger.trace("Entering to getRegisteredRequestCount");
- }
- return set.size();
- }
-}
diff --git a/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/requesthandler/helper/RequestValidator.java b/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/requesthandler/helper/RequestValidator.java
index e45341d3d..3ba7390c5 100644
--- a/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/requesthandler/helper/RequestValidator.java
+++ b/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/requesthandler/helper/RequestValidator.java
@@ -25,18 +25,8 @@
package org.onap.appc.requesthandler.helper;
import org.onap.appc.domainmodel.lcm.RuntimeContext;
-import org.onap.appc.executor.UnstableVNFException;
-import org.onap.appc.lifecyclemanager.objects.LifecycleException;
-import org.onap.appc.lifecyclemanager.objects.NoTransitionDefinedException;
-import org.onap.appc.requesthandler.exceptions.DGWorkflowNotFoundException;
-import org.onap.appc.requesthandler.exceptions.DuplicateRequestException;
-import org.onap.appc.requesthandler.exceptions.InvalidInputException;
-import org.onap.appc.requesthandler.exceptions.LCMOperationsDisabledException;
-import org.onap.appc.requesthandler.exceptions.MissingVNFDataInAAIException;
-import org.onap.appc.requesthandler.exceptions.RequestExpiredException;
-import org.onap.appc.requesthandler.exceptions.VNFNotFoundException;
-import org.onap.appc.requesthandler.exceptions.WorkflowNotFoundException;
+import org.onap.appc.exceptions.InvalidInputException;
public interface RequestValidator {
- public void validateRequest(RuntimeContext runtimeContext) throws VNFNotFoundException, RequestExpiredException, UnstableVNFException, InvalidInputException, DuplicateRequestException, NoTransitionDefinedException, LifecycleException, WorkflowNotFoundException, DGWorkflowNotFoundException, MissingVNFDataInAAIException, LCMOperationsDisabledException;
+ void validateRequest(RuntimeContext runtimeContext) throws Exception;
}
diff --git a/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/requesthandler/impl/AbstractRequestHandlerImpl.java b/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/requesthandler/impl/AbstractRequestHandlerImpl.java
index 8b56dda41..02ff3a321 100644
--- a/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/requesthandler/impl/AbstractRequestHandlerImpl.java
+++ b/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/requesthandler/impl/AbstractRequestHandlerImpl.java
@@ -26,21 +26,23 @@ package org.onap.appc.requesthandler.impl;
import com.att.eelf.configuration.EELFLogger;
import com.att.eelf.configuration.EELFManager;
-import com.att.eelf.i18n.EELFResourceManager;
import org.apache.commons.lang.ObjectUtils;
-import org.onap.appc.requesthandler.constant.Constants;
+import org.apache.commons.lang.StringUtils;
import org.onap.appc.configuration.Configuration;
import org.onap.appc.configuration.ConfigurationFactory;
-import org.onap.appc.domainmodel.lcm.*;
+import org.onap.appc.domainmodel.lcm.Flags;
+import org.onap.appc.domainmodel.lcm.RequestContext;
+import org.onap.appc.domainmodel.lcm.RequestStatus;
+import org.onap.appc.domainmodel.lcm.ResponseContext;
+import org.onap.appc.domainmodel.lcm.RuntimeContext;
+import org.onap.appc.domainmodel.lcm.Status;
+import org.onap.appc.domainmodel.lcm.TransactionRecord;
+import org.onap.appc.domainmodel.lcm.VNFOperation;
import org.onap.appc.exceptions.APPCException;
-import org.onap.appc.executor.CommandExecutor;
-import org.onap.appc.executor.UnstableVNFException;
+import org.onap.appc.exceptions.InvalidInputException;
import org.onap.appc.executor.objects.LCMCommandStatus;
import org.onap.appc.executor.objects.Params;
-import org.onap.appc.executor.objects.UniqueRequestIdentifier;
-import org.onap.appc.i18n.Msg;
-import org.onap.appc.lifecyclemanager.objects.LifecycleException;
-import org.onap.appc.lifecyclemanager.objects.NoTransitionDefinedException;
+import org.onap.appc.lockmanager.api.LockException;
import org.onap.appc.logging.LoggingConstants;
import org.onap.appc.logging.LoggingUtils;
import org.onap.appc.messageadapter.MessageAdapter;
@@ -53,53 +55,54 @@ import org.onap.appc.metricservice.metric.MetricType;
import org.onap.appc.metricservice.policy.PublishingPolicy;
import org.onap.appc.metricservice.publisher.LogPublisher;
import org.onap.appc.requesthandler.RequestHandler;
-import org.onap.appc.requesthandler.exceptions.*;
-import org.onap.appc.requesthandler.helper.RequestRegistry;
+import org.onap.appc.requesthandler.exceptions.RequestValidationException;
import org.onap.appc.requesthandler.helper.RequestValidator;
import org.onap.appc.requesthandler.objects.RequestHandlerInput;
import org.onap.appc.requesthandler.objects.RequestHandlerOutput;
import org.onap.appc.transactionrecorder.TransactionRecorder;
-import org.onap.appc.transactionrecorder.objects.TransactionRecord;
+import org.onap.appc.transactionrecorder.objects.TransactionConstants;
import org.osgi.framework.BundleContext;
import org.osgi.framework.FrameworkUtil;
import org.osgi.framework.ServiceReference;
import org.slf4j.MDC;
import java.net.InetAddress;
+import java.net.UnknownHostException;
+import java.text.SimpleDateFormat;
import java.time.Instant;
+import java.util.Date;
import java.util.HashMap;
+import java.util.Map;
import java.util.Properties;
+import java.util.UUID;
-import static com.att.eelf.configuration.Configuration.*;
+import static com.att.eelf.configuration.Configuration.MDC_INSTANCE_UUID;
+import static com.att.eelf.configuration.Configuration.MDC_KEY_REQUEST_ID;
+import static com.att.eelf.configuration.Configuration.MDC_SERVER_FQDN;
+import static com.att.eelf.configuration.Configuration.MDC_SERVER_IP_ADDRESS;
+import static com.att.eelf.configuration.Configuration.MDC_SERVICE_INSTANCE_ID;
+import static com.att.eelf.configuration.Configuration.MDC_SERVICE_NAME;
/**
* This class provides application logic for the Request/Response Handler Component.
- *
*/
public abstract class AbstractRequestHandlerImpl implements RequestHandler {
private RequestValidator requestValidator;
-
-
- private RequestRegistry requestRegistry;
-
- private CommandExecutor commandExecutor;
-
- private TransactionRecorder transactionRecorder;
+ protected TransactionRecorder transactionRecorder;
private MessageAdapter messageAdapter;
- private static MetricRegistry metricRegistry;
+ static MetricRegistry metricRegistry;
private boolean isMetricEnabled = false;
- protected static final Configuration configuration = ConfigurationFactory.getConfiguration();
+ protected final Configuration configuration = ConfigurationFactory.getConfiguration();
- private static final EELFLogger logger = EELFManager.getInstance().getLogger(AbstractRequestHandlerImpl.class);
+ private final EELFLogger logger = EELFManager.getInstance().getLogger(AbstractRequestHandlerImpl.class);
- public AbstractRequestHandlerImpl() {
- requestRegistry = new RequestRegistry();
+ AbstractRequestHandlerImpl() {
messageAdapter = new MessageAdapterImpl();
messageAdapter.init();
Properties properties = configuration.getProperties();
@@ -123,242 +126,181 @@ public abstract class AbstractRequestHandlerImpl implements RequestHandler {
this.messageAdapter = messageAdapter;
}
-
-
- public void setRequestRegistry(RequestRegistry requestRegistry) {
- this.requestRegistry = requestRegistry;
- }
-
- public void setCommandExecutor(CommandExecutor commandExecutor) {
- this.commandExecutor = commandExecutor;
- }
-
-
/**
* It receives requests from the north-bound REST API (Communication) Layer and
* performs following validations.
* 1. VNF exists in A&AI for the given targetID (VnfID)
* 2. For the current VNF Orchestration Status, the command can be executed
* 3. For the given VNF type and Operation, there exists work-flow definition in the APPC database
- * If any of the validation fails, it returns appropriate response
+ * If any of the validation fails, it returns appropriate response *
*
- * @param input RequestHandlerInput object which contains request header and other request parameters like command , target Id , payload etc.
+ * @param input RequestHandlerInput object which contains request header and other request parameters like
+ * command , target Id , payload etc.
* @return response for request as enum with Return code and message.
*/
@Override
public RequestHandlerOutput handleRequest(RequestHandlerInput input) {
if (logger.isTraceEnabled())
logger.trace("Entering to handleRequest with RequestHandlerInput = " + ObjectUtils.toString(input) + ")");
- Params params ;
- String vnfId, vnfType = null, errorMessage = null;
- Instant startTime = Instant.now();
- RequestHandlerOutput output = null;
- setInitialLogProperties(input.getRequestContext());
-
- RuntimeContext runtimeContext = new RuntimeContext();
- runtimeContext.setRequestContext(input.getRequestContext());
- runtimeContext.setTimeStart(startTime);
- runtimeContext.setRpcName(input.getRpcName());
-
- final ResponseContext responseContext = new ResponseContext();
- responseContext.setStatus(new Status(0,""));
- responseContext.setAdditionalContext(new HashMap<>(4));
- responseContext.setCommonHeader(input.getRequestContext().getCommonHeader());
+ String errorMessage = null;
+ RequestStatus requestStatus;
+ TransactionRecord transactionRecord = createTransactionRecord(input);
+ RuntimeContext runtimeContext = createRuntimeContext(input, transactionRecord);
+ ResponseContext responseContext = createResponseContext(input);
runtimeContext.setResponseContext(responseContext);
- runtimeContext.getResponseContext().setStatus(new Status(0,""));
-
- vnfId = runtimeContext.getRequestContext().getActionIdentifiers().getVnfId();
-
+ RequestHandlerOutput output = new RequestHandlerOutput();
try {
-
+ transactionRecorder.store(transactionRecord);
requestValidator.validateRequest(runtimeContext);
- handleRequest(runtimeContext);
+ setInitialLogProperties(input.getRequestContext());
- final int statusCode = runtimeContext.getResponseContext().getStatus().getCode();
- if (statusCode % 100 == 2 || statusCode % 100 == 3) {
- createTransactionRecord(runtimeContext);
- }
- output = new RequestHandlerOutput();
+ handleRequest(runtimeContext);
output.setResponseContext(runtimeContext.getResponseContext());
-
- } catch (VNFNotFoundException e) {
- errorMessage = e.getMessage();
- String logMessage = EELFResourceManager.format(Msg.APPC_NO_RESOURCE_FOUND, vnfId);
- storeErrorMessageToLog(runtimeContext, LoggingConstants.TargetNames.AAI, "", logMessage);
- params = new Params().addParam("vnfId", vnfId);
- output = buildRequestHandlerOutput(LCMCommandStatus.VNF_NOT_FOUND, params);
- } catch (NoTransitionDefinedException e) {
- errorMessage = e.getMessage();
- String logMessage = EELFResourceManager.format(Msg.VF_UNDEFINED_STATE, input.getRequestContext().getCommonHeader().getOriginatorId(), input.getRequestContext().getAction().name());
- params = new Params().addParam("actionName", input.getRequestContext().getAction()).addParam("currentState", e.currentState);
- output = buildRequestHandlerOutput(LCMCommandStatus.NO_TRANSITION_DEFINE, params);
- storeErrorMessageToLog(runtimeContext,
- LoggingConstants.TargetNames.APPC,
- LoggingConstants.TargetNames.STATE_MACHINE,
- logMessage);
- } catch (LifecycleException e) {
- errorMessage = e.getMessage();
- params = new Params().addParam("actionName", input.getRequestContext().getAction()).addParam("currentState", e.currentState);
- output = buildRequestHandlerOutput(LCMCommandStatus.INVALID_VNF_STATE, params);
- } catch (UnstableVNFException e) {
+ } catch (RequestValidationException e) {
errorMessage = e.getMessage();
- params = new Params().addParam("vnfId", vnfId);
- output = buildRequestHandlerOutput(LCMCommandStatus.UNSTABLE_VNF, params);
- } catch (WorkflowNotFoundException e) {
- errorMessage = e.getMessage();
- String vnfTypeVersion = e.vnfTypeVersion;
- params = new Params().addParam("actionName", input.getRequestContext().getAction()).addParam("vnfTypeVersion", vnfTypeVersion);
- output = buildRequestHandlerOutput(LCMCommandStatus.WORKFLOW_NOT_FOUND, params);
- } catch (DGWorkflowNotFoundException e) {
- errorMessage = e.getMessage();
- String logMessage = EELFResourceManager.format(Msg.APPC_WORKFLOW_NOT_FOUND, vnfType, input.getRequestContext().getAction().name());
- storeErrorMessageToLog(runtimeContext,
- LoggingConstants.TargetNames.APPC,
- LoggingConstants.TargetNames.WORKFLOW_MANAGER,
- logMessage);
- params = new Params().addParam("actionName", input.getRequestContext().getAction().name())
- .addParam("dgModule", e.workflowModule).addParam("dgName", e.workflowName).addParam("dgVersion", e.workflowVersion);
- output = buildRequestHandlerOutput(LCMCommandStatus.DG_WORKFLOW_NOT_FOUND, params);
- } catch (RequestExpiredException e) {
- errorMessage = e.getMessage();
- params = new Params().addParam("actionName", input.getRequestContext().getAction().name());
- output = buildRequestHandlerOutput(LCMCommandStatus.EXPIRED_REQUEST, params);
+ logger.error(errorMessage, e);
+ if (!StringUtils.isEmpty(e.getLogMessage()))
+ storeErrorMessageToLog(runtimeContext, e.getTargetEntity(), e.getTargetService(), e.getLogMessage());
+ output = buildRequestHandlerOutput(e.getLcmCommandStatus(), e.getParams());
} catch (InvalidInputException e) {
+ logger.error("InvalidInputException : " + e.getMessage(), e);
errorMessage = e.getMessage() != null ? e.getMessage() : e.toString();
- params = new Params().addParam("errorMsg", errorMessage);
- output = buildRequestHandlerOutput(LCMCommandStatus.INVALID_INPUT_PARAMETER, params);
- } catch (DuplicateRequestException e) {
- errorMessage = e.getMessage();
- output = buildRequestHandlerOutput(LCMCommandStatus.DUPLICATE_REQUEST, null);
- } catch (MissingVNFDataInAAIException e) {
- params = new Params().addParam("attributeName",e.getMissingAttributeName())
- .addParam("vnfId",vnfId);
- output = buildRequestHandlerOutput(LCMCommandStatus.MISSING_VNF_DATA_IN_AAI,params);
- errorMessage = output.getResponseContext().getStatus().getMessage();
- } catch (LCMOperationsDisabledException e) {
- errorMessage = e.getMessage();
- params = new Params().addParam("errorMsg", errorMessage);
- output = buildRequestHandlerOutput(LCMCommandStatus.REJECTED, params);
+ output = buildRequestHandlerOutput(LCMCommandStatus.INVALID_INPUT_PARAMETER, new Params().addParam
+ ("errorMsg", errorMessage));
+ } catch (LockException e) {
+ logger.error("LockException : " + e.getMessage(), e);
+ Params params = new Params().addParam("errorMsg", e.getMessage());
+ fillStatus(runtimeContext, LCMCommandStatus.LOCKED_VNF_ID, params);
+ output = buildRequestHandlerOutput(LCMCommandStatus.LOCKED_VNF_ID, params);
} catch (Exception e) {
+ logger.error("Exception : " + e.getMessage(), e);
storeErrorMessageToLog(runtimeContext, "", "", "Exception = " + e.getMessage());
errorMessage = e.getMessage() != null ? e.getMessage() : e.toString();
- params = new Params().addParam("errorMsg", errorMessage);
+ Params params = new Params().addParam("errorMsg", errorMessage);
output = buildRequestHandlerOutput(LCMCommandStatus.UNEXPECTED_ERROR, params);
} finally {
+ final int statusCode = output.getResponseContext().getStatus().getCode();
+ if (statusCode == LCMCommandStatus.ACCEPTED.getResponseCode()) {
+ requestStatus = RequestStatus.ACCEPTED;
+ } else if (statusCode == LCMCommandStatus.SUCCESS.getResponseCode()) {
+ requestStatus = RequestStatus.SUCCESSFUL;
+ if (isMetricEnabled)
+ ((DispatchingFuntionMetric) metricRegistry.metric("DISPATCH_FUNCTION")).incrementAcceptedRequest();
+ } else {
+ requestStatus = (statusCode == LCMCommandStatus.EXPIRED_REQUEST.getResponseCode()) ? RequestStatus
+ .TIMEOUT : RequestStatus.REJECTED;
+ if (isMetricEnabled)
+ ((DispatchingFuntionMetric) metricRegistry.metric("DISPATCH_FUNCTION")).incrementRejectedRequest();
+ }
try {
- if (logger.isDebugEnabled() && errorMessage != null)
+ if (errorMessage != null && logger.isDebugEnabled())
logger.debug("error occurred in handleRequest " + errorMessage);
- logger.debug("output.getResponse().getResponseCode().equals(LCMCommandStatus.ACCEPTED.getResponseCode(): " + (output.getResponseContext().getStatus().getCode() == LCMCommandStatus.ACCEPTED.getResponseCode()));
- logger.debug("output.getResponse().getResponseCode().equals(LCMCommandStatus.SUCCESS.getResponseCode(): " + (output.getResponseContext().getStatus().getCode() == LCMCommandStatus.SUCCESS.getResponseCode()));
-
+ logger.debug("output.getResponseContext().getStatus().getCode(): " + statusCode);
runtimeContext.setResponseContext(output.getResponseContext());
- if ((null == output) || !(output.getResponseContext().getStatus().getCode() == LCMCommandStatus.ACCEPTED.getResponseCode())) {
- if (isMetricEnabled) {
- if((output.getResponseContext().getStatus().getCode() == LCMCommandStatus.SUCCESS.getResponseCode())) {
- ((DispatchingFuntionMetric) metricRegistry.metric("DISPATCH_FUNCTION")).incrementAcceptedRequest();
- }else {
- ((DispatchingFuntionMetric) metricRegistry.metric("DISPATCH_FUNCTION")).incrementRejectedRequest();
- }
- }
- removeRequestFromRegistry(input.getRequestContext().getCommonHeader());
- }
} finally {
- storeAuditLogRecord(runtimeContext);
- storeMetricLogRecord(runtimeContext);
- clearRequestLogProperties();
+ runtimeContext.getTransactionRecord().setRequestState(requestStatus);
+ runtimeContext.getTransactionRecord().setResultCode(output.getResponseContext().getStatus().getCode());
+ updateTransactionStatus(runtimeContext.getTransactionRecord());
+ recordAndClearLogProperties(runtimeContext);
}
}
if (logger.isTraceEnabled()) {
- logger.trace("Exiting from handleRequest with (RequestHandlerOutput = " + ObjectUtils.toString(output.getResponseContext()) + ")");
+ logger.trace("Exiting from handleRequest with (RequestHandlerOutput = " +
+ ObjectUtils.toString(output.getResponseContext()) + ")");
}
return output;
}
- protected void storeErrorMessageToLog(RuntimeContext runtimeContext, String targetEntity, String targetServiceName, String additionalMessage) {
- LoggingUtils.logErrorMessage(runtimeContext.getResponseContext().getStatus() != null ?
- String.valueOf(runtimeContext.getResponseContext().getStatus().getCode()) : "",
- runtimeContext.getResponseContext().getStatus() != null ?
- String.valueOf(runtimeContext.getResponseContext().getStatus().getMessage()) : "",
- targetEntity,
- targetServiceName,
- additionalMessage,
- this.getClass().getCanonicalName());
+ private ResponseContext createResponseContext(RequestHandlerInput input) {
+ final ResponseContext responseContext = new ResponseContext();
+ responseContext.setStatus(new Status());
+ responseContext.setAdditionalContext(new HashMap<>(4));
+ responseContext.setCommonHeader(input.getRequestContext().getCommonHeader());
+ return responseContext;
}
- private void createTransactionRecord(RuntimeContext runtimeContext) {
- TransactionRecord transactionRecord = new TransactionRecord();
- transactionRecord.setTimeStamp(runtimeContext.getResponseContext().getCommonHeader().getTimeStamp());
- transactionRecord.setRequestID(runtimeContext.getResponseContext().getCommonHeader().getRequestId());
- transactionRecord.setStartTime(runtimeContext.getTimeStart());
- transactionRecord.setEndTime(Instant.now());
- transactionRecord.setTargetID(runtimeContext.getVnfContext().getId());
- transactionRecord.setTargetType(runtimeContext.getVnfContext().getType());
- transactionRecord.setOperation(runtimeContext.getRequestContext().getAction().name());
- transactionRecord.setResultCode(String.valueOf(runtimeContext.getResponseContext().getStatus().getCode()));
- transactionRecord.setDescription(runtimeContext.getResponseContext().getStatus().getMessage());
- transactionRecorder.store(transactionRecord);
+ private void updateTransactionStatus(TransactionRecord record) {
+ Map<TransactionConstants.TRANSACTION_ATTRIBUTES, String> updateColumns = new HashMap<>();
+ if (!StringUtils.isBlank(record.getTargetType())) {
+ updateColumns.put(TransactionConstants.TRANSACTION_ATTRIBUTES.TARGET_TYPE, record.getTargetType());
+ }
+ updateColumns.put(TransactionConstants.TRANSACTION_ATTRIBUTES.STATE, record.getRequestState());
+ updateColumns.put(TransactionConstants.TRANSACTION_ATTRIBUTES.RESULT_CODE,
+ String.valueOf(record.getResultCode()));
+ if (RequestStatus.valueOf(record.getRequestState()).isTerminal()) {
+ Date endTime = new Date(System.currentTimeMillis());
+ updateColumns.put(TransactionConstants.TRANSACTION_ATTRIBUTES.END_TIME,
+ dateToStringConverterMillis(endTime));
+ }
+ try {
+ transactionRecorder.update(record.getTransactionId(), updateColumns);
+ } catch (APPCException e) {
+ logger.error("Error accessing database", e);
+ }
}
- protected abstract void handleRequest(RuntimeContext runtimeContext) ;
-
- protected void callWfOperation(RuntimeContext runtimeContext) {
- int remainingTTL = calculateRemainingTTL(runtimeContext.getRequestContext().getCommonHeader());
- if (remainingTTL > 0) {
- if (logger.isDebugEnabled()) {
- logger.debug("Calling command Executor with remaining TTL value: " + remainingTTL);
- }
-
- RuntimeContext clonedContext = cloneContext(runtimeContext);
-
- try {
- commandExecutor.executeCommand(clonedContext);
- if(logger.isTraceEnabled()) {
- logger.trace("Command was added to queue successfully for vnfID = " + ObjectUtils.toString(runtimeContext.getRequestContext().getActionIdentifiers().getVnfId()));
- }
- fillStatus(runtimeContext, LCMCommandStatus.ACCEPTED, null);
- if (isMetricEnabled) {
- ((DispatchingFuntionMetric) metricRegistry.metric("DISPATCH_FUNCTION")).incrementAcceptedRequest();
- }
- } catch (APPCException e) {
- String errorMessage = e.getMessage() != null ? e.getMessage() : e.toString();
- Params params = new Params().addParam("errorMsg", errorMessage);
- fillStatus(runtimeContext, LCMCommandStatus.UNEXPECTED_ERROR, params);
- }
+ private RuntimeContext createRuntimeContext(RequestHandlerInput input, TransactionRecord transactionRecord) {
+ RuntimeContext runtimeContext;
+ runtimeContext = new RuntimeContext();
+ runtimeContext.setRequestContext(input.getRequestContext());
+ runtimeContext.setTimeStart(transactionRecord.getStartTime());
+ runtimeContext.setRpcName(input.getRpcName());
+ runtimeContext.setTransactionRecord(transactionRecord);
+ return runtimeContext;
+ }
+ private TransactionRecord createTransactionRecord(RequestHandlerInput input) {
+ Instant startTime = Instant.now();
+ TransactionRecord record = new TransactionRecord();
+ record.setTransactionId(UUID.randomUUID().toString());
+ record.setRequestState(RequestStatus.RECEIVED);
+ record.setRequestId(input.getRequestContext().getCommonHeader().getRequestId());
+ record.setSubRequestId(input.getRequestContext().getCommonHeader().getSubRequestId());
+ record.setOriginatorId(input.getRequestContext().getCommonHeader().getOriginatorId());
+ record.setOriginTimestamp(input.getRequestContext().getCommonHeader().getTimeStamp().toInstant());
+ record.setStartTime(startTime);
+ record.setOperation(VNFOperation.valueOf(input.getRequestContext().getAction().name()));
+ record.setTargetId(input.getRequestContext().getActionIdentifiers().getVnfId());
+ record.setVnfcName(input.getRequestContext().getActionIdentifiers().getVnfcName());
+ record.setVserverId(input.getRequestContext().getActionIdentifiers().getVserverId());
+ record.setVfModuleId(input.getRequestContext().getActionIdentifiers().getVfModuleId());
+ record.setServiceInstanceId(input.getRequestContext().getActionIdentifiers().getServiceInstanceId());
+ Flags.Mode mode;
+ if (input.getRequestContext().getCommonHeader().getFlags() != null &&
+ input.getRequestContext().getCommonHeader().getFlags().getMode() != null) {
+ mode = input.getRequestContext().getCommonHeader().getFlags().getMode();
} else {
- fillStatus(runtimeContext, LCMCommandStatus.EXPIRED_REQUEST, null);
- storeErrorMessageToLog(runtimeContext,
- LoggingConstants.TargetNames.APPC,
- LoggingConstants.TargetNames.REQUEST_HANDLER,
- EELFResourceManager.format(Msg.APPC_EXPIRED_REQUEST,
- runtimeContext.getRequestContext().getCommonHeader().getOriginatorId(),
- runtimeContext.getRequestContext().getActionIdentifiers().getVnfId(),
- String.valueOf(runtimeContext.getRequestContext().getCommonHeader().getFlags().getTtl())));
+ mode = Flags.Mode.NORMAL;
}
+ record.setMode(mode);
+ return record;
}
- protected void fillStatus(RuntimeContext runtimeContext, LCMCommandStatus lcmCommandStatus, Params params) {
- runtimeContext.getResponseContext().setStatus(new Status(lcmCommandStatus.getResponseCode(),lcmCommandStatus.getFormattedMessage(params)));
+ private void recordAndClearLogProperties(RuntimeContext runtimeContext) {
+ storeAuditLogRecord(runtimeContext);
+ storeMetricLogRecord(runtimeContext);
+ clearRequestLogProperties();
}
- /*
- * Workaround to clone context in order to prevent sharing of ResponseContext by two threads (one to set Accepted
- * status code and other - depending on DG status). Other properties should not be a problem
- */
- private RuntimeContext cloneContext(RuntimeContext runtimeContext) {
- RuntimeContext other = new RuntimeContext();
- other.setRequestContext(runtimeContext.getRequestContext());
- other.setResponseContext(new ResponseContext());
- other.getResponseContext().setStatus(new Status(0,""));
- other.getResponseContext().setCommonHeader(runtimeContext.getRequestContext().getCommonHeader());
- other.setVnfContext(runtimeContext.getVnfContext());
- other.setRpcName(runtimeContext.getRpcName());
- other.setTimeStart(runtimeContext.getTimeStart());
- other.setIsLockAcquired(runtimeContext.isLockAcquired());
- return other;
+ void storeErrorMessageToLog(RuntimeContext runtimeContext, String targetEntity, String targetServiceName,
+ String additionalMessage) {
+ LoggingUtils.logErrorMessage(runtimeContext.getResponseContext().getStatus() != null ?
+ String.valueOf(runtimeContext.getResponseContext().getStatus().getCode()) : "",
+ runtimeContext.getResponseContext().getStatus() != null ?
+ String.valueOf(runtimeContext.getResponseContext().getStatus().getMessage()) : "",
+ targetEntity,
+ targetServiceName,
+ additionalMessage,
+ this.getClass().getCanonicalName());
}
+ protected abstract void handleRequest(RuntimeContext runtimeContext);
+
+ void fillStatus(RuntimeContext runtimeContext, LCMCommandStatus lcmCommandStatus, Params params) {
+ runtimeContext.getResponseContext().getStatus().setCode(lcmCommandStatus.getResponseCode());
+ runtimeContext.getResponseContext().getStatus().setMessage(lcmCommandStatus.getFormattedMessage(params));
+ }
private void clearRequestLogProperties() {
try {
@@ -368,20 +310,10 @@ public abstract class AbstractRequestHandlerImpl implements RequestHandler {
MDC.remove(LoggingConstants.MDCKeys.PARTNER_NAME);
MDC.remove(LoggingConstants.MDCKeys.TARGET_VIRTUAL_ENTITY);
} catch (Exception e) {
- //do nothing
+ logger.error("Error clearing MDC log properties. " + e.getMessage(), e);
}
}
- private void removeRequestFromRegistry(CommonHeader commonHeader) {
- if (logger.isTraceEnabled())
- logger.trace("Entering to removeRequestFromRegistry with RequestHeader = " + ObjectUtils.toString(commonHeader));
- requestRegistry.removeRequest(
- new UniqueRequestIdentifier(commonHeader.getOriginatorId(),
- commonHeader.getRequestId(),
- commonHeader.getSubRequestId()));
- }
-
-
private void setInitialLogProperties(RequestContext requestContext) {
try {
@@ -391,183 +323,86 @@ public abstract class AbstractRequestHandlerImpl implements RequestHandler {
}
MDC.put(LoggingConstants.MDCKeys.PARTNER_NAME, requestContext.getCommonHeader().getOriginatorId());
MDC.put(MDC_INSTANCE_UUID, ""); // value should be created in the future
- try {
- MDC.put(MDC_SERVER_FQDN, InetAddress.getLocalHost().getCanonicalHostName()); //Don't change it to a .getHostName() again please. It's wrong!
- MDC.put(MDC_SERVER_IP_ADDRESS, InetAddress.getLocalHost().getHostAddress());
- MDC.put(LoggingConstants.MDCKeys.SERVER_NAME, InetAddress.getLocalHost().getHostName());
- MDC.put(MDC_SERVICE_NAME, requestContext.getAction().name());
- MDC.put(LoggingConstants.MDCKeys.TARGET_VIRTUAL_ENTITY, requestContext.getActionIdentifiers().getVnfId());
-
- } catch (Exception e) {
- logger.debug(e.getMessage());
- }
- } catch (RuntimeException e) {
- //ignore
+ //Don't change it to a.getHostName() again please. It's wrong!
+ MDC.put(MDC_SERVER_FQDN, InetAddress.getLocalHost().getCanonicalHostName());
+ MDC.put(MDC_SERVER_IP_ADDRESS, InetAddress.getLocalHost().getHostAddress());
+ MDC.put(LoggingConstants.MDCKeys.SERVER_NAME, InetAddress.getLocalHost().getHostName());
+ MDC.put(MDC_SERVICE_NAME, requestContext.getAction().name());
+ MDC.put(LoggingConstants.MDCKeys.TARGET_VIRTUAL_ENTITY, requestContext.getActionIdentifiers().getVnfId());
+ } catch (UnknownHostException e) {
+ logger.error("Error occured while setting initial log properties", e);
}
}
-
- private int calculateRemainingTTL(CommonHeader commonHeader) {
- if (logger.isTraceEnabled()) {
- logger.trace("Entering to calculateRemainingTTL with RequestHeader = " + ObjectUtils.toString(commonHeader));
- }
- long usedTimeInMillis = (System.currentTimeMillis() - commonHeader.getTimeStamp().toEpochMilli());
- logger.debug("usedTimeInMillis = " + usedTimeInMillis);
- int usedTimeInSeconds = Math.round(usedTimeInMillis / 1000);
- logger.debug("usedTimeInSeconds = " + usedTimeInSeconds);
- Integer inputTTL = this.getInputTTL(commonHeader);
- logger.debug("inputTTL = " + inputTTL);
- Integer remainingTTL = inputTTL - usedTimeInSeconds;
- logger.debug("Remaining TTL = " + remainingTTL);
- if (logger.isTraceEnabled())
- logger.trace("Exiting from calculateRemainingTTL with (remainingTTL = " + ObjectUtils.toString(remainingTTL) + ")");
- return remainingTTL;
- }
-
- private Integer getInputTTL(CommonHeader header) {
- if (logger.isTraceEnabled())
- logger.trace("Entering in getInputTTL with RequestHeader = " + ObjectUtils.toString(header));
- if (!isValidTTL(String.valueOf(header.getFlags().getTtl()))) {
- String defaultTTLStr = configuration.getProperty("org.onap.appc.workflow.default.ttl", String.valueOf(Constants.DEFAULT_TTL));
- Integer defaultTTL = Integer.parseInt(defaultTTLStr);
- if (logger.isTraceEnabled())
- logger.trace("Exiting from getInputTTL with (defaultTTL = " + ObjectUtils.toString(defaultTTL) + ")");
- return defaultTTL;
- }
- if (logger.isTraceEnabled())
- logger.trace("Exiting from getInputTTL with (inputTTL = " + ObjectUtils.toString(header.getFlags().getTtl()) + ")");
-
- return header.getFlags().getTtl();
- }
-
- private boolean isValidTTL(String ttl) {
- if (ttl == null || ttl.length() == 0) {
- if (logger.isTraceEnabled())
- logger.trace("Exiting from getInputTTL with (result = false)");
- return false;
- }
- try {
- Integer i = Integer.parseInt(ttl);
- return (i > 0);
- } catch (NumberFormatException e) {
- if (logger.isTraceEnabled())
- logger.trace("Exiting from getInputTTL with (result = false)");
- return false;
- }
- }
-
- private Boolean isLoggingEnabled() {
- String defaultFlagStr = configuration.getProperty("org.onap.appc.localTransactionRecorder.enable", String.valueOf(Constants.DEFAULT_LOGGING_FLAG));
- return Boolean.parseBoolean(defaultFlagStr);
- }
-
private static RequestHandlerOutput buildRequestHandlerOutput(LCMCommandStatus response, Params params) {
RequestHandlerOutput output = new RequestHandlerOutput();
ResponseContext responseContext = new ResponseContext();
- org.onap.appc.domainmodel.lcm.Status status = new org.onap.appc.domainmodel.lcm.Status(response.getResponseCode(),response.getFormattedMessage(params));
+ org.onap.appc.domainmodel.lcm.Status status = new org.onap.appc.domainmodel.lcm.Status();
+ status.setCode(response.getResponseCode());
+ status.setMessage(response.getFormattedMessage(params));
responseContext.setStatus(status);
output.setResponseContext(responseContext);
return output;
}
/**
- * This method perform operations required before execution of workflow starts. It retrieves next state for current operation from Lifecycle manager and update it in AAI.
- *
- * @param vnfId String of VNF ID
- * @param readOnlyActivity boolean indicator
- * @param requestIdentifierString - string contains id uniquely represents the request
- * @param forceFlag boolean indicator
- * @throws UnstableVNFException when failed
- */
- @Override
- public abstract void onRequestExecutionStart(String vnfId, boolean readOnlyActivity, String requestIdentifierString, boolean forceFlag) throws UnstableVNFException ;
-
- /**
* This method perform following operations required after execution of workflow.
* It posts asynchronous response to message bus (DMaaP).
* Unlock VNF Id
* Removes request from request registry.
* Generate audit logs.
* Adds transaction record to database id if transaction logging is enabled.
- *
- * @param isAAIUpdated boolean flag which indicate AAI upodate status after request completion.
*/
@Override
- public void onRequestExecutionEnd(RuntimeContext runtimeContext, boolean isAAIUpdated) {
+ public void onRequestExecutionEnd(RuntimeContext runtimeContext) {
if (logger.isTraceEnabled()) {
- logger.trace("Entering to onRequestExecutionEnd with runtimeContext = " + ObjectUtils.toString(runtimeContext));
+ logger.trace("Entering to onRequestExecutionEnd with runtimeContext = " +
+ ObjectUtils.toString(runtimeContext));
}
-
- postMessageToDMaaP(runtimeContext.getRequestContext().getAction(), runtimeContext.getRpcName(), runtimeContext.getResponseContext());
- requestRegistry.removeRequest(
- new UniqueRequestIdentifier(runtimeContext.getResponseContext().getCommonHeader().getOriginatorId(),
- runtimeContext.getResponseContext().getCommonHeader().getRequestId(),
- runtimeContext.getResponseContext().getCommonHeader().getSubRequestId()));
-
+ postMessageToDMaaP(runtimeContext.getRequestContext().getAction(), runtimeContext.getRpcName(),
+ runtimeContext.getResponseContext());
+ final int statusCode = runtimeContext.getResponseContext().getStatus().getCode();
+ RequestStatus requestStatus =
+ (statusCode == LCMCommandStatus.SUCCESS.getResponseCode()) ?
+ RequestStatus.SUCCESSFUL : RequestStatus.FAILED;
+ runtimeContext.getTransactionRecord().setRequestState(requestStatus);
+ runtimeContext.getTransactionRecord().setResultCode(runtimeContext.getResponseContext().getStatus().getCode());
+ updateTransactionStatus(runtimeContext.getTransactionRecord());
storeAuditLogRecord(runtimeContext);
- if (isLoggingEnabled()) {
- createTransactionRecord(runtimeContext);
- }
}
private void storeAuditLogRecord(RuntimeContext runtimeContext) {
LoggingUtils.logAuditMessage(runtimeContext.getTimeStart(),
- Instant.now(),
- String.valueOf(runtimeContext.getResponseContext().getStatus().getCode()),
- runtimeContext.getResponseContext().getStatus().getMessage(),
- this.getClass().getCanonicalName());
+ Instant.now(),
+ String.valueOf(runtimeContext.getResponseContext().getStatus().getCode()),
+ runtimeContext.getResponseContext().getStatus().getMessage(),
+ this.getClass().getCanonicalName());
}
private void storeMetricLogRecord(RuntimeContext runtimeContext) {
LoggingUtils.logMetricsMessage(runtimeContext.getTimeStart(),
- Instant.now(),
- LoggingConstants.TargetNames.APPC,
- runtimeContext.getRequestContext().getAction().name(),
- runtimeContext.getResponseContext().getStatus().getCode() == LCMCommandStatus.ACCEPTED.getResponseCode() ? LoggingConstants.StatusCodes.COMPLETE : LoggingConstants.StatusCodes.ERROR,
- String.valueOf(runtimeContext.getResponseContext().getStatus().getCode()),
- runtimeContext.getResponseContext().getStatus().getMessage(),
- this.getClass().getCanonicalName());
+ Instant.now(),
+ LoggingConstants.TargetNames.APPC,
+ runtimeContext.getRequestContext().getAction().name(),
+ runtimeContext.getResponseContext().getStatus().getCode() == LCMCommandStatus.ACCEPTED.getResponseCode()
+ ? LoggingConstants.StatusCodes.COMPLETE : LoggingConstants.StatusCodes.ERROR,
+ String.valueOf(runtimeContext.getResponseContext().getStatus().getCode()),
+ runtimeContext.getResponseContext().getStatus().getMessage(),
+ this.getClass().getCanonicalName());
}
-
-
-
private void postMessageToDMaaP(VNFOperation operation, String rpcName, ResponseContext responseContext) {
if (logger.isTraceEnabled()) {
- logger.trace("Entering to postMessageToDMaaP with AsyncResponse = " + ObjectUtils.toString(responseContext));
+ logger.trace("Entering to postMessageToDMaaP with AsyncResponse = " +
+ ObjectUtils.toString(responseContext));
}
boolean callbackResponse = messageAdapter.post(operation, rpcName, responseContext);
if (!callbackResponse) {
- logger.error("DMaaP posting status: " + callbackResponse, "dmaapMessage: " + responseContext);
+ logger.error("DMaaP posting status: false", "dmaapMessage: " + responseContext);
}
if (logger.isTraceEnabled())
- logger.trace("Exiting from postMessageToDMaaP with (callbackResponse = " + ObjectUtils.toString(callbackResponse) + ")");
- }
-
- /**
- * This method perform following operations required if TTL ends when request still waiting in execution queue .
- * It posts asynchronous response to message bus (DMaaP).
- * Unlock VNF Id
- * Removes request from request registry.
- *
- * @param runtimeContext AsyncResponse object which contains VNF Id , timestamp , apiVersion, responseId, executionSuccess, payload, isExpired, action, startTime, vnfType, originatorId, subResponseId;
- * @param updateAAI boolean flag which indicate AAI upodate status after request completion.
- */
- @Override
- public void onRequestTTLEnd(RuntimeContext runtimeContext, boolean updateAAI) {
- if (logger.isTraceEnabled()) {
- logger.trace("Entering to onRequestTTLEnd with " +
- "AsyncResponse = " + ObjectUtils.toString(runtimeContext) +
- ", updateAAI = " + ObjectUtils.toString(updateAAI));
- }
- logger.error(LCMCommandStatus.EXPIRED_REQUEST_FAILURE.getResponseMessage());
- fillStatus(runtimeContext, LCMCommandStatus.EXPIRED_REQUEST_FAILURE, null);
- postMessageToDMaaP(runtimeContext.getRequestContext().getAction(), runtimeContext.getRpcName(), runtimeContext.getResponseContext());
-
- requestRegistry.removeRequest(
- new UniqueRequestIdentifier(runtimeContext.getResponseContext().getCommonHeader().getOriginatorId(),
- runtimeContext.getResponseContext().getCommonHeader().getRequestId(),
- runtimeContext.getResponseContext().getCommonHeader().getSubRequestId()));
+ logger.trace("Exiting from postMessageToDMaaP with (callbackResponse = " +
+ ObjectUtils.toString(callbackResponse) + ")");
}
private void initMetric() {
@@ -576,20 +411,22 @@ public abstract class AbstractRequestHandlerImpl implements RequestHandler {
MetricService metricService = getMetricservice();
metricRegistry = metricService.createRegistry("APPC");
DispatchingFuntionMetric dispatchingFuntionMetric = metricRegistry.metricBuilderFactory().
- dispatchingFunctionCounterBuilder().
- withName("DISPATCH_FUNCTION").withType(MetricType.COUNTER).
- withAcceptRequestValue(0)
- .withRejectRequestValue(0)
- .build();
+ dispatchingFunctionCounterBuilder().
+ withName("DISPATCH_FUNCTION").withType(MetricType.COUNTER).
+ withAcceptRequestValue(0)
+ .withRejectRequestValue(0)
+ .build();
if (metricRegistry.register(dispatchingFuntionMetric)) {
Metric[] metrics = new Metric[]{dispatchingFuntionMetric};
LogPublisher logPublisher = new LogPublisher(metricRegistry, metrics);
LogPublisher[] logPublishers = new LogPublisher[1];
logPublishers[0] = logPublisher;
- PublishingPolicy manuallyScheduledPublishingPolicy = metricRegistry.policyBuilderFactory().
- scheduledPolicyBuilder().withPublishers(logPublishers).
- withMetrics(metrics).
- build();
+ PublishingPolicy manuallyScheduledPublishingPolicy = metricRegistry.policyBuilderFactory()
+ .scheduledPolicyBuilder()
+ .withPublishers(logPublishers)
+ .withMetrics(metrics)
+ .build();
+
if (logger.isDebugEnabled())
logger.debug("Policy getting initialized");
manuallyScheduledPublishingPolicy.init();
@@ -598,7 +435,6 @@ public abstract class AbstractRequestHandlerImpl implements RequestHandler {
}
}
-
private MetricService getMetricservice() {
BundleContext bctx = FrameworkUtil.getBundle(MetricService.class).getBundleContext();
ServiceReference sref = bctx.getServiceReference(MetricService.class.getName());
@@ -617,10 +453,18 @@ public abstract class AbstractRequestHandlerImpl implements RequestHandler {
* * @return in progress requests count
*/
@Override
- public int getInprogressRequestCount() {
+ public int getInprogressRequestCount() throws APPCException {
if (logger.isTraceEnabled()) {
logger.trace("Entering to getInprogressRequestCount");
}
- return requestRegistry.getRegisteredRequestCount();
+ return transactionRecorder.getInProgressRequestsCount();
+ }
+
+ public static String dateToStringConverterMillis(Date date) {
+ SimpleDateFormat customDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
+ if (date != null) {
+ return customDate.format(date);
+ }
+ return null;
}
}
diff --git a/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/requesthandler/impl/AbstractRequestValidatorImpl.java b/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/requesthandler/impl/AbstractRequestValidatorImpl.java
index 5b9e48615..254292345 100644
--- a/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/requesthandler/impl/AbstractRequestValidatorImpl.java
+++ b/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/requesthandler/impl/AbstractRequestValidatorImpl.java
@@ -29,49 +29,33 @@ import com.att.eelf.configuration.EELFManager;
import com.att.eelf.i18n.EELFResourceManager;
import org.apache.commons.lang.ObjectUtils;
import org.apache.commons.lang.StringUtils;
+import org.onap.appc.domainmodel.lcm.RequestContext;
+import org.onap.appc.domainmodel.lcm.RuntimeContext;
+import org.onap.appc.domainmodel.lcm.TransactionRecord;
+import org.onap.appc.exceptions.APPCException;
import org.onap.appc.requesthandler.constant.Constants;
import org.onap.appc.configuration.Configuration;
import org.onap.appc.configuration.ConfigurationFactory;
import org.onap.appc.domainmodel.lcm.CommonHeader;
-import org.onap.appc.domainmodel.lcm.RequestContext;
-import org.onap.appc.domainmodel.lcm.RuntimeContext;
-import org.onap.appc.domainmodel.lcm.VNFContext;
-import org.onap.appc.executor.UnstableVNFException;
-import org.onap.appc.executor.objects.UniqueRequestIdentifier;
+import org.onap.appc.exceptions.InvalidInputException;
import org.onap.appc.i18n.Msg;
-import org.onap.appc.lifecyclemanager.LifecycleManager;
-import org.onap.appc.lifecyclemanager.objects.LifecycleException;
-import org.onap.appc.lifecyclemanager.objects.NoTransitionDefinedException;
import org.onap.appc.logging.LoggingConstants;
import org.onap.appc.logging.LoggingUtils;
import org.onap.appc.requesthandler.LCMStateManager;
import org.onap.appc.requesthandler.exceptions.*;
-import org.onap.appc.requesthandler.helper.RequestRegistry;
import org.onap.appc.requesthandler.helper.RequestValidator;
-import org.onap.appc.workflow.WorkFlowManager;
-import org.onap.appc.workflow.objects.WorkflowExistsOutput;
-import org.onap.appc.workflow.objects.WorkflowRequest;
-import org.onap.ccsdk.sli.core.sli.SvcLogicContext;
-import org.onap.ccsdk.sli.core.sli.SvcLogicException;
-import org.onap.ccsdk.sli.core.sli.SvcLogicResource;
-import org.onap.ccsdk.sli.adaptors.aai.AAIService;
-import org.osgi.framework.BundleContext;
-import org.osgi.framework.FrameworkUtil;
-import org.osgi.framework.ServiceReference;
+import org.onap.appc.transactionrecorder.TransactionRecorder;
-import java.time.Instant;
import java.util.Calendar;
import java.util.Date;
public abstract class AbstractRequestValidatorImpl implements RequestValidator {
protected final EELFLogger logger = EELFManager.getInstance().getLogger(RequestValidatorImpl.class);
- private final Configuration configuration = ConfigurationFactory.getConfiguration();
- protected LifecycleManager lifecyclemanager;
- protected LCMStateManager lcmStateManager;
- private AAIService aaiService;
- private WorkFlowManager workflowManager;
- private RequestRegistry requestRegistry = new RequestRegistry();
+ protected final Configuration configuration = ConfigurationFactory.getConfiguration();
+
+ LCMStateManager lcmStateManager;
+ TransactionRecorder transactionRecorder;
protected static Calendar DateToCalendar(Date date) {
Calendar cal = Calendar.getInstance();
@@ -79,211 +63,22 @@ public abstract class AbstractRequestValidatorImpl implements RequestValidator {
return cal;
}
- public void setWorkflowManager(WorkFlowManager workflowManager) {
- this.workflowManager = workflowManager;
+ public void setTransactionRecorder(TransactionRecorder transactionRecorder) {
+ this.transactionRecorder = transactionRecorder;
}
public void setLcmStateManager(LCMStateManager lcmStateManager) {
this.lcmStateManager = lcmStateManager;
}
- public void setRequestRegistry(RequestRegistry requestRegistry) {
- this.requestRegistry = requestRegistry;
- }
-
- public abstract void validateRequest(RuntimeContext runtimeContext) throws VNFNotFoundException, RequestExpiredException, UnstableVNFException, InvalidInputException, DuplicateRequestException, NoTransitionDefinedException, LifecycleException, WorkflowNotFoundException, DGWorkflowNotFoundException, MissingVNFDataInAAIException, LCMOperationsDisabledException;
-
- private boolean isValidTTL(String ttl) {
- if (logger.isTraceEnabled()){
- logger.trace("Entering to isValidTTL where ttl = "+ ObjectUtils.toString(ttl));
- }
- if (ttl == null || ttl.length() == 0) {
- if (logger.isTraceEnabled()) {
- logger.trace("Exiting from isValidTT with (result = "+ ObjectUtils.toString(false)+")");
- }
- return false;
- }
- try {
- Integer i = Integer.parseInt(ttl);
- if (logger.isTraceEnabled()) {
- logger.trace("Exiting from isValidTTL with (result = "+ ObjectUtils.toString(i > 0)+")");
- }
- return (i > 0);
- } catch (NumberFormatException e) {
- if (logger.isTraceEnabled()) {
- logger.trace("Exiting from isValidTTL with (result = "+ ObjectUtils.toString(false)+")");
- }
- return false;
- }
- }
-
- protected void getAAIservice() {
- BundleContext bctx = FrameworkUtil.getBundle(AAIService.class).getBundleContext();
- // Get AAIadapter reference
- ServiceReference sref = bctx.getServiceReference(AAIService.class.getName());
- if (sref != null) {
- logger.info("AAIService from bundlecontext");
- aaiService = (AAIService) bctx.getService(sref);
-
- } else {
- logger.info("AAIService error from bundlecontext");
- logger.warn("Cannot find service reference for org.onap.ccsdk.sli.adaptors.aai.AAIService");
-
- }
- }
-
- protected VNFContext queryAAI(String vnfId) throws VNFNotFoundException, MissingVNFDataInAAIException {
- SvcLogicContext ctx = new SvcLogicContext();
- ctx = getVnfdata(vnfId, "vnf", ctx);
-
- VNFContext vnfContext = new VNFContext();
- populateVnfContext(vnfContext, ctx);
-
- return vnfContext;
- }
-
- protected void queryWFM(VNFContext vnfContext, RequestContext requestContext) throws WorkflowNotFoundException,DGWorkflowNotFoundException {
-
- checkWorkflowExists(vnfContext, requestContext);
- }
-
- private void checkWorkflowExists(VNFContext vnfContext, RequestContext requestContext) throws WorkflowNotFoundException,DGWorkflowNotFoundException {
-
- WorkflowExistsOutput workflowExistsOutput = workflowManager.workflowExists(getWorkflowQueryParams(vnfContext, requestContext));
- if (!workflowExistsOutput.isMappingExist()) {
- if (logger.isDebugEnabled()) {
- logger.debug("WorkflowManager : Workflow not found for vnfType = " + vnfContext.getType() + ", version = " + vnfContext.getVersion() + ", command = " + requestContext.getAction().name());
- }
-
- LoggingUtils.logErrorMessage(
- LoggingConstants.TargetNames.WORKFLOW_MANAGER,
- EELFResourceManager.format(Msg.APPC_WORKFLOW_NOT_FOUND, vnfContext.getType(), requestContext.getAction().name()),
- this.getClass().getCanonicalName());
-
-
- throw new WorkflowNotFoundException("Workflow not found for vnfType = " + vnfContext.getType() + ", command = " + requestContext.getAction().name(),vnfContext.getType(),requestContext.getAction().name());
- }
- if (!workflowExistsOutput.isDgExist()) {
- if (logger.isDebugEnabled()) {
- logger.debug("WorkflowManager : DG Workflow not found for vnfType = " + vnfContext.getType() + ", version = " + vnfContext.getVersion() + ", command = " + requestContext.getAction().name()+" "+workflowExistsOutput);
- }
-
-
- LoggingUtils.logErrorMessage(
- LoggingConstants.TargetNames.WORKFLOW_MANAGER,
- EELFResourceManager.format(Msg.APPC_WORKFLOW_NOT_FOUND, vnfContext.getType(), requestContext.getAction().name()),
- this.getClass().getCanonicalName());
-
-
- throw new DGWorkflowNotFoundException("Workflow not found for vnfType = " + vnfContext.getType() + ", command = " + requestContext.getAction().name(),
- workflowExistsOutput.getWorkflowModule(),workflowExistsOutput.getWorkflowName(),workflowExistsOutput.getWorkflowVersion());
- }
- }
-
- private void populateVnfContext(VNFContext vnfContext, SvcLogicContext ctx) throws MissingVNFDataInAAIException {
- String vnfType = ctx.getAttribute("vnf.vnf-type");
- String orchestrationStatus = ctx.getAttribute("vnf.orchestration-status");
- if(StringUtils.isEmpty(vnfType)){
- throw new MissingVNFDataInAAIException("vnf-type");
- }
- else if(StringUtils.isEmpty(orchestrationStatus)){
- throw new MissingVNFDataInAAIException("orchestration-status");
- }
- vnfContext.setType(vnfType);
- vnfContext.setStatus(orchestrationStatus);
- vnfContext.setId(ctx.getAttribute("vnf.vnf-id"));
- }
-
- private WorkflowRequest getWorkflowQueryParams(VNFContext vnfContext, RequestContext requestContext) {
-
- WorkflowRequest workflowRequest = new WorkflowRequest();
- workflowRequest.setVnfContext(vnfContext);
- workflowRequest.setRequestContext(requestContext);
- if (logger.isTraceEnabled()) {
- logger.trace("Exiting from etWorkflowQueryParams with (WorkflowRequest = "+ ObjectUtils.toString(workflowRequest)+")");
- }
- return workflowRequest;
- }
-
- protected void checkForDuplicateRequest(CommonHeader header) throws DuplicateRequestException {
- if (logger.isTraceEnabled()) {
- logger.trace("Entering to checkForDuplicateRequest with RequestHeader = "+ ObjectUtils.toString(header));
- }
-
- UniqueRequestIdentifier requestIdentifier = new UniqueRequestIdentifier(header.getOriginatorId(), header.getRequestId(), header.getSubRequestId());
- boolean requestAccepted = requestRegistry.registerRequest(requestIdentifier);
- if (!requestAccepted) {
- if (logger.isDebugEnabled()) {
- logger.debug("Duplicate Request with " + requestIdentifier);
- }
- throw new DuplicateRequestException("Duplicate Request with " + requestIdentifier);
- }
- }
-
- protected Integer readTTL(CommonHeader header) {
- if (logger.isTraceEnabled()) {
- logger.trace("Entering to readTTL with RequestHandlerInput = "+ ObjectUtils.toString(header));
- }
- if (header.getFlags()== null || !isValidTTL(String.valueOf(header.getFlags().getTtl()))) {
- String defaultTTLStr = configuration.getProperty("org.onap.appc.workflow.default.ttl", String.valueOf(Constants.DEFAULT_TTL));
- return Integer.parseInt(defaultTTLStr);
- }
- if (logger.isTraceEnabled()) {
- logger.trace("Exiting from readTTL with (TTL = "+ ObjectUtils.toString(header.getFlags().getTtl())+")");
- }
- return header.getFlags().getTtl();
- }
-
- private SvcLogicContext getVnfdata(String vnf_id, String prefix, SvcLogicContext ctx) throws VNFNotFoundException {
- if (logger.isTraceEnabled()) {
- logger.trace("Entering to getVnfdata with vnfid = "+ ObjectUtils.toString(vnf_id) + ", prefix = "+ ObjectUtils.toString(prefix)+ ", SvcLogicContext"+ ObjectUtils.toString(ctx));
- }
-
- String key = "vnf-id = '" + vnf_id + "'";
- logger.debug("inside getVnfdata=== " + key);
- try {
- Instant beginTimestamp = Instant.now();
- SvcLogicResource.QueryStatus response = aaiService.query("generic-vnf", false, null, key, prefix, null, ctx);
- Instant endTimestamp = Instant.now();
- String status = SvcLogicResource.QueryStatus.SUCCESS.equals(response) ? LoggingConstants.StatusCodes.COMPLETE : LoggingConstants.StatusCodes.ERROR;
- LoggingUtils.logMetricsMessage(
- beginTimestamp,
- endTimestamp,
- LoggingConstants.TargetNames.AAI,
- LoggingConstants.TargetServiceNames.AAIServiceNames.QUERY,
- status,
- "",
- response.name(),
- this.getClass().getCanonicalName());
- if (SvcLogicResource.QueryStatus.NOT_FOUND.equals(response)) {
- throw new VNFNotFoundException("VNF not found for vnf_id = " + vnf_id);
- } else if (SvcLogicResource.QueryStatus.FAILURE.equals(response)) {
- throw new RuntimeException("Error Querying AAI with vnfID = " + vnf_id);
- }
- logger.info("AAIResponse: " + response.toString());
- } catch (SvcLogicException e) {
-
- LoggingUtils.logErrorMessage(
- LoggingConstants.TargetServiceNames.AAIServiceNames.GET_VNF_DATA,
- "Error in getVnfdata" + e,
- this.getClass().getCanonicalName());
-
- throw new RuntimeException(e);
- }
- if (logger.isTraceEnabled()) {
- logger.trace("Exiting from getVnfdata with (SvcLogicContext = "+ ObjectUtils.toString(ctx)+")");
- }
- return ctx;
- }
-
- protected void validateInput(RequestContext requestContext)
- throws RequestExpiredException, InvalidInputException, DuplicateRequestException {
+ protected void validateInput(RuntimeContext runtimeContext)
+ throws RequestExpiredException, InvalidInputException, DuplicateRequestException {
+ RequestContext requestContext = runtimeContext.getRequestContext();
if (logger.isTraceEnabled()){
logger.trace("Entering to validateInput with RequestHandlerInput = "+ ObjectUtils.toString(requestContext));
}
- if (requestContext.getActionIdentifiers().getVnfId() == null || requestContext.getAction() == null
- || requestContext.getActionIdentifiers().getVnfId().length() == 0 || requestContext.getAction().name().length() == 0 ||
- null == requestContext.getCommonHeader().getApiVer()) {
+ if (StringUtils.isEmpty(requestContext.getActionIdentifiers().getVnfId()) || requestContext.getAction() == null
+ || StringUtils.isEmpty(requestContext.getAction().name()) || StringUtils.isEmpty(requestContext.getCommonHeader().getApiVer())){
if (logger.isDebugEnabled()) {
logger.debug("vnfID = " + requestContext.getActionIdentifiers().getVnfId() + ", action = " + requestContext.getAction().name());
}
@@ -296,10 +91,14 @@ public abstract class AbstractRequestValidatorImpl implements RequestValidator {
throw new InvalidInputException("vnfID or command is null");
}
CommonHeader commonHeader = requestContext.getCommonHeader();
+ try {
+ if(transactionRecorder.isTransactionDuplicate(runtimeContext.getTransactionRecord()))
+ throw new DuplicateRequestException("Duplicate Request with");
+ } catch (APPCException e) {
+ logger.error("Error accessing database for transaction data",e);
+ }
- checkForDuplicateRequest(commonHeader);
-
- Calendar inputTimeStamp = DateToCalendar(Date.from(commonHeader.getTimeStamp()));
+ Calendar inputTimeStamp = DateToCalendar(commonHeader.getTimeStamp());
Calendar currentTime = Calendar.getInstance();
// If input timestamp is of future, we reject the request
@@ -309,9 +108,16 @@ public abstract class AbstractRequestValidatorImpl implements RequestValidator {
}
throw new InvalidInputException("Input Timestamp is of future = " + inputTimeStamp.getTime());
}
- Integer ttl = readTTL(commonHeader);
+
+ // Set ttl value from commonHeader. If not available set it to default
+ Integer ttl = (commonHeader.getFlags()== null || commonHeader.getFlags().getTtl() <= 0 ) ?
+ Integer.parseInt(configuration.getProperty(Constants.DEFAULT_TTL_KEY, String.valueOf(Constants.DEFAULT_TTL))):
+ commonHeader.getFlags().getTtl();
+
logger.debug("TTL value set to (seconds) : " + ttl);
+
inputTimeStamp.add(Calendar.SECOND, ttl);
+
if (currentTime.getTime().getTime() >= inputTimeStamp.getTime().getTime()) {
LoggingUtils.logErrorMessage(
diff --git a/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/requesthandler/impl/LCMStateManagerImpl.java b/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/requesthandler/impl/LCMStateManagerImpl.java
index 276eaddab..1111f27ad 100644
--- a/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/requesthandler/impl/LCMStateManagerImpl.java
+++ b/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/requesthandler/impl/LCMStateManagerImpl.java
@@ -32,7 +32,7 @@ import java.util.concurrent.atomic.AtomicBoolean;
import org.onap.appc.requesthandler.LCMStateManager;
public class LCMStateManagerImpl implements LCMStateManager {
- private static final EELFLogger logger = EELFManager.getInstance().getLogger(LCMStateManagerImpl.class);
+ private final EELFLogger logger = EELFManager.getInstance().getLogger(LCMStateManagerImpl.class);
private static AtomicBoolean isLCMEnabled = new AtomicBoolean(true);
/**
diff --git a/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/requesthandler/impl/LocalRequestHandlerImpl.java b/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/requesthandler/impl/LocalRequestHandlerImpl.java
new file mode 100644
index 000000000..e7599aa4e
--- /dev/null
+++ b/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/requesthandler/impl/LocalRequestHandlerImpl.java
@@ -0,0 +1,208 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * ONAP : APPC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Copyright (C) 2017 Amdocs
+ * =============================================================================
+ * 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.
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.onap.appc.requesthandler.impl;
+
+import com.att.eelf.configuration.EELFLogger;
+import com.att.eelf.configuration.EELFManager;
+import org.json.JSONObject;
+import org.onap.appc.domainmodel.lcm.ActionIdentifiers;
+import org.onap.appc.domainmodel.lcm.RequestStatus;
+import org.onap.appc.domainmodel.lcm.ResponseContext;
+import org.onap.appc.domainmodel.lcm.RuntimeContext;
+import org.onap.appc.domainmodel.lcm.Status;
+import org.onap.appc.domainmodel.lcm.VNFOperation;
+import org.onap.appc.exceptions.APPCException;
+import org.onap.appc.executor.objects.LCMCommandStatus;
+import org.onap.appc.executor.objects.Params;
+import org.onap.appc.requesthandler.exceptions.MultipleRecordsRetrievedException;
+import org.onap.appc.util.JsonUtil;
+
+import java.io.IOException;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+/**
+ * This class handles the LCM-Requests that don't need communication with the VNF.
+ * The ideal flow is to validate the request, query locally and return data.
+ */
+public class LocalRequestHandlerImpl extends AbstractRequestHandlerImpl {
+ private final EELFLogger logger = EELFManager.getInstance().getLogger(LocalRequestHandlerImpl.class);
+
+ @Override
+ protected void handleRequest(RuntimeContext runtimeContext) {
+ final VNFOperation action = runtimeContext.getRequestContext().getAction();
+
+ switch (action) {
+ case ActionStatus:
+ processActionStatus(runtimeContext);
+ break;
+ default:
+ logger.error(String.format("Action: %s isn't mapped to a Local Request.", action));
+
+ }
+ }
+
+ /**
+ * Process request of ActionStatus.
+ * The <code>status</code> in the <code>ResponseContext</code> will be set according to
+ * the response from <code>getStatusOfRequest(String,String,String,String</code>
+ * <p>
+ * The MULTIPLE_REQUESTS_FOUND exception is caught when <code>getStatusOfRequest(String,String,String,String</code>
+ * throws MultipleRecordsRetrievedException. Otherwise, all the responses returned from here will be SUCCESS.
+ *
+ * @param runtimeContext an RuntimeContext Object
+ */
+ private void processActionStatus(RuntimeContext runtimeContext) {
+ // Get the input payload and Action Identifier to know the request to query
+ Map<String, String> payloadAttributeMap = getPayloadAttribute(runtimeContext.getRequestContext().getPayload());
+ String requestId = payloadAttributeMap.get("request-id");
+ String vnfId = getVnfId(runtimeContext.getRequestContext().getActionIdentifiers());
+ String originatorId = payloadAttributeMap.get("originator-id");
+ String subRequestId = payloadAttributeMap.get("sub-request-id");
+
+ ResponseContext context = runtimeContext.getResponseContext();
+ RequestStatus requestStatus;
+ String jsonPayload = null;
+ Status status;
+
+ // Use Transaction Recorder to query DB for this Request's status
+ try {
+ requestStatus = getStatusOfRequest(requestId, subRequestId, originatorId, vnfId);
+ jsonPayload = createPayload(requestStatus.getExternalActionStatusName(), requestStatus.name());
+ status = buildStatus(LCMCommandStatus.SUCCESS, null, null);
+ } catch (MultipleRecordsRetrievedException ex) {
+ status = buildStatus(LCMCommandStatus.MULTIPLE_REQUESTS_FOUND, "parameters",
+ getSearchCriteria(requestId, subRequestId, originatorId, vnfId));
+ logger.debug("RequestStatus is set to MULTIPLE_REQUESTS_FOUND due to MultipleRecordsRetrievedException",
+ ex.getMessage());
+ } catch (APPCException ex) {
+ jsonPayload = createPayload(RequestStatus.UNKNOWN.getExternalActionStatusName(),
+ RequestStatus.UNKNOWN.name());
+ status = buildStatus(LCMCommandStatus.SUCCESS, null, null);
+ logger.debug("RequestStatus is set to UNKNOWN due to APPCException:", ex.getMessage());
+ }
+
+ // Create ResponseContext with payload containing ActionStatus with status and status-reason
+ context.setStatus(status);
+ if (jsonPayload != null) {
+ context.setPayload(jsonPayload);
+ }
+ }
+
+ private String getSearchCriteria(String requestId, String subrequestId, String originatorid, String vnfId) {
+ StringBuilder suffix = new StringBuilder();
+ suffix.append(String.format("request-id=%s", requestId));
+ suffix.append(String.format(" AND vnf-id=%s", vnfId));
+ if (subrequestId != null) {
+ suffix.append(String.format(" AND sub-request-id=%s", subrequestId));
+ }
+ if (originatorid != null) {
+ suffix.append(String.format(" AND originator-id=%s", originatorid));
+ }
+
+ return suffix.toString();
+ }
+
+ private Map<String, String> getPayloadAttribute(String payload) {
+ Map<String, String> map;
+ try {
+ map = JsonUtil.convertJsonStringToFlatMap(payload);
+ } catch (IOException e) {
+ logger.error(String.format("Error encountered when converting JSON payload '%s' to map", payload), e);
+ throw new IllegalArgumentException("Search criteria cannot be determined from Payload");
+ }
+
+ if (map == null || !map.containsKey("request-id")) {
+ throw new IllegalArgumentException("request-id is absent in the Payload");
+ }
+
+ return map;
+ }
+
+ private String getVnfId(ActionIdentifiers identifiers) {
+ if (identifiers == null || identifiers.getVnfId() == null) {
+ throw new IllegalArgumentException("vnf-id is absent in Action Identifiers");
+ }
+ return identifiers.getVnfId();
+ }
+
+ /**
+ * Build a Status.
+ *
+ * @param lcmCommandStatus for the Status code and message format
+ * @param key String for the LCMcommandStatus format
+ * @param message String for the Status message vaiable
+ * @return the newly build Status
+ */
+ private Status buildStatus(LCMCommandStatus lcmCommandStatus, String key, String message) {
+ Status status = new Status();
+ status.setCode(lcmCommandStatus.getResponseCode());
+
+ if (key != null) {
+ Params params = new Params().addParam(key, message);
+ status.setMessage(lcmCommandStatus.getFormattedMessage(params));
+ } else {
+ status.setMessage(lcmCommandStatus.getResponseMessage());
+ }
+
+ return status;
+ }
+
+ private String createPayload(String status, String statusReason) {
+ Map<String, String> payload = new HashMap<>();
+ payload.put("status", status);
+ payload.put("status-reason", statusReason);
+ return (new JSONObject(payload)).toString();
+ }
+
+ private RequestStatus getStatusOfRequest(String requestId, String subRequestId, String originatorId, String vnfId)
+ throws MultipleRecordsRetrievedException, APPCException {
+ RequestStatus requestStatus = RequestStatus.UNKNOWN;
+
+ List<RequestStatus> records = transactionRecorder.getRecords(requestId, subRequestId, originatorId, vnfId);
+ if (records != null) {
+ final int size = records.size();
+ if (size > 1) {
+ throw new MultipleRecordsRetrievedException(
+ String.format("MULTIPLE REQUESTS FOUND USING SEARCH CRITERIA: %s", getSearchCriteria(requestId,
+ subRequestId, originatorId, vnfId)));
+ }
+
+ if (size == 0) {
+ requestStatus = RequestStatus.NOT_FOUND;
+ } else {
+ requestStatus = records.get(0);
+ }
+ }
+
+ return requestStatus;
+ }
+
+ @Override
+ public void onRequestExecutionStart(String vnf_id, boolean readOnlyActivity, boolean forceFlag) {
+ //Do nothing
+ }
+}
diff --git a/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/requesthandler/impl/LocalRequestValidatorImpl.java b/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/requesthandler/impl/LocalRequestValidatorImpl.java
new file mode 100644
index 000000000..e8cd66b1d
--- /dev/null
+++ b/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/requesthandler/impl/LocalRequestValidatorImpl.java
@@ -0,0 +1,95 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * ONAP : APPC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Copyright (C) 2017 Amdocs
+ * =============================================================================
+ * 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.
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.onap.appc.requesthandler.impl;
+
+import com.att.eelf.i18n.EELFResourceManager;
+import org.onap.appc.domainmodel.lcm.ActionIdentifiers;
+import org.onap.appc.domainmodel.lcm.RequestContext;
+import org.onap.appc.domainmodel.lcm.RuntimeContext;
+import org.onap.appc.exceptions.InvalidInputException;
+import org.onap.appc.i18n.Msg;
+import org.onap.appc.logging.LoggingConstants;
+import org.onap.appc.logging.LoggingUtils;
+import org.onap.appc.requesthandler.exceptions.DuplicateRequestException;
+import org.onap.appc.requesthandler.exceptions.LCMOperationsDisabledException;
+import org.onap.appc.requesthandler.exceptions.RequestExpiredException;
+import org.onap.appc.util.JsonUtil;
+
+import java.io.IOException;
+import java.util.Map;
+
+/**
+ * * This class validates the LCM-Requests that don't need communication with the VNF.
+ */
+public class LocalRequestValidatorImpl extends AbstractRequestValidatorImpl {
+ @Override
+ public void validateRequest(RuntimeContext runtimeContext) throws LCMOperationsDisabledException,
+ DuplicateRequestException, RequestExpiredException, InvalidInputException {
+
+ if (!lcmStateManager.isLCMOperationEnabled()) {
+ LoggingUtils.logErrorMessage(
+ LoggingConstants.TargetNames.REQUEST_VALIDATOR,
+ EELFResourceManager.format(Msg.LCM_OPERATIONS_DISABLED),
+ this.getClass().getCanonicalName());
+ throw new LCMOperationsDisabledException("APPC LCM operations have been administratively disabled");
+ }
+
+ validateInput(runtimeContext);
+ }
+
+ @Override
+ public void validateInput(RuntimeContext runtimeContext) throws DuplicateRequestException,
+ RequestExpiredException, InvalidInputException {
+ RequestContext requestContext = runtimeContext.getRequestContext();
+ super.validateInput(runtimeContext);
+ switch (requestContext.getAction()) {
+ case ActionStatus:
+ validateActionStatusPayload(requestContext.getPayload());
+ validateActionStatusActionIdentifiers(requestContext.getActionIdentifiers());
+ break;
+ default:
+ logger.warn(String.format("Action %s not supported!", requestContext.getAction()));
+ }
+ }
+
+ private void validateActionStatusPayload(String payload) throws InvalidInputException {
+ Map<String, String> map;
+ try {
+ map = JsonUtil.convertJsonStringToFlatMap(payload);
+ } catch (IOException e) {
+ logger.error(String.format("Error encountered when converting JSON payload '%s' to map", payload), e);
+ throw new InvalidInputException("Search criteria cannot be determined from Payload due to format issue");
+ }
+ if ((map == null) || !map.containsKey("request-id")) {
+ throw new InvalidInputException("request-id is absent in the Payload");
+ }
+ }
+
+ private void validateActionStatusActionIdentifiers(ActionIdentifiers identifiers) throws InvalidInputException {
+ if (identifiers == null || identifiers.getVnfId() == null) {
+ throw new InvalidInputException("VNF-Id is absent in Action Identifiers");
+ }
+ }
+}
diff --git a/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/requesthandler/impl/RequestHandlerImpl.java b/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/requesthandler/impl/RequestHandlerImpl.java
index 1f07b277c..8dec8a4a6 100644
--- a/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/requesthandler/impl/RequestHandlerImpl.java
+++ b/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/requesthandler/impl/RequestHandlerImpl.java
@@ -27,24 +27,22 @@ package org.onap.appc.requesthandler.impl;
import com.att.eelf.configuration.EELFLogger;
import com.att.eelf.configuration.EELFManager;
import com.att.eelf.i18n.EELFResourceManager;
+import org.apache.commons.lang.ObjectUtils;
+import org.onap.appc.domainmodel.lcm.*;
+import org.onap.appc.exceptions.APPCException;
+import org.onap.appc.executor.CommandExecutor;
+import org.onap.appc.executor.objects.CommandExecutorInput;
+import org.onap.appc.metricservice.metric.DispatchingFuntionMetric;
import org.onap.appc.requesthandler.constant.Constants;
-import org.onap.appc.domainmodel.lcm.RuntimeContext;
-import org.onap.appc.domainmodel.lcm.Status;
-import org.onap.appc.domainmodel.lcm.VNFOperation;
-import org.onap.appc.executor.UnstableVNFException;
import org.onap.appc.executor.objects.LCMCommandStatus;
import org.onap.appc.executor.objects.Params;
-import org.onap.appc.executor.objects.UniqueRequestIdentifier;
import org.onap.appc.i18n.Msg;
import org.onap.appc.lockmanager.api.LockException;
import org.onap.appc.lockmanager.api.LockManager;
import org.onap.appc.logging.LoggingConstants;
-import org.onap.appc.workingstatemanager.WorkingStateManager;
-import org.onap.appc.workingstatemanager.objects.VNFWorkingState;
/**
* This class provides application logic for the Request/Response Handler Component.
- *
*/
public class RequestHandlerImpl extends AbstractRequestHandlerImpl {
@@ -53,30 +51,37 @@ public class RequestHandlerImpl extends AbstractRequestHandlerImpl {
*/
private static final String PROP_IDLE_TIMEOUT = "org.onap.appc.lock.idleTimeout";
+ private final EELFLogger logger = EELFManager.getInstance().getLogger(RequestHandlerImpl.class);
+
private LockManager lockManager;
+ private CommandExecutor commandExecutor;
+ private boolean isMetricEnabled = false;
- private WorkingStateManager workingStateManager;
+ public RequestHandlerImpl() {
+ super();
+ }
public void setLockManager(LockManager lockManager) {
this.lockManager = lockManager;
}
- public void setWorkingStateManager(WorkingStateManager workingStateManager) {
- this.workingStateManager = workingStateManager;
+ public void setCommandExecutor(CommandExecutor commandExecutor) {
+ this.commandExecutor = commandExecutor;
}
- private static final EELFLogger logger = EELFManager.getInstance().getLogger(RequestHandlerImpl.class);
-
- protected void handleRequest(RuntimeContext runtimeContext) {
+ public void handleRequest(RuntimeContext runtimeContext) {
switch (runtimeContext.getRequestContext().getAction()) {
case Lock:
try {
- lockWithTimeout(runtimeContext.getVnfContext().getId(), runtimeContext.getRequestContext().getCommonHeader().getRequestId());
+ long timeout = configuration.getLongProperty(PROP_IDLE_TIMEOUT, Constants.DEFAULT_IDLE_TIMEOUT);
+ boolean lockAcquired = lockManager.acquireLock(runtimeContext.getVnfContext().getId(), runtimeContext.getRequestContext().getCommonHeader().getRequestId(), timeout);
+ logger.info(String.format(lockAcquired ? "Lock acquired for vnfID = %s" : " VnfId : %s was already locked.", runtimeContext.getVnfContext().getId()));
fillStatus(runtimeContext, LCMCommandStatus.SUCCESS, null);
} catch (LockException e) {
+ logger.error("Error during Lock operation: " + e.getMessage(), e);
Params params = new Params().addParam("errorMsg", e.getMessage());
- fillStatus(runtimeContext, LCMCommandStatus.LOCKING_FAILURE, params);
+ fillStatus(runtimeContext, LCMCommandStatus.LOCKED_VNF_ID, params);
storeErrorMessageToLog(runtimeContext,
LoggingConstants.TargetNames.APPC,
LoggingConstants.TargetNames.LOCK_MANAGER,
@@ -86,150 +91,115 @@ public class RequestHandlerImpl extends AbstractRequestHandlerImpl {
case Unlock:
try {
- releaseVNFLock(runtimeContext.getVnfContext().getId(), runtimeContext.getRequestContext().getCommonHeader().getRequestId());
- fillStatus(runtimeContext,LCMCommandStatus.SUCCESS, null);
+ lockManager.releaseLock(runtimeContext.getVnfContext().getId(), runtimeContext.getRequestContext().getCommonHeader().getRequestId());
+ logger.info("Lock released for vnfID = " + runtimeContext.getVnfContext().getId());
+ fillStatus(runtimeContext, LCMCommandStatus.SUCCESS, null);
} catch (LockException e) {
- //TODO add proper error code and message
- // logger.error(EELFResourceManager.format(Msg.VF_SERVER_BUSY, runtimeContext.getVnfContext().getId()));
+ logger.error("Error during Unlock operation: " + e.getMessage(), e);
Params params = new Params().addParam("errorMsg", e.getMessage());
- fillStatus(runtimeContext, LCMCommandStatus.LOCKING_FAILURE, params);
+ fillStatus(runtimeContext, LCMCommandStatus.LOCKED_VNF_ID, params);
}
break;
case CheckLock:
boolean isLocked = lockManager.isLocked(runtimeContext.getVnfContext().getId());
- fillStatus(runtimeContext,LCMCommandStatus.SUCCESS, null);
+ fillStatus(runtimeContext, LCMCommandStatus.SUCCESS, null);
runtimeContext.getResponseContext().addKeyValueToAdditionalContext("locked", String.valueOf(isLocked).toUpperCase());
break;
default:
- try {
- boolean lockAcquired = acquireVNFLock(runtimeContext.getVnfContext().getId(), runtimeContext.getRequestContext().getCommonHeader().getRequestId(), 0);
- runtimeContext.setIsLockAcquired(lockAcquired);
- callWfOperation(runtimeContext);
- } catch (LockException e) {
- Params params = new Params().addParam("errorMsg", e.getMessage());
- fillStatus(runtimeContext, LCMCommandStatus.LOCKING_FAILURE, params);
- } finally {
- if (runtimeContext.isLockAcquired()) {
- final int statusCode = runtimeContext.getResponseContext().getStatus().getCode();
- if (statusCode % 100 == 2 || statusCode % 100 == 3) {
- try {
- releaseVNFLock(runtimeContext.getVnfContext().getId(), runtimeContext.getRequestContext().getCommonHeader().getRequestId());
- } catch (LockException e) {
- logger.error("Error releasing the lock",e);
- }
- }
- }
- }
+ callWfOperation(runtimeContext);
}
}
- private void releaseVNFLock(String vnfId, String transactionId) throws LockException {
- lockManager.releaseLock(vnfId, transactionId);
- logger.info("Lock released for vnfID = " + vnfId);
- }
- protected void lockWithTimeout(String vnfId, String requestId) throws LockException {
- long timeout = configuration.getLongProperty(PROP_IDLE_TIMEOUT, Constants.DEFAULT_IDLE_TIMEOUT);
- acquireVNFLock(vnfId, requestId, timeout);
- }
+ private void callWfOperation(RuntimeContext runtimeContext) {
+ int remainingTTL = calculateRemainingTTL(runtimeContext.getRequestContext().getCommonHeader());
+ if (remainingTTL > 0) {
+ if (logger.isDebugEnabled()) {
+ logger.debug("Calling command Executor with remaining TTL value: " + remainingTTL);
+ }
- private boolean acquireVNFLock(String vnfID, String requestId, long timeout) throws LockException {
- if (logger.isTraceEnabled())
- logger.trace("Entering to acquireVNFLock with vnfID = " + vnfID);
- boolean lockAcquired = lockManager.acquireLock(vnfID, requestId, timeout);
- if (lockAcquired) {
- logger.info("Lock acquired for vnfID = " + vnfID);
- } else {
- logger.info("vnfID = " + vnfID + " was already locked");
- }
- return lockAcquired;
- }
+ RuntimeContext clonedContext = cloneContext(runtimeContext);
- /**
- * This method perform operations required before execution of workflow starts. It retrieves next state for current operation from Lifecycle manager and update it in AAI.
- *
- * @param vnfId String of VNF ID
- * @param readOnlyActivity boolean indicator
- * @param requestIdentifierString - string contains id uniquely represents the request
- * @param forceFlag boolean indicator
- * @throws UnstableVNFException when failed
- */
- @Override
- public void onRequestExecutionStart(String vnfId, boolean readOnlyActivity, String requestIdentifierString, boolean forceFlag) throws UnstableVNFException {
- if (logger.isTraceEnabled()) {
- logger.trace("Entering to onRequestExecutionStart with vnfId = " + vnfId + "and requestIdentifierString = " + requestIdentifierString);
- }
+ CommandExecutorInput commandExecutorInput = new CommandExecutorInput();
+ commandExecutorInput.setRuntimeContext(clonedContext);
+ commandExecutorInput.setTtl(remainingTTL);
- if(!readOnlyActivity || !forceFlag || workingStateManager.isVNFStable(vnfId)) {
- boolean updated = false;
try {
- updated = workingStateManager.setWorkingState(vnfId, VNFWorkingState.UNSTABLE, requestIdentifierString, forceFlag);
- } catch (Exception e) {
- logger.error("Error updating working state for vnf " + vnfId + e);
- throw new RuntimeException(e);
- }
- if (!updated) {
- throw new UnstableVNFException("VNF is not stable for vnfID = " + vnfId);
+ commandExecutor.executeCommand(commandExecutorInput);
+ if (logger.isTraceEnabled()) {
+ logger.trace("Command was added to queue successfully for vnfID = " + ObjectUtils.toString(runtimeContext.getRequestContext().getActionIdentifiers().getVnfId()));
+ }
+ fillStatus(runtimeContext, LCMCommandStatus.ACCEPTED, null);
+ if (isMetricEnabled) {
+ ((DispatchingFuntionMetric) metricRegistry.metric("DISPATCH_FUNCTION")).incrementAcceptedRequest();
+ }
+ } catch (APPCException e) {
+ logger.error("Unexpected Error : " + e.getMessage(), e);
+ String errorMessage = e.getMessage() != null ? e.getMessage() : e.toString();
+ Params params = new Params().addParam("errorMsg", errorMessage);
+ fillStatus(runtimeContext, LCMCommandStatus.UNEXPECTED_ERROR, params);
}
- }
-
- if (logger.isTraceEnabled())
- logger.trace("Exiting from onRequestExecutionStart ");
- }
-
- private boolean isReadOnlyAction(VNFOperation action) {
- if (VNFOperation.Sync.toString().equals(action) ||
- VNFOperation.Audit.toString().equals(action) ||
- VNFOperation.ConfigBackup.toString().equals(action) ||
- VNFOperation.ConfigBackupDelete.toString().equals(action) ||
- VNFOperation.ConfigExport.toString().equals(action)){
- return true;
- }
- return false;
- }
- @Override
- public void onRequestExecutionEnd(RuntimeContext runtimeContext, boolean isAAIUpdated) {
- super.onRequestExecutionEnd(runtimeContext,isAAIUpdated);
- VNFWorkingState workingState;
- Status status = runtimeContext.getResponseContext().getStatus();
- if (status.getCode() == LCMCommandStatus.SUCCESS.getResponseCode() || isReadOnlyAction(runtimeContext.getRequestContext().getAction())) {
- workingState = VNFWorkingState.STABLE;
} else {
- workingState = VNFWorkingState.UNKNOWN;
+ fillStatus(runtimeContext, LCMCommandStatus.EXPIRED_REQUEST, null);
+ storeErrorMessageToLog(runtimeContext,
+ LoggingConstants.TargetNames.APPC,
+ LoggingConstants.TargetNames.REQUEST_HANDLER,
+ EELFResourceManager.format(Msg.APPC_EXPIRED_REQUEST,
+ runtimeContext.getRequestContext().getCommonHeader().getOriginatorId(),
+ runtimeContext.getRequestContext().getActionIdentifiers().getVnfId(),
+ String.valueOf(runtimeContext.getRequestContext().getCommonHeader().getFlags().getTtl())));
}
+ }
- UniqueRequestIdentifier requestIdentifier = new UniqueRequestIdentifier(runtimeContext.getResponseContext().getCommonHeader().getOriginatorId(),
- runtimeContext.getResponseContext().getCommonHeader().getRequestId(),
- runtimeContext.getResponseContext().getCommonHeader().getSubRequestId());
- String requestIdentifierString = requestIdentifier.toIdentifierString();
- workingStateManager.setWorkingState(runtimeContext.getVnfContext().getId(), workingState, requestIdentifierString, false);
- logger.debug("Reset lock for vnfId " + runtimeContext.getVnfContext().getId());
- resetLock(runtimeContext.getVnfContext().getId(), runtimeContext.getResponseContext().getCommonHeader().getRequestId(), runtimeContext.isLockAcquired(), true);
+ private int calculateRemainingTTL(CommonHeader commonHeader) {
+ if (logger.isTraceEnabled()) {
+ logger.trace("Entering to calculateRemainingTTL with RequestHeader = " + ObjectUtils.toString(commonHeader));
+ }
+ long usedTimeInMillis = (System.currentTimeMillis() - commonHeader.getTimeStamp().getTime());
+ int usedTimeInSeconds = (int) (usedTimeInMillis / 1000);
+ logger.debug("usedTimeInSeconds = " + usedTimeInSeconds + "usedTimeInMillis = " + usedTimeInMillis);
+ // Set ttl value from commonHeader. If not available set it to default
+ Integer inputTTL = (commonHeader.getFlags() == null || commonHeader.getFlags().getTtl() <= 0) ?
+ Integer.parseInt(configuration.getProperty(Constants.DEFAULT_TTL_KEY, String.valueOf(Constants.DEFAULT_TTL))) :
+ commonHeader.getFlags().getTtl();
+ logger.debug("inputTTL = " + inputTTL);
+ Integer remainingTTL = inputTTL - usedTimeInSeconds;
+ logger.debug("Remaining TTL = " + remainingTTL);
+ if (logger.isTraceEnabled())
+ logger.trace("Exiting from calculateRemainingTTL with (remainingTTL = " + ObjectUtils.toString(remainingTTL) + ")");
+ return remainingTTL;
}
- private void resetLock(String vnfId, String requestId, boolean lockAcquired, boolean resetLockTimeout) {
- if (lockAcquired) {
- try {
- releaseVNFLock(vnfId, requestId);
- } catch (LockException e) {
- logger.error("Unlock VNF [" + vnfId + "] failed. Request id: [" + requestId + "]", e);
- }
- } else if (resetLockTimeout) {
- try {
- // reset timeout to previous value
- lockWithTimeout(vnfId, requestId);
- } catch (LockException e) {
- logger.error("Reset lock idle timeout for VNF [" + vnfId + "] failed. Request id: [" + requestId + "]", e);
- }
- }
+ /*
+ * Workaround to clone context in order to prevent sharing of ResponseContext by two threads (one to set Accepted
+ * status code and other - depending on DG status). Other properties should not be a problem
+ */
+ private RuntimeContext cloneContext(RuntimeContext runtimeContext) {
+ RuntimeContext other = new RuntimeContext();
+ other.setRequestContext(runtimeContext.getRequestContext());
+ other.setResponseContext(new ResponseContext());
+ other.getResponseContext().setStatus(new Status());
+ other.getResponseContext().setCommonHeader(runtimeContext.getRequestContext().getCommonHeader());
+ other.setVnfContext(runtimeContext.getVnfContext());
+ other.setRpcName(runtimeContext.getRpcName());
+ other.setTimeStart(runtimeContext.getTimeStart());
+ other.setTransactionRecord(runtimeContext.getTransactionRecord());
+ return other;
}
+
+ /**
+ * This method perform operations required before execution of workflow starts. It retrieves next state for current operation from Lifecycle manager and update it in AAI.
+ *
+ * @param vnfId String of VNF ID
+ * @param readOnlyActivity boolean indicator
+ * @param forceFlag boolean indicator
+ */
@Override
- public void onRequestTTLEnd(RuntimeContext runtimeContext, boolean updateAAI) {
- super.onRequestTTLEnd(runtimeContext,updateAAI);
- resetLock(runtimeContext.getVnfContext().getId(), runtimeContext.getResponseContext().getCommonHeader().getRequestId(), runtimeContext.isLockAcquired(), true);
+ public void onRequestExecutionStart(String vnfId, boolean readOnlyActivity, boolean forceFlag) {
+
}
}
diff --git a/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/requesthandler/impl/RequestValidatorImpl.java b/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/requesthandler/impl/RequestValidatorImpl.java
index 8724adc59..933cff28c 100644
--- a/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/requesthandler/impl/RequestValidatorImpl.java
+++ b/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/requesthandler/impl/RequestValidatorImpl.java
@@ -25,108 +25,477 @@
package org.onap.appc.requesthandler.impl;
import com.att.eelf.i18n.EELFResourceManager;
+import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.fasterxml.jackson.databind.node.ObjectNode;
+
+import jline.internal.Log;
+
+import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.ObjectUtils;
+import org.apache.commons.lang.StringUtils;
+import org.apache.http.HttpResponse;
+import org.json.JSONObject;
+import org.onap.appc.domainmodel.lcm.Flags;
+import org.onap.appc.domainmodel.lcm.RequestContext;
import org.onap.appc.domainmodel.lcm.RuntimeContext;
+import org.onap.appc.domainmodel.lcm.TransactionRecord;
import org.onap.appc.domainmodel.lcm.VNFContext;
import org.onap.appc.domainmodel.lcm.VNFOperation;
-import org.onap.appc.executor.UnstableVNFException;
+import org.onap.appc.exceptions.APPCException;
+import org.onap.appc.executor.objects.LCMCommandStatus;
+import org.onap.appc.executor.objects.Params;
import org.onap.appc.i18n.Msg;
-import org.onap.appc.lifecyclemanager.LifecycleManager;
-import org.onap.appc.lifecyclemanager.objects.LifecycleException;
-import org.onap.appc.lifecyclemanager.objects.NoTransitionDefinedException;
+import org.onap.appc.lockmanager.api.LockException;
+import org.onap.appc.lockmanager.api.LockManager;
import org.onap.appc.logging.LoggingConstants;
import org.onap.appc.logging.LoggingUtils;
-import org.onap.appc.requesthandler.LCMStateManager;
-import org.onap.appc.requesthandler.exceptions.*;
-import org.onap.appc.workingstatemanager.WorkingStateManager;
+import org.onap.appc.requesthandler.exceptions.DGWorkflowNotFoundException;
+import org.onap.appc.requesthandler.exceptions.LCMOperationsDisabledException;
+import org.onap.appc.requesthandler.exceptions.MissingVNFDataInAAIException;
+import org.onap.appc.requesthandler.exceptions.RequestValidationException;
+import org.onap.appc.requesthandler.exceptions.VNFNotFoundException;
+import org.onap.appc.requesthandler.exceptions.WorkflowNotFoundException;
+import org.onap.appc.requesthandler.model.ActionIdentifierModel;
+import org.onap.appc.requesthandler.model.Input;
+import org.onap.appc.requesthandler.model.Request;
+import org.onap.appc.requesthandler.model.RequestData;
+import org.onap.appc.requesthandler.model.RequestModel;
+import org.onap.appc.requesthandler.model.ScopeOverlapModel;
+import org.onap.appc.rest.client.RestClientInvoker;
+import org.onap.appc.validationpolicy.RequestValidationPolicy;
+import org.onap.appc.validationpolicy.executors.RuleExecutor;
+import org.onap.appc.validationpolicy.objects.RuleResult;
+import org.onap.appc.workflow.WorkFlowManager;
+import org.onap.appc.workflow.objects.WorkflowExistsOutput;
+import org.onap.appc.workflow.objects.WorkflowRequest;
+import org.onap.ccsdk.sli.core.sli.SvcLogicContext;
+import org.onap.ccsdk.sli.core.sli.SvcLogicException;
+import org.onap.ccsdk.sli.core.sli.SvcLogicResource;
+import org.onap.ccsdk.sli.adaptors.aai.AAIService;
+import org.osgi.framework.BundleContext;
+import org.osgi.framework.FrameworkUtil;
+import org.osgi.framework.ServiceReference;
+import java.io.IOException;
+import java.net.MalformedURLException;
+import java.net.URL;
+import java.util.ArrayList;
+import java.util.Date;
+import java.util.List;
+import java.util.Properties;
+import java.util.stream.Collectors;
public class RequestValidatorImpl extends AbstractRequestValidatorImpl {
- private WorkingStateManager workingStateManager;
- private LCMStateManager lcmStateManager;
+ private WorkFlowManager workflowManager;
+ private LockManager lockManager;
+ private AAIService aaiService;
+ private RequestValidationPolicy requestValidationPolicy;
+ private RestClientInvoker client;
+ private String path;
+
+ static final String SCOPE_OVERLAP_ENDPOINT = "appc.LCM.scopeOverlap.endpoint";
+ static final String ODL_USER = "appc.LCM.provider.user";
+ static final String ODL_PASS = "appc.LCM.provider.pass";
+
+ public void initialize() throws APPCException {
+ logger.info("Initializing RequestValidatorImpl.");
+ String endpoint = null;
+ String user = null;
+ String pass =null;
+ Properties properties = configuration.getProperties();
+ if (properties != null) {
+ endpoint = properties.getProperty(SCOPE_OVERLAP_ENDPOINT);
+ user = properties.getProperty(ODL_USER);
+ pass = properties.getProperty(ODL_PASS);
+ }
+ if (endpoint == null) {
+ String message = "End point is not defined for scope over lap service in appc.properties.";
+ logger.error(message);
+ // TODO throw following exception (and remove the "return") when
+ // entry in appc.properties file is made for scope overlap service
+ // endpoint
+ // and remove @Ignore in unit tests:
+ // testInitializeWithNullConfigProps,
+ // testInitializeWithoutEndpointProp
+ // throw new APPCException(message);
+ return;
+ }
+
+ try {
+ URL url = new URL(endpoint);
+ client = new RestClientInvoker(url);
+ client.setAuthentication(user, pass);
+ path = url.getPath();
+
+ } catch (MalformedURLException e) {
+ String message = "Invalid endpoint " + endpoint;
+ logger.error(message, e);
+ // TODO throw following exception when entry in appc.properties file
+ // is made for scope overlap service endpoint
+ // and remove @Ignore in unit test:
+ // testInitializeWithMalFormatEndpoint
+ // throw new APPCException(message);
+ }
+ }
+
+ private void getAAIservice() {
+ BundleContext bctx = FrameworkUtil.getBundle(AAIService.class).getBundleContext();
+ // Get AAIadapter reference
+ ServiceReference sref = bctx.getServiceReference(AAIService.class.getName());
+ if (sref != null) {
+ logger.info("AAIService from bundlecontext");
+ aaiService = (AAIService) bctx.getService(sref);
+
+ } else {
+ logger.error("Cannot find service reference for org.onap.ccsdk.sli.adaptors.aai.AAIService");
+
+ }
+ }
- public void setLifecyclemanager(LifecycleManager lifecyclemanager) {
- this.lifecyclemanager = lifecyclemanager;
+ public void setLockManager(LockManager lockManager) {
+ this.lockManager = lockManager;
}
- public void setWorkingStateManager(WorkingStateManager workingStateManager) {
- this.workingStateManager = workingStateManager;
+ public void setClient(RestClientInvoker client) {
+ this.client = client;
}
- public void setLcmStateManager(LCMStateManager lcmStateManager) {
- this.lcmStateManager = lcmStateManager;
+ public void setWorkflowManager(WorkFlowManager workflowManager) {
+ this.workflowManager = workflowManager;
}
- public RequestValidatorImpl() {
+ public void setRequestValidationPolicy(RequestValidationPolicy requestValidationPolicy) {
+ this.requestValidationPolicy = requestValidationPolicy;
}
- @Override
- public void validateRequest(RuntimeContext runtimeContext)
- throws VNFNotFoundException, RequestExpiredException, UnstableVNFException, InvalidInputException,
- DuplicateRequestException, NoTransitionDefinedException, LifecycleException, WorkflowNotFoundException,
- DGWorkflowNotFoundException, MissingVNFDataInAAIException, LCMOperationsDisabledException {
- if (logger.isTraceEnabled()){
- logger.trace("Entering to validateRequest with RequestHandlerInput = "+ ObjectUtils.toString(runtimeContext));
+ public void validateRequest(RuntimeContext runtimeContext) throws Exception {
+ if (logger.isTraceEnabled()) {
+ logger.trace(
+ "Entering to validateRequest with RequestHandlerInput = " + ObjectUtils.toString(runtimeContext));
}
- if(!lcmStateManager.isLCMOperationEnabled()) {
- LoggingUtils.logErrorMessage(
- LoggingConstants.TargetNames.REQUEST_VALIDATOR,
- EELFResourceManager.format(Msg.LCM_OPERATIONS_DISABLED),
- this.getClass().getCanonicalName());
+ if (!lcmStateManager.isLCMOperationEnabled()) {
+ LoggingUtils.logErrorMessage(LoggingConstants.TargetNames.REQUEST_VALIDATOR,
+ EELFResourceManager.format(Msg.LCM_OPERATIONS_DISABLED), this.getClass().getCanonicalName());
throw new LCMOperationsDisabledException("APPC LCM operations have been administratively disabled");
}
getAAIservice();
- validateInput(runtimeContext.getRequestContext());
- checkVNFWorkingState(runtimeContext);
+ validateInput(runtimeContext);
String vnfId = runtimeContext.getRequestContext().getActionIdentifiers().getVnfId();
VNFContext vnfContext = queryAAI(vnfId);
runtimeContext.setVnfContext(vnfContext);
+ runtimeContext.getTransactionRecord().setTargetType(vnfContext.getType());
- queryLCM(runtimeContext.getVnfContext().getStatus(), runtimeContext.getRequestContext().getAction());
VNFOperation operation = runtimeContext.getRequestContext().getAction();
- if(!operation.isBuiltIn()) {
- // for built-in operations skip WF presence check
- queryWFM(vnfContext, runtimeContext.getRequestContext());
+ if (operation.isBuiltIn()) {
+ return;
+ }
+
+ validateVNFLock(runtimeContext);
+ checkWorkflowExists(vnfContext, runtimeContext.getRequestContext());
+
+ if (runtimeContext.getRequestContext().getCommonHeader().getFlags().isForce()) {
+ return;
+ }
+
+ List<TransactionRecord> inProgressTransactions = transactionRecorder
+ .getInProgressRequests(runtimeContext.getTransactionRecord());
+ logger.debug("In progress requests " + inProgressTransactions.toString());
+
+ Long exclusiveRequestCount = inProgressTransactions.stream()
+ .filter(record -> record.getMode().equals(Flags.Mode.EXCLUSIVE.name())).count();
+ if (exclusiveRequestCount > 0) {
+ String message = "Request rejected - Existing request in progress with exclusive mode for VNF: " + vnfId;
+ throw new RequestValidationException(message, LCMCommandStatus.EXLCUSIVE_REQUEST_IN_PROGRESS,
+ (new Params()).addParam("errorMsg", message));
+ }
+
+ Boolean scopeOverLap = checkScopeOverLap(runtimeContext.getRequestContext(), inProgressTransactions);
+ logger.debug("Scope overlap " + scopeOverLap);
+ if (scopeOverLap) {
+ List<VNFOperation> inProgressActions = inProgressTransactions.stream().map(TransactionRecord::getOperation)
+ .collect(Collectors.toList());
+
+ RuleExecutor ruleExecutor = requestValidationPolicy.getInProgressRuleExecutor();
+ RuleResult result = ruleExecutor.executeRule(operation.name(), inProgressActions);
+ logger.debug("Policy validation result " + result);
+ if (RuleResult.REJECT == result) {
+ String message = "Request rejected as per the request validation policy";
+ throw new RequestValidationException(message, LCMCommandStatus.POLICY_VALIDATION_FAILURE,
+ (new Params()).addParam("errorMsg", message));
+ }
}
}
+ private void validateVNFLock(RuntimeContext runtimeContext) throws LockException {
+ String vnfId = runtimeContext.getRequestContext().getActionIdentifiers().getVnfId();
+ String lockOwner = lockManager.getLockOwner(vnfId);
+ logger.debug("Current lock owner is " + lockOwner + " for vnf " + vnfId);
+ if (lockOwner != null
+ && !lockOwner.equals(runtimeContext.getRequestContext().getCommonHeader().getRequestId())) {
+ String message = new StringBuilder("VNF : ").append(vnfId).append(" is locked by request id :")
+ .append(lockOwner).toString();
+ throw new LockException(message);
+ }
+ }
- private String queryLCM(String orchestrationStatus, VNFOperation action) throws LifecycleException, NoTransitionDefinedException {
- if (logger.isTraceEnabled()) {
- logger.trace("Entering to queryLCM with Orchestration Status = "+ ObjectUtils.toString(orchestrationStatus)+
- ", command = "+ ObjectUtils.toString(action));
+ /*
+ * Do not remove this method, this is actual method for invoking scope
+ * overlap service When the service becomes available, its dummy
+ * implementation should be removed and this implementation should be used.
+ */
+ private Boolean checkScopeOverLap(RequestContext requestContext, List<TransactionRecord> inProgressTransactions)
+ throws APPCException {
+ Boolean scopeOverlap = null;
+ try {
+ JsonNode inputJSON = convertToJsonInput(requestContext, inProgressTransactions);
+ logger.debug("Input to scope overlap service " + inputJSON.toString());
+ HttpResponse response = client.doPost(path, inputJSON.toString());
+ int httpCode = response.getStatusLine().getStatusCode();
+ if (httpCode < 200 || httpCode >= 300) {
+ logger.debug("http error code " + httpCode);
+ throw new APPCException("Exception occurred on invoking check scope overlap api");
+ }
+ String respBody = IOUtils.toString(response.getEntity().getContent());
+ logger.debug("response body " + respBody);
+ ObjectMapper mapper = new ObjectMapper();
+ JsonNode outputJSON = mapper.readTree(respBody);
+ scopeOverlap = readScopeOverlap(outputJSON);
+ } catch (IOException e) {
+ String message = "Error accessing check scope overlap service";
+ logger.error(message, e);
+ throw new APPCException(message);
}
+ return scopeOverlap;
+ }
- String nextState = lifecyclemanager.getNextState(null, orchestrationStatus, action.name());
- if (logger.isDebugEnabled()) {
- logger.trace("Exiting from queryLCM with (LCMResponse = "+ ObjectUtils.toString(nextState)+")");
+ private Boolean readScopeOverlap(JsonNode outputJSON) throws APPCException {
+ logger.debug("Response JSON " + outputJSON.toString());
+ String message = "Error reading response JSON from scope overlap service ";
+ JsonNode outputNode = outputJSON.get("output");
+ JsonNode statusNode = outputNode.get("status");
+ if (statusNode == null) {
+ throw new APPCException(message);
}
- return nextState;
+
+ if (null == statusNode.get("message"))
+ throw new APPCException(message + "Status message is null.");
+ String responseStatusMessage = statusNode.get("message").textValue();
+
+ if (null == statusNode.get("code"))
+ throw new APPCException(message + "Status code is null.");
+ String code = statusNode.get("code").textValue();
+
+ JsonNode responseInfoNode = outputNode.get("response-info");
+ JsonNode blockNode = responseInfoNode.get("block");
+ String requestOverlapValue = null;
+
+ if (null != blockNode)
+ requestOverlapValue = blockNode.textValue();
+
+ logger.debug("Response JSON " + requestOverlapValue);
+
+ if (code.equals("400")) {
+ if(null==requestOverlapValue)
+ throw new APPCException("Response code is 400 but requestOverlapValue is null ");
+ if (requestOverlapValue.contains("true")) {
+ return Boolean.TRUE;
+ } else if (requestOverlapValue.contains("false")) {
+ return Boolean.FALSE;
+ } else {
+ throw new APPCException(
+ message + "requestOverlap value is other than True and False, it is " + requestOverlapValue);
+ }
+ } else if (code.equals("401")) {
+ throw new APPCException(message + responseStatusMessage);
+ } else {
+ throw new APPCException(message + "Status code is neither 400 nor 401, it is " + code);
+ }
+
}
+ private JsonNode convertToJsonInput(RequestContext requestContext, List<TransactionRecord> inProgressTransactions) {
+ ObjectMapper objectMapper = new ObjectMapper();
+ ScopeOverlapModel scopeOverlapModel = getScopeOverlapModel(requestContext, inProgressTransactions);
+ // Added for change in interface for action level
+
+ JsonNode jsonObject = objectMapper.valueToTree(scopeOverlapModel);
- private void checkVNFWorkingState(RuntimeContext runtimeContext) throws UnstableVNFException {
+ return jsonObject;
+ }
- if (logger.isTraceEnabled()) {
- logger.trace("Entering to checkVNFWorkingState with RequestHandlerInput = "+ ObjectUtils.toString(runtimeContext.getRequestContext()));
+ public ScopeOverlapModel getScopeOverlapModel(RequestContext requestContext,
+ List<TransactionRecord> inProgressTransactions) {
+ ScopeOverlapModel scopeOverlapModel = new ScopeOverlapModel();
+ RequestData requestData = new RequestData();
+
+ List<RequestModel> inProgressRequests = new ArrayList<>();
+ RequestModel requestModel = new RequestModel();
+ ActionIdentifierModel actionIdentifierModel = extractActionIdentifierModel(requestContext);
+ requestModel.setAction(requestContext.getAction().toString());
+ requestModel.setActionIdentifier(actionIdentifierModel);
+
+ if (requestModel.getActionIdentifier().getVnfId() != null) {
+ requestData.setVnfID(requestModel.getActionIdentifier().getVnfId());
}
- boolean forceFlag = runtimeContext.getRequestContext().getCommonHeader().getFlags() != null && runtimeContext.getRequestContext().getCommonHeader().getFlags().isForce();
- String vnfId = runtimeContext.getRequestContext().getActionIdentifiers().getVnfId();
- if (logger.isDebugEnabled()) {
- logger.debug("forceFlag = " + forceFlag);
+ if (requestModel.getActionIdentifier().getVnfcName() != null
+ || requestModel.getActionIdentifier().getVfModuleId() != null
+ || requestModel.getActionIdentifier().getVserverId() != null) {
+
+ requestModel.getActionIdentifier().setVnfId(null);
}
- boolean isVNFStable = workingStateManager.isVNFStable(vnfId);
- if (!isVNFStable && !forceFlag) {
- if (logger.isDebugEnabled()) {
- logger.debug("VNF is not stable for VNF ID = " + vnfId);
+
+ requestData.setCurrentRequest(requestModel);
+
+ for (TransactionRecord record : inProgressTransactions) {
+ RequestModel request = new RequestModel();
+ ActionIdentifierModel actionIdentifier = new ActionIdentifierModel();
+
+ actionIdentifier.setServiceInstanceId(record.getServiceInstanceId());
+ actionIdentifier.setVnfId(record.getTargetId());
+ actionIdentifier.setVnfcName(record.getVnfcName());
+ actionIdentifier.setVfModuleId(record.getVfModuleId());
+ actionIdentifier.setVserverId(record.getVserverId());
+
+ request.setAction(record.getOperation().name());
+ request.setActionIdentifier(actionIdentifier);
+ if (request.getActionIdentifier().getVnfcName() != null
+ || request.getActionIdentifier().getVfModuleId() != null
+ || request.getActionIdentifier().getVserverId() != null) {
+
+ request.getActionIdentifier().setVnfId(null);
+ }
+ inProgressRequests.add(request);
+ }
+
+ requestData.setInProgressRequests(inProgressRequests);
+
+ Request request = new Request();
+
+ Date date = new Date();
+ request.setRequestID("RequestId-ScopeOverlap " + date.toString());
+ request.setAction("isScopeOverlap");
+ ObjectMapper objectMapper = new ObjectMapper();
+ JsonNode json = objectMapper.valueToTree(requestData);
+ request.setRequestData(json.toString());
+ Input input = new Input();
+ input.setRequest(request);
+ scopeOverlapModel.setInput(input);
+
+ return scopeOverlapModel;
+ }
+
+ private ActionIdentifierModel extractActionIdentifierModel(RequestContext requestContext) {
+ ActionIdentifierModel actionIdentifierModel = new ActionIdentifierModel();
+ actionIdentifierModel.setServiceInstanceId(requestContext.getActionIdentifiers().getServiceInstanceId());
+ actionIdentifierModel.setVnfId(requestContext.getActionIdentifiers().getVnfId());
+ actionIdentifierModel.setVnfcName(requestContext.getActionIdentifiers().getVnfcName());
+ actionIdentifierModel.setVfModuleId(requestContext.getActionIdentifiers().getVfModuleId());
+ actionIdentifierModel.setVserverId(requestContext.getActionIdentifiers().getVserverId());
+ return actionIdentifierModel;
+ }
+
+ private VNFContext queryAAI(String vnfId) throws VNFNotFoundException, MissingVNFDataInAAIException {
+ SvcLogicContext ctx = new SvcLogicContext();
+ ctx = getVnfdata(vnfId, "vnf", ctx);
+
+ VNFContext vnfContext = new VNFContext();
+ populateVnfContext(vnfContext, ctx);
+
+ return vnfContext;
+ }
+
+ private SvcLogicContext getVnfdata(String vnf_id, String prefix, SvcLogicContext ctx) throws VNFNotFoundException {
+ if (logger.isTraceEnabled()) {
+ logger.trace("Entering to getVnfdata with vnfid = " + ObjectUtils.toString(vnf_id) + ", prefix = "
+ + ObjectUtils.toString(prefix) + ", SvcLogicContext" + ObjectUtils.toString(ctx));
+ }
+ String key = "vnf-id = '" + vnf_id + "'";
+ logger.debug("inside getVnfdata=== " + key);
+ try {
+ Date beginTimestamp = new Date();
+ SvcLogicResource.QueryStatus response = aaiService.query("generic-vnf", false, null, key, prefix, null,
+ ctx);
+ Date endTimestamp = new Date();
+ String status = SvcLogicResource.QueryStatus.SUCCESS.equals(response)
+ ? LoggingConstants.StatusCodes.COMPLETE : LoggingConstants.StatusCodes.ERROR;
+ LoggingUtils.logMetricsMessage(beginTimestamp.toInstant(), endTimestamp.toInstant(),
+ LoggingConstants.TargetNames.AAI, LoggingConstants.TargetServiceNames.AAIServiceNames.QUERY, status,
+ "", response.name(), this.getClass().getCanonicalName());
+ if (SvcLogicResource.QueryStatus.NOT_FOUND.equals(response)) {
+ throw new VNFNotFoundException("VNF not found for vnf_id = " + vnf_id, vnf_id);
+ } else if (SvcLogicResource.QueryStatus.FAILURE.equals(response)) {
+ throw new RuntimeException("Error Querying AAI with vnfID = " + vnf_id);
}
- throw new UnstableVNFException("VNF is not stable for vnfID = " + vnfId);
+ logger.info("AAIResponse: " + response.toString());
+ } catch (SvcLogicException e) {
+
+ LoggingUtils.logErrorMessage(LoggingConstants.TargetServiceNames.AAIServiceNames.GET_VNF_DATA,
+ "Error in getVnfdata" + e, this.getClass().getCanonicalName());
+
+ throw new RuntimeException(e);
}
+ if (logger.isTraceEnabled()) {
+ logger.trace("Exiting from getVnfdata with (SvcLogicContext = " + ObjectUtils.toString(ctx) + ")");
+ }
+ return ctx;
+ }
+ private void populateVnfContext(VNFContext vnfContext, SvcLogicContext ctx) throws MissingVNFDataInAAIException {
+ String vnfType = ctx.getAttribute("vnf.vnf-type");
+ if (StringUtils.isEmpty(vnfType)) {
+ throw new MissingVNFDataInAAIException("vnf-type", ctx.getAttribute("vnf.vnf-id"));
+ }
+ vnfContext.setType(vnfType);
+ vnfContext.setId(ctx.getAttribute("vnf.vnf-id"));
}
+ private void checkWorkflowExists(VNFContext vnfContext, RequestContext requestContext)
+ throws WorkflowNotFoundException, DGWorkflowNotFoundException {
+ WorkflowExistsOutput workflowExistsOutput = workflowManager
+ .workflowExists(getWorkflowQueryParams(vnfContext, requestContext));
+ if (!workflowExistsOutput.isMappingExist()) {
+ if (logger.isDebugEnabled()) {
+ logger.debug("WorkflowManager : Workflow mapping not found for vnfType = " + vnfContext.getType()
+ + ", version = " + vnfContext.getVersion() + ", command = "
+ + requestContext.getAction().name());
+ }
+ LoggingUtils.logErrorMessage(LoggingConstants.TargetNames.WORKFLOW_MANAGER, EELFResourceManager
+ .format(Msg.APPC_WORKFLOW_NOT_FOUND, vnfContext.getType(), requestContext.getAction().name()),
+ this.getClass().getCanonicalName());
+ throw new WorkflowNotFoundException(
+ "Workflow mapping not found for vnfType = " + vnfContext.getType() + ", command = "
+ + requestContext.getAction().name(),
+ vnfContext.getType(), requestContext.getAction().name());
+ }
+ if (!workflowExistsOutput.isDgExist()) {
+ if (logger.isDebugEnabled()) {
+ logger.debug("WorkflowManager : DG Workflow not found for vnfType = " + vnfContext.getType()
+ + ", version = " + vnfContext.getVersion() + ", command = " + requestContext.getAction().name()
+ + " " + workflowExistsOutput);
+ }
+ LoggingUtils.logErrorMessage(LoggingConstants.TargetNames.WORKFLOW_MANAGER, EELFResourceManager
+ .format(Msg.APPC_WORKFLOW_NOT_FOUND, vnfContext.getType(), requestContext.getAction().name()),
+ this.getClass().getCanonicalName());
+ throw new DGWorkflowNotFoundException(
+ "Workflow not found for vnfType = " + vnfContext.getType() + ", command = "
+ + requestContext.getAction().name(),
+ workflowExistsOutput.getWorkflowModule(), workflowExistsOutput.getWorkflowName(),
+ workflowExistsOutput.getWorkflowVersion(), vnfContext.getType(), requestContext.getAction().name());
+ }
+ }
+ private WorkflowRequest getWorkflowQueryParams(VNFContext vnfContext, RequestContext requestContext) {
+ WorkflowRequest workflowRequest = new WorkflowRequest();
+ workflowRequest.setVnfContext(vnfContext);
+ workflowRequest.setRequestContext(requestContext);
+ if (logger.isTraceEnabled()) {
+ logger.trace("Exiting from getWorkflowQueryParams with (WorkflowRequest = "
+ + ObjectUtils.toString(workflowRequest) + ")");
+ }
+ return workflowRequest;
+ }
}
diff --git a/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/requesthandler/impl/VMRequestValidatorImpl.java b/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/requesthandler/impl/VMRequestValidatorImpl.java
deleted file mode 100644
index b645b8222..000000000
--- a/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/requesthandler/impl/VMRequestValidatorImpl.java
+++ /dev/null
@@ -1,81 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * ONAP : APPC
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Copyright (C) 2017 Amdocs
- * =============================================================================
- * 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.
- *
- * ECOMP is a trademark and service mark of AT&T Intellectual Property.
- * ============LICENSE_END=========================================================
- */
-
-package org.onap.appc.requesthandler.impl;
-
-import com.att.eelf.i18n.EELFResourceManager;
-import org.onap.appc.domainmodel.lcm.RuntimeContext;
-import org.onap.appc.domainmodel.lcm.VNFContext;
-import org.onap.appc.domainmodel.lcm.VNFOperation;
-import org.onap.appc.i18n.Msg;
-import org.onap.appc.logging.LoggingConstants;
-import org.onap.appc.logging.LoggingUtils;
-import org.onap.appc.requesthandler.exceptions.*;
-
-import java.util.HashSet;
-import java.util.Set;
-
-public class VMRequestValidatorImpl extends AbstractRequestValidatorImpl {
-
- @Override
- public void validateRequest(RuntimeContext runtimeContext) throws VNFNotFoundException, RequestExpiredException, InvalidInputException, WorkflowNotFoundException, DGWorkflowNotFoundException, MissingVNFDataInAAIException, LCMOperationsDisabledException, DuplicateRequestException {
- if(!lcmStateManager.isLCMOperationEnabled()) {
- LoggingUtils.logErrorMessage(
- LoggingConstants.TargetNames.REQUEST_VALIDATOR,
- EELFResourceManager.format(Msg.LCM_OPERATIONS_DISABLED),
- this.getClass().getCanonicalName());
- throw new LCMOperationsDisabledException("APPC LCM operations have been administratively disabled");
- }
-
- getAAIservice();
- super.validateInput(runtimeContext.getRequestContext());
- String vnfId = runtimeContext.getRequestContext().getActionIdentifiers().getVnfId();
-
- VNFContext vnfContext = queryAAI(vnfId);
- runtimeContext.setVnfContext(vnfContext);
-
- VNFOperation operation = runtimeContext.getRequestContext().getAction();
- if(supportedVMLevelAction().contains(operation)) {
- queryWFM(vnfContext, runtimeContext.getRequestContext());
- }
- else{
- throw new LCMOperationsDisabledException("Action "+ operation.name() + " is not supported on VM level");
- }
- }
-
- public Set<VNFOperation> supportedVMLevelAction(){
- Set<VNFOperation> vnfOperations = new HashSet<>();
- vnfOperations.add(VNFOperation.Start);
- vnfOperations.add(VNFOperation.Stop);
- vnfOperations.add(VNFOperation.Restart);
- vnfOperations.add(VNFOperation.Rebuild);
- vnfOperations.add(VNFOperation.Terminate);
- vnfOperations.add(VNFOperation.Migrate);
- vnfOperations.add(VNFOperation.Evacuate);
- vnfOperations.add(VNFOperation.Snapshot);
- return vnfOperations;
- }
-
-
-}
diff --git a/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/workingstatemanager/objects/VnfWorkingStateDto.java b/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/requesthandler/model/ActionIdentifierModel.java
index 948d4ca59..9261abb1d 100644
--- a/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/workingstatemanager/objects/VnfWorkingStateDto.java
+++ b/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/requesthandler/model/ActionIdentifierModel.java
@@ -22,22 +22,24 @@
* ============LICENSE_END=========================================================
*/
-package org.onap.appc.workingstatemanager.objects;
+package org.onap.appc.requesthandler.model;
+import com.fasterxml.jackson.annotation.JsonInclude;
+import com.fasterxml.jackson.annotation.JsonProperty;
-public class VnfWorkingStateDto {
+@JsonInclude(JsonInclude.Include.NON_NULL)
+public class ActionIdentifierModel {
+ @JsonProperty("service-instance-id")
+ private String serviceInstanceId;
+ @JsonProperty("vnf-id")
private String vnfId;
- private VNFWorkingState state;
- private String ownerId;
- private long updated;
- private long ver;
+ @JsonProperty("vnfc-name")
+ private String vnfcName;
+ @JsonProperty("vf-module-id")
+ private String vfModuleId;
+ @JsonProperty("vserver-id")
+ private String vserverId;
- public VnfWorkingStateDto() {
- }
-
- public VnfWorkingStateDto(String vnfId) {
- this.vnfId = vnfId;
- }
public String getVnfId() {
return vnfId;
@@ -47,47 +49,36 @@ public class VnfWorkingStateDto {
this.vnfId = vnfId;
}
- public VNFWorkingState getState() {
- return state;
+ public String getVnfcName() {
+ return vnfcName;
}
- public void setState(VNFWorkingState state) {
- this.state = state;
+ public void setVnfcName(String vnfcName) {
+ this.vnfcName = vnfcName;
}
- public String getOwnerId() {
- return ownerId;
+ public String getVfModuleId() {
+ return vfModuleId;
}
- public void setOwnerId(String ownerId) {
- this.ownerId = ownerId;
+ public void setVfModuleId(String vfModuleId) {
+ this.vfModuleId = vfModuleId;
}
- public long getUpdated() {
- return updated;
+ public String getVserverId() {
+ return vserverId;
}
- public void setUpdated(long updated) {
- this.updated = updated;
+ public void setVserverId(String vserverId) {
+ this.vserverId = vserverId;
}
-
- public long getVer() {
- return ver;
- }
-
- public void setVer(long ver) {
- this.ver = ver;
+ public String getServiceInstanceId() {
+ return serviceInstanceId;
}
-
- @Override
- public String toString() {
- return "VnfWorkingStateDto{" +
- "vnfId='" + vnfId + '\'' +
- ", state=" + state +
- ", ownerId='" + ownerId + '\'' +
- ", updated=" + updated +
- ", ver=" + ver +
- '}';
+ public void setServiceInstanceId(String serviceInstanceId) {
+ this.serviceInstanceId = serviceInstanceId;
}
+
+
}
diff --git a/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/workingstatemanager/impl/RequestHandlerMessages.java b/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/requesthandler/model/Input.java
index 206d57229..d895c7789 100644
--- a/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/workingstatemanager/impl/RequestHandlerMessages.java
+++ b/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/requesthandler/model/Input.java
@@ -22,10 +22,22 @@
* ============LICENSE_END=========================================================
*/
-package org.onap.appc.workingstatemanager.impl;
+package org.onap.appc.requesthandler.model;
+import com.fasterxml.jackson.annotation.JsonProperty;
+
+public class Input {
+
+ @JsonProperty("request")
+ private Request request;
+
+ public Request getRequest() {
+ return request;
+ }
+
+ public void setRequest(Request request) {
+ this.request = request;
+ }
+
-public class RequestHandlerMessages {
- public final static String VNF_WORKING_STATE_UPDATED = "VNF WorkingState for vnfId ${vnfId} was updated to ${workingState} at attempt ${attempt} out of ${maxAttempts} with ownerId = ${ownerId} and forceFlag = ${forceFlag}";
- public final static String VNF_WORKING_STATE_WAS_NOT_UPDATED = "VNF WorkingState for vnfId ${vnfId} was not updated to ${workingState} attempt ${attempt} out of ${maxAttempts} with ownerId = ${ownerId} and forceFlag = ${forceFlag}";
}
diff --git a/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/requesthandler/model/Request.java b/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/requesthandler/model/Request.java
new file mode 100644
index 000000000..8f36e6a21
--- /dev/null
+++ b/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/requesthandler/model/Request.java
@@ -0,0 +1,66 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * ONAP : APPC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Copyright (C) 2017 Amdocs
+ * =============================================================================
+ * 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.
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.onap.appc.requesthandler.model;
+
+import com.fasterxml.jackson.annotation.JsonInclude;
+import com.fasterxml.jackson.annotation.JsonProperty;
+
+@JsonInclude(JsonInclude.Include.NON_NULL)
+public class Request {
+
+ @JsonProperty("request-id")
+ private String requestID;
+
+ @JsonProperty("action")
+ private String action;
+
+ @JsonProperty("request-data")
+ private String requestData;
+
+ public String getRequestData() {
+ return requestData;
+ }
+
+ public void setRequestData(String requestData) {
+ this.requestData = requestData;
+ }
+
+ public String getRequestID() {
+ return requestID;
+ }
+
+ public void setRequestID(String requestID) {
+ this.requestID = requestID;
+ }
+
+ public String getAction() {
+ return action;
+ }
+
+ public void setAction(String action) {
+ this.action = action;
+ }
+
+}
diff --git a/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/requesthandler/model/RequestData.java b/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/requesthandler/model/RequestData.java
new file mode 100644
index 000000000..7a25f050f
--- /dev/null
+++ b/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/requesthandler/model/RequestData.java
@@ -0,0 +1,68 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * ONAP : APPC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Copyright (C) 2017 Amdocs
+ * =============================================================================
+ * 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.
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.onap.appc.requesthandler.model;
+
+import java.util.List;
+
+import com.fasterxml.jackson.annotation.JsonInclude;
+import com.fasterxml.jackson.annotation.JsonProperty;
+
+@JsonInclude(JsonInclude.Include.NON_NULL)
+public class RequestData {
+
+ @JsonProperty("vnf-id")
+ private String vnfID;
+
+ @JsonProperty("current-request")
+ private RequestModel currentRequest;
+
+ @JsonProperty("in-progress-requests")
+ private List<RequestModel> inProgressRequests;
+
+ public String getVnfID() {
+ return vnfID;
+ }
+
+ public void setVnfID(String vnfID) {
+ this.vnfID = vnfID;
+ }
+
+ public RequestModel getCurrentRequest() {
+ return currentRequest;
+ }
+
+ public void setCurrentRequest(RequestModel currentRequest) {
+ this.currentRequest = currentRequest;
+ }
+
+ public List<RequestModel> getInProgressRequests() {
+ return inProgressRequests;
+ }
+
+ public void setInProgressRequests(List<RequestModel> inProgressRequests) {
+ this.inProgressRequests = inProgressRequests;
+ }
+
+}
diff --git a/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/requesthandler/model/RequestModel.java b/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/requesthandler/model/RequestModel.java
new file mode 100644
index 000000000..acfd00d04
--- /dev/null
+++ b/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/requesthandler/model/RequestModel.java
@@ -0,0 +1,54 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * ONAP : APPC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Copyright (C) 2017 Amdocs
+ * =============================================================================
+ * 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.
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.onap.appc.requesthandler.model;
+
+import com.fasterxml.jackson.annotation.JsonInclude;
+import com.fasterxml.jackson.annotation.JsonProperty;
+
+@JsonInclude(JsonInclude.Include.NON_NULL)
+public class RequestModel {
+
+ @JsonProperty("action")
+ private String action;
+ @JsonProperty("action-identifiers")
+ private ActionIdentifierModel actionIdentifier;
+
+ public ActionIdentifierModel getActionIdentifier() {
+ return actionIdentifier;
+ }
+
+ public void setActionIdentifier(ActionIdentifierModel actionIdentifier) {
+ this.actionIdentifier = actionIdentifier;
+ }
+
+ public String getAction() {
+ return action;
+ }
+
+ public void setAction(String action) {
+ this.action = action;
+ }
+
+}
diff --git a/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/requesthandler/model/ScopeOverlapModel.java b/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/requesthandler/model/ScopeOverlapModel.java
new file mode 100644
index 000000000..38b3a0ff7
--- /dev/null
+++ b/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/requesthandler/model/ScopeOverlapModel.java
@@ -0,0 +1,67 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * ONAP : APPC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Copyright (C) 2017 Amdocs
+ * =============================================================================
+ * 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.
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.onap.appc.requesthandler.model;
+
+import com.fasterxml.jackson.annotation.JsonInclude;
+import com.fasterxml.jackson.annotation.JsonProperty;
+
+import java.util.List;
+
+@JsonInclude(JsonInclude.Include.NON_NULL)
+public class ScopeOverlapModel {
+ @JsonProperty("input")
+ private Input input;
+
+ public Input getInput() {
+ return input;
+ }
+
+ public void setInput(Input input) {
+ this.input = input;
+ }
+
+
+ /* @JsonProperty("current-request")
+ private RequestModel currentRequest;
+
+ @JsonProperty("in-progress-requests")
+ private List<RequestModel> inProgressRequests;
+
+ public RequestModel getCurrentRequest() {
+ return currentRequest;
+ }
+
+ public void setCurrentRequest(RequestModel currentRequest) {
+ this.currentRequest = currentRequest;
+ }
+
+ public List<RequestModel> getInProgressRequests() {
+ return inProgressRequests;
+ }
+
+ public void setInProgressRequests(List<RequestModel> inProgressRequests) {
+ this.inProgressRequests = inProgressRequests;
+ }*/
+}
diff --git a/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/validationpolicy/RequestValidationPolicy.java b/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/validationpolicy/RequestValidationPolicy.java
new file mode 100644
index 000000000..46bba6efd
--- /dev/null
+++ b/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/validationpolicy/RequestValidationPolicy.java
@@ -0,0 +1,142 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * ONAP : APPC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Copyright (C) 2017 Amdocs
+ * =============================================================================
+ * 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.
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.onap.appc.validationpolicy;
+
+import com.att.eelf.configuration.EELFLogger;
+import com.att.eelf.configuration.EELFManager;
+import com.fasterxml.jackson.databind.DeserializationFeature;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import org.apache.commons.lang.StringUtils;
+import org.onap.appc.domainmodel.lcm.VNFOperation;
+import org.onap.appc.validationpolicy.executors.ActionInProgressRuleExecutor;
+import org.onap.appc.validationpolicy.executors.RuleExecutor;
+import org.onap.appc.validationpolicy.objects.Policy;
+import org.onap.appc.validationpolicy.objects.PolicyNames;
+import org.onap.appc.validationpolicy.objects.Rule;
+import org.onap.appc.validationpolicy.objects.ValidationJSON;
+import org.onap.appc.validationpolicy.rules.RuleFactory;
+import org.onap.ccsdk.sli.core.dblib.DbLibService;
+
+import javax.sql.rowset.CachedRowSet;
+import java.sql.SQLException;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.stream.Collectors;
+
+/**
+ * Reads the request validation policy on start-up and provides
+ * accessors for rule executors
+ */
+public class RequestValidationPolicy {
+
+ private DbLibService dbLibService;
+
+ private RuleExecutor actionInProgressRuleExecutor;
+
+ private final EELFLogger logger = EELFManager.getInstance().getLogger(RequestValidationPolicy.class);
+
+ public void setDbLibService(DbLibService dbLibService) {
+ this.dbLibService = dbLibService;
+ }
+
+ public void initialize(){
+ try {
+ String jsonContent = getPolicyJson();
+ if (jsonContent == null) return;
+
+ ObjectMapper objectMapper = new ObjectMapper();
+ objectMapper.configure(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true);
+ ValidationJSON validationJSON = objectMapper.readValue(jsonContent, ValidationJSON.class);
+ List<Policy> policyList = validationJSON.getPolicies();
+ policyList.stream()
+ .filter(policy -> PolicyNames.ActionInProgress.name().equals(policy.getPolicyName()))
+ .forEach(policy -> {
+ Rule[] ruleDTOs = policy.getRules();
+ Map<String, org.onap.appc.validationpolicy.rules.Rule> rules = new HashMap<>();
+ for(Rule ruleDTO : ruleDTOs) {
+ String action = ruleDTO.getActionReceived();
+ String validationRule = ruleDTO.getValidationRule();
+ Set<VNFOperation> inclusionSet = null;
+ Set<VNFOperation> exclusionSet = null;
+ if (ruleDTO.getInclusionList() != null && !ruleDTO.getInclusionList().isEmpty()) {
+ inclusionSet = ruleDTO.getInclusionList().stream()
+ .map(VNFOperation::findByString).filter(operation -> operation!=null)
+ .collect(Collectors.toSet());
+ }
+ if (ruleDTO.getExclusionList() != null && !ruleDTO.getExclusionList().isEmpty()) {
+ exclusionSet = ruleDTO.getExclusionList().stream()
+ .map(VNFOperation::findByString).filter(operation -> operation!=null)
+ .collect(Collectors.toSet());
+ }
+ org.onap.appc.validationpolicy.rules.Rule rule = RuleFactory
+ .createRule(validationRule, inclusionSet, exclusionSet);
+ rules.put(action, rule);
+ }
+ actionInProgressRuleExecutor = new ActionInProgressRuleExecutor(Collections.unmodifiableMap(rules));
+ });
+ } catch (Exception e) {
+ logger.error("Error reading request validation policies",e);
+ }
+ }
+
+ protected String getPolicyJson() {
+ String schema = "sdnctl";
+ String query = "SELECT MAX(INTERNAL_VERSION),ARTIFACT_CONTENT " +
+ "FROM ASDC_ARTIFACTS " +
+ "WHERE ARTIFACT_NAME = ? " +
+ "GROUP BY ARTIFACT_NAME";
+ ArrayList<String> arguments = new ArrayList<>();
+ arguments.add("request_validation_policy");
+ String jsonContent =null;
+ try{
+ CachedRowSet rowSet = dbLibService.getData(query,arguments,schema);
+ if(rowSet.next()){
+ jsonContent = rowSet.getString("ARTIFACT_CONTENT");
+ }
+ if(logger.isDebugEnabled()){
+ logger.debug("request validation policy = " + jsonContent);
+ }
+ if(StringUtils.isBlank(jsonContent)){
+ logger.warn("request validation policy not found in app-c database");
+ }
+ }
+ catch(SQLException e){
+ logger.error("Error accessing database",e);
+ throw new RuntimeException(e);
+ }
+ return jsonContent;
+ }
+
+ public RuleExecutor getInProgressRuleExecutor(){
+ if(actionInProgressRuleExecutor ==null){
+ throw new RuntimeException("Rule executor not available, initialization of RequestValidationPolicy failed");
+ }
+ return actionInProgressRuleExecutor;
+ }
+}
diff --git a/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/validationpolicy/executors/ActionInProgressRuleExecutor.java b/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/validationpolicy/executors/ActionInProgressRuleExecutor.java
new file mode 100644
index 000000000..6e9838e49
--- /dev/null
+++ b/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/validationpolicy/executors/ActionInProgressRuleExecutor.java
@@ -0,0 +1,50 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * ONAP : APPC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Copyright (C) 2017 Amdocs
+ * =============================================================================
+ * 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.
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.onap.appc.validationpolicy.executors;
+
+import org.onap.appc.domainmodel.lcm.VNFOperation;
+import org.onap.appc.validationpolicy.objects.RuleResult;
+import org.onap.appc.validationpolicy.rules.Rule;
+
+import java.util.List;
+import java.util.Map;
+
+public class ActionInProgressRuleExecutor implements RuleExecutor {
+
+ Map<String,Rule> rules;
+
+ public ActionInProgressRuleExecutor(Map<String,Rule> rules) {
+ this.rules = rules;
+ }
+
+ public RuleResult executeRule(String action, List<VNFOperation> inProgressActionList){
+ Rule rule = rules.get(action);
+ if(rule == null){
+ rule = rules.get("Default");
+ }
+ return rule.executeRule(action,inProgressActionList);
+ }
+
+}
diff --git a/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/validationpolicy/executors/RuleExecutor.java b/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/validationpolicy/executors/RuleExecutor.java
new file mode 100644
index 000000000..38e8d1e5d
--- /dev/null
+++ b/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/validationpolicy/executors/RuleExecutor.java
@@ -0,0 +1,44 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * ONAP : APPC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Copyright (C) 2017 Amdocs
+ * =============================================================================
+ * 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.
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.onap.appc.validationpolicy.executors;
+
+import org.onap.appc.domainmodel.lcm.VNFOperation;
+import org.onap.appc.validationpolicy.objects.RuleResult;
+
+import java.util.List;
+
+/**
+ * Provides API for executing request validation rules defined by
+ * request validation policy
+ */
+public interface RuleExecutor {
+ /**
+ * Executes request validation rules defined in request validation policy
+ * @param actionReceived current/new lcm request action
+ * @param inProgressRequestActions list of in-progress lcm action for the same vnf
+ * @return returns RuleResult (ACCEPT/REJECT) based on the rules
+ */
+ RuleResult executeRule(String actionReceived, List<VNFOperation> inProgressRequestActions);
+}
diff --git a/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/requesthandler/impl/VMRequestHandlerImpl.java b/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/validationpolicy/objects/Policy.java
index 7e3917313..5006c89ca 100644
--- a/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/requesthandler/impl/VMRequestHandlerImpl.java
+++ b/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/validationpolicy/objects/Policy.java
@@ -22,20 +22,34 @@
* ============LICENSE_END=========================================================
*/
-package org.onap.appc.requesthandler.impl;
+package org.onap.appc.validationpolicy.objects;
-import org.onap.appc.domainmodel.lcm.RuntimeContext;
-import org.onap.appc.executor.UnstableVNFException;
-public class VMRequestHandlerImpl extends AbstractRequestHandlerImpl{
+import com.fasterxml.jackson.annotation.JsonProperty;
- protected void handleRequest(RuntimeContext runtimeContext) {
- runtimeContext.setIsLockAcquired(false);
- callWfOperation(runtimeContext);
+
+public class Policy {
+ @JsonProperty("name")
+ private String policyName;
+
+ @JsonProperty("rules")
+ private Rule[] rules;
+
+ public String getPolicyName() {
+ return policyName;
+ }
+
+ public void setPolicyName(String policyName) {
+ this.policyName = policyName;
}
- @Override
- public void onRequestExecutionStart(String vnfId, boolean readOnlyActivity, String requestIdentifierString, boolean forceFlag) throws UnstableVNFException {
+ public Rule[] getRules() {
+ return rules;
+ }
+ public void setRules(Rule[] rules) {
+ this.rules = rules;
}
}
+
+
diff --git a/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/workingstatemanager/objects/VNFWorkingState.java b/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/validationpolicy/objects/PolicyNames.java
index 9c638de20..77d1c2ceb 100644
--- a/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/workingstatemanager/objects/VNFWorkingState.java
+++ b/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/validationpolicy/objects/PolicyNames.java
@@ -22,12 +22,8 @@
* ============LICENSE_END=========================================================
*/
-package org.onap.appc.workingstatemanager.objects;
+package org.onap.appc.validationpolicy.objects;
-
-public enum VNFWorkingState {
- STABLE,UNSTABLE,UNKNOWN;
- public String toString(){
- return this.name();
- }
+public enum PolicyNames {
+ ActionInProgress;
}
diff --git a/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/validationpolicy/objects/Rule.java b/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/validationpolicy/objects/Rule.java
new file mode 100644
index 000000000..1ac516767
--- /dev/null
+++ b/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/validationpolicy/objects/Rule.java
@@ -0,0 +1,76 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * ONAP : APPC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Copyright (C) 2017 Amdocs
+ * =============================================================================
+ * 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.
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.onap.appc.validationpolicy.objects;
+
+import com.fasterxml.jackson.annotation.JsonProperty;
+
+import java.util.List;
+
+public class Rule {
+ @JsonProperty("action-received")
+ private String actionReceived;
+ @JsonProperty("validation-rule")
+ private String validationRule;
+ @JsonProperty("in-progress-action-inclusion-list")
+ private List<String> inclusionList;
+ @JsonProperty("in-progress-action-exclusion-list")
+ private List<String> exclusionList;
+
+ public Rule(){
+
+ }
+
+ public String getActionReceived() {
+ return actionReceived;
+ }
+
+ public void setActionReceived(String actionReceived) {
+ this.actionReceived = actionReceived;
+ }
+
+ public String getValidationRule() {
+ return validationRule;
+ }
+
+ public void setValidationRule(String validationRule) {
+ this.validationRule = validationRule;
+ }
+
+ public List<String> getInclusionList() {
+ return inclusionList;
+ }
+
+ public void setInclusionList(List<String> inclusionList) {
+ this.inclusionList = inclusionList;
+ }
+
+ public List<String> getExclusionList() {
+ return exclusionList;
+ }
+
+ public void setExclusionList(List<String> exclusionList) {
+ this.exclusionList = exclusionList;
+ }
+}
diff --git a/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/requesthandler/exceptions/InvalidInputException.java b/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/validationpolicy/objects/RuleResult.java
index 6e2435559..bf302c2cd 100644
--- a/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/requesthandler/exceptions/InvalidInputException.java
+++ b/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/validationpolicy/objects/RuleResult.java
@@ -22,11 +22,8 @@
* ============LICENSE_END=========================================================
*/
-package org.onap.appc.requesthandler.exceptions;
+package org.onap.appc.validationpolicy.objects;
-
-public class InvalidInputException extends Exception {
- public InvalidInputException(String message){
- super(message);
- }
+public enum RuleResult {
+ ACCEPT,REJECT
}
diff --git a/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/workingstatemanager/impl/JdbcWorkingStateManager.java b/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/validationpolicy/objects/ValidationJSON.java
index 041cf7e84..02c788614 100644
--- a/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/workingstatemanager/impl/JdbcWorkingStateManager.java
+++ b/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/validationpolicy/objects/ValidationJSON.java
@@ -22,26 +22,30 @@
* ============LICENSE_END=========================================================
*/
-package org.onap.appc.workingstatemanager.impl;
+package org.onap.appc.validationpolicy.objects;
-import java.sql.Connection;
+import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
+import com.fasterxml.jackson.annotation.JsonProperty;
+import com.fasterxml.jackson.databind.annotation.JsonSerialize;
-import org.onap.appc.dao.util.JdbcConnectionFactory;
-import org.onap.appc.workingstatemanager.WorkingStateManager;
+import java.util.List;
-public abstract class JdbcWorkingStateManager implements WorkingStateManager {
+@JsonSerialize(include = JsonSerialize.Inclusion.NON_NULL)
+@JsonIgnoreProperties(ignoreUnknown = true)
+public class ValidationJSON {
- private JdbcConnectionFactory connectionFactory;
+ @JsonProperty("request-validation-policies")
+ private List<Policy> policies;
+
+ public ValidationJSON(){
- public void setConnectionFactory(JdbcConnectionFactory connectionFactory) {
- this.connectionFactory = connectionFactory;
}
- protected Connection openDbConnection() {
- return connectionFactory.openDbConnection();
+ public List<Policy> getPolicies() {
+ return policies;
}
- protected void closeDbConnection(Connection connection) {
- connectionFactory.closeDbConnection(connection);
+ public void setPolicies(List<Policy> policies) {
+ this.policies = policies;
}
}
diff --git a/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/validationpolicy/rules/AcceptRule.java b/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/validationpolicy/rules/AcceptRule.java
new file mode 100644
index 000000000..0e6c4db09
--- /dev/null
+++ b/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/validationpolicy/rules/AcceptRule.java
@@ -0,0 +1,76 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * ONAP : APPC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Copyright (C) 2017 Amdocs
+ * =============================================================================
+ * 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.
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.onap.appc.validationpolicy.rules;
+
+import org.onap.appc.domainmodel.lcm.VNFOperation;
+import org.onap.appc.validationpolicy.objects.RuleResult;
+
+import java.util.List;
+import java.util.Set;
+import java.util.stream.Collectors;
+
+/**
+ * Implementation of Accept Rule
+ */
+public class AcceptRule extends Rule {
+
+ AcceptRule(Set<VNFOperation> inclusions,Set<VNFOperation> exclusions){
+ super(inclusions,exclusions);
+ }
+
+ @Override
+ public RuleResult executeRule(String action, List<VNFOperation> inProgressActionList) {
+
+ if(inclusions!=null && !inclusions.isEmpty()){
+ /* new action (action-received) should be rejected,
+ if any of the in-progress request action
+ is mentioned in the in-progress-exclusion list*/
+ if(logger.isDebugEnabled()){
+ logger.debug("Executing accept rule for action-received = "+action+" and in-progress-actions-inclusions = "+ inProgressActionList.toString());
+ }
+ Set<String> inProgressActionSet = inProgressActionList.stream().map(VNFOperation::name).collect(Collectors.toSet());
+ inProgressActionSet.removeAll(inclusions.stream().map(VNFOperation::name).collect(Collectors.toList()));
+ if(!inProgressActionSet.isEmpty()){
+ return RuleResult.REJECT;
+ }
+ return RuleResult.ACCEPT;
+ }
+ else if(exclusions!=null && !exclusions.isEmpty()){
+ /* new action (action-received) should be accepted,
+ if all of the in-progress request actions
+ are mentioned in the in-progress-inclusion list */
+ if(logger.isDebugEnabled()){
+ logger.debug("Executing accept rule for action-received = %s and in-progress-actions-exclusions = %s",action,inProgressActionList.toString());
+ }
+ Set<String> inProgressActionSet = inProgressActionList.stream().map(VNFOperation::name).collect(Collectors.toSet());
+ inProgressActionSet.retainAll(exclusions.stream().map(VNFOperation::name).collect(Collectors.toList()));
+ if(!inProgressActionSet.isEmpty()){
+ return RuleResult.REJECT;
+ }
+ return RuleResult.ACCEPT;
+ }
+ return RuleResult.ACCEPT;
+ }
+}
diff --git a/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/validationpolicy/rules/RejectRule.java b/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/validationpolicy/rules/RejectRule.java
new file mode 100644
index 000000000..9bf60a135
--- /dev/null
+++ b/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/validationpolicy/rules/RejectRule.java
@@ -0,0 +1,75 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * ONAP : APPC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Copyright (C) 2017 Amdocs
+ * =============================================================================
+ * 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.
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.onap.appc.validationpolicy.rules;
+
+import org.onap.appc.domainmodel.lcm.VNFOperation;
+import org.onap.appc.validationpolicy.objects.RuleResult;
+
+import java.util.List;
+import java.util.Set;
+import java.util.stream.Collectors;
+
+/**
+ * Implementation of Reject Rule
+ */
+public class RejectRule extends Rule {
+
+ RejectRule(Set<VNFOperation> inclusions, Set<VNFOperation> exclusions){
+ super(inclusions, exclusions);
+ }
+
+ @Override
+ public RuleResult executeRule(String action, List<VNFOperation> inProgressActionList) {
+ if(inclusions!= null && !inclusions.isEmpty()){
+ /* new action (action-received) should be rejected,
+ if any of the in-progress request actions
+ are mentioned in the in-progress-inclusion list*/
+ if(logger.isDebugEnabled()){
+ logger.debug("Executing reject rule for action-received = " + action+ " and in-progress-actions-inclusions =" + inProgressActionList.toString());
+ }
+ Set<String> inProgressActionSet = inProgressActionList.stream().map(VNFOperation::name).collect(Collectors.toSet());
+ inProgressActionSet.retainAll(inclusions.stream().map(VNFOperation::name).collect(Collectors.toList()));
+ if(!inProgressActionSet.isEmpty()){
+ return RuleResult.REJECT;
+ }
+ return RuleResult.ACCEPT;
+ }
+ else if(exclusions != null && !exclusions.isEmpty()){
+ /* new action (action-received) should be accepted,
+ if all of the in-progress request actions
+ are mentioned in the in-progress-exclusion list*/
+ if(logger.isDebugEnabled()){
+ logger.debug("Executing reject rule for action-received = " + action + " and in-progress-actions-inclusions = " + inProgressActionList.toString());
+ }
+ Set<String> inProgressActionSet = inProgressActionList.stream().map(VNFOperation::name).collect(Collectors.toSet());
+ inProgressActionSet.removeAll(exclusions.stream().map(VNFOperation::name).collect(Collectors.toList()));
+ if(inProgressActionSet.isEmpty()){
+ return RuleResult.ACCEPT;
+ }
+ return RuleResult.REJECT;
+ }
+ return RuleResult.REJECT;
+ }
+}
diff --git a/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/validationpolicy/rules/Rule.java b/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/validationpolicy/rules/Rule.java
new file mode 100644
index 000000000..abc46cc9a
--- /dev/null
+++ b/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/validationpolicy/rules/Rule.java
@@ -0,0 +1,51 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * ONAP : APPC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Copyright (C) 2017 Amdocs
+ * =============================================================================
+ * 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.
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.onap.appc.validationpolicy.rules;
+
+import com.att.eelf.configuration.EELFLogger;
+import com.att.eelf.configuration.EELFManager;
+import org.onap.appc.domainmodel.lcm.VNFOperation;
+import org.onap.appc.validationpolicy.objects.RuleResult;
+
+import java.util.List;
+import java.util.Set;
+
+/**
+ * Abstract implementation of request validation rule
+ */
+public abstract class Rule {
+
+ protected Set<VNFOperation> inclusions;
+ protected Set<VNFOperation> exclusions;
+
+ protected final EELFLogger logger = EELFManager.getInstance().getLogger(Rule.class);
+
+ Rule(Set<VNFOperation> inclusions,Set<VNFOperation> exclusions){
+ this.inclusions = inclusions;
+ this.exclusions = exclusions;
+ }
+
+ public abstract RuleResult executeRule(String action, List<VNFOperation> inProgressActionList);
+}
diff --git a/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/validationpolicy/rules/RuleFactory.java b/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/validationpolicy/rules/RuleFactory.java
new file mode 100644
index 000000000..a78dc571a
--- /dev/null
+++ b/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/validationpolicy/rules/RuleFactory.java
@@ -0,0 +1,47 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * ONAP : APPC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Copyright (C) 2017 Amdocs
+ * =============================================================================
+ * 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.
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.onap.appc.validationpolicy.rules;
+
+import org.onap.appc.domainmodel.lcm.VNFOperation;
+
+import java.util.Set;
+
+public class RuleFactory {
+
+ private RuleFactory(){
+
+ }
+
+ public static Rule createRule(String validationRule, Set<VNFOperation> inclusions, Set<VNFOperation> exclusions){
+ switch (validationRule) {
+ case "Accept":
+ return new AcceptRule(inclusions, exclusions);
+ case "Reject":
+ return new RejectRule(inclusions, exclusions);
+ default:
+ throw new RuntimeException("Rule not supported " + validationRule);
+ }
+ }
+}
diff --git a/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/workingstatemanager/WorkingStateManager.java b/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/workingstatemanager/WorkingStateManager.java
deleted file mode 100644
index 87fd685e9..000000000
--- a/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/workingstatemanager/WorkingStateManager.java
+++ /dev/null
@@ -1,50 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * ONAP : APPC
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Copyright (C) 2017 Amdocs
- * =============================================================================
- * 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.
- *
- * ECOMP is a trademark and service mark of AT&T Intellectual Property.
- * ============LICENSE_END=========================================================
- */
-
-package org.onap.appc.workingstatemanager;
-
-import org.onap.appc.workingstatemanager.objects.VNFWorkingState;
-
-
-public interface WorkingStateManager {
-
- /**
- * Return true if vnf state exists in working state map and state is STABLE else return false. If vnf does not exists in working state map throws vnf not found exception.
- * @param vnfId vnf Id to be verified for stable state
- * @return True if vnf Exists and state is STABLE else False.
- */
- public boolean isVNFStable(String vnfId);
-
- /**
- * Updates working state for given vnf Id. Returns true if update was allowed and succeeded. Update will success only if the existing vnf state is 'STABLE' or
- * if the registered ownerId is equal to the given ownerId or if the forceFlag is true.
- * Note on case of simultaneously updates the latest updates will be failed, and another attempts will be done after refetching the updated data from persistent store.
- * @param vnfId vnf Id to be updated
- * @param workingState new working state
- * @param ownerId
- * @param forceFlag - force to update also on case given onwerId is different then the registered one
- */
- public boolean setWorkingState(String vnfId, VNFWorkingState workingState, String ownerId, boolean forceFlag);
-
-}
diff --git a/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/workingstatemanager/impl/WorkingStateManagerImpl.java b/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/workingstatemanager/impl/WorkingStateManagerImpl.java
deleted file mode 100644
index a680c86a3..000000000
--- a/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/onap/appc/workingstatemanager/impl/WorkingStateManagerImpl.java
+++ /dev/null
@@ -1,230 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * ONAP : APPC
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Copyright (C) 2017 Amdocs
- * =============================================================================
- * 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.
- *
- * ECOMP is a trademark and service mark of AT&T Intellectual Property.
- * ============LICENSE_END=========================================================
- */
-
-package org.onap.appc.workingstatemanager.impl;
-
-import java.sql.Connection;
-import java.sql.PreparedStatement;
-import java.sql.ResultSet;
-import java.sql.SQLException;
-import java.util.Map;
-import java.util.concurrent.ConcurrentHashMap;
-
-import org.apache.commons.lang.ObjectUtils;
-import org.apache.commons.lang3.StringUtils;
-import org.onap.appc.configuration.ConfigurationFactory;
-import org.onap.appc.executor.objects.Params;
-import org.onap.appc.message.RequestHandlerMessages;
-import org.onap.appc.util.MessageFormatter;
-import org.onap.appc.workingstatemanager.objects.VNFWorkingState;
-import org.onap.appc.workingstatemanager.objects.VnfWorkingStateDto;
-import com.att.eelf.configuration.EELFLogger;
-import com.att.eelf.configuration.EELFManager;
-
-
-public class WorkingStateManagerImpl extends JdbcWorkingStateManager {
-
- private static final String SQL_RETRIEVE_VNF_STATE_MANAGEMENT = "SELECT VNF_ID,STATE,OWNER_ID,UPDATED,VER FROM VNF_STATE_MANAGEMENT WHERE VNF_ID=?";
- private static final String SQL_INSERT_VNF_STATE_MANAGEMENT = "INSERT IGNORE INTO VNF_STATE_MANAGEMENT (VNF_ID,STATE,OWNER_ID,UPDATED,VER) VALUES (?, ?, ?, ?, ?)";
- private static final String SQL_UPDATE_VNF_STATE_MANAGEMENT = "UPDATE VNF_STATE_MANAGEMENT SET OWNER_ID=?, UPDATED=?, STATE=?, VER=? WHERE VNF_ID=? AND VER=?";
- private static final String SQL_CURRENT_TIMESTAMP = "SELECT CURRENT_TIMESTAMP()";
- private static int maxAttempts = ConfigurationFactory.getConfiguration().getIntegerProperty("org.onap.appc.workingstatemanager.maxAttempts",20);
-
- private static Map<String,VNFWorkingState> workingStateMap = new ConcurrentHashMap<>();
- private static final EELFLogger logger = EELFManager.getInstance().getLogger(WorkingStateManagerImpl.class);
-
-
- /**
- * Return true if vnf state exists in working state map and state is STABLE else return false. If vnf does not exists in working state map throws vnf not found exception.
- * @param vnfId vnf Id to be verified for stable state
- * @return True if vnf Exists and state is STABLE else False.
- */
- @Override
- public boolean isVNFStable(String vnfId){
- if (logger.isTraceEnabled()) {
- logger.trace("Entering to isVNFStable with vnfId = "+ vnfId);
- }
- Connection connection = null;
- boolean vnfStable = false;
- try {
- connection = openDbConnection();
- VnfWorkingStateDto vnfWorkingStateDto = retrieveVnfWorkingState(connection, vnfId);
- vnfStable = isVNFStable(vnfWorkingStateDto);
- } catch (SQLException e) {
- String errMsg = StringUtils.isEmpty(e.getMessage())? e.toString() :e.getMessage();
- throw new RuntimeException(errMsg);
- } finally {
- if(connection != null) {
- closeDbConnection(connection);
- }
- }
- if (logger.isTraceEnabled()) {
- logger.trace("Exiting from isVNFStable for vnfId = "+ vnfId+" with Result = "+vnfStable);
- }
- return vnfStable;
- }
-
- /**
- * Updates working state for given vnf Id. Returns true if update was allowed and succeeded. Update will success only if the existing vnf state is 'STABLE' or
- * if the registered ownerId is equal to the given ownerId or if the forceFlag is true.
- * Note on case of simultaneously updates the latest updates will be failed, and another attempts will be done after refetching the updated data from persistent store.
- * @param vnfId vnf Id to be updated
- * @param workingState new working state
- * @param ownerId
- * @param forceFlag - force to update also on case given onwerId is different then the registered one
- */
- @Override
- public boolean setWorkingState(String vnfId, VNFWorkingState workingState, String ownerId, boolean forceFlag){
- boolean updated = false;
- if (logger.isTraceEnabled()) {
- logger.trace("Entering to setWorkingState with vnfId = "+ ObjectUtils.toString(vnfId)+ ", VNFWorkingState = " + workingState.name() + ", ownerId = "+ownerId+", forceFlag = "+forceFlag);
- }
- Connection connection = null;
- try {
- connection = openDbConnection();
- updated = setWorkingStateIfStableOrSameOwnerIdOrForce(connection, vnfId, workingState, ownerId, forceFlag, maxAttempts);
- } catch (SQLException e) {
- String errMsg = StringUtils.isEmpty(e.getMessage())? e.toString() :e.getMessage();
- throw new RuntimeException(errMsg);
- } finally {
- if(connection != null) {
- closeDbConnection(connection);
- }
- }
-
- logger.trace("setWorkingState exit with output updated = "+updated);
- return updated;
- }
-
- public boolean setWorkingStateIfStableOrSameOwnerIdOrForce(Connection connection, String vnfId, VNFWorkingState workingState, String ownerId, boolean forceFlag, int maxAttempts) throws SQLException {
- return setWorkingStateIfStableOrSameOwnerIdOrForce(connection, vnfId, workingState, ownerId, forceFlag,1,maxAttempts);
- }
- public boolean setWorkingStateIfStableOrSameOwnerIdOrForce(Connection connection, String vnfId, VNFWorkingState workingState, String ownerId, boolean forceFlag,int attempt, int maxAttempts) throws SQLException {
- boolean updated = false;
- VnfWorkingStateDto vnfWorkingStateDto = retrieveVnfWorkingState(connection, vnfId);
- Long currentVersion = vnfWorkingStateDto != null ? vnfWorkingStateDto.getVer() : null;
- if(forceFlag || isVNFStable(vnfWorkingStateDto) ||
- ( vnfWorkingStateDto != null && vnfWorkingStateDto.getOwnerId().equals(ownerId)) ) {
- updated = storeWorkingStateIfSameVersion(connection, vnfId, workingState, ownerId, currentVersion);
-
- Params params = new Params().addParam("vnfId", vnfId).addParam("workingState",workingState.name())
- .addParam("attempt",attempt).addParam("maxAttempts",maxAttempts).addParam("ownerId",ownerId).addParam("forceFlag",forceFlag);
- String logMessage;
- if(updated) {
- logMessage = MessageFormatter.format(RequestHandlerMessages.VNF_WORKING_STATE_UPDATED, params.getParams());
- }else {
- logMessage = MessageFormatter.format(RequestHandlerMessages.VNF_WORKING_STATE_WAS_NOT_UPDATED, params.getParams());
- }
- logger.debug(logMessage);
- if(!updated && attempt<maxAttempts){
- setWorkingStateIfStableOrSameOwnerIdOrForce(connection, vnfId, workingState, ownerId, forceFlag,++attempt,maxAttempts);
- }
-
- }
- return updated;
- }
-
-
- public boolean storeWorkingStateIfSameVersion(Connection connection, String vnfId, VNFWorkingState workingState, String ownerId, Long currentVersion) throws SQLException {
- boolean stored = false;
- if (currentVersion != null) {
- stored = updateStateIfSameVersion(connection, vnfId, ownerId, workingState.name(), currentVersion);
- } else {
- stored = addVnfWorkingStateIfNotExists(connection, vnfId, ownerId, workingState.name());
- }
-
- return stored;
- }
-
- private boolean isVNFStable(VnfWorkingStateDto vnfWorkingStateDto) {
- if( vnfWorkingStateDto == null || vnfWorkingStateDto.getState() ==VNFWorkingState.STABLE){
- return true;
- }
- return false;
- }
-
- public boolean updateStateIfSameVersion(Connection connection, String vnfId, String ownerId, String state, long currentVer) throws SQLException {
- try(PreparedStatement statement = connection.prepareStatement(SQL_UPDATE_VNF_STATE_MANAGEMENT)) {
- long newVer = (currentVer >= Long.MAX_VALUE) ? 1 : (currentVer + 1);
- statement.setString(1, ownerId);
- statement.setLong(2, getCurrentTime(connection));
- statement.setString(3, state);
- statement.setLong(4, newVer);
- statement.setString(5, vnfId);
- statement.setLong(6, currentVer);
- return (statement.executeUpdate() != 0);
- }
- }
-
- protected VnfWorkingStateDto retrieveVnfWorkingState(Connection connection, String vnfId) throws SQLException {
- VnfWorkingStateDto res = null;
-
- try(PreparedStatement statement = connection.prepareStatement(SQL_RETRIEVE_VNF_STATE_MANAGEMENT)) { //VNF_ID,STATE,OWNER_ID,UPDATED,VER
- statement.setString(1, vnfId);
- try(ResultSet resultSet = statement.executeQuery()) {
- if(resultSet.next()) {
- res = new VnfWorkingStateDto(vnfId);
- String stateString = resultSet.getString(2);
- VNFWorkingState vnfWorkingState = VNFWorkingState.valueOf(stateString);
- res.setState(vnfWorkingState);
- res.setOwnerId(resultSet.getString(3));
- res.setUpdated(resultSet.getLong(4));
- res.setVer(resultSet.getLong(5));
- }
- }
- }
- return res;
- }
-
- private long getCurrentTime(Connection connection) throws SQLException {
- long res = -1;
- if(connection != null) {
- try(PreparedStatement statement = connection.prepareStatement(SQL_CURRENT_TIMESTAMP)) {
- try(ResultSet resultSet = statement.executeQuery()) {
- if(resultSet.next()) {
- res = resultSet.getTimestamp(1).getTime();
- }
- }
- }
- }
- if(res == -1) {
- res = System.currentTimeMillis();
- }
- return res;
- }
-
- protected boolean addVnfWorkingStateIfNotExists(Connection connection, String vnfId, String ownerId, String state) throws SQLException {
- boolean added = false;
- try(PreparedStatement statement = connection.prepareStatement(SQL_INSERT_VNF_STATE_MANAGEMENT)) { //VNF_ID,STATE,OWNER_ID,UPDATED,VER
- statement.setString(1, vnfId);
- statement.setString(2, state);
- statement.setString(3, ownerId);
- statement.setLong(4, getCurrentTime(connection));
- statement.setLong(5, 1L);
- int rowCount = statement.executeUpdate();
- added = rowCount != 0 ? true : false;
- }
- return added;
- }
-}