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.drools.system.PolicyEngine;
48 import org.onap.policy.so.SOResponse;
49 import org.onap.policy.vfc.VFCResponse;
50 import org.onap.policy.guard.Util;
51 import org.slf4j.Logger;
52 import org.slf4j.LoggerFactory;
54 public class ControlLoopOperationManager implements Serializable {
59 private static final long serialVersionUID = -3773199283624595410L;
60 private static final Logger logger = LoggerFactory.getLogger(ControlLoopOperationManager.class);
63 public String toString() {
64 return "ControlLoopOperationManager [onset=" + (onset != null ? onset.requestID : "null") + ", policy="
65 + (policy != null ? policy.getId() : "null") + ", attempts=" + attempts
66 + ", policyResult=" + policyResult
67 + ", currentOperation=" + currentOperation + ", operationHistory=" + operationHistory
72 // These properties are not changeable, but accessible
73 // for Drools Rule statements.
75 //public final ATTControlLoopEvent onset;
76 public final ControlLoopEvent onset;
77 public final transient Policy policy;
80 // Properties used to track the Operation
82 private int attempts = 0;
83 private transient Operation currentOperation = null;
84 private LinkedList<Operation> operationHistory = new LinkedList<Operation>();
85 private PolicyResult policyResult = null;
86 private ControlLoopEventManager eventManager = null;
88 public ControlLoopEventManager getEventManager() {
92 public void setEventManager(ControlLoopEventManager eventManager) {
93 this.eventManager = eventManager;
98 // Internal class used for tracking
100 private class Operation {
101 public ControlLoopOperation operation = new ControlLoopOperation();
102 public PolicyResult policyResult = null;
103 public int attempt = 0;
106 public String toString() {
107 return "Operation [attempt=" + attempt + ", policyResult=" + policyResult + ", operation=" + operation
112 private String guardApprovalStatus = "NONE";//"NONE", "PERMIT", "DENY"
113 private transient Object operationRequest;
115 public Object getOperationRequest() {
116 return operationRequest;
119 public String getGuardApprovalStatus() {
120 return guardApprovalStatus;
122 public void setGuardApprovalStatus(String guardApprovalStatus) {
123 this.guardApprovalStatus = guardApprovalStatus;
127 public ControlLoopOperationManager(ControlLoopEvent onset, Policy policy, ControlLoopEventManager em) throws ControlLoopException {
129 this.policy = policy;
130 this.guardApprovalStatus = "NONE";
131 this.eventManager = em;
134 // Let's make a sanity check
136 switch (policy.getActor()) {
144 throw new ControlLoopException("ControlLoopEventManager: policy has an unknown actor.");
148 public Object startOperation(/*VirtualControlLoopEvent*/ControlLoopEvent onset) {
150 // They shouldn't call us if we currently running something
152 if (this.currentOperation != null) {
154 // what do we do if we are already running an operation?
159 // Check if we have maxed out on retries
161 if (this.policy.getRetry() == null || this.policy.getRetry() < 1) {
163 // No retries are allowed, so check have we even made
164 // one attempt to execute the operation?
166 if (this.attempts >= 1) {
168 // We have, let's ensure our PolicyResult is set
170 if (this.policyResult == null) {
171 this.policyResult = PolicyResult.FAILURE_RETRIES;
180 // Have we maxed out on retries?
182 if (this.attempts > this.policy.getRetry()) {
183 if (this.policyResult == null) {
184 this.policyResult = PolicyResult.FAILURE_RETRIES;
192 this.policyResult = null;
193 Operation operation = new Operation();
194 operation.attempt = ++this.attempts;
195 operation.operation.actor = this.policy.getActor();
196 operation.operation.operation = this.policy.getRecipe();
197 operation.operation.target = this.policy.getTarget().toString();
198 operation.operation.subRequestId = Integer.toString(operation.attempt);
200 // Now determine which actor we need to construct a request for
202 switch (policy.getActor()) {
205 * If the recipe is ModifyConfig, a legacy APPC
206 * request is constructed. Otherwise an LCMRequest
209 if ("ModifyConfig".equalsIgnoreCase(policy.getRecipe())) {
211 this.operationRequest = APPCActorServiceProvider.constructRequest((VirtualControlLoopEvent)onset, operation.operation, this.policy);
214 this.operationRequest = AppcLcmActorServiceProvider.constructRequest((VirtualControlLoopEvent) onset, operation.operation, this.policy);
217 // Save the operation
219 this.currentOperation = operation;
220 return operationRequest;
222 SOActorServiceProvider SOAsp = new SOActorServiceProvider();
223 this.operationRequest = SOAsp.constructRequest((VirtualControlLoopEvent)onset, operation.operation, this.policy);
225 // Save the operation
226 this.currentOperation = operation;
228 if (this.operationRequest == null) {
229 this.policyResult = PolicyResult.FAILURE;
232 return operationRequest;
234 this.operationRequest = VFCActorServiceProvider.constructRequest((VirtualControlLoopEvent) onset, operation.operation, this.policy, this.eventManager.getVnfResponse());
235 this.currentOperation = operation;
236 return operationRequest;
242 public PolicyResult onResponse(Object response) {
244 // Which response is it?
246 if (response instanceof Response) {
250 Response appcResponse = (Response) response;
252 // Determine which subrequestID (ie. attempt)
254 Integer operationAttempt = null;
256 operationAttempt = Integer.parseInt(appcResponse.CommonHeader.SubRequestID);
257 } catch (NumberFormatException e) {
259 // We cannot tell what happened if this doesn't exist
261 this.completeOperation(operationAttempt, "Policy was unable to parse APP-C SubRequestID (it was null).", PolicyResult.FAILURE_EXCEPTION);
262 return PolicyResult.FAILURE_EXCEPTION;
265 // Sanity check the response message
267 if (appcResponse.Status == null) {
269 // We cannot tell what happened if this doesn't exist
271 this.completeOperation(operationAttempt, "Policy was unable to parse APP-C response status field (it was null).", PolicyResult.FAILURE_EXCEPTION);
272 return PolicyResult.FAILURE_EXCEPTION;
275 // Get the Response Code
277 ResponseCode code = ResponseCode.toResponseCode(appcResponse.Status.Code);
280 // We are unaware of this code
282 this.completeOperation(operationAttempt, "Policy was unable to parse APP-C response status code field.", PolicyResult.FAILURE_EXCEPTION);
283 return PolicyResult.FAILURE_EXCEPTION;
286 // Ok, let's figure out what APP-C's response is
291 // This is good, they got our original message and
294 // Is there any need to track this?
300 // We'll consider these two codes as exceptions
302 this.completeOperation(operationAttempt, appcResponse.getStatus().Description, PolicyResult.FAILURE_EXCEPTION);
303 if (this.policyResult != null && this.policyResult.equals(PolicyResult.FAILURE_TIMEOUT)) {
306 return PolicyResult.FAILURE_EXCEPTION;
311 this.completeOperation(operationAttempt, appcResponse.getStatus().Description, PolicyResult.SUCCESS);
312 if (this.policyResult != null && this.policyResult.equals(PolicyResult.FAILURE_TIMEOUT)) {
315 return PolicyResult.SUCCESS;
320 this.completeOperation(operationAttempt, appcResponse.getStatus().Description, PolicyResult.FAILURE);
321 if (this.policyResult != null && this.policyResult.equals(PolicyResult.FAILURE_TIMEOUT)) {
324 return PolicyResult.FAILURE;
327 else if (response instanceof LCMResponseWrapper) {
329 LCMResponseWrapper dmaapResponse = (LCMResponseWrapper) response;
332 * Parse out the operation attempt using the subrequestid
334 Integer operationAttempt = AppcLcmActorServiceProvider.parseOperationAttempt(dmaapResponse.getBody().getCommonHeader().getSubRequestId());
335 if (operationAttempt == null) {
336 this.completeOperation(operationAttempt, "Policy was unable to parse APP-C SubRequestID (it was null).", PolicyResult.FAILURE_EXCEPTION);
340 * Process the APPCLCM response to see what PolicyResult
343 AbstractMap.SimpleEntry<PolicyResult, String> result = AppcLcmActorServiceProvider.processResponse(dmaapResponse);
345 if (result.getKey() != null) {
346 this.completeOperation(operationAttempt, result.getValue(), result.getKey());
347 if (PolicyResult.FAILURE_TIMEOUT.equals(this.policyResult)) {
350 return result.getKey();
353 } else if (response instanceof SOResponse) {
354 SOResponse msoResponse = (SOResponse) response;
356 switch (msoResponse.httpResponseCode) {
360 // Consider it as success
362 this.completeOperation(this.attempts, msoResponse.httpResponseCode + " Success", PolicyResult.SUCCESS);
363 if (this.policyResult != null && this.policyResult.equals(PolicyResult.FAILURE_TIMEOUT)) {
366 return PolicyResult.SUCCESS;
369 // Consider it as failure
371 this.completeOperation(this.attempts, msoResponse.httpResponseCode + " Failed", PolicyResult.FAILURE);
372 if (this.policyResult != null && this.policyResult.equals(PolicyResult.FAILURE_TIMEOUT)) {
375 return PolicyResult.FAILURE;
378 } else if (response instanceof VFCResponse) {
379 VFCResponse vfcResponse = (VFCResponse) response;
381 if (vfcResponse.responseDescriptor.getStatus().equalsIgnoreCase("finished")) {
383 // Consider it as success
385 this.completeOperation(this.attempts, " Success", PolicyResult.SUCCESS);
386 if (this.policyResult != null && this.policyResult.equals(PolicyResult.FAILURE_TIMEOUT)) {
389 return PolicyResult.SUCCESS;
392 // Consider it as failure
394 this.completeOperation(this.attempts, " Failed", PolicyResult.FAILURE);
395 if (this.policyResult != null && this.policyResult.equals(PolicyResult.FAILURE_TIMEOUT)) {
398 // increment operation attempts for retries
400 return PolicyResult.FAILURE;
406 public Integer getOperationTimeout() {
410 if (this.policy == null) {
411 logger.debug("getOperationTimeout returning 0");
414 logger.debug("getOperationTimeout returning {}", this.policy.getTimeout());
415 return this.policy.getTimeout();
418 public String getOperationTimeoutString(int defaultTimeout) {
419 Integer to = this.getOperationTimeout();
420 if (to == null || to == 0) {
421 return Integer.toString(defaultTimeout) + "s";
423 return to.toString() + "s";
426 public PolicyResult getOperationResult() {
427 return this.policyResult;
430 public String getOperationMessage() {
431 if (this.currentOperation != null && this.currentOperation.operation != null) {
432 return this.currentOperation.operation.toMessage();
435 if (!this.operationHistory.isEmpty()) {
436 return this.operationHistory.getLast().operation.toMessage();
441 public String getOperationMessage(String guardResult) {
442 if (this.currentOperation != null && this.currentOperation.operation != null) {
443 return this.currentOperation.operation.toMessage()+ ", Guard result: " + guardResult;
446 if (!this.operationHistory.isEmpty()) {
447 return this.operationHistory.getLast().operation.toMessage() + ", Guard result: " + guardResult;
452 public String getOperationHistory() {
453 if (this.currentOperation != null && this.currentOperation.operation != null) {
454 return this.currentOperation.operation.toHistory();
457 if (!this.operationHistory.isEmpty()) {
458 return this.operationHistory.getLast().operation.toHistory();
463 public LinkedList<ControlLoopOperation> getHistory() {
464 LinkedList<ControlLoopOperation> history = new LinkedList<ControlLoopOperation>();
465 for (Operation op : this.operationHistory) {
466 history.add(new ControlLoopOperation(op.operation));
472 public void setOperationHasTimedOut() {
476 this.completeOperation(this.attempts, "Operation timed out", PolicyResult.FAILURE_TIMEOUT);
479 public void setOperationHasGuardDeny() {
483 this.completeOperation(this.attempts, "Operation denied by Guard", PolicyResult.FAILURE_GUARD);
486 public boolean isOperationComplete() {
488 // Is there currently a result?
490 if (this.policyResult == null) {
492 // either we are in process or we
498 // We have some result, check if the operation failed
500 if (this.policyResult.equals(PolicyResult.FAILURE)) {
502 // Check if there were no retries specified
504 if (policy.getRetry() == null || policy.getRetry() == 0) {
506 // The result is the failure
513 if (this.isRetriesMaxedOut()) {
515 // No more attempts allowed, reset
516 // that our actual result is failure due to retries
518 this.policyResult = PolicyResult.FAILURE_RETRIES;
522 // There are more attempts available to try the
529 // Other results mean we are done
534 public boolean isOperationRunning() {
535 return (this.currentOperation != null);
538 private boolean isRetriesMaxedOut() {
539 if (policy.getRetry() == null || policy.getRetry() == 0) {
541 // There were NO retries specified, so declare
542 // this as completed.
544 return (this.attempts > 0);
546 return (this.attempts > policy.getRetry());
549 private void storeOperationInDataBase(){
550 // Only store in DB if enabled
551 boolean guardEnabled = "false".equalsIgnoreCase(PolicyEngine.manager.getEnvironmentProperty("guard.disabled"));
558 Properties props = new Properties();
559 if(PolicyEngine.manager.getEnvironmentProperty(Util.ONAP_KEY_URL) != null &&
560 PolicyEngine.manager.getEnvironmentProperty(Util.ONAP_KEY_USER) != null &&
561 PolicyEngine.manager.getEnvironmentProperty(Util.ONAP_KEY_PASS) != null){
562 props.put(Util.ECLIPSE_LINK_KEY_URL, PolicyEngine.manager.getEnvironmentProperty(Util.ONAP_KEY_URL));
563 props.put(Util.ECLIPSE_LINK_KEY_USER, PolicyEngine.manager.getEnvironmentProperty(Util.ONAP_KEY_USER));
564 props.put(Util.ECLIPSE_LINK_KEY_PASS, PolicyEngine.manager.getEnvironmentProperty(Util.ONAP_KEY_PASS));
568 String OpsHistPU = System.getProperty("OperationsHistoryPU");
569 if(OpsHistPU == null || !OpsHistPU.equals("TestOperationsHistoryPU")){
570 OpsHistPU = "OperationsHistoryPU";
577 em = Persistence.createEntityManagerFactory(OpsHistPU, props).createEntityManager();
579 logger.error("storeOperationInDataBase threw: ", e);
583 OperationsHistoryDbEntry newEntry = new OperationsHistoryDbEntry();
585 newEntry.closedLoopName = this.onset.closedLoopControlName;
586 newEntry.requestId = this.onset.requestID.toString();
587 newEntry.actor = this.currentOperation.operation.actor;
588 newEntry.operation = this.currentOperation.operation.operation;
589 newEntry.target = this.eventManager.getTargetInstance(this.policy);
590 newEntry.starttime = Timestamp.from(this.currentOperation.operation.start);
591 newEntry.subrequestId = this.currentOperation.operation.subRequestId;
592 newEntry.endtime = new Timestamp(this.currentOperation.operation.end.toEpochMilli());
593 newEntry.message = this.currentOperation.operation.message;
594 newEntry.outcome = this.currentOperation.operation.outcome;
596 em.getTransaction().begin();
597 em.persist(newEntry);
598 em.getTransaction().commit();
606 private void completeOperation(Integer attempt, String message, PolicyResult result) {
607 if (attempt == null) {
608 logger.debug("attempt cannot be null (i.e. subRequestID)");
611 if (this.currentOperation != null) {
612 if (this.currentOperation.attempt == attempt.intValue()) {
613 this.currentOperation.operation.end = Instant.now();
614 this.currentOperation.operation.message = message;
615 this.currentOperation.operation.outcome = result.toString();
616 this.currentOperation.policyResult = result;
618 // Save it in history
620 this.operationHistory.add(this.currentOperation);
621 this.storeOperationInDataBase();
623 // Set our last result
625 this.policyResult = result;
627 // Clear the current operation field
629 this.currentOperation = null;
632 logger.debug("not current");
634 for (Operation op : this.operationHistory) {
635 if (op.attempt == attempt.intValue()) {
636 op.operation.end = Instant.now();
637 op.operation.message = message;
638 op.operation.outcome = result.toString();
639 op.policyResult = result;
643 logger.debug("Could not find associated operation");