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.LinkedList;
28 import javax.persistence.EntityManager;
29 import javax.persistence.Persistence;
31 import org.onap.policy.appc.Response;
32 import org.onap.policy.appc.ResponseCode;
33 import org.onap.policy.controlloop.ControlLoopEvent;
34 import org.onap.policy.controlloop.ControlLoopOperation;
35 import org.onap.policy.controlloop.VirtualControlLoopEvent;
36 import org.onap.policy.controlloop.ControlLoopException;
37 import org.onap.policy.controlloop.policy.Policy;
38 import org.onap.policy.controlloop.policy.PolicyResult;
39 import org.onap.policy.controlloop.actor.appc.APPCActorServiceProvider;
40 import org.slf4j.Logger;
41 import org.slf4j.LoggerFactory;
44 public class ControlLoopOperationManager implements Serializable {
49 private static final long serialVersionUID = -3773199283624595410L;
50 private static final Logger logger = LoggerFactory.getLogger(ControlLoopOperationManager.class);
53 public String toString() {
54 return "ControlLoopOperationManager [onset=" + (onset != null ? onset.requestID : "null") + ", policy="
55 + (policy != null ? policy.getId() : "null") + ", attempts=" + attempts
56 + ", policyResult=" + policyResult
57 + ", currentOperation=" + currentOperation + ", operationHistory=" + operationHistory
62 // These properties are not changeable, but accessible
63 // for Drools Rule statements.
65 //public final ATTControlLoopEvent onset;
66 public final ControlLoopEvent onset;
67 public final Policy policy;
70 // Properties used to track the Operation
72 private int attempts = 0;
73 private Operation currentOperation = null;
74 private LinkedList<Operation> operationHistory = new LinkedList<Operation>();
75 private PolicyResult policyResult = null;
76 private ControlLoopEventManager eventManager = null;
78 public ControlLoopEventManager getEventManager() {
82 public void setEventManager(ControlLoopEventManager eventManager) {
83 this.eventManager = eventManager;
88 // Internal class used for tracking
90 private class Operation {
91 public ControlLoopOperation operation = new ControlLoopOperation();
92 public PolicyResult policyResult = null;
93 public int attempt = 0;
96 public String toString() {
97 return "Operation [attempt=" + attempt + ", policyResult=" + policyResult + ", operation=" + operation
102 private String guardApprovalStatus = "NONE";//"NONE", "PERMIT", "DENY"
103 private Object operationRequest;
105 public Object getOperationRequest() {
106 return operationRequest;
109 public String getGuardApprovalStatus() {
110 return guardApprovalStatus;
112 public void setGuardApprovalStatus(String guardApprovalStatus) {
113 this.guardApprovalStatus = guardApprovalStatus;
117 public ControlLoopOperationManager(/*ATTControlLoopEvent*/ControlLoopEvent onset, Policy policy, ControlLoopEventManager em) throws ControlLoopException {
119 this.policy = policy;
120 this.guardApprovalStatus = "NONE";
121 this.eventManager = em;
124 // Let's make a sanity check
126 switch (policy.getActor()) {
138 throw new ControlLoopException("ControlLoopEventManager: policy has an unknown actor.");
142 public Object startOperation(/*VirtualControlLoopEvent*/ControlLoopEvent onset) {
144 // They shouldn't call us if we currently running something
146 if (this.currentOperation != null) {
148 // what do we do if we are already running an operation?
153 // Check if we have maxed out on retries
155 if (this.policy.getRetry() == null || this.policy.getRetry() < 1) {
157 // No retries are allowed, so check have we even made
158 // one attempt to execute the operation?
160 if (this.attempts >= 1) {
162 // We have, let's ensure our PolicyResult is set
164 if (this.policyResult == null) {
165 this.policyResult = PolicyResult.FAILURE_RETRIES;
174 // Have we maxed out on retries?
176 if (this.attempts > this.policy.getRetry()) {
177 if (this.policyResult == null) {
178 this.policyResult = PolicyResult.FAILURE_RETRIES;
186 this.policyResult = null;
187 Operation operation = new Operation();
188 operation.attempt = ++this.attempts;
189 operation.operation.actor = this.policy.getActor().toString();
190 operation.operation.operation = this.policy.getRecipe();
191 operation.operation.target = this.policy.getTarget().toString();
192 operation.operation.subRequestId = Integer.toString(operation.attempt);
194 // Now determine which actor we need to construct a request for
196 switch (policy.getActor()) {
198 //Request request = APPCActorServiceProvider.constructRequest(onset, operation.operation, this.policy);
199 this.operationRequest = APPCActorServiceProvider.constructRequest((VirtualControlLoopEvent)onset, operation.operation, this.policy);
201 // Save the operation
203 this.currentOperation = operation;
204 //System.out.print("************* BEFORE STORING.....");
205 //this.storeOperationInDataBase("startOperation");
206 //System.out.print("************* AFTER STORING.....");
208 return operationRequest;
211 // We are not supporting MSO interface at the moment
213 System.out.println("We are not supporting MSO actor in the latest release.");
219 public PolicyResult onResponse(Object response) {
221 // Which response is it?
223 if (response instanceof Response) {
227 Response appcResponse = (Response) response;
229 // Determine which subrequestID (ie. attempt)
231 Integer operationAttempt = null;
233 operationAttempt = Integer.parseInt(appcResponse.CommonHeader.SubRequestID);
234 } catch (NumberFormatException e) {
236 // We cannot tell what happened if this doesn't exist
238 this.completeOperation(operationAttempt, "Policy was unable to parse APP-C SubRequestID (it was null).", PolicyResult.FAILURE_EXCEPTION);
239 return PolicyResult.FAILURE_EXCEPTION;
242 // Sanity check the response message
244 if (appcResponse.Status == null) {
246 // We cannot tell what happened if this doesn't exist
248 this.completeOperation(operationAttempt, "Policy was unable to parse APP-C response status field (it was null).", PolicyResult.FAILURE_EXCEPTION);
249 return PolicyResult.FAILURE_EXCEPTION;
252 // Get the Response Code
254 ResponseCode code = ResponseCode.toResponseCode(appcResponse.Status.Code);
257 // We are unaware of this code
259 this.completeOperation(operationAttempt, "Policy was unable to parse APP-C response status code field.", PolicyResult.FAILURE_EXCEPTION);
260 return PolicyResult.FAILURE_EXCEPTION;
263 // Ok, let's figure out what APP-C's response is
268 // This is good, they got our original message and
271 // Is there any need to track this?
277 // We'll consider these two codes as exceptions
279 this.completeOperation(operationAttempt, appcResponse.getStatus().Description, PolicyResult.FAILURE_EXCEPTION);
280 if (this.policyResult != null && this.policyResult.equals(PolicyResult.FAILURE_TIMEOUT)) {
283 return PolicyResult.FAILURE_EXCEPTION;
288 this.completeOperation(operationAttempt, appcResponse.getStatus().Description, PolicyResult.SUCCESS);
289 if (this.policyResult != null && this.policyResult.equals(PolicyResult.FAILURE_TIMEOUT)) {
292 return PolicyResult.SUCCESS;
297 this.completeOperation(operationAttempt, appcResponse.getStatus().Description, PolicyResult.FAILURE);
298 if (this.policyResult != null && this.policyResult.equals(PolicyResult.FAILURE_TIMEOUT)) {
301 return PolicyResult.FAILURE;
307 public Integer getOperationTimeout() {
311 if (this.policy == null) {
312 System.out.println("getOperationTimeout returning 0");
315 System.out.println("getOperationTimeout returning " + this.policy.getTimeout());
316 return this.policy.getTimeout();
319 public String getOperationTimeoutString(int defaultTimeout) {
320 Integer to = this.getOperationTimeout();
321 if (to == null || to == 0) {
322 return Integer.toString(defaultTimeout) + "s";
324 return to.toString() + "s";
327 public PolicyResult getOperationResult() {
328 return this.policyResult;
331 public String getOperationMessage() {
332 if (this.currentOperation != null && this.currentOperation.operation != null) {
333 return this.currentOperation.operation.toMessage();
335 if (this.operationHistory != null && this.operationHistory.size() > 0) {
336 return this.operationHistory.getLast().operation.toMessage();
341 public String getOperationMessage(String guardResult) {
342 if (this.currentOperation != null && this.currentOperation.operation != null) {
343 return this.currentOperation.operation.toMessage()+ ", Guard result: " + guardResult;
345 if (this.operationHistory != null && this.operationHistory.size() > 0) {
346 return this.operationHistory.getLast().operation.toMessage() + ", Guard result: " + guardResult;
351 public String getOperationHistory() {
352 if (this.currentOperation != null && this.currentOperation.operation != null) {
353 return this.currentOperation.operation.toHistory();
355 if (this.operationHistory != null && this.operationHistory.size() > 0) {
356 return this.operationHistory.getLast().operation.toHistory();
361 public LinkedList<ControlLoopOperation> getHistory() {
362 LinkedList<ControlLoopOperation> history = new LinkedList<ControlLoopOperation>();
363 for (Operation op : this.operationHistory) {
364 history.add(new ControlLoopOperation(op.operation));
370 public void setOperationHasTimedOut() {
374 this.completeOperation(this.attempts, "Operation timed out", PolicyResult.FAILURE_TIMEOUT);
377 public void setOperationHasGuardDeny() {
381 this.completeOperation(this.attempts, "Operation denied by Guard", PolicyResult.FAILURE_GUARD);
384 public boolean isOperationComplete() {
386 // Is there currently a result?
388 if (this.policyResult == null) {
390 // either we are in process or we
396 // We have some result, check if the operation failed
398 if (this.policyResult.equals(PolicyResult.FAILURE)) {
400 // Check if there were no retries specified
402 if (policy.getRetry() == null || policy.getRetry() == 0) {
404 // The result is the failure
411 if (this.isRetriesMaxedOut()) {
413 // No more attempts allowed, reset
414 // that our actual result is failure due to retries
416 this.policyResult = PolicyResult.FAILURE_RETRIES;
420 // There are more attempts available to try the
427 // Other results mean we are done
432 public boolean isOperationRunning() {
433 return (this.currentOperation != null);
436 private boolean isRetriesMaxedOut() {
437 if (policy.getRetry() == null || policy.getRetry() == 0) {
439 // There were NO retries specified, so declare
440 // this as completed.
442 return (this.attempts > 0);
444 return (this.attempts > policy.getRetry());
447 private void storeOperationInDataBase(){
451 em = Persistence.createEntityManagerFactory("OperationsHistoryPU").createEntityManager();//emf.createEntityManager();
453 logger.error("storeOperationInDataBase threw: ", e);
457 OperationsHistoryDbEntry newEntry = new OperationsHistoryDbEntry();
459 newEntry.closedLoopName = this.onset.closedLoopControlName;
460 newEntry.requestId = this.onset.requestID.toString();
461 newEntry.actor = this.currentOperation.operation.actor;
462 newEntry.operation = this.currentOperation.operation.operation;
463 newEntry.target = this.eventManager.getTargetInstance(this.policy);
464 newEntry.starttime = Timestamp.from(this.currentOperation.operation.start);
465 newEntry.subrequestId = this.currentOperation.operation.subRequestId;
466 newEntry.endtime = new Timestamp(this.currentOperation.operation.end.toEpochMilli());
467 newEntry.message = this.currentOperation.operation.message;
468 newEntry.outcome = this.currentOperation.operation.outcome;
470 em.getTransaction().begin();
471 em.persist(newEntry);
472 em.getTransaction().commit();
480 private void completeOperation(Integer attempt, String message, PolicyResult result) {
481 if (attempt == null) {
482 System.out.println("attempt cannot be null (i.e. subRequestID)");
485 if (this.currentOperation != null) {
486 if (this.currentOperation.attempt == attempt.intValue()) {
487 this.currentOperation.operation.end = Instant.now();
488 this.currentOperation.operation.message = message;
489 this.currentOperation.operation.outcome = result.toString();
490 this.currentOperation.policyResult = result;
492 // Save it in history
494 this.operationHistory.add(this.currentOperation);
495 this.storeOperationInDataBase();
497 // Set our last result
499 this.policyResult = result;
501 // Clear the current operation field
503 this.currentOperation = null;
506 System.out.println("not current");
508 for (Operation op : this.operationHistory) {
509 if (op.attempt == attempt.intValue()) {
510 op.operation.end = Instant.now();
511 op.operation.message = message;
512 op.operation.outcome = result.toString();
513 op.policyResult = result;
517 System.out.println("Could not find associated operation");