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;
28 import java.util.Properties;
30 import javax.persistence.EntityManager;
31 import javax.persistence.Persistence;
33 import org.onap.policy.aai.util.AAIException;
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.so.SOActorServiceProvider;
44 import org.onap.policy.controlloop.actor.vfc.VFCActorServiceProvider;
45 import org.onap.policy.controlloop.policy.Policy;
46 import org.onap.policy.controlloop.policy.PolicyResult;
47 import org.onap.policy.drools.system.PolicyEngine;
48 import org.onap.policy.guard.Util;
49 import org.onap.policy.so.SOResponse;
50 import org.onap.policy.vfc.VFCResponse;
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) throws AAIException {
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 this.currentOperation = operation;
210 if ("ModifyConfig".equalsIgnoreCase(policy.getRecipe())) {
212 this.operationRequest = APPCActorServiceProvider.constructRequest((VirtualControlLoopEvent)onset, operation.operation, this.policy);
215 this.operationRequest = AppcLcmActorServiceProvider.constructRequest((VirtualControlLoopEvent) onset, operation.operation, this.policy);
218 // Save the operation
221 return operationRequest;
223 SOActorServiceProvider SOAsp = new SOActorServiceProvider();
224 this.operationRequest = SOAsp.constructRequest((VirtualControlLoopEvent)onset, operation.operation, this.policy);
226 // Save the operation
227 this.currentOperation = operation;
229 if (this.operationRequest == null) {
230 this.policyResult = PolicyResult.FAILURE;
233 return operationRequest;
235 this.operationRequest = VFCActorServiceProvider.constructRequest((VirtualControlLoopEvent) onset, operation.operation, this.policy, this.eventManager.getVnfResponse());
236 this.currentOperation = operation;
237 return operationRequest;
243 public PolicyResult onResponse(Object response) {
245 // Which response is it?
247 if (response instanceof Response) {
251 Response appcResponse = (Response) response;
253 // Determine which subrequestID (ie. attempt)
255 Integer operationAttempt = null;
257 operationAttempt = Integer.parseInt(appcResponse.CommonHeader.SubRequestID);
258 } catch (NumberFormatException e) {
260 // We cannot tell what happened if this doesn't exist
262 this.completeOperation(operationAttempt, "Policy was unable to parse APP-C SubRequestID (it was null).", PolicyResult.FAILURE_EXCEPTION);
263 return PolicyResult.FAILURE_EXCEPTION;
266 // Sanity check the response message
268 if (appcResponse.Status == null) {
270 // We cannot tell what happened if this doesn't exist
272 this.completeOperation(operationAttempt, "Policy was unable to parse APP-C response status field (it was null).", PolicyResult.FAILURE_EXCEPTION);
273 return PolicyResult.FAILURE_EXCEPTION;
276 // Get the Response Code
278 ResponseCode code = ResponseCode.toResponseCode(appcResponse.Status.Code);
281 // We are unaware of this code
283 this.completeOperation(operationAttempt, "Policy was unable to parse APP-C response status code field.", PolicyResult.FAILURE_EXCEPTION);
284 return PolicyResult.FAILURE_EXCEPTION;
287 // Ok, let's figure out what APP-C's response is
292 // This is good, they got our original message and
295 // Is there any need to track this?
301 // We'll consider these two codes as exceptions
303 this.completeOperation(operationAttempt, appcResponse.getStatus().Description, PolicyResult.FAILURE_EXCEPTION);
304 if (this.policyResult != null && this.policyResult.equals(PolicyResult.FAILURE_TIMEOUT)) {
307 return PolicyResult.FAILURE_EXCEPTION;
312 this.completeOperation(operationAttempt, appcResponse.getStatus().Description, PolicyResult.SUCCESS);
313 if (this.policyResult != null && this.policyResult.equals(PolicyResult.FAILURE_TIMEOUT)) {
316 return PolicyResult.SUCCESS;
321 this.completeOperation(operationAttempt, appcResponse.getStatus().Description, PolicyResult.FAILURE);
322 if (this.policyResult != null && this.policyResult.equals(PolicyResult.FAILURE_TIMEOUT)) {
325 return PolicyResult.FAILURE;
328 else if (response instanceof LCMResponseWrapper) {
330 LCMResponseWrapper dmaapResponse = (LCMResponseWrapper) response;
333 * Parse out the operation attempt using the subrequestid
335 Integer operationAttempt = AppcLcmActorServiceProvider.parseOperationAttempt(dmaapResponse.getBody().getCommonHeader().getSubRequestId());
336 if (operationAttempt == null) {
337 this.completeOperation(operationAttempt, "Policy was unable to parse APP-C SubRequestID (it was null).", PolicyResult.FAILURE_EXCEPTION);
341 * Process the APPCLCM response to see what PolicyResult
344 AbstractMap.SimpleEntry<PolicyResult, String> result = AppcLcmActorServiceProvider.processResponse(dmaapResponse);
346 if (result.getKey() != null) {
347 this.completeOperation(operationAttempt, result.getValue(), result.getKey());
348 if (PolicyResult.FAILURE_TIMEOUT.equals(this.policyResult)) {
351 return result.getKey();
354 } else if (response instanceof SOResponse) {
355 SOResponse msoResponse = (SOResponse) response;
357 switch (msoResponse.httpResponseCode) {
361 // Consider it as success
363 this.completeOperation(this.attempts, msoResponse.httpResponseCode + " Success", PolicyResult.SUCCESS);
364 if (this.policyResult != null && this.policyResult.equals(PolicyResult.FAILURE_TIMEOUT)) {
367 return PolicyResult.SUCCESS;
370 // Consider it as failure
372 this.completeOperation(this.attempts, msoResponse.httpResponseCode + " Failed", PolicyResult.FAILURE);
373 if (this.policyResult != null && this.policyResult.equals(PolicyResult.FAILURE_TIMEOUT)) {
376 return PolicyResult.FAILURE;
379 } else if (response instanceof VFCResponse) {
380 VFCResponse vfcResponse = (VFCResponse) response;
382 if (vfcResponse.responseDescriptor.getStatus().equalsIgnoreCase("finished")) {
384 // Consider it as success
386 this.completeOperation(this.attempts, " Success", PolicyResult.SUCCESS);
387 if (this.policyResult != null && this.policyResult.equals(PolicyResult.FAILURE_TIMEOUT)) {
390 return PolicyResult.SUCCESS;
393 // Consider it as failure
395 this.completeOperation(this.attempts, " Failed", PolicyResult.FAILURE);
396 if (this.policyResult != null && this.policyResult.equals(PolicyResult.FAILURE_TIMEOUT)) {
399 // increment operation attempts for retries
401 return PolicyResult.FAILURE;
407 public Integer getOperationTimeout() {
411 if (this.policy == null) {
412 logger.debug("getOperationTimeout returning 0");
415 logger.debug("getOperationTimeout returning {}", this.policy.getTimeout());
416 return this.policy.getTimeout();
419 public String getOperationTimeoutString(int defaultTimeout) {
420 Integer to = this.getOperationTimeout();
421 if (to == null || to == 0) {
422 return Integer.toString(defaultTimeout) + "s";
424 return to.toString() + "s";
427 public PolicyResult getOperationResult() {
428 return this.policyResult;
431 public String getOperationMessage() {
432 if (this.currentOperation != null && this.currentOperation.operation != null) {
433 return this.currentOperation.operation.toMessage();
436 if (!this.operationHistory.isEmpty()) {
437 return this.operationHistory.getLast().operation.toMessage();
442 public String getOperationMessage(String guardResult) {
443 if (this.currentOperation != null && this.currentOperation.operation != null) {
444 return this.currentOperation.operation.toMessage()+ ", Guard result: " + guardResult;
447 if (!this.operationHistory.isEmpty()) {
448 return this.operationHistory.getLast().operation.toMessage() + ", Guard result: " + guardResult;
453 public String getOperationHistory() {
454 if (this.currentOperation != null && this.currentOperation.operation != null) {
455 return this.currentOperation.operation.toHistory();
458 if (!this.operationHistory.isEmpty()) {
459 return this.operationHistory.getLast().operation.toHistory();
464 public LinkedList<ControlLoopOperation> getHistory() {
465 LinkedList<ControlLoopOperation> history = new LinkedList<ControlLoopOperation>();
466 for (Operation op : this.operationHistory) {
467 history.add(new ControlLoopOperation(op.operation));
473 public void setOperationHasTimedOut() {
477 this.completeOperation(this.attempts, "Operation timed out", PolicyResult.FAILURE_TIMEOUT);
480 public void setOperationHasGuardDeny() {
484 this.completeOperation(this.attempts, "Operation denied by Guard", PolicyResult.FAILURE_GUARD);
487 public void setOperationHasException(String message) {
488 this.completeOperation(this.attempts, message, PolicyResult.FAILURE_EXCEPTION);
491 public boolean isOperationComplete() {
493 // Is there currently a result?
495 if (this.policyResult == null) {
497 // either we are in process or we
503 // We have some result, check if the operation failed
505 if (this.policyResult.equals(PolicyResult.FAILURE)) {
507 // Check if there were no retries specified
509 if (policy.getRetry() == null || policy.getRetry() == 0) {
511 // The result is the failure
518 if (this.isRetriesMaxedOut()) {
520 // No more attempts allowed, reset
521 // that our actual result is failure due to retries
523 this.policyResult = PolicyResult.FAILURE_RETRIES;
527 // There are more attempts available to try the
534 // Other results mean we are done
539 public boolean isOperationRunning() {
540 return (this.currentOperation != null);
543 private boolean isRetriesMaxedOut() {
544 if (policy.getRetry() == null || policy.getRetry() == 0) {
546 // There were NO retries specified, so declare
547 // this as completed.
549 return (this.attempts > 0);
551 return (this.attempts > policy.getRetry());
554 private void storeOperationInDataBase(){
555 // Only store in DB if enabled
556 boolean guardEnabled = "false".equalsIgnoreCase(PolicyEngine.manager.getEnvironmentProperty("guard.disabled"));
563 Properties props = new Properties();
564 if(PolicyEngine.manager.getEnvironmentProperty(Util.ONAP_KEY_URL) != null &&
565 PolicyEngine.manager.getEnvironmentProperty(Util.ONAP_KEY_USER) != null &&
566 PolicyEngine.manager.getEnvironmentProperty(Util.ONAP_KEY_PASS) != null){
567 props.put(Util.ECLIPSE_LINK_KEY_URL, PolicyEngine.manager.getEnvironmentProperty(Util.ONAP_KEY_URL));
568 props.put(Util.ECLIPSE_LINK_KEY_USER, PolicyEngine.manager.getEnvironmentProperty(Util.ONAP_KEY_USER));
569 props.put(Util.ECLIPSE_LINK_KEY_PASS, PolicyEngine.manager.getEnvironmentProperty(Util.ONAP_KEY_PASS));
573 String OpsHistPU = System.getProperty("OperationsHistoryPU");
574 if(OpsHistPU == null || !OpsHistPU.equals("TestOperationsHistoryPU")){
575 OpsHistPU = "OperationsHistoryPU";
582 em = Persistence.createEntityManagerFactory(OpsHistPU, props).createEntityManager();
584 logger.error("storeOperationInDataBase threw: ", e);
588 OperationsHistoryDbEntry newEntry = new OperationsHistoryDbEntry();
590 newEntry.closedLoopName = this.onset.closedLoopControlName;
591 newEntry.requestId = this.onset.requestID.toString();
592 newEntry.actor = this.currentOperation.operation.actor;
593 newEntry.operation = this.currentOperation.operation.operation;
594 newEntry.target = this.eventManager.getTargetInstance(this.policy);
595 newEntry.starttime = Timestamp.from(this.currentOperation.operation.start);
596 newEntry.subrequestId = this.currentOperation.operation.subRequestId;
597 newEntry.endtime = new Timestamp(this.currentOperation.operation.end.toEpochMilli());
598 newEntry.message = this.currentOperation.operation.message;
599 newEntry.outcome = this.currentOperation.operation.outcome;
601 em.getTransaction().begin();
602 em.persist(newEntry);
603 em.getTransaction().commit();
611 private void completeOperation(Integer attempt, String message, PolicyResult result) {
612 if (attempt == null) {
613 logger.debug("attempt cannot be null (i.e. subRequestID)");
616 if (this.currentOperation != null) {
617 if (this.currentOperation.attempt == attempt.intValue()) {
618 this.currentOperation.operation.end = Instant.now();
619 this.currentOperation.operation.message = message;
620 this.currentOperation.operation.outcome = result.toString();
621 this.currentOperation.policyResult = result;
623 // Save it in history
625 this.operationHistory.add(this.currentOperation);
626 this.storeOperationInDataBase();
628 // Set our last result
630 this.policyResult = result;
632 // Clear the current operation field
634 this.currentOperation = null;
637 logger.debug("not current");
639 for (Operation op : this.operationHistory) {
640 if (op.attempt == attempt.intValue()) {
641 op.operation.end = Instant.now();
642 op.operation.message = message;
643 op.operation.outcome = result.toString();
644 op.policyResult = result;
648 logger.debug("Could not find associated operation");