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.InputStream;
24 import java.io.Serializable;
25 import java.sql.Timestamp;
26 import java.time.Instant;
27 import java.util.AbstractMap;
28 import java.util.LinkedList;
29 import java.util.Properties;
31 import javax.persistence.EntityManager;
32 import javax.persistence.Persistence;
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.vfc.VFCActorServiceProvider;
44 import org.onap.policy.controlloop.policy.Policy;
45 import org.onap.policy.controlloop.policy.PolicyResult;
46 import org.onap.policy.controlloop.actor.so.SOActorServiceProvider;
47 import org.onap.policy.drools.system.PolicyEngine;
48 import org.onap.policy.so.SOResponse;
49 import org.onap.policy.vfc.VFCResponse;
50 import org.slf4j.Logger;
51 import org.slf4j.LoggerFactory;
53 public class ControlLoopOperationManager implements Serializable {
58 private static final long serialVersionUID = -3773199283624595410L;
59 private static final Logger logger = LoggerFactory.getLogger(ControlLoopOperationManager.class);
62 public String toString() {
63 return "ControlLoopOperationManager [onset=" + (onset != null ? onset.requestID : "null") + ", policy="
64 + (policy != null ? policy.getId() : "null") + ", attempts=" + attempts
65 + ", policyResult=" + policyResult
66 + ", currentOperation=" + currentOperation + ", operationHistory=" + operationHistory
71 // These properties are not changeable, but accessible
72 // for Drools Rule statements.
74 //public final ATTControlLoopEvent onset;
75 public final ControlLoopEvent onset;
76 public final transient Policy policy;
79 // Properties used to track the Operation
81 private int attempts = 0;
82 private transient Operation currentOperation = null;
83 private LinkedList<Operation> operationHistory = new LinkedList<Operation>();
84 private PolicyResult policyResult = null;
85 private ControlLoopEventManager eventManager = null;
87 public ControlLoopEventManager getEventManager() {
91 public void setEventManager(ControlLoopEventManager eventManager) {
92 this.eventManager = eventManager;
97 // Internal class used for tracking
99 private class Operation {
100 public ControlLoopOperation operation = new ControlLoopOperation();
101 public PolicyResult policyResult = null;
102 public int attempt = 0;
105 public String toString() {
106 return "Operation [attempt=" + attempt + ", policyResult=" + policyResult + ", operation=" + operation
111 private String guardApprovalStatus = "NONE";//"NONE", "PERMIT", "DENY"
112 private transient Object operationRequest;
114 public Object getOperationRequest() {
115 return operationRequest;
118 public String getGuardApprovalStatus() {
119 return guardApprovalStatus;
121 public void setGuardApprovalStatus(String guardApprovalStatus) {
122 this.guardApprovalStatus = guardApprovalStatus;
126 public ControlLoopOperationManager(ControlLoopEvent onset, Policy policy, ControlLoopEventManager em) throws ControlLoopException {
128 this.policy = policy;
129 this.guardApprovalStatus = "NONE";
130 this.eventManager = em;
133 // Let's make a sanity check
135 switch (policy.getActor()) {
143 throw new ControlLoopException("ControlLoopEventManager: policy has an unknown actor.");
147 public Object startOperation(/*VirtualControlLoopEvent*/ControlLoopEvent onset) {
149 // They shouldn't call us if we currently running something
151 if (this.currentOperation != null) {
153 // what do we do if we are already running an operation?
158 // Check if we have maxed out on retries
160 if (this.policy.getRetry() == null || this.policy.getRetry() < 1) {
162 // No retries are allowed, so check have we even made
163 // one attempt to execute the operation?
165 if (this.attempts >= 1) {
167 // We have, let's ensure our PolicyResult is set
169 if (this.policyResult == null) {
170 this.policyResult = PolicyResult.FAILURE_RETRIES;
179 // Have we maxed out on retries?
181 if (this.attempts > this.policy.getRetry()) {
182 if (this.policyResult == null) {
183 this.policyResult = PolicyResult.FAILURE_RETRIES;
191 this.policyResult = null;
192 Operation operation = new Operation();
193 operation.attempt = ++this.attempts;
194 operation.operation.actor = this.policy.getActor();
195 operation.operation.operation = this.policy.getRecipe();
196 operation.operation.target = this.policy.getTarget().toString();
197 operation.operation.subRequestId = Integer.toString(operation.attempt);
199 // Now determine which actor we need to construct a request for
201 switch (policy.getActor()) {
204 * If the recipe is ModifyConfig, a legacy APPC
205 * request is constructed. Otherwise an LCMRequest
208 if ("ModifyConfig".equalsIgnoreCase(policy.getRecipe())) {
210 this.operationRequest = APPCActorServiceProvider.constructRequest((VirtualControlLoopEvent)onset, operation.operation, this.policy);
213 this.operationRequest = AppcLcmActorServiceProvider.constructRequest((VirtualControlLoopEvent) onset, operation.operation, this.policy);
216 // Save the operation
218 this.currentOperation = operation;
219 return operationRequest;
221 SOActorServiceProvider SOAsp = new SOActorServiceProvider();
222 this.operationRequest = SOAsp.constructRequest((VirtualControlLoopEvent)onset, operation.operation, this.policy);
224 // Save the operation
225 this.currentOperation = operation;
227 return operationRequest;
229 this.operationRequest = VFCActorServiceProvider.constructRequest((VirtualControlLoopEvent) onset, operation.operation, this.policy, this.eventManager.getVnfResponse());
230 this.currentOperation = operation;
231 return operationRequest;
237 public PolicyResult onResponse(Object response) {
239 // Which response is it?
241 if (response instanceof Response) {
245 Response appcResponse = (Response) response;
247 // Determine which subrequestID (ie. attempt)
249 Integer operationAttempt = null;
251 operationAttempt = Integer.parseInt(appcResponse.CommonHeader.SubRequestID);
252 } catch (NumberFormatException e) {
254 // We cannot tell what happened if this doesn't exist
256 this.completeOperation(operationAttempt, "Policy was unable to parse APP-C SubRequestID (it was null).", PolicyResult.FAILURE_EXCEPTION);
257 return PolicyResult.FAILURE_EXCEPTION;
260 // Sanity check the response message
262 if (appcResponse.Status == null) {
264 // We cannot tell what happened if this doesn't exist
266 this.completeOperation(operationAttempt, "Policy was unable to parse APP-C response status field (it was null).", PolicyResult.FAILURE_EXCEPTION);
267 return PolicyResult.FAILURE_EXCEPTION;
270 // Get the Response Code
272 ResponseCode code = ResponseCode.toResponseCode(appcResponse.Status.Code);
275 // We are unaware of this code
277 this.completeOperation(operationAttempt, "Policy was unable to parse APP-C response status code field.", PolicyResult.FAILURE_EXCEPTION);
278 return PolicyResult.FAILURE_EXCEPTION;
281 // Ok, let's figure out what APP-C's response is
286 // This is good, they got our original message and
289 // Is there any need to track this?
295 // We'll consider these two codes as exceptions
297 this.completeOperation(operationAttempt, appcResponse.getStatus().Description, PolicyResult.FAILURE_EXCEPTION);
298 if (this.policyResult != null && this.policyResult.equals(PolicyResult.FAILURE_TIMEOUT)) {
301 return PolicyResult.FAILURE_EXCEPTION;
306 this.completeOperation(operationAttempt, appcResponse.getStatus().Description, PolicyResult.SUCCESS);
307 if (this.policyResult != null && this.policyResult.equals(PolicyResult.FAILURE_TIMEOUT)) {
310 return PolicyResult.SUCCESS;
315 this.completeOperation(operationAttempt, appcResponse.getStatus().Description, PolicyResult.FAILURE);
316 if (this.policyResult != null && this.policyResult.equals(PolicyResult.FAILURE_TIMEOUT)) {
319 return PolicyResult.FAILURE;
322 else if (response instanceof LCMResponseWrapper) {
324 LCMResponseWrapper dmaapResponse = (LCMResponseWrapper) response;
327 * Parse out the operation attempt using the subrequestid
329 Integer operationAttempt = AppcLcmActorServiceProvider.parseOperationAttempt(dmaapResponse.getBody().getCommonHeader().getSubRequestId());
330 if (operationAttempt == null) {
331 this.completeOperation(operationAttempt, "Policy was unable to parse APP-C SubRequestID (it was null).", PolicyResult.FAILURE_EXCEPTION);
335 * Process the APPCLCM response to see what PolicyResult
338 AbstractMap.SimpleEntry<PolicyResult, String> result = AppcLcmActorServiceProvider.processResponse(dmaapResponse);
340 if (result.getKey() != null) {
341 this.completeOperation(operationAttempt, result.getValue(), result.getKey());
342 if (PolicyResult.FAILURE_TIMEOUT.equals(this.policyResult)) {
345 return result.getKey();
348 } else if (response instanceof SOResponse) {
349 SOResponse msoResponse = (SOResponse) response;
351 switch (msoResponse.httpResponseCode) {
355 // Consider it as success
357 this.completeOperation(this.attempts, msoResponse.httpResponseCode + " Success", PolicyResult.SUCCESS);
358 if (this.policyResult != null && this.policyResult.equals(PolicyResult.FAILURE_TIMEOUT)) {
361 return PolicyResult.SUCCESS;
364 // Consider it as failure
366 this.completeOperation(this.attempts, msoResponse.httpResponseCode + " Failed", PolicyResult.FAILURE);
367 if (this.policyResult != null && this.policyResult.equals(PolicyResult.FAILURE_TIMEOUT)) {
370 return PolicyResult.FAILURE;
373 } else if (response instanceof VFCResponse) {
374 VFCResponse vfcResponse = (VFCResponse) response;
376 if (vfcResponse.responseDescriptor.getStatus().equalsIgnoreCase("finished")) {
378 // Consider it as success
380 this.completeOperation(this.attempts, " Success", PolicyResult.SUCCESS);
381 if (this.policyResult != null && this.policyResult.equals(PolicyResult.FAILURE_TIMEOUT)) {
384 return PolicyResult.SUCCESS;
387 // Consider it as failure
389 this.completeOperation(this.attempts, " Failed", PolicyResult.FAILURE);
390 if (this.policyResult != null && this.policyResult.equals(PolicyResult.FAILURE_TIMEOUT)) {
393 // increment operation attempts for retries
395 return PolicyResult.FAILURE;
401 public Integer getOperationTimeout() {
405 if (this.policy == null) {
406 logger.debug("getOperationTimeout returning 0");
409 logger.debug("getOperationTimeout returning {}", this.policy.getTimeout());
410 return this.policy.getTimeout();
413 public String getOperationTimeoutString(int defaultTimeout) {
414 Integer to = this.getOperationTimeout();
415 if (to == null || to == 0) {
416 return Integer.toString(defaultTimeout) + "s";
418 return to.toString() + "s";
421 public PolicyResult getOperationResult() {
422 return this.policyResult;
425 public String getOperationMessage() {
426 if (this.currentOperation != null && this.currentOperation.operation != null) {
427 return this.currentOperation.operation.toMessage();
430 if (!this.operationHistory.isEmpty()) {
431 return this.operationHistory.getLast().operation.toMessage();
436 public String getOperationMessage(String guardResult) {
437 if (this.currentOperation != null && this.currentOperation.operation != null) {
438 return this.currentOperation.operation.toMessage()+ ", Guard result: " + guardResult;
441 if (!this.operationHistory.isEmpty()) {
442 return this.operationHistory.getLast().operation.toMessage() + ", Guard result: " + guardResult;
447 public String getOperationHistory() {
448 if (this.currentOperation != null && this.currentOperation.operation != null) {
449 return this.currentOperation.operation.toHistory();
452 if (!this.operationHistory.isEmpty()) {
453 return this.operationHistory.getLast().operation.toHistory();
458 public LinkedList<ControlLoopOperation> getHistory() {
459 LinkedList<ControlLoopOperation> history = new LinkedList<ControlLoopOperation>();
460 for (Operation op : this.operationHistory) {
461 history.add(new ControlLoopOperation(op.operation));
467 public void setOperationHasTimedOut() {
471 this.completeOperation(this.attempts, "Operation timed out", PolicyResult.FAILURE_TIMEOUT);
474 public void setOperationHasGuardDeny() {
478 this.completeOperation(this.attempts, "Operation denied by Guard", PolicyResult.FAILURE_GUARD);
481 public boolean isOperationComplete() {
483 // Is there currently a result?
485 if (this.policyResult == null) {
487 // either we are in process or we
493 // We have some result, check if the operation failed
495 if (this.policyResult.equals(PolicyResult.FAILURE)) {
497 // Check if there were no retries specified
499 if (policy.getRetry() == null || policy.getRetry() == 0) {
501 // The result is the failure
508 if (this.isRetriesMaxedOut()) {
510 // No more attempts allowed, reset
511 // that our actual result is failure due to retries
513 this.policyResult = PolicyResult.FAILURE_RETRIES;
517 // There are more attempts available to try the
524 // Other results mean we are done
529 public boolean isOperationRunning() {
530 return (this.currentOperation != null);
533 private boolean isRetriesMaxedOut() {
534 if (policy.getRetry() == null || policy.getRetry() == 0) {
536 // There were NO retries specified, so declare
537 // this as completed.
539 return (this.attempts > 0);
541 return (this.attempts > policy.getRetry());
544 private void storeOperationInDataBase(){
545 // Only store in DB if enabled
546 boolean guardEnabled = "false".equalsIgnoreCase(PolicyEngine.manager.getEnvironmentProperty("guard.disabled"));
553 Properties props = new Properties();
554 try (InputStream is = org.onap.policy.guard.PIPEngineGetHistory.class.getResourceAsStream(org.onap.policy.guard.PIPEngineGetHistory.OPS_HIST_PROPS_LOC)){
556 } catch (Exception ex) {
557 logger.error("getCountFromDB threw: ", ex);
560 String OpsHistPU = System.getProperty("OperationsHistoryPU");
561 if(OpsHistPU == null || !OpsHistPU.equals("TestOperationsHistoryPU")){
562 OpsHistPU = "OperationsHistoryPU";
569 em = Persistence.createEntityManagerFactory(OpsHistPU, props).createEntityManager();
571 logger.error("storeOperationInDataBase threw: ", e);
575 OperationsHistoryDbEntry newEntry = new OperationsHistoryDbEntry();
577 newEntry.closedLoopName = this.onset.closedLoopControlName;
578 newEntry.requestId = this.onset.requestID.toString();
579 newEntry.actor = this.currentOperation.operation.actor;
580 newEntry.operation = this.currentOperation.operation.operation;
581 newEntry.target = this.eventManager.getTargetInstance(this.policy);
582 newEntry.starttime = Timestamp.from(this.currentOperation.operation.start);
583 newEntry.subrequestId = this.currentOperation.operation.subRequestId;
584 newEntry.endtime = new Timestamp(this.currentOperation.operation.end.toEpochMilli());
585 newEntry.message = this.currentOperation.operation.message;
586 newEntry.outcome = this.currentOperation.operation.outcome;
588 em.getTransaction().begin();
589 em.persist(newEntry);
590 em.getTransaction().commit();
598 private void completeOperation(Integer attempt, String message, PolicyResult result) {
599 if (attempt == null) {
600 logger.debug("attempt cannot be null (i.e. subRequestID)");
603 if (this.currentOperation != null) {
604 if (this.currentOperation.attempt == attempt.intValue()) {
605 this.currentOperation.operation.end = Instant.now();
606 this.currentOperation.operation.message = message;
607 this.currentOperation.operation.outcome = result.toString();
608 this.currentOperation.policyResult = result;
610 // Save it in history
612 this.operationHistory.add(this.currentOperation);
613 this.storeOperationInDataBase();
615 // Set our last result
617 this.policyResult = result;
619 // Clear the current operation field
621 this.currentOperation = null;
624 logger.debug("not current");
626 for (Operation op : this.operationHistory) {
627 if (op.attempt == attempt.intValue()) {
628 op.operation.end = Instant.now();
629 op.operation.message = message;
630 op.operation.outcome = result.toString();
631 op.policyResult = result;
635 logger.debug("Could not find associated operation");