2 * ============LICENSE_START=======================================================
3 * controlloop operation manager
4 * ================================================================================
5 * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
6 * ================================================================================
7 * Licensed under the Apache License, Version 2.0 (the "License");
8 * you may not use this file except in compliance with the License.
9 * You may obtain a copy of the License at
11 * http://www.apache.org/licenses/LICENSE-2.0
13 * Unless required by applicable law or agreed to in writing, software
14 * distributed under the License is distributed on an "AS IS" BASIS,
15 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 * See the License for the specific language governing permissions and
17 * limitations under the License.
18 * ============LICENSE_END=========================================================
21 package org.onap.policy.controlloop.eventmanager;
23 import java.io.Serializable;
24 import java.sql.Timestamp;
25 import java.time.Instant;
26 import java.util.AbstractMap;
27 import java.util.LinkedList;
28 import java.util.Properties;
30 import javax.persistence.EntityManager;
31 import javax.persistence.Persistence;
33 import org.onap.policy.aai.util.AAIException;
34 import org.onap.policy.appc.Response;
35 import org.onap.policy.appc.ResponseCode;
36 import org.onap.policy.appclcm.LCMResponseWrapper;
37 import org.onap.policy.controlloop.ControlLoopEvent;
38 import org.onap.policy.controlloop.ControlLoopException;
39 import org.onap.policy.controlloop.ControlLoopOperation;
40 import org.onap.policy.controlloop.VirtualControlLoopEvent;
41 import org.onap.policy.controlloop.actor.appc.APPCActorServiceProvider;
42 import org.onap.policy.controlloop.actor.appclcm.AppcLcmActorServiceProvider;
43 import org.onap.policy.controlloop.actor.so.SOActorServiceProvider;
44 import org.onap.policy.controlloop.actor.vfc.VFCActorServiceProvider;
45 import org.onap.policy.controlloop.policy.Policy;
46 import org.onap.policy.controlloop.policy.PolicyResult;
47 import org.onap.policy.drools.system.PolicyEngine;
48 import org.onap.policy.guard.Util;
49 import org.onap.policy.so.SOResponse;
50 import org.onap.policy.vfc.VFCResponse;
51 import org.slf4j.Logger;
52 import org.slf4j.LoggerFactory;
54 public class ControlLoopOperationManager implements Serializable {
59 private static final long serialVersionUID = -3773199283624595410L;
60 private static final Logger logger = LoggerFactory.getLogger(ControlLoopOperationManager.class);
63 public String toString() {
64 return "ControlLoopOperationManager [onset=" + (onset != null ? onset.requestID : "null") + ", policy="
65 + (policy != null ? policy.getId() : "null") + ", attempts=" + attempts
66 + ", policyResult=" + policyResult
67 + ", currentOperation=" + currentOperation + ", operationHistory=" + operationHistory
72 // These properties are not changeable, but accessible
73 // for Drools Rule statements.
75 //public final ATTControlLoopEvent onset;
76 public final ControlLoopEvent onset;
77 public final transient Policy policy;
80 // Properties used to track the Operation
82 private int attempts = 0;
83 private transient Operation currentOperation = null;
84 private LinkedList<Operation> operationHistory = new LinkedList<Operation>();
85 private PolicyResult policyResult = null;
86 private ControlLoopEventManager eventManager = null;
87 private String targetEntity;
89 public ControlLoopEventManager getEventManager() {
93 public void setEventManager(ControlLoopEventManager eventManager) {
94 this.eventManager = eventManager;
97 public String getTargetEntity() {
98 return this.targetEntity;
102 // Internal class used for tracking
104 private class Operation {
105 public ControlLoopOperation operation = new ControlLoopOperation();
106 public PolicyResult policyResult = null;
107 public int attempt = 0;
110 public String toString() {
111 return "Operation [attempt=" + attempt + ", policyResult=" + policyResult + ", operation=" + operation
116 private String guardApprovalStatus = "NONE";//"NONE", "PERMIT", "DENY"
117 private transient Object operationRequest;
119 public Object getOperationRequest() {
120 return operationRequest;
123 public String getGuardApprovalStatus() {
124 return guardApprovalStatus;
126 public void setGuardApprovalStatus(String guardApprovalStatus) {
127 this.guardApprovalStatus = guardApprovalStatus;
130 public String getTarget(Policy policy) throws ControlLoopException, AAIException {
131 if (policy.getTarget() != null) {
132 if (policy.getTarget().getType() != null) {
133 switch(policy.getTarget().getType()) {
138 VirtualControlLoopEvent virtualOnset = (VirtualControlLoopEvent) this.onset;
139 if (this.onset.target.equalsIgnoreCase("vserver.vserver-name")) {
140 return virtualOnset.AAI.get("vserver.vserver-name");
142 else if (this.onset.target.equalsIgnoreCase("generic-vnf.vnf-id")) {
143 return virtualOnset.AAI.get("generic-vnf.vnf-id");
145 else if (this.onset.target.equalsIgnoreCase("generic-vnf.vnf-name")) {
147 * If the vnf-name was retrieved from the onset then the vnf-id
148 * must be obtained from the event manager's A&AI GET query
150 String vnfId = this.eventManager.getVnfResponse().vnfID;
152 throw new AAIException("No vnf-id found");
158 throw new ControlLoopException("The target type is not supported");
162 throw new ControlLoopException("The target type is null");
166 throw new ControlLoopException("The target is null");
171 public ControlLoopOperationManager(ControlLoopEvent onset, Policy policy, ControlLoopEventManager em) throws ControlLoopException, AAIException {
173 this.policy = policy;
174 this.guardApprovalStatus = "NONE";
175 this.eventManager = em;
176 this.targetEntity = getTarget(policy);
179 // Let's make a sanity check
181 switch (policy.getActor()) {
183 if ("ModifyConfig".equalsIgnoreCase(policy.getRecipe())) {
185 * The target vnf-id may not be the same as the source vnf-id
186 * specified in the yaml, the target vnf-id is retrieved by
187 * a named query to A&AI.
189 String targetVnf = AppcLcmActorServiceProvider.vnfNamedQuery(
190 policy.getTarget().getResourceID(), this.targetEntity);
191 this.targetEntity = targetVnf;
199 throw new ControlLoopException("ControlLoopEventManager: policy has an unknown actor.");
203 public Object startOperation(/*VirtualControlLoopEvent*/ControlLoopEvent onset) throws AAIException {
205 // They shouldn't call us if we currently running something
207 if (this.currentOperation != null) {
209 // what do we do if we are already running an operation?
214 // Check if we have maxed out on retries
216 if (this.policy.getRetry() == null || this.policy.getRetry() < 1) {
218 // No retries are allowed, so check have we even made
219 // one attempt to execute the operation?
221 if (this.attempts >= 1) {
223 // We have, let's ensure our PolicyResult is set
225 if (this.policyResult == null) {
226 this.policyResult = PolicyResult.FAILURE_RETRIES;
235 // Have we maxed out on retries?
237 if (this.attempts > this.policy.getRetry()) {
238 if (this.policyResult == null) {
239 this.policyResult = PolicyResult.FAILURE_RETRIES;
247 this.policyResult = null;
248 Operation operation = new Operation();
249 operation.attempt = ++this.attempts;
250 operation.operation.actor = this.policy.getActor();
251 operation.operation.operation = this.policy.getRecipe();
252 operation.operation.target = this.policy.getTarget().toString();
253 operation.operation.subRequestId = Integer.toString(operation.attempt);
255 // Now determine which actor we need to construct a request for
257 switch (policy.getActor()) {
260 * If the recipe is ModifyConfig, a legacy APPC
261 * request is constructed. Otherwise an LCMRequest
264 this.currentOperation = operation;
265 if ("ModifyConfig".equalsIgnoreCase(policy.getRecipe())) {
267 this.operationRequest = APPCActorServiceProvider.constructRequest((VirtualControlLoopEvent) onset,
268 operation.operation, this.policy, this.targetEntity);
271 this.operationRequest = AppcLcmActorServiceProvider.constructRequest((VirtualControlLoopEvent) onset,
272 operation.operation, this.policy, this.targetEntity);
275 // Save the operation
278 return operationRequest;
280 SOActorServiceProvider SOAsp = new SOActorServiceProvider();
281 this.operationRequest = SOAsp.constructRequest((VirtualControlLoopEvent)onset, operation.operation, this.policy);
283 // Save the operation
284 this.currentOperation = operation;
286 if (this.operationRequest == null) {
287 this.policyResult = PolicyResult.FAILURE;
290 return operationRequest;
292 this.operationRequest = VFCActorServiceProvider.constructRequest((VirtualControlLoopEvent) onset, operation.operation, this.policy, this.eventManager.getVnfResponse());
293 this.currentOperation = operation;
294 return operationRequest;
300 public PolicyResult onResponse(Object response) {
302 // Which response is it?
304 if (response instanceof Response) {
308 Response appcResponse = (Response) response;
310 // Determine which subrequestID (ie. attempt)
312 Integer operationAttempt = null;
314 operationAttempt = Integer.parseInt(appcResponse.CommonHeader.SubRequestID);
315 } catch (NumberFormatException e) {
317 // We cannot tell what happened if this doesn't exist
319 this.completeOperation(operationAttempt, "Policy was unable to parse APP-C SubRequestID (it was null).", PolicyResult.FAILURE_EXCEPTION);
320 return PolicyResult.FAILURE_EXCEPTION;
323 // Sanity check the response message
325 if (appcResponse.Status == null) {
327 // We cannot tell what happened if this doesn't exist
329 this.completeOperation(operationAttempt, "Policy was unable to parse APP-C response status field (it was null).", PolicyResult.FAILURE_EXCEPTION);
330 return PolicyResult.FAILURE_EXCEPTION;
333 // Get the Response Code
335 ResponseCode code = ResponseCode.toResponseCode(appcResponse.Status.Code);
338 // We are unaware of this code
340 this.completeOperation(operationAttempt, "Policy was unable to parse APP-C response status code field.", PolicyResult.FAILURE_EXCEPTION);
341 return PolicyResult.FAILURE_EXCEPTION;
344 // Ok, let's figure out what APP-C's response is
349 // This is good, they got our original message and
352 // Is there any need to track this?
358 // We'll consider these two codes as exceptions
360 this.completeOperation(operationAttempt, appcResponse.getStatus().Description, PolicyResult.FAILURE_EXCEPTION);
361 if (this.policyResult != null && this.policyResult.equals(PolicyResult.FAILURE_TIMEOUT)) {
364 return PolicyResult.FAILURE_EXCEPTION;
369 this.completeOperation(operationAttempt, appcResponse.getStatus().Description, PolicyResult.SUCCESS);
370 if (this.policyResult != null && this.policyResult.equals(PolicyResult.FAILURE_TIMEOUT)) {
373 return PolicyResult.SUCCESS;
378 this.completeOperation(operationAttempt, appcResponse.getStatus().Description, PolicyResult.FAILURE);
379 if (this.policyResult != null && this.policyResult.equals(PolicyResult.FAILURE_TIMEOUT)) {
382 return PolicyResult.FAILURE;
385 else if (response instanceof LCMResponseWrapper) {
387 LCMResponseWrapper dmaapResponse = (LCMResponseWrapper) response;
390 * Parse out the operation attempt using the subrequestid
392 Integer operationAttempt = AppcLcmActorServiceProvider.parseOperationAttempt(dmaapResponse.getBody().getCommonHeader().getSubRequestId());
393 if (operationAttempt == null) {
394 this.completeOperation(operationAttempt, "Policy was unable to parse APP-C SubRequestID (it was null).", PolicyResult.FAILURE_EXCEPTION);
398 * Process the APPCLCM response to see what PolicyResult
401 AbstractMap.SimpleEntry<PolicyResult, String> result = AppcLcmActorServiceProvider.processResponse(dmaapResponse);
403 if (result.getKey() != null) {
404 this.completeOperation(operationAttempt, result.getValue(), result.getKey());
405 if (PolicyResult.FAILURE_TIMEOUT.equals(this.policyResult)) {
408 return result.getKey();
411 } else if (response instanceof SOResponse) {
412 SOResponse msoResponse = (SOResponse) response;
414 switch (msoResponse.httpResponseCode) {
418 // Consider it as success
420 this.completeOperation(this.attempts, msoResponse.httpResponseCode + " Success", PolicyResult.SUCCESS);
421 if (this.policyResult != null && this.policyResult.equals(PolicyResult.FAILURE_TIMEOUT)) {
424 return PolicyResult.SUCCESS;
427 // Consider it as failure
429 this.completeOperation(this.attempts, msoResponse.httpResponseCode + " Failed", PolicyResult.FAILURE);
430 if (this.policyResult != null && this.policyResult.equals(PolicyResult.FAILURE_TIMEOUT)) {
433 return PolicyResult.FAILURE;
436 } else if (response instanceof VFCResponse) {
437 VFCResponse vfcResponse = (VFCResponse) response;
439 if (vfcResponse.responseDescriptor.getStatus().equalsIgnoreCase("finished")) {
441 // Consider it as success
443 this.completeOperation(this.attempts, " Success", PolicyResult.SUCCESS);
444 if (this.policyResult != null && this.policyResult.equals(PolicyResult.FAILURE_TIMEOUT)) {
447 return PolicyResult.SUCCESS;
450 // Consider it as failure
452 this.completeOperation(this.attempts, " Failed", PolicyResult.FAILURE);
453 if (this.policyResult != null && this.policyResult.equals(PolicyResult.FAILURE_TIMEOUT)) {
456 // increment operation attempts for retries
458 return PolicyResult.FAILURE;
464 public Integer getOperationTimeout() {
468 if (this.policy == null) {
469 logger.debug("getOperationTimeout returning 0");
472 logger.debug("getOperationTimeout returning {}", this.policy.getTimeout());
473 return this.policy.getTimeout();
476 public String getOperationTimeoutString(int defaultTimeout) {
477 Integer to = this.getOperationTimeout();
478 if (to == null || to == 0) {
479 return Integer.toString(defaultTimeout) + "s";
481 return to.toString() + "s";
484 public PolicyResult getOperationResult() {
485 return this.policyResult;
488 public String getOperationMessage() {
489 if (this.currentOperation != null && this.currentOperation.operation != null) {
490 return this.currentOperation.operation.toMessage();
493 if (!this.operationHistory.isEmpty()) {
494 return this.operationHistory.getLast().operation.toMessage();
499 public String getOperationMessage(String guardResult) {
500 if (this.currentOperation != null && this.currentOperation.operation != null) {
501 return this.currentOperation.operation.toMessage()+ ", Guard result: " + guardResult;
504 if (!this.operationHistory.isEmpty()) {
505 return this.operationHistory.getLast().operation.toMessage() + ", Guard result: " + guardResult;
510 public String getOperationHistory() {
511 if (this.currentOperation != null && this.currentOperation.operation != null) {
512 return this.currentOperation.operation.toHistory();
515 if (!this.operationHistory.isEmpty()) {
516 return this.operationHistory.getLast().operation.toHistory();
521 public LinkedList<ControlLoopOperation> getHistory() {
522 LinkedList<ControlLoopOperation> history = new LinkedList<ControlLoopOperation>();
523 for (Operation op : this.operationHistory) {
524 history.add(new ControlLoopOperation(op.operation));
530 public void setOperationHasTimedOut() {
534 this.completeOperation(this.attempts, "Operation timed out", PolicyResult.FAILURE_TIMEOUT);
537 public void setOperationHasGuardDeny() {
541 this.completeOperation(this.attempts, "Operation denied by Guard", PolicyResult.FAILURE_GUARD);
544 public void setOperationHasException(String message) {
545 this.completeOperation(this.attempts, message, PolicyResult.FAILURE_EXCEPTION);
548 public boolean isOperationComplete() {
550 // Is there currently a result?
552 if (this.policyResult == null) {
554 // either we are in process or we
560 // We have some result, check if the operation failed
562 if (this.policyResult.equals(PolicyResult.FAILURE)) {
564 // Check if there were no retries specified
566 if (policy.getRetry() == null || policy.getRetry() == 0) {
568 // The result is the failure
575 if (this.isRetriesMaxedOut()) {
577 // No more attempts allowed, reset
578 // that our actual result is failure due to retries
580 this.policyResult = PolicyResult.FAILURE_RETRIES;
584 // There are more attempts available to try the
591 // Other results mean we are done
596 public boolean isOperationRunning() {
597 return (this.currentOperation != null);
600 private boolean isRetriesMaxedOut() {
601 if (policy.getRetry() == null || policy.getRetry() == 0) {
603 // There were NO retries specified, so declare
604 // this as completed.
606 return (this.attempts > 0);
608 return (this.attempts > policy.getRetry());
611 private void storeOperationInDataBase(){
612 // Only store in DB if enabled
613 boolean guardEnabled = "false".equalsIgnoreCase(PolicyEngine.manager.getEnvironmentProperty("guard.disabled"));
620 Properties props = new Properties();
621 if(PolicyEngine.manager.getEnvironmentProperty(Util.ONAP_KEY_URL) != null &&
622 PolicyEngine.manager.getEnvironmentProperty(Util.ONAP_KEY_USER) != null &&
623 PolicyEngine.manager.getEnvironmentProperty(Util.ONAP_KEY_PASS) != null){
624 props.put(Util.ECLIPSE_LINK_KEY_URL, PolicyEngine.manager.getEnvironmentProperty(Util.ONAP_KEY_URL));
625 props.put(Util.ECLIPSE_LINK_KEY_USER, PolicyEngine.manager.getEnvironmentProperty(Util.ONAP_KEY_USER));
626 props.put(Util.ECLIPSE_LINK_KEY_PASS, PolicyEngine.manager.getEnvironmentProperty(Util.ONAP_KEY_PASS));
630 String OpsHistPU = System.getProperty("OperationsHistoryPU");
631 if(OpsHistPU == null || !OpsHistPU.equals("TestOperationsHistoryPU")){
632 OpsHistPU = "OperationsHistoryPU";
639 em = Persistence.createEntityManagerFactory(OpsHistPU, props).createEntityManager();
641 logger.error("storeOperationInDataBase threw: ", e);
645 OperationsHistoryDbEntry newEntry = new OperationsHistoryDbEntry();
647 newEntry.closedLoopName = this.onset.closedLoopControlName;
648 newEntry.requestId = this.onset.requestID.toString();
649 newEntry.actor = this.currentOperation.operation.actor;
650 newEntry.operation = this.currentOperation.operation.operation;
651 newEntry.target = this.targetEntity;
652 newEntry.starttime = Timestamp.from(this.currentOperation.operation.start);
653 newEntry.subrequestId = this.currentOperation.operation.subRequestId;
654 newEntry.endtime = new Timestamp(this.currentOperation.operation.end.toEpochMilli());
655 newEntry.message = this.currentOperation.operation.message;
656 newEntry.outcome = this.currentOperation.operation.outcome;
658 em.getTransaction().begin();
659 em.persist(newEntry);
660 em.getTransaction().commit();
668 private void completeOperation(Integer attempt, String message, PolicyResult result) {
669 if (attempt == null) {
670 logger.debug("attempt cannot be null (i.e. subRequestID)");
673 if (this.currentOperation != null) {
674 if (this.currentOperation.attempt == attempt.intValue()) {
675 this.currentOperation.operation.end = Instant.now();
676 this.currentOperation.operation.message = message;
677 this.currentOperation.operation.outcome = result.toString();
678 this.currentOperation.policyResult = result;
680 // Save it in history
682 this.operationHistory.add(this.currentOperation);
683 this.storeOperationInDataBase();
685 // Set our last result
687 this.policyResult = result;
689 // Clear the current operation field
691 this.currentOperation = null;
694 logger.debug("not current");
696 for (Operation op : this.operationHistory) {
697 if (op.attempt == attempt.intValue()) {
698 op.operation.end = Instant.now();
699 op.operation.message = message;
700 op.operation.outcome = result.toString();
701 op.policyResult = result;
705 logger.debug("Could not find associated operation");