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;
349 switch (msoResponse.httpResponseCode) {
353 // Consider it as success
355 this.completeOperation(new Integer(1), msoResponse.httpResponseCode + " Success", PolicyResult.SUCCESS);
356 if (this.policyResult != null && this.policyResult.equals(PolicyResult.FAILURE_TIMEOUT)) {
359 return PolicyResult.SUCCESS;
362 // Consider it as failure
364 this.completeOperation(new Integer(1), msoResponse.httpResponseCode + " Failed", PolicyResult.FAILURE);
365 if (this.policyResult != null && this.policyResult.equals(PolicyResult.FAILURE_TIMEOUT)) {
368 return PolicyResult.FAILURE;
371 } else if (response instanceof VFCResponse) {
372 VFCResponse vfcResponse = (VFCResponse) response;
373 if (vfcResponse.responseDescriptor.getStatus().equalsIgnoreCase("finished")) {
375 // Consider it as success
377 this.completeOperation(new Integer(1), " Success", PolicyResult.SUCCESS);
378 if (this.policyResult != null && this.policyResult.equals(PolicyResult.FAILURE_TIMEOUT)) {
381 return PolicyResult.SUCCESS;
384 // Consider it as failure
386 this.completeOperation(new Integer(1), " Failed", PolicyResult.FAILURE);
387 if (this.policyResult != null && this.policyResult.equals(PolicyResult.FAILURE_TIMEOUT)) {
390 return PolicyResult.FAILURE;
396 public Integer getOperationTimeout() {
400 if (this.policy == null) {
401 logger.debug("getOperationTimeout returning 0");
404 logger.debug("getOperationTimeout returning {}", this.policy.getTimeout());
405 return this.policy.getTimeout();
408 public String getOperationTimeoutString(int defaultTimeout) {
409 Integer to = this.getOperationTimeout();
410 if (to == null || to == 0) {
411 return Integer.toString(defaultTimeout) + "s";
413 return to.toString() + "s";
416 public PolicyResult getOperationResult() {
417 return this.policyResult;
420 public String getOperationMessage() {
421 if (this.currentOperation != null && this.currentOperation.operation != null) {
422 return this.currentOperation.operation.toMessage();
425 if (!this.operationHistory.isEmpty()) {
426 return this.operationHistory.getLast().operation.toMessage();
431 public String getOperationMessage(String guardResult) {
432 if (this.currentOperation != null && this.currentOperation.operation != null) {
433 return this.currentOperation.operation.toMessage()+ ", Guard result: " + guardResult;
436 if (!this.operationHistory.isEmpty()) {
437 return this.operationHistory.getLast().operation.toMessage() + ", Guard result: " + guardResult;
442 public String getOperationHistory() {
443 if (this.currentOperation != null && this.currentOperation.operation != null) {
444 return this.currentOperation.operation.toHistory();
447 if (!this.operationHistory.isEmpty()) {
448 return this.operationHistory.getLast().operation.toHistory();
453 public LinkedList<ControlLoopOperation> getHistory() {
454 LinkedList<ControlLoopOperation> history = new LinkedList<ControlLoopOperation>();
455 for (Operation op : this.operationHistory) {
456 history.add(new ControlLoopOperation(op.operation));
462 public void setOperationHasTimedOut() {
466 this.completeOperation(this.attempts, "Operation timed out", PolicyResult.FAILURE_TIMEOUT);
469 public void setOperationHasGuardDeny() {
473 this.completeOperation(this.attempts, "Operation denied by Guard", PolicyResult.FAILURE_GUARD);
476 public boolean isOperationComplete() {
478 // Is there currently a result?
480 if (this.policyResult == null) {
482 // either we are in process or we
488 // We have some result, check if the operation failed
490 if (this.policyResult.equals(PolicyResult.FAILURE)) {
492 // Check if there were no retries specified
494 if (policy.getRetry() == null || policy.getRetry() == 0) {
496 // The result is the failure
503 if (this.isRetriesMaxedOut()) {
505 // No more attempts allowed, reset
506 // that our actual result is failure due to retries
508 this.policyResult = PolicyResult.FAILURE_RETRIES;
512 // There are more attempts available to try the
519 // Other results mean we are done
524 public boolean isOperationRunning() {
525 return (this.currentOperation != null);
528 private boolean isRetriesMaxedOut() {
529 if (policy.getRetry() == null || policy.getRetry() == 0) {
531 // There were NO retries specified, so declare
532 // this as completed.
534 return (this.attempts > 0);
536 return (this.attempts > policy.getRetry());
539 private void storeOperationInDataBase(){
542 Properties props = new Properties();
543 try (InputStream is = org.onap.policy.guard.PIPEngineGetHistory.class.getResourceAsStream(org.onap.policy.guard.PIPEngineGetHistory.OPS_HIST_PROPS_LOC)){
545 } catch (Exception ex) {
546 logger.error("getCountFromDB threw: ", ex);
549 String OpsHistPU = System.getProperty("OperationsHistoryPU");
550 if(OpsHistPU == null || !OpsHistPU.equals("TestOperationsHistoryPU")){
551 OpsHistPU = "OperationsHistoryPU";
558 em = Persistence.createEntityManagerFactory(OpsHistPU, props).createEntityManager();
560 logger.error("storeOperationInDataBase threw: ", e);
564 OperationsHistoryDbEntry newEntry = new OperationsHistoryDbEntry();
566 newEntry.closedLoopName = this.onset.closedLoopControlName;
567 newEntry.requestId = this.onset.requestID.toString();
568 newEntry.actor = this.currentOperation.operation.actor;
569 newEntry.operation = this.currentOperation.operation.operation;
570 newEntry.target = this.eventManager.getTargetInstance(this.policy);
571 newEntry.starttime = Timestamp.from(this.currentOperation.operation.start);
572 newEntry.subrequestId = this.currentOperation.operation.subRequestId;
573 newEntry.endtime = new Timestamp(this.currentOperation.operation.end.toEpochMilli());
574 newEntry.message = this.currentOperation.operation.message;
575 newEntry.outcome = this.currentOperation.operation.outcome;
577 em.getTransaction().begin();
578 em.persist(newEntry);
579 em.getTransaction().commit();
587 private void completeOperation(Integer attempt, String message, PolicyResult result) {
588 if (attempt == null) {
589 logger.debug("attempt cannot be null (i.e. subRequestID)");
592 if (this.currentOperation != null) {
593 if (this.currentOperation.attempt == attempt.intValue()) {
594 this.currentOperation.operation.end = Instant.now();
595 this.currentOperation.operation.message = message;
596 this.currentOperation.operation.outcome = result.toString();
597 this.currentOperation.policyResult = result;
599 // Save it in history
601 this.operationHistory.add(this.currentOperation);
602 this.storeOperationInDataBase();
604 // Set our last result
606 this.policyResult = result;
608 // Clear the current operation field
610 this.currentOperation = null;
613 logger.debug("not current");
615 for (Operation op : this.operationHistory) {
616 if (op.attempt == attempt.intValue()) {
617 op.operation.end = Instant.now();
618 op.operation.message = message;
619 op.operation.outcome = result.toString();
620 op.policyResult = result;
624 logger.debug("Could not find associated operation");