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.slf4j.Logger;
49 import org.slf4j.LoggerFactory;
51 public class ControlLoopOperationManager implements Serializable {
56 private static final long serialVersionUID = -3773199283624595410L;
57 private static final Logger logger = LoggerFactory.getLogger(ControlLoopOperationManager.class);
60 public String toString() {
61 return "ControlLoopOperationManager [onset=" + (onset != null ? onset.requestID : "null") + ", policy="
62 + (policy != null ? policy.getId() : "null") + ", attempts=" + attempts
63 + ", policyResult=" + policyResult
64 + ", currentOperation=" + currentOperation + ", operationHistory=" + operationHistory
69 // These properties are not changeable, but accessible
70 // for Drools Rule statements.
72 //public final ATTControlLoopEvent onset;
73 public final ControlLoopEvent onset;
74 public final transient Policy policy;
77 // Properties used to track the Operation
79 private int attempts = 0;
80 private transient Operation currentOperation = null;
81 private LinkedList<Operation> operationHistory = new LinkedList<Operation>();
82 private PolicyResult policyResult = null;
83 private ControlLoopEventManager eventManager = null;
85 public ControlLoopEventManager getEventManager() {
89 public void setEventManager(ControlLoopEventManager eventManager) {
90 this.eventManager = eventManager;
95 // Internal class used for tracking
97 private class Operation {
98 public ControlLoopOperation operation = new ControlLoopOperation();
99 public PolicyResult policyResult = null;
100 public int attempt = 0;
103 public String toString() {
104 return "Operation [attempt=" + attempt + ", policyResult=" + policyResult + ", operation=" + operation
109 private String guardApprovalStatus = "NONE";//"NONE", "PERMIT", "DENY"
110 private transient Object operationRequest;
112 public Object getOperationRequest() {
113 return operationRequest;
116 public String getGuardApprovalStatus() {
117 return guardApprovalStatus;
119 public void setGuardApprovalStatus(String guardApprovalStatus) {
120 this.guardApprovalStatus = guardApprovalStatus;
124 public ControlLoopOperationManager(ControlLoopEvent onset, Policy policy, ControlLoopEventManager em) throws ControlLoopException {
126 this.policy = policy;
127 this.guardApprovalStatus = "NONE";
128 this.eventManager = em;
131 // Let's make a sanity check
133 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;
219 SOActorServiceProvider SOAsp = new SOActorServiceProvider();
220 this.operationRequest = SOAsp.constructRequest((VirtualControlLoopEvent)onset, operation.operation, this.policy);
222 // Save the operation
223 this.currentOperation = operation;
225 return operationRequest;
227 this.operationRequest = VFCActorServiceProvider.constructRequest((VirtualControlLoopEvent) onset, operation.operation, this.policy);
228 this.currentOperation = operation;
229 return operationRequest;
235 public PolicyResult onResponse(Object response) {
237 // Which response is it?
239 if (response instanceof Response) {
243 Response appcResponse = (Response) response;
245 // Determine which subrequestID (ie. attempt)
247 Integer operationAttempt = null;
249 operationAttempt = Integer.parseInt(appcResponse.CommonHeader.SubRequestID);
250 } catch (NumberFormatException e) {
252 // We cannot tell what happened if this doesn't exist
254 this.completeOperation(operationAttempt, "Policy was unable to parse APP-C SubRequestID (it was null).", PolicyResult.FAILURE_EXCEPTION);
255 return PolicyResult.FAILURE_EXCEPTION;
258 // Sanity check the response message
260 if (appcResponse.Status == null) {
262 // We cannot tell what happened if this doesn't exist
264 this.completeOperation(operationAttempt, "Policy was unable to parse APP-C response status field (it was null).", PolicyResult.FAILURE_EXCEPTION);
265 return PolicyResult.FAILURE_EXCEPTION;
268 // Get the Response Code
270 ResponseCode code = ResponseCode.toResponseCode(appcResponse.Status.Code);
273 // We are unaware of this code
275 this.completeOperation(operationAttempt, "Policy was unable to parse APP-C response status code field.", PolicyResult.FAILURE_EXCEPTION);
276 return PolicyResult.FAILURE_EXCEPTION;
279 // Ok, let's figure out what APP-C's response is
284 // This is good, they got our original message and
287 // Is there any need to track this?
293 // We'll consider these two codes as exceptions
295 this.completeOperation(operationAttempt, appcResponse.getStatus().Description, PolicyResult.FAILURE_EXCEPTION);
296 if (this.policyResult != null && this.policyResult.equals(PolicyResult.FAILURE_TIMEOUT)) {
299 return PolicyResult.FAILURE_EXCEPTION;
304 this.completeOperation(operationAttempt, appcResponse.getStatus().Description, PolicyResult.SUCCESS);
305 if (this.policyResult != null && this.policyResult.equals(PolicyResult.FAILURE_TIMEOUT)) {
308 return PolicyResult.SUCCESS;
313 this.completeOperation(operationAttempt, appcResponse.getStatus().Description, PolicyResult.FAILURE);
314 if (this.policyResult != null && this.policyResult.equals(PolicyResult.FAILURE_TIMEOUT)) {
317 return PolicyResult.FAILURE;
320 else if (response instanceof LCMResponseWrapper) {
322 LCMResponseWrapper dmaapResponse = (LCMResponseWrapper) response;
325 * Parse out the operation attempt using the subrequestid
327 Integer operationAttempt = AppcLcmActorServiceProvider.parseOperationAttempt(dmaapResponse.getBody().getCommonHeader().getSubRequestId());
328 if (operationAttempt == null) {
329 this.completeOperation(operationAttempt, "Policy was unable to parse APP-C SubRequestID (it was null).", PolicyResult.FAILURE_EXCEPTION);
333 * Process the APPCLCM response to see what PolicyResult
336 AbstractMap.SimpleEntry<PolicyResult, String> result = AppcLcmActorServiceProvider.processResponse(dmaapResponse);
338 if (result.getKey() != null) {
339 this.completeOperation(operationAttempt, result.getValue(), result.getKey());
340 if (PolicyResult.FAILURE_TIMEOUT.equals(this.policyResult)) {
343 return result.getKey();
346 } else if (response instanceof SOResponse) {
347 SOResponse msoResponse = (SOResponse) response;
348 switch (msoResponse.httpResponseCode) {
352 // Consider it as success
354 this.completeOperation(new Integer(1), msoResponse.httpResponseCode + " Success", PolicyResult.SUCCESS);
355 if (this.policyResult != null && this.policyResult.equals(PolicyResult.FAILURE_TIMEOUT)) {
358 return PolicyResult.SUCCESS;
361 // Consider it as failure
363 this.completeOperation(new Integer(1), msoResponse.httpResponseCode + " Failed", PolicyResult.FAILURE);
364 if (this.policyResult != null && this.policyResult.equals(PolicyResult.FAILURE_TIMEOUT)) {
367 return PolicyResult.FAILURE;
375 public Integer getOperationTimeout() {
379 if (this.policy == null) {
380 logger.debug("getOperationTimeout returning 0");
383 logger.debug("getOperationTimeout returning {}", this.policy.getTimeout());
384 return this.policy.getTimeout();
387 public String getOperationTimeoutString(int defaultTimeout) {
388 Integer to = this.getOperationTimeout();
389 if (to == null || to == 0) {
390 return Integer.toString(defaultTimeout) + "s";
392 return to.toString() + "s";
395 public PolicyResult getOperationResult() {
396 return this.policyResult;
399 public String getOperationMessage() {
400 if (this.currentOperation != null && this.currentOperation.operation != null) {
401 return this.currentOperation.operation.toMessage();
403 if (this.operationHistory != null && this.operationHistory.size() > 0) {
404 return this.operationHistory.getLast().operation.toMessage();
409 public String getOperationMessage(String guardResult) {
410 if (this.currentOperation != null && this.currentOperation.operation != null) {
411 return this.currentOperation.operation.toMessage()+ ", Guard result: " + guardResult;
413 if (this.operationHistory != null && this.operationHistory.size() > 0) {
414 return this.operationHistory.getLast().operation.toMessage() + ", Guard result: " + guardResult;
419 public String getOperationHistory() {
420 if (this.currentOperation != null && this.currentOperation.operation != null) {
421 return this.currentOperation.operation.toHistory();
423 if (this.operationHistory != null && this.operationHistory.size() > 0) {
424 return this.operationHistory.getLast().operation.toHistory();
429 public LinkedList<ControlLoopOperation> getHistory() {
430 LinkedList<ControlLoopOperation> history = new LinkedList<ControlLoopOperation>();
431 for (Operation op : this.operationHistory) {
432 history.add(new ControlLoopOperation(op.operation));
438 public void setOperationHasTimedOut() {
442 this.completeOperation(this.attempts, "Operation timed out", PolicyResult.FAILURE_TIMEOUT);
445 public void setOperationHasGuardDeny() {
449 this.completeOperation(this.attempts, "Operation denied by Guard", PolicyResult.FAILURE_GUARD);
452 public boolean isOperationComplete() {
454 // Is there currently a result?
456 if (this.policyResult == null) {
458 // either we are in process or we
464 // We have some result, check if the operation failed
466 if (this.policyResult.equals(PolicyResult.FAILURE)) {
468 // Check if there were no retries specified
470 if (policy.getRetry() == null || policy.getRetry() == 0) {
472 // The result is the failure
479 if (this.isRetriesMaxedOut()) {
481 // No more attempts allowed, reset
482 // that our actual result is failure due to retries
484 this.policyResult = PolicyResult.FAILURE_RETRIES;
488 // There are more attempts available to try the
495 // Other results mean we are done
500 public boolean isOperationRunning() {
501 return (this.currentOperation != null);
504 private boolean isRetriesMaxedOut() {
505 if (policy.getRetry() == null || policy.getRetry() == 0) {
507 // There were NO retries specified, so declare
508 // this as completed.
510 return (this.attempts > 0);
512 return (this.attempts > policy.getRetry());
515 private void storeOperationInDataBase(){
518 Properties props = new Properties();
519 try (InputStream is = org.onap.policy.guard.PIPEngineGetHistory.class.getResourceAsStream(org.onap.policy.guard.PIPEngineGetHistory.OPS_HIST_PROPS_LOC)){
521 } catch (Exception ex) {
522 logger.error("getCountFromDB threw: ", ex);
525 String OpsHistPU = System.getProperty("OperationsHistoryPU");
526 if(OpsHistPU == null || !OpsHistPU.equals("TestOperationsHistoryPU")){
527 OpsHistPU = "OperationsHistoryPU";
534 em = Persistence.createEntityManagerFactory(OpsHistPU, props).createEntityManager();
536 logger.error("storeOperationInDataBase threw: ", e);
540 OperationsHistoryDbEntry newEntry = new OperationsHistoryDbEntry();
542 newEntry.closedLoopName = this.onset.closedLoopControlName;
543 newEntry.requestId = this.onset.requestID.toString();
544 newEntry.actor = this.currentOperation.operation.actor;
545 newEntry.operation = this.currentOperation.operation.operation;
546 newEntry.target = this.eventManager.getTargetInstance(this.policy);
547 newEntry.starttime = Timestamp.from(this.currentOperation.operation.start);
548 newEntry.subrequestId = this.currentOperation.operation.subRequestId;
549 newEntry.endtime = new Timestamp(this.currentOperation.operation.end.toEpochMilli());
550 newEntry.message = this.currentOperation.operation.message;
551 newEntry.outcome = this.currentOperation.operation.outcome;
553 em.getTransaction().begin();
554 em.persist(newEntry);
555 em.getTransaction().commit();
563 private void completeOperation(Integer attempt, String message, PolicyResult result) {
564 if (attempt == null) {
565 logger.debug("attempt cannot be null (i.e. subRequestID)");
568 if (this.currentOperation != null) {
569 if (this.currentOperation.attempt == attempt.intValue()) {
570 this.currentOperation.operation.end = Instant.now();
571 this.currentOperation.operation.message = message;
572 this.currentOperation.operation.outcome = result.toString();
573 this.currentOperation.policyResult = result;
575 // Save it in history
577 this.operationHistory.add(this.currentOperation);
578 this.storeOperationInDataBase();
580 // Set our last result
582 this.policyResult = result;
584 // Clear the current operation field
586 this.currentOperation = null;
589 logger.debug("not current");
591 for (Operation op : this.operationHistory) {
592 if (op.attempt == attempt.intValue()) {
593 op.operation.end = Instant.now();
594 op.operation.message = message;
595 op.operation.outcome = result.toString();
596 op.policyResult = result;
600 logger.debug("Could not find associated operation");