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");
168 throw new ControlLoopException("Target does not match target type");
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 if (this.operationRequest == null) {
295 this.policyResult = PolicyResult.FAILURE;
297 return operationRequest;
303 public PolicyResult onResponse(Object response) {
305 // Which response is it?
307 if (response instanceof Response) {
311 Response appcResponse = (Response) response;
313 // Determine which subrequestID (ie. attempt)
315 Integer operationAttempt = null;
317 operationAttempt = Integer.parseInt(appcResponse.CommonHeader.SubRequestID);
318 } catch (NumberFormatException e) {
320 // We cannot tell what happened if this doesn't exist
322 this.completeOperation(operationAttempt, "Policy was unable to parse APP-C SubRequestID (it was null).", PolicyResult.FAILURE_EXCEPTION);
323 return PolicyResult.FAILURE_EXCEPTION;
326 // Sanity check the response message
328 if (appcResponse.Status == null) {
330 // We cannot tell what happened if this doesn't exist
332 this.completeOperation(operationAttempt, "Policy was unable to parse APP-C response status field (it was null).", PolicyResult.FAILURE_EXCEPTION);
333 return PolicyResult.FAILURE_EXCEPTION;
336 // Get the Response Code
338 ResponseCode code = ResponseCode.toResponseCode(appcResponse.Status.Code);
341 // We are unaware of this code
343 this.completeOperation(operationAttempt, "Policy was unable to parse APP-C response status code field.", PolicyResult.FAILURE_EXCEPTION);
344 return PolicyResult.FAILURE_EXCEPTION;
347 // Ok, let's figure out what APP-C's response is
352 // This is good, they got our original message and
355 // Is there any need to track this?
361 // We'll consider these two codes as exceptions
363 this.completeOperation(operationAttempt, appcResponse.getStatus().Description, PolicyResult.FAILURE_EXCEPTION);
364 if (this.policyResult != null && this.policyResult.equals(PolicyResult.FAILURE_TIMEOUT)) {
367 return PolicyResult.FAILURE_EXCEPTION;
372 this.completeOperation(operationAttempt, appcResponse.getStatus().Description, PolicyResult.SUCCESS);
373 if (this.policyResult != null && this.policyResult.equals(PolicyResult.FAILURE_TIMEOUT)) {
376 return PolicyResult.SUCCESS;
381 this.completeOperation(operationAttempt, appcResponse.getStatus().Description, PolicyResult.FAILURE);
382 if (this.policyResult != null && this.policyResult.equals(PolicyResult.FAILURE_TIMEOUT)) {
385 return PolicyResult.FAILURE;
388 else if (response instanceof LCMResponseWrapper) {
390 LCMResponseWrapper dmaapResponse = (LCMResponseWrapper) response;
393 * Parse out the operation attempt using the subrequestid
395 Integer operationAttempt = AppcLcmActorServiceProvider.parseOperationAttempt(dmaapResponse.getBody().getCommonHeader().getSubRequestId());
396 if (operationAttempt == null) {
397 this.completeOperation(operationAttempt, "Policy was unable to parse APP-C SubRequestID (it was null).", PolicyResult.FAILURE_EXCEPTION);
401 * Process the APPCLCM response to see what PolicyResult
404 AbstractMap.SimpleEntry<PolicyResult, String> result = AppcLcmActorServiceProvider.processResponse(dmaapResponse);
406 if (result.getKey() != null) {
407 this.completeOperation(operationAttempt, result.getValue(), result.getKey());
408 if (PolicyResult.FAILURE_TIMEOUT.equals(this.policyResult)) {
411 return result.getKey();
414 } else if (response instanceof SOResponse) {
415 SOResponse msoResponse = (SOResponse) response;
417 switch (msoResponse.httpResponseCode) {
421 // Consider it as success
423 this.completeOperation(this.attempts, msoResponse.httpResponseCode + " Success", PolicyResult.SUCCESS);
424 if (this.policyResult != null && this.policyResult.equals(PolicyResult.FAILURE_TIMEOUT)) {
427 return PolicyResult.SUCCESS;
430 // Consider it as failure
432 this.completeOperation(this.attempts, msoResponse.httpResponseCode + " Failed", PolicyResult.FAILURE);
433 if (this.policyResult != null && this.policyResult.equals(PolicyResult.FAILURE_TIMEOUT)) {
436 return PolicyResult.FAILURE;
439 } else if (response instanceof VFCResponse) {
440 VFCResponse vfcResponse = (VFCResponse) response;
442 if (vfcResponse.responseDescriptor.getStatus().equalsIgnoreCase("finished")) {
444 // Consider it as success
446 this.completeOperation(this.attempts, " Success", PolicyResult.SUCCESS);
447 if (this.policyResult != null && this.policyResult.equals(PolicyResult.FAILURE_TIMEOUT)) {
450 return PolicyResult.SUCCESS;
453 // Consider it as failure
455 this.completeOperation(this.attempts, " Failed", PolicyResult.FAILURE);
456 if (this.policyResult != null && this.policyResult.equals(PolicyResult.FAILURE_TIMEOUT)) {
459 // increment operation attempts for retries
461 return PolicyResult.FAILURE;
467 public Integer getOperationTimeout() {
471 if (this.policy == null) {
472 logger.debug("getOperationTimeout returning 0");
475 logger.debug("getOperationTimeout returning {}", this.policy.getTimeout());
476 return this.policy.getTimeout();
479 public String getOperationTimeoutString(int defaultTimeout) {
480 Integer to = this.getOperationTimeout();
481 if (to == null || to == 0) {
482 return Integer.toString(defaultTimeout) + "s";
484 return to.toString() + "s";
487 public PolicyResult getOperationResult() {
488 return this.policyResult;
491 public String getOperationMessage() {
492 if (this.currentOperation != null && this.currentOperation.operation != null) {
493 return this.currentOperation.operation.toMessage();
496 if (!this.operationHistory.isEmpty()) {
497 return this.operationHistory.getLast().operation.toMessage();
502 public String getOperationMessage(String guardResult) {
503 if (this.currentOperation != null && this.currentOperation.operation != null) {
504 return this.currentOperation.operation.toMessage()+ ", Guard result: " + guardResult;
507 if (!this.operationHistory.isEmpty()) {
508 return this.operationHistory.getLast().operation.toMessage() + ", Guard result: " + guardResult;
513 public String getOperationHistory() {
514 if (this.currentOperation != null && this.currentOperation.operation != null) {
515 return this.currentOperation.operation.toHistory();
518 if (!this.operationHistory.isEmpty()) {
519 return this.operationHistory.getLast().operation.toHistory();
524 public LinkedList<ControlLoopOperation> getHistory() {
525 LinkedList<ControlLoopOperation> history = new LinkedList<ControlLoopOperation>();
526 for (Operation op : this.operationHistory) {
527 history.add(new ControlLoopOperation(op.operation));
533 public void setOperationHasTimedOut() {
537 this.completeOperation(this.attempts, "Operation timed out", PolicyResult.FAILURE_TIMEOUT);
540 public void setOperationHasGuardDeny() {
544 this.completeOperation(this.attempts, "Operation denied by Guard", PolicyResult.FAILURE_GUARD);
547 public void setOperationHasException(String message) {
548 this.completeOperation(this.attempts, message, PolicyResult.FAILURE_EXCEPTION);
551 public boolean isOperationComplete() {
553 // Is there currently a result?
555 if (this.policyResult == null) {
557 // either we are in process or we
563 // We have some result, check if the operation failed
565 if (this.policyResult.equals(PolicyResult.FAILURE)) {
567 // Check if there were no retries specified
569 if (policy.getRetry() == null || policy.getRetry() == 0) {
571 // The result is the failure
578 if (this.isRetriesMaxedOut()) {
580 // No more attempts allowed, reset
581 // that our actual result is failure due to retries
583 this.policyResult = PolicyResult.FAILURE_RETRIES;
587 // There are more attempts available to try the
594 // Other results mean we are done
599 public boolean isOperationRunning() {
600 return (this.currentOperation != null);
603 private boolean isRetriesMaxedOut() {
604 if (policy.getRetry() == null || policy.getRetry() == 0) {
606 // There were NO retries specified, so declare
607 // this as completed.
609 return (this.attempts > 0);
611 return (this.attempts > policy.getRetry());
614 private void storeOperationInDataBase(){
615 // Only store in DB if enabled
616 boolean guardEnabled = "false".equalsIgnoreCase(PolicyEngine.manager.getEnvironmentProperty("guard.disabled"));
623 Properties props = new Properties();
624 if(PolicyEngine.manager.getEnvironmentProperty(Util.ONAP_KEY_URL) != null &&
625 PolicyEngine.manager.getEnvironmentProperty(Util.ONAP_KEY_USER) != null &&
626 PolicyEngine.manager.getEnvironmentProperty(Util.ONAP_KEY_PASS) != null){
627 props.put(Util.ECLIPSE_LINK_KEY_URL, PolicyEngine.manager.getEnvironmentProperty(Util.ONAP_KEY_URL));
628 props.put(Util.ECLIPSE_LINK_KEY_USER, PolicyEngine.manager.getEnvironmentProperty(Util.ONAP_KEY_USER));
629 props.put(Util.ECLIPSE_LINK_KEY_PASS, PolicyEngine.manager.getEnvironmentProperty(Util.ONAP_KEY_PASS));
633 String OpsHistPU = System.getProperty("OperationsHistoryPU");
634 if(OpsHistPU == null || !OpsHistPU.equals("TestOperationsHistoryPU")){
635 OpsHistPU = "OperationsHistoryPU";
642 em = Persistence.createEntityManagerFactory(OpsHistPU, props).createEntityManager();
644 logger.error("storeOperationInDataBase threw: ", e);
648 OperationsHistoryDbEntry newEntry = new OperationsHistoryDbEntry();
650 newEntry.closedLoopName = this.onset.closedLoopControlName;
651 newEntry.requestId = this.onset.requestID.toString();
652 newEntry.actor = this.currentOperation.operation.actor;
653 newEntry.operation = this.currentOperation.operation.operation;
654 newEntry.target = this.targetEntity;
655 newEntry.starttime = Timestamp.from(this.currentOperation.operation.start);
656 newEntry.subrequestId = this.currentOperation.operation.subRequestId;
657 newEntry.endtime = new Timestamp(this.currentOperation.operation.end.toEpochMilli());
658 newEntry.message = this.currentOperation.operation.message;
659 newEntry.outcome = this.currentOperation.operation.outcome;
661 em.getTransaction().begin();
662 em.persist(newEntry);
663 em.getTransaction().commit();
671 private void completeOperation(Integer attempt, String message, PolicyResult result) {
672 if (attempt == null) {
673 logger.debug("attempt cannot be null (i.e. subRequestID)");
676 if (this.currentOperation != null) {
677 if (this.currentOperation.attempt == attempt.intValue()) {
678 this.currentOperation.operation.end = Instant.now();
679 this.currentOperation.operation.message = message;
680 this.currentOperation.operation.outcome = result.toString();
681 this.currentOperation.policyResult = result;
683 // Save it in history
685 this.operationHistory.add(this.currentOperation);
686 this.storeOperationInDataBase();
688 // Set our last result
690 this.policyResult = result;
692 // Clear the current operation field
694 this.currentOperation = null;
697 logger.debug("not current");
699 for (Operation op : this.operationHistory) {
700 if (op.attempt == attempt.intValue()) {
701 op.operation.end = Instant.now();
702 op.operation.message = message;
703 op.operation.outcome = result.toString();
704 op.policyResult = result;
708 logger.debug("Could not find associated operation");