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.ControlLoopException;
37 import org.onap.policy.controlloop.ControlLoopOperation;
38 import org.onap.policy.controlloop.VirtualControlLoopEvent;
39 import org.onap.policy.controlloop.actor.appc.APPCActorServiceProvider;
40 import org.onap.policy.controlloop.actor.vfc.VFCActorServiceProvider;
41 import org.onap.policy.controlloop.policy.Policy;
42 import org.onap.policy.controlloop.policy.PolicyResult;
43 import org.onap.policy.controlloop.actor.mso.MSOActorServiceProvider;
44 import org.onap.policy.mso.SOResponse;
45 import org.slf4j.Logger;
46 import org.slf4j.LoggerFactory;
47 import org.onap.policy.controlloop.actor.appclcm.AppcLcmActorServiceProvider;
49 public class ControlLoopOperationManager implements Serializable {
54 private static final long serialVersionUID = -3773199283624595410L;
55 private static final Logger logger = LoggerFactory.getLogger(ControlLoopOperationManager.class);
58 public String toString() {
59 return "ControlLoopOperationManager [onset=" + (onset != null ? onset.requestID : "null") + ", policy="
60 + (policy != null ? policy.getId() : "null") + ", attempts=" + attempts
61 + ", policyResult=" + policyResult
62 + ", currentOperation=" + currentOperation + ", operationHistory=" + operationHistory
67 // These properties are not changeable, but accessible
68 // for Drools Rule statements.
70 //public final ATTControlLoopEvent onset;
71 public final ControlLoopEvent onset;
72 public final Policy policy;
75 // Properties used to track the Operation
77 private int attempts = 0;
78 private Operation currentOperation = null;
79 private LinkedList<Operation> operationHistory = new LinkedList<Operation>();
80 private PolicyResult policyResult = null;
81 private ControlLoopEventManager eventManager = null;
83 public ControlLoopEventManager getEventManager() {
87 public void setEventManager(ControlLoopEventManager eventManager) {
88 this.eventManager = eventManager;
93 // Internal class used for tracking
95 private class Operation {
96 public ControlLoopOperation operation = new ControlLoopOperation();
97 public PolicyResult policyResult = null;
98 public int attempt = 0;
101 public String toString() {
102 return "Operation [attempt=" + attempt + ", policyResult=" + policyResult + ", operation=" + operation
107 private String guardApprovalStatus = "NONE";//"NONE", "PERMIT", "DENY"
108 private Object operationRequest;
110 public Object getOperationRequest() {
111 return operationRequest;
114 public String getGuardApprovalStatus() {
115 return guardApprovalStatus;
117 public void setGuardApprovalStatus(String guardApprovalStatus) {
118 this.guardApprovalStatus = guardApprovalStatus;
122 public ControlLoopOperationManager(ControlLoopEvent onset, Policy policy, ControlLoopEventManager em) throws ControlLoopException {
124 this.policy = policy;
125 this.guardApprovalStatus = "NONE";
126 this.eventManager = em;
129 // Let's make a sanity check
131 switch (policy.getActor()) {
139 throw new ControlLoopException("ControlLoopEventManager: policy has an unknown actor.");
143 public Object startOperation(/*VirtualControlLoopEvent*/ControlLoopEvent onset) {
145 // They shouldn't call us if we currently running something
147 if (this.currentOperation != null) {
149 // what do we do if we are already running an operation?
154 // Check if we have maxed out on retries
156 if (this.policy.getRetry() == null || this.policy.getRetry() < 1) {
158 // No retries are allowed, so check have we even made
159 // one attempt to execute the operation?
161 if (this.attempts >= 1) {
163 // We have, let's ensure our PolicyResult is set
165 if (this.policyResult == null) {
166 this.policyResult = PolicyResult.FAILURE_RETRIES;
175 // Have we maxed out on retries?
177 if (this.attempts > this.policy.getRetry()) {
178 if (this.policyResult == null) {
179 this.policyResult = PolicyResult.FAILURE_RETRIES;
187 this.policyResult = null;
188 Operation operation = new Operation();
189 operation.attempt = ++this.attempts;
190 operation.operation.actor = this.policy.getActor().toString();
191 operation.operation.operation = this.policy.getRecipe();
192 operation.operation.target = this.policy.getTarget().toString();
193 operation.operation.subRequestId = Integer.toString(operation.attempt);
195 // Now determine which actor we need to construct a request for
197 switch (policy.getActor()) {
200 * If the recipe is ModifyConfig, a legacy APPC
201 * request is constructed. Otherwise an LCMRequest
204 if ("ModifyConfig".equalsIgnoreCase(policy.getRecipe())) {
206 this.operationRequest = APPCActorServiceProvider.constructRequest((VirtualControlLoopEvent)onset, operation.operation, this.policy);
209 this.operationRequest = AppcLcmActorServiceProvider.constructRequest((VirtualControlLoopEvent) onset, operation.operation, this.policy);
212 // Save the operation
214 this.currentOperation = operation;
215 return operationRequest;
217 MSOActorServiceProvider SOAsp = new MSOActorServiceProvider();
218 this.operationRequest = SOAsp.constructRequest((VirtualControlLoopEvent)onset, operation.operation, this.policy);
220 // Save the operation
221 this.currentOperation = operation;
223 return operationRequest;
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();
344 } else if (response instanceof SOResponse) {
345 SOResponse msoResponse = (SOResponse) response;
346 switch (msoResponse.httpResponseCode) {
350 // Consider it as success
352 this.completeOperation(new Integer(1), msoResponse.httpResponseCode + " Success", PolicyResult.SUCCESS);
353 if (this.policyResult != null && this.policyResult.equals(PolicyResult.FAILURE_TIMEOUT)) {
356 return PolicyResult.SUCCESS;
359 // Consider it as failure
361 this.completeOperation(new Integer(1), msoResponse.httpResponseCode + " Failed", PolicyResult.FAILURE);
362 if (this.policyResult != null && this.policyResult.equals(PolicyResult.FAILURE_TIMEOUT)) {
365 return PolicyResult.FAILURE;
373 public Integer getOperationTimeout() {
377 if (this.policy == null) {
378 logger.debug("getOperationTimeout returning 0");
381 logger.debug("getOperationTimeout returning {}", this.policy.getTimeout());
382 return this.policy.getTimeout();
385 public String getOperationTimeoutString(int defaultTimeout) {
386 Integer to = this.getOperationTimeout();
387 if (to == null || to == 0) {
388 return Integer.toString(defaultTimeout) + "s";
390 return to.toString() + "s";
393 public PolicyResult getOperationResult() {
394 return this.policyResult;
397 public String getOperationMessage() {
398 if (this.currentOperation != null && this.currentOperation.operation != null) {
399 return this.currentOperation.operation.toMessage();
401 if (this.operationHistory != null && this.operationHistory.size() > 0) {
402 return this.operationHistory.getLast().operation.toMessage();
407 public String getOperationMessage(String guardResult) {
408 if (this.currentOperation != null && this.currentOperation.operation != null) {
409 return this.currentOperation.operation.toMessage()+ ", Guard result: " + guardResult;
411 if (this.operationHistory != null && this.operationHistory.size() > 0) {
412 return this.operationHistory.getLast().operation.toMessage() + ", Guard result: " + guardResult;
417 public String getOperationHistory() {
418 if (this.currentOperation != null && this.currentOperation.operation != null) {
419 return this.currentOperation.operation.toHistory();
421 if (this.operationHistory != null && this.operationHistory.size() > 0) {
422 return this.operationHistory.getLast().operation.toHistory();
427 public LinkedList<ControlLoopOperation> getHistory() {
428 LinkedList<ControlLoopOperation> history = new LinkedList<ControlLoopOperation>();
429 for (Operation op : this.operationHistory) {
430 history.add(new ControlLoopOperation(op.operation));
436 public void setOperationHasTimedOut() {
440 this.completeOperation(this.attempts, "Operation timed out", PolicyResult.FAILURE_TIMEOUT);
443 public void setOperationHasGuardDeny() {
447 this.completeOperation(this.attempts, "Operation denied by Guard", PolicyResult.FAILURE_GUARD);
450 public boolean isOperationComplete() {
452 // Is there currently a result?
454 if (this.policyResult == null) {
456 // either we are in process or we
462 // We have some result, check if the operation failed
464 if (this.policyResult.equals(PolicyResult.FAILURE)) {
466 // Check if there were no retries specified
468 if (policy.getRetry() == null || policy.getRetry() == 0) {
470 // The result is the failure
477 if (this.isRetriesMaxedOut()) {
479 // No more attempts allowed, reset
480 // that our actual result is failure due to retries
482 this.policyResult = PolicyResult.FAILURE_RETRIES;
486 // There are more attempts available to try the
493 // Other results mean we are done
498 public boolean isOperationRunning() {
499 return (this.currentOperation != null);
502 private boolean isRetriesMaxedOut() {
503 if (policy.getRetry() == null || policy.getRetry() == 0) {
505 // There were NO retries specified, so declare
506 // this as completed.
508 return (this.attempts > 0);
510 return (this.attempts > policy.getRetry());
513 private void storeOperationInDataBase(){
515 String OpsHistPU = System.getProperty("OperationsHistoryPU");
516 if(OpsHistPU == null || !OpsHistPU.equals("TestOperationsHistoryPU")){
517 OpsHistPU = "OperationsHistoryPU";
521 em = Persistence.createEntityManagerFactory(OpsHistPU).createEntityManager();
523 logger.error("storeOperationInDataBase threw: ", e);
527 OperationsHistoryDbEntry newEntry = new OperationsHistoryDbEntry();
529 newEntry.closedLoopName = this.onset.closedLoopControlName;
530 newEntry.requestId = this.onset.requestID.toString();
531 newEntry.actor = this.currentOperation.operation.actor;
532 newEntry.operation = this.currentOperation.operation.operation;
533 newEntry.target = this.eventManager.getTargetInstance(this.policy);
534 newEntry.starttime = Timestamp.from(this.currentOperation.operation.start);
535 newEntry.subrequestId = this.currentOperation.operation.subRequestId;
536 newEntry.endtime = new Timestamp(this.currentOperation.operation.end.toEpochMilli());
537 newEntry.message = this.currentOperation.operation.message;
538 newEntry.outcome = this.currentOperation.operation.outcome;
540 em.getTransaction().begin();
541 em.persist(newEntry);
542 em.getTransaction().commit();
550 private void completeOperation(Integer attempt, String message, PolicyResult result) {
551 if (attempt == null) {
552 logger.debug("attempt cannot be null (i.e. subRequestID)");
555 if (this.currentOperation != null) {
556 if (this.currentOperation.attempt == attempt.intValue()) {
557 this.currentOperation.operation.end = Instant.now();
558 this.currentOperation.operation.message = message;
559 this.currentOperation.operation.outcome = result.toString();
560 this.currentOperation.policyResult = result;
562 // Save it in history
564 this.operationHistory.add(this.currentOperation);
565 this.storeOperationInDataBase();
567 // Set our last result
569 this.policyResult = result;
571 // Clear the current operation field
573 this.currentOperation = null;
576 logger.debug("not current");
578 for (Operation op : this.operationHistory) {
579 if (op.attempt == attempt.intValue()) {
580 op.operation.end = Instant.now();
581 op.operation.message = message;
582 op.operation.outcome = result.toString();
583 op.policyResult = result;
587 logger.debug("Could not find associated operation");