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;
88 public ControlLoopEventManager getEventManager() {
92 public void setEventManager(ControlLoopEventManager eventManager) {
93 this.eventManager = eventManager;
98 // Internal class used for tracking
100 private class Operation {
101 public ControlLoopOperation operation = new ControlLoopOperation();
102 public PolicyResult policyResult = null;
103 public int attempt = 0;
106 public String toString() {
107 return "Operation [attempt=" + attempt + ", policyResult=" + policyResult + ", operation=" + operation
112 private String guardApprovalStatus = "NONE";//"NONE", "PERMIT", "DENY"
113 private transient Object operationRequest;
115 public Object getOperationRequest() {
116 return operationRequest;
119 public String getGuardApprovalStatus() {
120 return guardApprovalStatus;
122 public void setGuardApprovalStatus(String guardApprovalStatus) {
123 this.guardApprovalStatus = guardApprovalStatus;
127 public ControlLoopOperationManager(ControlLoopEvent onset, Policy policy, ControlLoopEventManager em) throws ControlLoopException {
129 this.policy = policy;
130 this.guardApprovalStatus = "NONE";
131 this.eventManager = em;
134 // Let's make a sanity check
136 switch (policy.getActor()) {
144 throw new ControlLoopException("ControlLoopEventManager: policy has an unknown actor.");
148 public Object startOperation(/*VirtualControlLoopEvent*/ControlLoopEvent onset) throws AAIException {
150 // They shouldn't call us if we currently running something
152 if (this.currentOperation != null) {
154 // what do we do if we are already running an operation?
159 // Check if we have maxed out on retries
161 if (this.policy.getRetry() == null || this.policy.getRetry() < 1) {
163 // No retries are allowed, so check have we even made
164 // one attempt to execute the operation?
166 if (this.attempts >= 1) {
168 // We have, let's ensure our PolicyResult is set
170 if (this.policyResult == null) {
171 this.policyResult = PolicyResult.FAILURE_RETRIES;
180 // Have we maxed out on retries?
182 if (this.attempts > this.policy.getRetry()) {
183 if (this.policyResult == null) {
184 this.policyResult = PolicyResult.FAILURE_RETRIES;
192 this.policyResult = null;
193 Operation operation = new Operation();
194 operation.attempt = ++this.attempts;
195 operation.operation.actor = this.policy.getActor();
196 operation.operation.operation = this.policy.getRecipe();
197 operation.operation.target = this.policy.getTarget().toString();
198 operation.operation.subRequestId = Integer.toString(operation.attempt);
200 // Now determine which actor we need to construct a request for
202 switch (policy.getActor()) {
205 * If the recipe is ModifyConfig, a legacy APPC
206 * request is constructed. Otherwise an LCMRequest
209 this.currentOperation = operation;
210 if ("ModifyConfig".equalsIgnoreCase(policy.getRecipe())) {
212 this.operationRequest = APPCActorServiceProvider.constructRequest((VirtualControlLoopEvent) onset,
213 operation.operation, this.policy, eventManager.getVnfResponse());
216 this.operationRequest = AppcLcmActorServiceProvider.constructRequest((VirtualControlLoopEvent) onset,
217 operation.operation, this.policy, eventManager.getVnfResponse());
220 // Save the operation
223 return operationRequest;
225 SOActorServiceProvider SOAsp = new SOActorServiceProvider();
226 this.operationRequest = SOAsp.constructRequest((VirtualControlLoopEvent)onset, operation.operation, this.policy);
228 // Save the operation
229 this.currentOperation = operation;
231 if (this.operationRequest == null) {
232 this.policyResult = PolicyResult.FAILURE;
235 return operationRequest;
237 this.operationRequest = VFCActorServiceProvider.constructRequest((VirtualControlLoopEvent) onset, operation.operation, this.policy, this.eventManager.getVnfResponse());
238 this.currentOperation = operation;
239 return operationRequest;
245 public PolicyResult onResponse(Object response) {
247 // Which response is it?
249 if (response instanceof Response) {
253 Response appcResponse = (Response) response;
255 // Determine which subrequestID (ie. attempt)
257 Integer operationAttempt = null;
259 operationAttempt = Integer.parseInt(appcResponse.CommonHeader.SubRequestID);
260 } catch (NumberFormatException e) {
262 // We cannot tell what happened if this doesn't exist
264 this.completeOperation(operationAttempt, "Policy was unable to parse APP-C SubRequestID (it was null).", PolicyResult.FAILURE_EXCEPTION);
265 return PolicyResult.FAILURE_EXCEPTION;
268 // Sanity check the response message
270 if (appcResponse.Status == null) {
272 // We cannot tell what happened if this doesn't exist
274 this.completeOperation(operationAttempt, "Policy was unable to parse APP-C response status field (it was null).", PolicyResult.FAILURE_EXCEPTION);
275 return PolicyResult.FAILURE_EXCEPTION;
278 // Get the Response Code
280 ResponseCode code = ResponseCode.toResponseCode(appcResponse.Status.Code);
283 // We are unaware of this code
285 this.completeOperation(operationAttempt, "Policy was unable to parse APP-C response status code field.", PolicyResult.FAILURE_EXCEPTION);
286 return PolicyResult.FAILURE_EXCEPTION;
289 // Ok, let's figure out what APP-C's response is
294 // This is good, they got our original message and
297 // Is there any need to track this?
303 // We'll consider these two codes as exceptions
305 this.completeOperation(operationAttempt, appcResponse.getStatus().Description, PolicyResult.FAILURE_EXCEPTION);
306 if (this.policyResult != null && this.policyResult.equals(PolicyResult.FAILURE_TIMEOUT)) {
309 return PolicyResult.FAILURE_EXCEPTION;
314 this.completeOperation(operationAttempt, appcResponse.getStatus().Description, PolicyResult.SUCCESS);
315 if (this.policyResult != null && this.policyResult.equals(PolicyResult.FAILURE_TIMEOUT)) {
318 return PolicyResult.SUCCESS;
323 this.completeOperation(operationAttempt, appcResponse.getStatus().Description, PolicyResult.FAILURE);
324 if (this.policyResult != null && this.policyResult.equals(PolicyResult.FAILURE_TIMEOUT)) {
327 return PolicyResult.FAILURE;
330 else if (response instanceof LCMResponseWrapper) {
332 LCMResponseWrapper dmaapResponse = (LCMResponseWrapper) response;
335 * Parse out the operation attempt using the subrequestid
337 Integer operationAttempt = AppcLcmActorServiceProvider.parseOperationAttempt(dmaapResponse.getBody().getCommonHeader().getSubRequestId());
338 if (operationAttempt == null) {
339 this.completeOperation(operationAttempt, "Policy was unable to parse APP-C SubRequestID (it was null).", PolicyResult.FAILURE_EXCEPTION);
343 * Process the APPCLCM response to see what PolicyResult
346 AbstractMap.SimpleEntry<PolicyResult, String> result = AppcLcmActorServiceProvider.processResponse(dmaapResponse);
348 if (result.getKey() != null) {
349 this.completeOperation(operationAttempt, result.getValue(), result.getKey());
350 if (PolicyResult.FAILURE_TIMEOUT.equals(this.policyResult)) {
353 return result.getKey();
356 } else if (response instanceof SOResponse) {
357 SOResponse msoResponse = (SOResponse) response;
359 switch (msoResponse.httpResponseCode) {
363 // Consider it as success
365 this.completeOperation(this.attempts, msoResponse.httpResponseCode + " Success", PolicyResult.SUCCESS);
366 if (this.policyResult != null && this.policyResult.equals(PolicyResult.FAILURE_TIMEOUT)) {
369 return PolicyResult.SUCCESS;
372 // Consider it as failure
374 this.completeOperation(this.attempts, msoResponse.httpResponseCode + " Failed", PolicyResult.FAILURE);
375 if (this.policyResult != null && this.policyResult.equals(PolicyResult.FAILURE_TIMEOUT)) {
378 return PolicyResult.FAILURE;
381 } else if (response instanceof VFCResponse) {
382 VFCResponse vfcResponse = (VFCResponse) response;
384 if (vfcResponse.responseDescriptor.getStatus().equalsIgnoreCase("finished")) {
386 // Consider it as success
388 this.completeOperation(this.attempts, " Success", PolicyResult.SUCCESS);
389 if (this.policyResult != null && this.policyResult.equals(PolicyResult.FAILURE_TIMEOUT)) {
392 return PolicyResult.SUCCESS;
395 // Consider it as failure
397 this.completeOperation(this.attempts, " Failed", PolicyResult.FAILURE);
398 if (this.policyResult != null && this.policyResult.equals(PolicyResult.FAILURE_TIMEOUT)) {
401 // increment operation attempts for retries
403 return PolicyResult.FAILURE;
409 public Integer getOperationTimeout() {
413 if (this.policy == null) {
414 logger.debug("getOperationTimeout returning 0");
417 logger.debug("getOperationTimeout returning {}", this.policy.getTimeout());
418 return this.policy.getTimeout();
421 public String getOperationTimeoutString(int defaultTimeout) {
422 Integer to = this.getOperationTimeout();
423 if (to == null || to == 0) {
424 return Integer.toString(defaultTimeout) + "s";
426 return to.toString() + "s";
429 public PolicyResult getOperationResult() {
430 return this.policyResult;
433 public String getOperationMessage() {
434 if (this.currentOperation != null && this.currentOperation.operation != null) {
435 return this.currentOperation.operation.toMessage();
438 if (!this.operationHistory.isEmpty()) {
439 return this.operationHistory.getLast().operation.toMessage();
444 public String getOperationMessage(String guardResult) {
445 if (this.currentOperation != null && this.currentOperation.operation != null) {
446 return this.currentOperation.operation.toMessage()+ ", Guard result: " + guardResult;
449 if (!this.operationHistory.isEmpty()) {
450 return this.operationHistory.getLast().operation.toMessage() + ", Guard result: " + guardResult;
455 public String getOperationHistory() {
456 if (this.currentOperation != null && this.currentOperation.operation != null) {
457 return this.currentOperation.operation.toHistory();
460 if (!this.operationHistory.isEmpty()) {
461 return this.operationHistory.getLast().operation.toHistory();
466 public LinkedList<ControlLoopOperation> getHistory() {
467 LinkedList<ControlLoopOperation> history = new LinkedList<ControlLoopOperation>();
468 for (Operation op : this.operationHistory) {
469 history.add(new ControlLoopOperation(op.operation));
475 public void setOperationHasTimedOut() {
479 this.completeOperation(this.attempts, "Operation timed out", PolicyResult.FAILURE_TIMEOUT);
482 public void setOperationHasGuardDeny() {
486 this.completeOperation(this.attempts, "Operation denied by Guard", PolicyResult.FAILURE_GUARD);
489 public void setOperationHasException(String message) {
490 this.completeOperation(this.attempts, message, PolicyResult.FAILURE_EXCEPTION);
493 public boolean isOperationComplete() {
495 // Is there currently a result?
497 if (this.policyResult == null) {
499 // either we are in process or we
505 // We have some result, check if the operation failed
507 if (this.policyResult.equals(PolicyResult.FAILURE)) {
509 // Check if there were no retries specified
511 if (policy.getRetry() == null || policy.getRetry() == 0) {
513 // The result is the failure
520 if (this.isRetriesMaxedOut()) {
522 // No more attempts allowed, reset
523 // that our actual result is failure due to retries
525 this.policyResult = PolicyResult.FAILURE_RETRIES;
529 // There are more attempts available to try the
536 // Other results mean we are done
541 public boolean isOperationRunning() {
542 return (this.currentOperation != null);
545 private boolean isRetriesMaxedOut() {
546 if (policy.getRetry() == null || policy.getRetry() == 0) {
548 // There were NO retries specified, so declare
549 // this as completed.
551 return (this.attempts > 0);
553 return (this.attempts > policy.getRetry());
556 private void storeOperationInDataBase(){
557 // Only store in DB if enabled
558 boolean guardEnabled = "false".equalsIgnoreCase(PolicyEngine.manager.getEnvironmentProperty("guard.disabled"));
565 Properties props = new Properties();
566 if(PolicyEngine.manager.getEnvironmentProperty(Util.ONAP_KEY_URL) != null &&
567 PolicyEngine.manager.getEnvironmentProperty(Util.ONAP_KEY_USER) != null &&
568 PolicyEngine.manager.getEnvironmentProperty(Util.ONAP_KEY_PASS) != null){
569 props.put(Util.ECLIPSE_LINK_KEY_URL, PolicyEngine.manager.getEnvironmentProperty(Util.ONAP_KEY_URL));
570 props.put(Util.ECLIPSE_LINK_KEY_USER, PolicyEngine.manager.getEnvironmentProperty(Util.ONAP_KEY_USER));
571 props.put(Util.ECLIPSE_LINK_KEY_PASS, PolicyEngine.manager.getEnvironmentProperty(Util.ONAP_KEY_PASS));
575 String OpsHistPU = System.getProperty("OperationsHistoryPU");
576 if(OpsHistPU == null || !OpsHistPU.equals("TestOperationsHistoryPU")){
577 OpsHistPU = "OperationsHistoryPU";
584 em = Persistence.createEntityManagerFactory(OpsHistPU, props).createEntityManager();
586 logger.error("storeOperationInDataBase threw: ", e);
590 OperationsHistoryDbEntry newEntry = new OperationsHistoryDbEntry();
592 newEntry.closedLoopName = this.onset.closedLoopControlName;
593 newEntry.requestId = this.onset.requestID.toString();
594 newEntry.actor = this.currentOperation.operation.actor;
595 newEntry.operation = this.currentOperation.operation.operation;
596 newEntry.target = this.eventManager.getTargetInstance(this.policy);
597 newEntry.starttime = Timestamp.from(this.currentOperation.operation.start);
598 newEntry.subrequestId = this.currentOperation.operation.subRequestId;
599 newEntry.endtime = new Timestamp(this.currentOperation.operation.end.toEpochMilli());
600 newEntry.message = this.currentOperation.operation.message;
601 newEntry.outcome = this.currentOperation.operation.outcome;
603 em.getTransaction().begin();
604 em.persist(newEntry);
605 em.getTransaction().commit();
613 private void completeOperation(Integer attempt, String message, PolicyResult result) {
614 if (attempt == null) {
615 logger.debug("attempt cannot be null (i.e. subRequestID)");
618 if (this.currentOperation != null) {
619 if (this.currentOperation.attempt == attempt.intValue()) {
620 this.currentOperation.operation.end = Instant.now();
621 this.currentOperation.operation.message = message;
622 this.currentOperation.operation.outcome = result.toString();
623 this.currentOperation.policyResult = result;
625 // Save it in history
627 this.operationHistory.add(this.currentOperation);
628 this.storeOperationInDataBase();
630 // Set our last result
632 this.policyResult = result;
634 // Clear the current operation field
636 this.currentOperation = null;
639 logger.debug("not current");
641 for (Operation op : this.operationHistory) {
642 if (op.attempt == attempt.intValue()) {
643 op.operation.end = Instant.now();
644 op.operation.message = message;
645 op.operation.outcome = result.toString();
646 op.policyResult = result;
650 logger.debug("Could not find associated operation");