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;
29 import javax.persistence.EntityManager;
30 import javax.persistence.Persistence;
32 import org.onap.policy.appc.Response;
33 import org.onap.policy.appc.ResponseCode;
34 import org.onap.policy.appclcm.LCMResponseWrapper;
35 import org.onap.policy.controlloop.ControlLoopEvent;
36 import org.onap.policy.controlloop.ControlLoopOperation;
37 import org.onap.policy.controlloop.VirtualControlLoopEvent;
38 import org.onap.policy.controlloop.ControlLoopException;
39 import org.onap.policy.controlloop.policy.Policy;
40 import org.onap.policy.controlloop.policy.PolicyResult;
41 import org.onap.policy.controlloop.actor.appc.APPCActorServiceProvider;
42 import org.onap.policy.controlloop.actor.vfc.VFCActorServiceProvider;
43 import org.slf4j.Logger;
44 import org.slf4j.LoggerFactory;
45 import org.onap.policy.controlloop.actor.appclcm.AppcLcmActorServiceProvider;
47 public class ControlLoopOperationManager implements Serializable {
52 private static final long serialVersionUID = -3773199283624595410L;
53 private static final Logger logger = LoggerFactory.getLogger(ControlLoopOperationManager.class);
56 public String toString() {
57 return "ControlLoopOperationManager [onset=" + (onset != null ? onset.requestID : "null") + ", policy="
58 + (policy != null ? policy.getId() : "null") + ", attempts=" + attempts
59 + ", policyResult=" + policyResult
60 + ", currentOperation=" + currentOperation + ", operationHistory=" + operationHistory
65 // These properties are not changeable, but accessible
66 // for Drools Rule statements.
68 //public final ATTControlLoopEvent onset;
69 public final ControlLoopEvent onset;
70 public final Policy policy;
73 // Properties used to track the Operation
75 private int attempts = 0;
76 private Operation currentOperation = null;
77 private LinkedList<Operation> operationHistory = new LinkedList<Operation>();
78 private PolicyResult policyResult = null;
79 private ControlLoopEventManager eventManager = null;
81 public ControlLoopEventManager getEventManager() {
85 public void setEventManager(ControlLoopEventManager eventManager) {
86 this.eventManager = eventManager;
91 // Internal class used for tracking
93 private class Operation {
94 public ControlLoopOperation operation = new ControlLoopOperation();
95 public PolicyResult policyResult = null;
96 public int attempt = 0;
99 public String toString() {
100 return "Operation [attempt=" + attempt + ", policyResult=" + policyResult + ", operation=" + operation
105 private String guardApprovalStatus = "NONE";//"NONE", "PERMIT", "DENY"
106 private Object operationRequest;
108 public Object getOperationRequest() {
109 return operationRequest;
112 public String getGuardApprovalStatus() {
113 return guardApprovalStatus;
115 public void setGuardApprovalStatus(String guardApprovalStatus) {
116 this.guardApprovalStatus = guardApprovalStatus;
120 public ControlLoopOperationManager(/*ATTControlLoopEvent*/ControlLoopEvent onset, Policy policy, ControlLoopEventManager em) throws ControlLoopException {
122 this.policy = policy;
123 this.guardApprovalStatus = "NONE";
124 this.eventManager = em;
127 // Let's make a sanity check
129 switch (policy.getActor()) {
141 throw new ControlLoopException("ControlLoopEventManager: policy has an unknown actor.");
145 public Object startOperation(/*VirtualControlLoopEvent*/ControlLoopEvent onset) {
147 // They shouldn't call us if we currently running something
149 if (this.currentOperation != null) {
151 // what do we do if we are already running an operation?
156 // Check if we have maxed out on retries
158 if (this.policy.getRetry() == null || this.policy.getRetry() < 1) {
160 // No retries are allowed, so check have we even made
161 // one attempt to execute the operation?
163 if (this.attempts >= 1) {
165 // We have, let's ensure our PolicyResult is set
167 if (this.policyResult == null) {
168 this.policyResult = PolicyResult.FAILURE_RETRIES;
177 // Have we maxed out on retries?
179 if (this.attempts > this.policy.getRetry()) {
180 if (this.policyResult == null) {
181 this.policyResult = PolicyResult.FAILURE_RETRIES;
189 this.policyResult = null;
190 Operation operation = new Operation();
191 operation.attempt = ++this.attempts;
192 operation.operation.actor = this.policy.getActor().toString();
193 operation.operation.operation = this.policy.getRecipe();
194 operation.operation.target = this.policy.getTarget().toString();
195 operation.operation.subRequestId = Integer.toString(operation.attempt);
197 // Now determine which actor we need to construct a request for
199 switch (policy.getActor()) {
202 * If the recipe is ModifyConfig, a legacy APPC
203 * request is constructed. Otherwise an LCMRequest
206 if ("ModifyConfig".equalsIgnoreCase(policy.getRecipe())) {
208 this.operationRequest = APPCActorServiceProvider.constructRequest((VirtualControlLoopEvent)onset, operation.operation, this.policy);
211 this.operationRequest = AppcLcmActorServiceProvider.constructRequest((VirtualControlLoopEvent) onset, operation.operation, this.policy);
214 // Save the operation
216 this.currentOperation = operation;
217 return operationRequest;
220 // We are not supporting MSO interface at the moment
222 logger.debug("We are not supporting MSO actor in the latest release.");
225 this.operationRequest = VFCActorServiceProvider.constructRequest((VirtualControlLoopEvent) onset, operation.operation, this.policy);
226 this.currentOperation = operation;
227 return operationRequest;
233 public PolicyResult onResponse(Object response) {
235 // Which response is it?
237 if (response instanceof Response) {
241 Response appcResponse = (Response) response;
243 // Determine which subrequestID (ie. attempt)
245 Integer operationAttempt = null;
247 operationAttempt = Integer.parseInt(appcResponse.CommonHeader.SubRequestID);
248 } catch (NumberFormatException e) {
250 // We cannot tell what happened if this doesn't exist
252 this.completeOperation(operationAttempt, "Policy was unable to parse APP-C SubRequestID (it was null).", PolicyResult.FAILURE_EXCEPTION);
253 return PolicyResult.FAILURE_EXCEPTION;
256 // Sanity check the response message
258 if (appcResponse.Status == null) {
260 // We cannot tell what happened if this doesn't exist
262 this.completeOperation(operationAttempt, "Policy was unable to parse APP-C response status field (it was null).", PolicyResult.FAILURE_EXCEPTION);
263 return PolicyResult.FAILURE_EXCEPTION;
266 // Get the Response Code
268 ResponseCode code = ResponseCode.toResponseCode(appcResponse.Status.Code);
271 // We are unaware of this code
273 this.completeOperation(operationAttempt, "Policy was unable to parse APP-C response status code field.", PolicyResult.FAILURE_EXCEPTION);
274 return PolicyResult.FAILURE_EXCEPTION;
277 // Ok, let's figure out what APP-C's response is
282 // This is good, they got our original message and
285 // Is there any need to track this?
291 // We'll consider these two codes as exceptions
293 this.completeOperation(operationAttempt, appcResponse.getStatus().Description, PolicyResult.FAILURE_EXCEPTION);
294 if (this.policyResult != null && this.policyResult.equals(PolicyResult.FAILURE_TIMEOUT)) {
297 return PolicyResult.FAILURE_EXCEPTION;
302 this.completeOperation(operationAttempt, appcResponse.getStatus().Description, PolicyResult.SUCCESS);
303 if (this.policyResult != null && this.policyResult.equals(PolicyResult.FAILURE_TIMEOUT)) {
306 return PolicyResult.SUCCESS;
311 this.completeOperation(operationAttempt, appcResponse.getStatus().Description, PolicyResult.FAILURE);
312 if (this.policyResult != null && this.policyResult.equals(PolicyResult.FAILURE_TIMEOUT)) {
315 return PolicyResult.FAILURE;
318 else if (response instanceof LCMResponseWrapper) {
320 LCMResponseWrapper dmaapResponse = (LCMResponseWrapper) response;
323 * Parse out the operation attempt using the subrequestid
325 Integer operationAttempt = AppcLcmActorServiceProvider.parseOperationAttempt(dmaapResponse.getBody().getCommonHeader().getSubRequestId());
326 if (operationAttempt == null) {
327 this.completeOperation(operationAttempt, "Policy was unable to parse APP-C SubRequestID (it was null).", PolicyResult.FAILURE_EXCEPTION);
331 * Process the APPCLCM response to see what PolicyResult
334 AbstractMap.SimpleEntry<PolicyResult, String> result = AppcLcmActorServiceProvider.processResponse(dmaapResponse);
336 if (result.getKey() != null) {
337 this.completeOperation(operationAttempt, result.getValue(), result.getKey());
338 if (PolicyResult.FAILURE_TIMEOUT.equals(this.policyResult)) {
341 return result.getKey();
348 public Integer getOperationTimeout() {
352 if (this.policy == null) {
353 logger.debug("getOperationTimeout returning 0");
356 logger.debug("getOperationTimeout returning {}", this.policy.getTimeout());
357 return this.policy.getTimeout();
360 public String getOperationTimeoutString(int defaultTimeout) {
361 Integer to = this.getOperationTimeout();
362 if (to == null || to == 0) {
363 return Integer.toString(defaultTimeout) + "s";
365 return to.toString() + "s";
368 public PolicyResult getOperationResult() {
369 return this.policyResult;
372 public String getOperationMessage() {
373 if (this.currentOperation != null && this.currentOperation.operation != null) {
374 return this.currentOperation.operation.toMessage();
376 if (this.operationHistory != null && this.operationHistory.size() > 0) {
377 return this.operationHistory.getLast().operation.toMessage();
382 public String getOperationMessage(String guardResult) {
383 if (this.currentOperation != null && this.currentOperation.operation != null) {
384 return this.currentOperation.operation.toMessage()+ ", Guard result: " + guardResult;
386 if (this.operationHistory != null && this.operationHistory.size() > 0) {
387 return this.operationHistory.getLast().operation.toMessage() + ", Guard result: " + guardResult;
392 public String getOperationHistory() {
393 if (this.currentOperation != null && this.currentOperation.operation != null) {
394 return this.currentOperation.operation.toHistory();
396 if (this.operationHistory != null && this.operationHistory.size() > 0) {
397 return this.operationHistory.getLast().operation.toHistory();
402 public LinkedList<ControlLoopOperation> getHistory() {
403 LinkedList<ControlLoopOperation> history = new LinkedList<ControlLoopOperation>();
404 for (Operation op : this.operationHistory) {
405 history.add(new ControlLoopOperation(op.operation));
411 public void setOperationHasTimedOut() {
415 this.completeOperation(this.attempts, "Operation timed out", PolicyResult.FAILURE_TIMEOUT);
418 public void setOperationHasGuardDeny() {
422 this.completeOperation(this.attempts, "Operation denied by Guard", PolicyResult.FAILURE_GUARD);
425 public boolean isOperationComplete() {
427 // Is there currently a result?
429 if (this.policyResult == null) {
431 // either we are in process or we
437 // We have some result, check if the operation failed
439 if (this.policyResult.equals(PolicyResult.FAILURE)) {
441 // Check if there were no retries specified
443 if (policy.getRetry() == null || policy.getRetry() == 0) {
445 // The result is the failure
452 if (this.isRetriesMaxedOut()) {
454 // No more attempts allowed, reset
455 // that our actual result is failure due to retries
457 this.policyResult = PolicyResult.FAILURE_RETRIES;
461 // There are more attempts available to try the
468 // Other results mean we are done
473 public boolean isOperationRunning() {
474 return (this.currentOperation != null);
477 private boolean isRetriesMaxedOut() {
478 if (policy.getRetry() == null || policy.getRetry() == 0) {
480 // There were NO retries specified, so declare
481 // this as completed.
483 return (this.attempts > 0);
485 return (this.attempts > policy.getRetry());
488 private void storeOperationInDataBase(){
492 em = Persistence.createEntityManagerFactory("OperationsHistoryPU").createEntityManager();//emf.createEntityManager();
494 logger.error("storeOperationInDataBase threw: ", e);
498 OperationsHistoryDbEntry newEntry = new OperationsHistoryDbEntry();
500 newEntry.closedLoopName = this.onset.closedLoopControlName;
501 newEntry.requestId = this.onset.requestID.toString();
502 newEntry.actor = this.currentOperation.operation.actor;
503 newEntry.operation = this.currentOperation.operation.operation;
504 newEntry.target = this.eventManager.getTargetInstance(this.policy);
505 newEntry.starttime = Timestamp.from(this.currentOperation.operation.start);
506 newEntry.subrequestId = this.currentOperation.operation.subRequestId;
507 newEntry.endtime = new Timestamp(this.currentOperation.operation.end.toEpochMilli());
508 newEntry.message = this.currentOperation.operation.message;
509 newEntry.outcome = this.currentOperation.operation.outcome;
511 em.getTransaction().begin();
512 em.persist(newEntry);
513 em.getTransaction().commit();
521 private void completeOperation(Integer attempt, String message, PolicyResult result) {
522 if (attempt == null) {
523 logger.debug("attempt cannot be null (i.e. subRequestID)");
526 if (this.currentOperation != null) {
527 if (this.currentOperation.attempt == attempt.intValue()) {
528 this.currentOperation.operation.end = Instant.now();
529 this.currentOperation.operation.message = message;
530 this.currentOperation.operation.outcome = result.toString();
531 this.currentOperation.policyResult = result;
533 // Save it in history
535 this.operationHistory.add(this.currentOperation);
536 this.storeOperationInDataBase();
538 // Set our last result
540 this.policyResult = result;
542 // Clear the current operation field
544 this.currentOperation = null;
547 logger.debug("not current");
549 for (Operation op : this.operationHistory) {
550 if (op.attempt == attempt.intValue()) {
551 op.operation.end = Instant.now();
552 op.operation.message = message;
553 op.operation.outcome = result.toString();
554 op.policyResult = result;
558 logger.debug("Could not find associated operation");