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;
34 import org.onap.policy.controlloop.ControlLoopEvent;
35 import org.onap.policy.controlloop.ControlLoopOperation;
36 import org.onap.policy.controlloop.VirtualControlLoopEvent;
38 import org.onap.policy.controlloop.ControlLoopException;
39 import org.onap.policy.controlloop.policy.Policy;
40 import org.onap.policy.controlloop.policy.PolicyResult;
41 import org.onap.policy.controlloop.actor.appc.APPCActorServiceProvider;
44 public class ControlLoopOperationManager implements Serializable {
49 private static final long serialVersionUID = -3773199283624595410L;
52 public String toString() {
53 return "ControlLoopOperationManager [onset=" + (onset != null ? onset.requestID : "null") + ", policy="
54 + (policy != null ? policy.getId() : "null") + ", attempts=" + attempts
55 + ", policyResult=" + policyResult
56 + ", currentOperation=" + currentOperation + ", operationHistory=" + operationHistory
61 // These properties are not changeable, but accessible
62 // for Drools Rule statements.
64 //public final ATTControlLoopEvent onset;
65 public final ControlLoopEvent onset;
66 public final Policy policy;
69 // Properties used to track the Operation
71 private int attempts = 0;
72 private Operation currentOperation = null;
73 private LinkedList<Operation> operationHistory = new LinkedList<Operation>();
74 private PolicyResult policyResult = null;
75 private ControlLoopEventManager eventManager = null;
77 public ControlLoopEventManager getEventManager() {
81 public void setEventManager(ControlLoopEventManager eventManager) {
82 this.eventManager = eventManager;
87 // Internal class used for tracking
89 private class Operation {
90 public ControlLoopOperation operation = new ControlLoopOperation();
91 public PolicyResult policyResult = null;
92 public int attempt = 0;
95 public String toString() {
96 return "Operation [attempt=" + attempt + ", policyResult=" + policyResult + ", operation=" + operation
101 private String guardApprovalStatus = "NONE";//"NONE", "PERMIT", "DENY"
102 private Object operationRequest;
104 public Object getOperationRequest() {
105 return operationRequest;
108 public String getGuardApprovalStatus() {
109 return guardApprovalStatus;
111 public void setGuardApprovalStatus(String guardApprovalStatus) {
112 this.guardApprovalStatus = guardApprovalStatus;
116 public ControlLoopOperationManager(/*ATTControlLoopEvent*/ControlLoopEvent onset, Policy policy, ControlLoopEventManager em) throws ControlLoopException {
118 this.policy = policy;
119 this.guardApprovalStatus = "NONE";
120 this.eventManager = em;
123 // Let's make a sanity check
125 switch (policy.getActor()) {
137 throw new ControlLoopException("ControlLoopEventManager: policy has an unknown actor.");
141 public Object startOperation(/*VirtualControlLoopEvent*/ControlLoopEvent onset) {
143 // They shouldn't call us if we currently running something
145 if (this.currentOperation != null) {
147 // what do we do if we are already running an operation?
152 // Check if we have maxed out on retries
154 if (this.policy.getRetry() == null || this.policy.getRetry() < 1) {
156 // No retries are allowed, so check have we even made
157 // one attempt to execute the operation?
159 if (this.attempts >= 1) {
161 // We have, let's ensure our PolicyResult is set
163 if (this.policyResult == null) {
164 this.policyResult = PolicyResult.FAILURE_RETRIES;
173 // Have we maxed out on retries?
175 if (this.attempts > this.policy.getRetry()) {
176 if (this.policyResult == null) {
177 this.policyResult = PolicyResult.FAILURE_RETRIES;
185 this.policyResult = null;
186 Operation operation = new Operation();
187 operation.attempt = ++this.attempts;
188 operation.operation.actor = this.policy.getActor().toString();
189 operation.operation.operation = this.policy.getRecipe();
190 operation.operation.target = this.policy.getTarget().toString();
191 operation.operation.subRequestId = Integer.toString(operation.attempt);
193 // Now determine which actor we need to construct a request for
195 switch (policy.getActor()) {
197 //Request request = APPCActorServiceProvider.constructRequest(onset, operation.operation, this.policy);
198 this.operationRequest = APPCActorServiceProvider.constructRequest((VirtualControlLoopEvent)onset, operation.operation, this.policy);
200 // Save the operation
202 this.currentOperation = operation;
203 //System.out.print("************* BEFORE STORING.....");
204 //this.storeOperationInDataBase("startOperation");
205 //System.out.print("************* AFTER STORING.....");
207 return operationRequest;
210 // We are not supporting MSO interface at the moment
212 System.out.println("We are not supporting MSO actor in the latest release.");
218 public PolicyResult onResponse(Object response) {
220 // Which response is it?
222 if (response instanceof Response) {
226 Response appcResponse = (Response) response;
228 // Determine which subrequestID (ie. attempt)
230 Integer operationAttempt = null;
232 operationAttempt = Integer.parseInt(appcResponse.CommonHeader.SubRequestID);
233 } catch (NumberFormatException e) {
235 // We cannot tell what happened if this doesn't exist
237 this.completeOperation(operationAttempt, "Policy was unable to parse APP-C SubRequestID (it was null).", PolicyResult.FAILURE_EXCEPTION);
238 return PolicyResult.FAILURE_EXCEPTION;
241 // Sanity check the response message
243 if (appcResponse.Status == null) {
245 // We cannot tell what happened if this doesn't exist
247 this.completeOperation(operationAttempt, "Policy was unable to parse APP-C response status field (it was null).", PolicyResult.FAILURE_EXCEPTION);
248 return PolicyResult.FAILURE_EXCEPTION;
251 // Get the Response Code
253 ResponseCode code = ResponseCode.toResponseCode(appcResponse.Status.Code);
256 // We are unaware of this code
258 this.completeOperation(operationAttempt, "Policy was unable to parse APP-C response status code field.", PolicyResult.FAILURE_EXCEPTION);
259 return PolicyResult.FAILURE_EXCEPTION;
262 // Ok, let's figure out what APP-C's response is
267 // This is good, they got our original message and
270 // Is there any need to track this?
276 // We'll consider these two codes as exceptions
278 this.completeOperation(operationAttempt, appcResponse.getStatus().Description, PolicyResult.FAILURE_EXCEPTION);
279 if (this.policyResult != null && this.policyResult.equals(PolicyResult.FAILURE_TIMEOUT)) {
282 return PolicyResult.FAILURE_EXCEPTION;
287 this.completeOperation(operationAttempt, appcResponse.getStatus().Description, PolicyResult.SUCCESS);
288 if (this.policyResult != null && this.policyResult.equals(PolicyResult.FAILURE_TIMEOUT)) {
291 return PolicyResult.SUCCESS;
296 this.completeOperation(operationAttempt, appcResponse.getStatus().Description, PolicyResult.FAILURE);
297 if (this.policyResult != null && this.policyResult.equals(PolicyResult.FAILURE_TIMEOUT)) {
300 return PolicyResult.FAILURE;
306 public Integer getOperationTimeout() {
310 if (this.policy == null) {
311 System.out.println("getOperationTimeout returning 0");
314 System.out.println("getOperationTimeout returning " + this.policy.getTimeout());
315 return this.policy.getTimeout();
318 public String getOperationTimeoutString(int defaultTimeout) {
319 Integer to = this.getOperationTimeout();
320 if (to == null || to == 0) {
321 return Integer.toString(defaultTimeout) + "s";
323 return to.toString() + "s";
326 public PolicyResult getOperationResult() {
327 return this.policyResult;
330 public String getOperationMessage() {
331 if (this.currentOperation != null && this.currentOperation.operation != null) {
332 return this.currentOperation.operation.toMessage();
334 if (this.operationHistory != null && this.operationHistory.size() > 0) {
335 return this.operationHistory.getLast().operation.toMessage();
340 public String getOperationMessage(String guardResult) {
341 if (this.currentOperation != null && this.currentOperation.operation != null) {
342 return this.currentOperation.operation.toMessage()+ ", Guard result: " + guardResult;
344 if (this.operationHistory != null && this.operationHistory.size() > 0) {
345 return this.operationHistory.getLast().operation.toMessage() + ", Guard result: " + guardResult;
350 public String getOperationHistory() {
351 if (this.currentOperation != null && this.currentOperation.operation != null) {
352 return this.currentOperation.operation.toHistory();
354 if (this.operationHistory != null && this.operationHistory.size() > 0) {
355 return this.operationHistory.getLast().operation.toHistory();
360 public LinkedList<ControlLoopOperation> getHistory() {
361 LinkedList<ControlLoopOperation> history = new LinkedList<ControlLoopOperation>();
362 for (Operation op : this.operationHistory) {
363 history.add(new ControlLoopOperation(op.operation));
369 public void setOperationHasTimedOut() {
373 this.completeOperation(this.attempts, "Operation timed out", PolicyResult.FAILURE_TIMEOUT);
376 public void setOperationHasGuardDeny() {
380 this.completeOperation(this.attempts, "Operation denied by Guard", PolicyResult.FAILURE_GUARD);
383 public boolean isOperationComplete() {
385 // Is there currently a result?
387 if (this.policyResult == null) {
389 // either we are in process or we
395 // We have some result, check if the operation failed
397 if (this.policyResult.equals(PolicyResult.FAILURE)) {
399 // Check if there were no retries specified
401 if (policy.getRetry() == null || policy.getRetry() == 0) {
403 // The result is the failure
410 if (this.isRetriesMaxedOut()) {
412 // No more attempts allowed, reset
413 // that our actual result is failure due to retries
415 this.policyResult = PolicyResult.FAILURE_RETRIES;
419 // There are more attempts available to try the
426 // Other results mean we are done
431 public boolean isOperationRunning() {
432 return (this.currentOperation != null);
435 private boolean isRetriesMaxedOut() {
436 if (policy.getRetry() == null || policy.getRetry() == 0) {
438 // There were NO retries specified, so declare
439 // this as completed.
441 return (this.attempts > 0);
443 return (this.attempts > policy.getRetry());
446 private void storeOperationInDataBase(){
450 em = Persistence.createEntityManagerFactory("OperationsHistoryPU").createEntityManager();//emf.createEntityManager();
452 System.err.println("Test thread got Exception " + e.getLocalizedMessage() + " Can't write to Operations History DB.");
456 OperationsHistoryDbEntry newEntry = new OperationsHistoryDbEntry();
458 newEntry.closedLoopName = this.onset.closedLoopControlName;
459 newEntry.requestId = this.onset.requestID.toString();
460 newEntry.actor = this.currentOperation.operation.actor;
461 newEntry.operation = this.currentOperation.operation.operation;
462 newEntry.target = this.eventManager.getTargetInstance(this.policy);
463 newEntry.starttime = Timestamp.from(this.currentOperation.operation.start);
464 newEntry.subrequestId = this.currentOperation.operation.subRequestId;
465 newEntry.endtime = new Timestamp(this.currentOperation.operation.end.toEpochMilli());
466 newEntry.message = this.currentOperation.operation.message;
467 newEntry.outcome = this.currentOperation.operation.outcome;
469 em.getTransaction().begin();
470 em.persist(newEntry);
471 em.getTransaction().commit();
479 private void completeOperation(Integer attempt, String message, PolicyResult result) {
480 if (attempt == null) {
481 System.out.println("attempt cannot be null (i.e. subRequestID)");
484 if (this.currentOperation != null) {
485 if (this.currentOperation.attempt == attempt.intValue()) {
486 this.currentOperation.operation.end = Instant.now();
487 this.currentOperation.operation.message = message;
488 this.currentOperation.operation.outcome = result.toString();
489 this.currentOperation.policyResult = result;
491 // Save it in history
493 this.operationHistory.add(this.currentOperation);
494 this.storeOperationInDataBase();
496 // Set our last result
498 this.policyResult = result;
500 // Clear the current operation field
502 this.currentOperation = null;
505 System.out.println("not current");
507 for (Operation op : this.operationHistory) {
508 if (op.attempt == attempt.intValue()) {
509 op.operation.end = Instant.now();
510 op.operation.message = message;
511 op.operation.outcome = result.toString();
512 op.policyResult = result;
516 System.out.println("Could not find associated operation");