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.so.SOResponse;
48 import org.onap.policy.vfc.VFCResponse;
49 import org.slf4j.Logger;
50 import org.slf4j.LoggerFactory;
52 public class ControlLoopOperationManager implements Serializable {
57 private static final long serialVersionUID = -3773199283624595410L;
58 private static final Logger logger = LoggerFactory.getLogger(ControlLoopOperationManager.class);
61 public String toString() {
62 return "ControlLoopOperationManager [onset=" + (onset != null ? onset.requestID : "null") + ", policy="
63 + (policy != null ? policy.getId() : "null") + ", attempts=" + attempts
64 + ", policyResult=" + policyResult
65 + ", currentOperation=" + currentOperation + ", operationHistory=" + operationHistory
70 // These properties are not changeable, but accessible
71 // for Drools Rule statements.
73 //public final ATTControlLoopEvent onset;
74 public final ControlLoopEvent onset;
75 public final transient Policy policy;
78 // Properties used to track the Operation
80 private int attempts = 0;
81 private transient Operation currentOperation = null;
82 private LinkedList<Operation> operationHistory = new LinkedList<Operation>();
83 private PolicyResult policyResult = null;
84 private ControlLoopEventManager eventManager = null;
86 public ControlLoopEventManager getEventManager() {
90 public void setEventManager(ControlLoopEventManager eventManager) {
91 this.eventManager = eventManager;
96 // Internal class used for tracking
98 private class Operation {
99 public ControlLoopOperation operation = new ControlLoopOperation();
100 public PolicyResult policyResult = null;
101 public int attempt = 0;
104 public String toString() {
105 return "Operation [attempt=" + attempt + ", policyResult=" + policyResult + ", operation=" + operation
110 private String guardApprovalStatus = "NONE";//"NONE", "PERMIT", "DENY"
111 private transient Object operationRequest;
113 public Object getOperationRequest() {
114 return operationRequest;
117 public String getGuardApprovalStatus() {
118 return guardApprovalStatus;
120 public void setGuardApprovalStatus(String guardApprovalStatus) {
121 this.guardApprovalStatus = guardApprovalStatus;
125 public ControlLoopOperationManager(ControlLoopEvent onset, Policy policy, ControlLoopEventManager em) throws ControlLoopException {
127 this.policy = policy;
128 this.guardApprovalStatus = "NONE";
129 this.eventManager = em;
132 // Let's make a sanity check
134 switch (policy.getActor()) {
142 throw new ControlLoopException("ControlLoopEventManager: policy has an unknown actor.");
146 public Object startOperation(/*VirtualControlLoopEvent*/ControlLoopEvent onset) {
148 // They shouldn't call us if we currently running something
150 if (this.currentOperation != null) {
152 // what do we do if we are already running an operation?
157 // Check if we have maxed out on retries
159 if (this.policy.getRetry() == null || this.policy.getRetry() < 1) {
161 // No retries are allowed, so check have we even made
162 // one attempt to execute the operation?
164 if (this.attempts >= 1) {
166 // We have, let's ensure our PolicyResult is set
168 if (this.policyResult == null) {
169 this.policyResult = PolicyResult.FAILURE_RETRIES;
178 // Have we maxed out on retries?
180 if (this.attempts > this.policy.getRetry()) {
181 if (this.policyResult == null) {
182 this.policyResult = PolicyResult.FAILURE_RETRIES;
190 this.policyResult = null;
191 Operation operation = new Operation();
192 operation.attempt = ++this.attempts;
193 operation.operation.actor = this.policy.getActor();
194 operation.operation.operation = this.policy.getRecipe();
195 operation.operation.target = this.policy.getTarget().toString();
196 operation.operation.subRequestId = Integer.toString(operation.attempt);
198 // Now determine which actor we need to construct a request for
200 switch (policy.getActor()) {
203 * If the recipe is ModifyConfig, a legacy APPC
204 * request is constructed. Otherwise an LCMRequest
207 if ("ModifyConfig".equalsIgnoreCase(policy.getRecipe())) {
209 this.operationRequest = APPCActorServiceProvider.constructRequest((VirtualControlLoopEvent)onset, operation.operation, this.policy);
212 this.operationRequest = AppcLcmActorServiceProvider.constructRequest((VirtualControlLoopEvent) onset, operation.operation, this.policy);
215 // Save the operation
217 this.currentOperation = operation;
218 return operationRequest;
220 SOActorServiceProvider SOAsp = new SOActorServiceProvider();
221 this.operationRequest = SOAsp.constructRequest((VirtualControlLoopEvent)onset, operation.operation, this.policy);
223 // Save the operation
224 this.currentOperation = operation;
226 return operationRequest;
228 this.operationRequest = VFCActorServiceProvider.constructRequest((VirtualControlLoopEvent) onset, operation.operation, this.policy);
229 this.currentOperation = operation;
230 return operationRequest;
236 public PolicyResult onResponse(Object response) {
238 // Which response is it?
240 if (response instanceof Response) {
244 Response appcResponse = (Response) response;
246 // Determine which subrequestID (ie. attempt)
248 Integer operationAttempt = null;
250 operationAttempt = Integer.parseInt(appcResponse.CommonHeader.SubRequestID);
251 } catch (NumberFormatException e) {
253 // We cannot tell what happened if this doesn't exist
255 this.completeOperation(operationAttempt, "Policy was unable to parse APP-C SubRequestID (it was null).", PolicyResult.FAILURE_EXCEPTION);
256 return PolicyResult.FAILURE_EXCEPTION;
259 // Sanity check the response message
261 if (appcResponse.Status == null) {
263 // We cannot tell what happened if this doesn't exist
265 this.completeOperation(operationAttempt, "Policy was unable to parse APP-C response status field (it was null).", PolicyResult.FAILURE_EXCEPTION);
266 return PolicyResult.FAILURE_EXCEPTION;
269 // Get the Response Code
271 ResponseCode code = ResponseCode.toResponseCode(appcResponse.Status.Code);
274 // We are unaware of this code
276 this.completeOperation(operationAttempt, "Policy was unable to parse APP-C response status code field.", PolicyResult.FAILURE_EXCEPTION);
277 return PolicyResult.FAILURE_EXCEPTION;
280 // Ok, let's figure out what APP-C's response is
285 // This is good, they got our original message and
288 // Is there any need to track this?
294 // We'll consider these two codes as exceptions
296 this.completeOperation(operationAttempt, appcResponse.getStatus().Description, PolicyResult.FAILURE_EXCEPTION);
297 if (this.policyResult != null && this.policyResult.equals(PolicyResult.FAILURE_TIMEOUT)) {
300 return PolicyResult.FAILURE_EXCEPTION;
305 this.completeOperation(operationAttempt, appcResponse.getStatus().Description, PolicyResult.SUCCESS);
306 if (this.policyResult != null && this.policyResult.equals(PolicyResult.FAILURE_TIMEOUT)) {
309 return PolicyResult.SUCCESS;
314 this.completeOperation(operationAttempt, appcResponse.getStatus().Description, PolicyResult.FAILURE);
315 if (this.policyResult != null && this.policyResult.equals(PolicyResult.FAILURE_TIMEOUT)) {
318 return PolicyResult.FAILURE;
321 else if (response instanceof LCMResponseWrapper) {
323 LCMResponseWrapper dmaapResponse = (LCMResponseWrapper) response;
326 * Parse out the operation attempt using the subrequestid
328 Integer operationAttempt = AppcLcmActorServiceProvider.parseOperationAttempt(dmaapResponse.getBody().getCommonHeader().getSubRequestId());
329 if (operationAttempt == null) {
330 this.completeOperation(operationAttempt, "Policy was unable to parse APP-C SubRequestID (it was null).", PolicyResult.FAILURE_EXCEPTION);
334 * Process the APPCLCM response to see what PolicyResult
337 AbstractMap.SimpleEntry<PolicyResult, String> result = AppcLcmActorServiceProvider.processResponse(dmaapResponse);
339 if (result.getKey() != null) {
340 this.completeOperation(operationAttempt, result.getValue(), result.getKey());
341 if (PolicyResult.FAILURE_TIMEOUT.equals(this.policyResult)) {
344 return result.getKey();
347 } else if (response instanceof SOResponse) {
348 SOResponse msoResponse = (SOResponse) response;
350 Integer operationAttempt = this.attempts;
352 switch (msoResponse.httpResponseCode) {
356 // Consider it as success
358 this.completeOperation(operationAttempt, msoResponse.httpResponseCode + " Success", PolicyResult.SUCCESS);
359 if (this.policyResult != null && this.policyResult.equals(PolicyResult.FAILURE_TIMEOUT)) {
362 return PolicyResult.SUCCESS;
365 // Consider it as failure
367 this.completeOperation(operationAttempt, msoResponse.httpResponseCode + " Failed", PolicyResult.FAILURE);
368 if (this.policyResult != null && this.policyResult.equals(PolicyResult.FAILURE_TIMEOUT)) {
371 // increment operation attempts for retries
373 return PolicyResult.FAILURE;
376 } else if (response instanceof VFCResponse) {
377 VFCResponse vfcResponse = (VFCResponse) response;
378 Integer operationAttempt = this.attempts;
379 if (vfcResponse.responseDescriptor.getStatus().equalsIgnoreCase("finished")) {
381 // Consider it as success
383 this.completeOperation(operationAttempt, " Success", PolicyResult.SUCCESS);
384 if (this.policyResult != null && this.policyResult.equals(PolicyResult.FAILURE_TIMEOUT)) {
387 return PolicyResult.SUCCESS;
390 // Consider it as failure
392 this.completeOperation(operationAttempt, " Failed", PolicyResult.FAILURE);
393 if (this.policyResult != null && this.policyResult.equals(PolicyResult.FAILURE_TIMEOUT)) {
396 // increment operation attempts for retries
398 return PolicyResult.FAILURE;
404 public Integer getOperationTimeout() {
408 if (this.policy == null) {
409 logger.debug("getOperationTimeout returning 0");
412 logger.debug("getOperationTimeout returning {}", this.policy.getTimeout());
413 return this.policy.getTimeout();
416 public String getOperationTimeoutString(int defaultTimeout) {
417 Integer to = this.getOperationTimeout();
418 if (to == null || to == 0) {
419 return Integer.toString(defaultTimeout) + "s";
421 return to.toString() + "s";
424 public PolicyResult getOperationResult() {
425 return this.policyResult;
428 public String getOperationMessage() {
429 if (this.currentOperation != null && this.currentOperation.operation != null) {
430 return this.currentOperation.operation.toMessage();
433 if (!this.operationHistory.isEmpty()) {
434 return this.operationHistory.getLast().operation.toMessage();
439 public String getOperationMessage(String guardResult) {
440 if (this.currentOperation != null && this.currentOperation.operation != null) {
441 return this.currentOperation.operation.toMessage()+ ", Guard result: " + guardResult;
444 if (!this.operationHistory.isEmpty()) {
445 return this.operationHistory.getLast().operation.toMessage() + ", Guard result: " + guardResult;
450 public String getOperationHistory() {
451 if (this.currentOperation != null && this.currentOperation.operation != null) {
452 return this.currentOperation.operation.toHistory();
455 if (!this.operationHistory.isEmpty()) {
456 return this.operationHistory.getLast().operation.toHistory();
461 public LinkedList<ControlLoopOperation> getHistory() {
462 LinkedList<ControlLoopOperation> history = new LinkedList<ControlLoopOperation>();
463 for (Operation op : this.operationHistory) {
464 history.add(new ControlLoopOperation(op.operation));
470 public void setOperationHasTimedOut() {
474 this.completeOperation(this.attempts, "Operation timed out", PolicyResult.FAILURE_TIMEOUT);
477 public void setOperationHasGuardDeny() {
481 this.completeOperation(this.attempts, "Operation denied by Guard", PolicyResult.FAILURE_GUARD);
484 public boolean isOperationComplete() {
486 // Is there currently a result?
488 if (this.policyResult == null) {
490 // either we are in process or we
496 // We have some result, check if the operation failed
498 if (this.policyResult.equals(PolicyResult.FAILURE)) {
500 // Check if there were no retries specified
502 if (policy.getRetry() == null || policy.getRetry() == 0) {
504 // The result is the failure
511 if (this.isRetriesMaxedOut()) {
513 // No more attempts allowed, reset
514 // that our actual result is failure due to retries
516 this.policyResult = PolicyResult.FAILURE_RETRIES;
520 // There are more attempts available to try the
527 // Other results mean we are done
532 public boolean isOperationRunning() {
533 return (this.currentOperation != null);
536 private boolean isRetriesMaxedOut() {
537 if (policy.getRetry() == null || policy.getRetry() == 0) {
539 // There were NO retries specified, so declare
540 // this as completed.
542 return (this.attempts > 0);
544 return (this.attempts > policy.getRetry());
547 private void storeOperationInDataBase(){
550 Properties props = new Properties();
551 try (InputStream is = org.onap.policy.guard.PIPEngineGetHistory.class.getResourceAsStream(org.onap.policy.guard.PIPEngineGetHistory.OPS_HIST_PROPS_LOC)){
553 } catch (Exception ex) {
554 logger.error("getCountFromDB threw: ", ex);
557 String OpsHistPU = System.getProperty("OperationsHistoryPU");
558 if(OpsHistPU == null || !OpsHistPU.equals("TestOperationsHistoryPU")){
559 OpsHistPU = "OperationsHistoryPU";
566 em = Persistence.createEntityManagerFactory(OpsHistPU, props).createEntityManager();
568 logger.error("storeOperationInDataBase threw: ", e);
572 OperationsHistoryDbEntry newEntry = new OperationsHistoryDbEntry();
574 newEntry.closedLoopName = this.onset.closedLoopControlName;
575 newEntry.requestId = this.onset.requestID.toString();
576 newEntry.actor = this.currentOperation.operation.actor;
577 newEntry.operation = this.currentOperation.operation.operation;
578 newEntry.target = this.eventManager.getTargetInstance(this.policy);
579 newEntry.starttime = Timestamp.from(this.currentOperation.operation.start);
580 newEntry.subrequestId = this.currentOperation.operation.subRequestId;
581 newEntry.endtime = new Timestamp(this.currentOperation.operation.end.toEpochMilli());
582 newEntry.message = this.currentOperation.operation.message;
583 newEntry.outcome = this.currentOperation.operation.outcome;
585 em.getTransaction().begin();
586 em.persist(newEntry);
587 em.getTransaction().commit();
595 private void completeOperation(Integer attempt, String message, PolicyResult result) {
596 if (attempt == null) {
597 logger.debug("attempt cannot be null (i.e. subRequestID)");
600 if (this.currentOperation != null) {
601 if (this.currentOperation.attempt == attempt.intValue()) {
602 this.currentOperation.operation.end = Instant.now();
603 this.currentOperation.operation.message = message;
604 this.currentOperation.operation.outcome = result.toString();
605 this.currentOperation.policyResult = result;
607 // Save it in history
609 this.operationHistory.add(this.currentOperation);
610 this.storeOperationInDataBase();
612 // Set our last result
614 this.policyResult = result;
616 // Clear the current operation field
618 this.currentOperation = null;
621 logger.debug("not current");
623 for (Operation op : this.operationHistory) {
624 if (op.attempt == attempt.intValue()) {
625 op.operation.end = Instant.now();
626 op.operation.message = message;
627 op.operation.outcome = result.toString();
628 op.policyResult = result;
632 logger.debug("Could not find associated operation");