980799171e7944008a80ef9cf888a67f5ec46481
[policy/drools-applications.git] /
1 /*-
2  * ============LICENSE_START=======================================================
3  * controlloop operation manager
4  * ================================================================================
5  * Copyright (C) 2017-2018 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
10  *
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  *
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=========================================================
19  */
20
21 package org.onap.policy.controlloop.eventmanager;
22
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.List;
29 import java.util.NoSuchElementException;
30 import java.util.Properties;
31
32 import javax.persistence.EntityManager;
33 import javax.persistence.Persistence;
34
35 import org.eclipse.persistence.config.PersistenceUnitProperties;
36 import org.onap.policy.aai.util.AaiException;
37 import org.onap.policy.appc.Response;
38 import org.onap.policy.appc.ResponseCode;
39 import org.onap.policy.appclcm.LcmResponseWrapper;
40 import org.onap.policy.controlloop.ControlLoopEvent;
41 import org.onap.policy.controlloop.ControlLoopException;
42 import org.onap.policy.controlloop.ControlLoopOperation;
43 import org.onap.policy.controlloop.VirtualControlLoopEvent;
44 import org.onap.policy.controlloop.actor.appc.AppcActorServiceProvider;
45 import org.onap.policy.controlloop.actor.appclcm.AppcLcmActorServiceProvider;
46 import org.onap.policy.controlloop.actor.sdnc.SdncActorServiceProvider;
47 import org.onap.policy.controlloop.actor.sdnr.SdnrActorServiceProvider;
48 import org.onap.policy.controlloop.actor.so.SoActorServiceProvider;
49 import org.onap.policy.controlloop.actor.vfc.VfcActorServiceProvider;
50 import org.onap.policy.controlloop.policy.Policy;
51 import org.onap.policy.controlloop.policy.PolicyResult;
52 import org.onap.policy.drools.system.PolicyEngine;
53 import org.onap.policy.guard.Util;
54 import org.onap.policy.sdnc.SdncResponse;
55 import org.onap.policy.sdnr.PciResponseWrapper;
56 import org.onap.policy.so.SOResponseWrapper;
57 import org.onap.policy.vfc.VFCResponse;
58 import org.slf4j.Logger;
59 import org.slf4j.LoggerFactory;
60
61 public class ControlLoopOperationManager implements Serializable {
62     private static final long serialVersionUID = -3773199283624595410L;
63     private static final Logger logger = LoggerFactory.getLogger(ControlLoopOperationManager.class);
64
65     private static final String VSERVER_VSERVER_NAME = "vserver.vserver-name";
66     private static final String GENERIC_VNF_VNF_NAME = "generic-vnf.vnf-name";
67     private static final String GENERIC_VNF_VNF_ID = "generic-vnf.vnf-id";
68
69     //
70     // These properties are not changeable, but accessible
71     // for Drools Rule statements.
72     //
73     public final ControlLoopEvent onset;
74     public final Policy policy;
75
76     //
77     // Properties used to track the Operation
78     //
79     private int attempts = 0;
80     private Operation currentOperation = null;
81     private LinkedList<Operation> operationHistory = new LinkedList<>();
82     private PolicyResult policyResult = null;
83     private ControlLoopEventManager eventManager = null;
84     private String targetEntity;
85     private String guardApprovalStatus = "NONE";// "NONE", "PERMIT", "DENY"
86     private transient Object operationRequest;
87
88     /**
89      * Construct an instance.
90      * 
91      * @param onset the onset event
92      * @param policy the policy
93      * @param em the event manager
94      * @throws ControlLoopException if an error occurs
95      * @throws AaiException if an error occurs retrieving information from A&AI
96      */
97     public ControlLoopOperationManager(ControlLoopEvent onset, Policy policy, ControlLoopEventManager em)
98             throws ControlLoopException, AaiException {
99         this.onset = onset;
100         this.policy = policy;
101         this.guardApprovalStatus = "NONE";
102         this.eventManager = em;
103         this.targetEntity = getTarget(policy);
104
105         //
106         // Let's make a sanity check
107         //
108         switch (policy.getActor()) {
109             case "APPC":
110                 if ("ModifyConfig".equalsIgnoreCase(policy.getRecipe())) {
111                     /*
112                      * The target vnf-id may not be the same as the source vnf-id specified in the
113                      * yaml, the target vnf-id is retrieved by a named query to A&AI.
114                      */
115                     String targetVnf = AppcLcmActorServiceProvider.vnfNamedQuery(policy.getTarget().getResourceID(),
116                             this.targetEntity);
117                     this.targetEntity = targetVnf;
118                 }
119                 break;
120             case "SO":
121                 break;
122             case "SDNR":
123                 break;
124             case "VFC":
125                 break;
126             case "SDNC":
127                 break;
128             default:
129                 throw new ControlLoopException("ControlLoopEventManager: policy has an unknown actor.");
130         }
131     }
132
133     public ControlLoopEventManager getEventManager() {
134         return eventManager;
135     }
136
137     public void setEventManager(ControlLoopEventManager eventManager) {
138         this.eventManager = eventManager;
139     }
140
141     public String getTargetEntity() {
142         return this.targetEntity;
143     }
144
145     @Override
146     public String toString() {
147         return "ControlLoopOperationManager [onset=" + (onset != null ? onset.getRequestId() : "null") + ", policy="
148                 + (policy != null ? policy.getId() : "null") + ", attempts=" + attempts + ", policyResult="
149                 + policyResult + ", currentOperation=" + currentOperation + ", operationHistory=" + operationHistory
150                 + "]";
151     }
152
153     //
154     // Internal class used for tracking
155     //
156     private class Operation implements Serializable {
157         private static final long serialVersionUID = 1L;
158         
159         private ControlLoopOperation clOperation = new ControlLoopOperation();
160         private PolicyResult policyResult = null;
161         private int attempt = 0;
162
163         @Override
164         public String toString() {
165             return "Operation [attempt=" + attempt + ", policyResult=" + policyResult + ", operation=" + clOperation
166                     + "]";
167         }
168     }
169
170     public Object getOperationRequest() {
171         return operationRequest;
172     }
173
174     public String getGuardApprovalStatus() {
175         return guardApprovalStatus;
176     }
177
178     public void setGuardApprovalStatus(String guardApprovalStatus) {
179         this.guardApprovalStatus = guardApprovalStatus;
180     }
181
182     /**
183      * Get the target for a policy.
184      * 
185      * @param policy the policy
186      * @return the target
187      * @throws ControlLoopException if an error occurs
188      * @throws AaiException if an error occurs retrieving information from A&AI
189      */
190     public String getTarget(Policy policy) throws ControlLoopException, AaiException {
191         if (policy.getTarget() == null) {
192             throw new ControlLoopException("The target is null");
193         }
194
195         if (policy.getTarget().getType() == null) {
196             throw new ControlLoopException("The target type is null");
197         }
198
199         switch (policy.getTarget().getType()) {
200             case PNF:
201                 throw new ControlLoopException("PNF target is not supported");
202             case VM:
203             case VNF:
204                 VirtualControlLoopEvent virtualOnset = (VirtualControlLoopEvent) this.onset;
205                 if (this.onset.getTarget().equalsIgnoreCase(VSERVER_VSERVER_NAME)) {
206                     return virtualOnset.getAai().get(VSERVER_VSERVER_NAME);
207                 } else if (this.onset.getTarget().equalsIgnoreCase(GENERIC_VNF_VNF_ID)) {
208                     return virtualOnset.getAai().get(GENERIC_VNF_VNF_ID);
209                 } else if (this.onset.getTarget().equalsIgnoreCase(GENERIC_VNF_VNF_NAME)) {
210                     /*
211                      * If the onset is enriched with the vnf-id, we don't need an A&AI response
212                      */
213                     if (virtualOnset.getAai().containsKey(GENERIC_VNF_VNF_ID)) {
214                         return virtualOnset.getAai().get(GENERIC_VNF_VNF_ID);
215                     }
216
217                     /*
218                      * If the vnf-name was retrieved from the onset then the vnf-id must be obtained
219                      * from the event manager's A&AI GET query
220                      */
221                     String vnfId = this.eventManager.getVnfResponse().getVnfId();
222                     if (vnfId == null) {
223                         throw new AaiException("No vnf-id found");
224                     }
225                     return vnfId;
226                 }
227                 throw new ControlLoopException("Target does not match target type");
228             default:
229                 throw new ControlLoopException("The target type is not supported");
230         }
231     }
232
233     /**
234      * Start an operation.
235      * 
236      * @param onset the onset event
237      * @return the operation request
238      * @throws ControlLoopException if an error occurs
239      */
240     public Object startOperation(/* VirtualControlLoopEvent */ControlLoopEvent onset) throws ControlLoopException {
241         verifyOperatonCanRun();
242
243         //
244         // Setup
245         //
246         this.policyResult = null;
247         Operation operation = new Operation();
248         operation.attempt = ++this.attempts;
249         operation.clOperation.setActor(this.policy.getActor());
250         operation.clOperation.setOperation(this.policy.getRecipe());
251         operation.clOperation.setTarget(this.policy.getTarget().toString());
252         operation.clOperation.setSubRequestId(Integer.toString(operation.attempt));
253         //
254         // Now determine which actor we need to construct a request for
255         //
256         switch (policy.getActor()) {
257             case "APPC":
258                 /*
259                  * If the recipe is ModifyConfig, a legacy APPC request is constructed. Otherwise an
260                  * LCMRequest is constructed.
261                  */
262                 this.currentOperation = operation;
263                 if ("ModifyConfig".equalsIgnoreCase(policy.getRecipe())) {
264                     this.operationRequest = AppcActorServiceProvider.constructRequest((VirtualControlLoopEvent) onset,
265                             operation.clOperation, this.policy, this.targetEntity);
266                 } else {
267                     this.operationRequest = AppcLcmActorServiceProvider.constructRequest(
268                             (VirtualControlLoopEvent) onset, operation.clOperation, this.policy, this.targetEntity);
269                 }
270                 //
271                 // Save the operation
272                 //
273
274                 return operationRequest;
275             case "SO":
276                 SoActorServiceProvider soActorSp = new SoActorServiceProvider();
277                 this.operationRequest = soActorSp.constructRequest((VirtualControlLoopEvent) onset,
278                                 operation.clOperation, this.policy, eventManager.getNqVserverFromAai());
279
280                 // Save the operation
281                 this.currentOperation = operation;
282
283                 if (this.operationRequest == null) {
284                     this.policyResult = PolicyResult.FAILURE;
285                 }
286
287                 return operationRequest;
288             case "VFC":
289                 this.operationRequest = VfcActorServiceProvider.constructRequest((VirtualControlLoopEvent) onset,
290                         operation.clOperation, this.policy, this.eventManager.getVnfResponse());
291                 this.currentOperation = operation;
292                 if (this.operationRequest == null) {
293                     this.policyResult = PolicyResult.FAILURE;
294                 }
295                 return operationRequest;
296             case "SDNR":
297                 /*
298                  * If the recipe is ModifyConfig, a SDNR request is constructed.
299                  */
300                 this.currentOperation = operation;
301                 this.operationRequest = SdnrActorServiceProvider.constructRequest((VirtualControlLoopEvent) onset,
302                             operation.clOperation, this.policy);
303                 //
304                 // Save the operation
305                 //
306                 if (this.operationRequest == null) {
307                     this.policyResult = PolicyResult.FAILURE;
308                 }
309
310                 return operationRequest;
311             case "SDNC":
312                 this.operationRequest = SdncActorServiceProvider.constructRequest((VirtualControlLoopEvent) onset,
313                         operation.clOperation, this.policy);
314                 this.currentOperation = operation;
315                 if (this.operationRequest == null) {
316                     this.policyResult = PolicyResult.FAILURE;
317                 }
318                 return operationRequest;                
319             default:
320                 throw new ControlLoopException("invalid actor " + policy.getActor() + " on policy");
321         }
322     }
323
324     /**
325      * Handle a response.
326      * 
327      * @param response the response
328      * @return a PolicyResult
329      */
330     public PolicyResult onResponse(Object response) {
331         //
332         // Which response is it?
333         //
334         if (response instanceof Response) {
335             //
336             // Cast APPC response and handle it
337             //
338             return onResponse((Response) response);
339         } else if (response instanceof LcmResponseWrapper) {
340             //
341             // Cast LCM response and handle it
342             //
343             return onResponse((LcmResponseWrapper) response);
344         } else if (response instanceof PciResponseWrapper) {
345             //
346             // Cast SDNR response and handle it
347             //
348             return onResponse((PciResponseWrapper) response);
349         } else if (response instanceof SOResponseWrapper) {
350             //
351             // Cast SO response and handle it
352             //
353             return onResponse((SOResponseWrapper) response);
354         } else if (response instanceof VFCResponse) {
355             //
356             // Cast VFC response and handle it
357             //
358             return onResponse((VFCResponse) response);
359         } else {
360             return null;
361         }
362     }
363
364     /**
365      * This method handles operation responses from APPC.
366      * 
367      * @param appcResponse the APPC response
368      * @return The result of the response handling
369      */
370     private PolicyResult onResponse(Response appcResponse) {
371         //
372         // Determine which subrequestID (ie. attempt)
373         //
374         Integer operationAttempt = null;
375         try {
376             operationAttempt = Integer.parseInt(appcResponse.getCommonHeader().getSubRequestId());
377         } catch (NumberFormatException e) {
378             //
379             // We cannot tell what happened if this doesn't exist
380             //
381             this.completeOperation(operationAttempt, "Policy was unable to parse APP-C SubRequestID (it was null).",
382                     PolicyResult.FAILURE_EXCEPTION);
383             return PolicyResult.FAILURE_EXCEPTION;
384         }
385         //
386         // Sanity check the response message
387         //
388         if (appcResponse.getStatus() == null) {
389             //
390             // We cannot tell what happened if this doesn't exist
391             //
392             this.completeOperation(operationAttempt,
393                     "Policy was unable to parse APP-C response status field (it was null).",
394                     PolicyResult.FAILURE_EXCEPTION);
395             return PolicyResult.FAILURE_EXCEPTION;
396         }
397         //
398         // Get the Response Code
399         //
400         ResponseCode code = ResponseCode.toResponseCode(appcResponse.getStatus().getCode());
401         if (code == null) {
402             //
403             // We are unaware of this code
404             //
405             this.completeOperation(operationAttempt, "Policy was unable to parse APP-C response status code field.",
406                     PolicyResult.FAILURE_EXCEPTION);
407             return PolicyResult.FAILURE_EXCEPTION;
408         }
409         //
410         // Ok, let's figure out what APP-C's response is
411         //
412         switch (code) {
413             case ACCEPT:
414                 //
415                 // This is good, they got our original message and
416                 // acknowledged it.
417                 //
418                 // Is there any need to track this?
419                 //
420                 return null;
421             case ERROR:
422             case REJECT:
423                 //
424                 // We'll consider these two codes as exceptions
425                 //
426                 this.completeOperation(operationAttempt, appcResponse.getStatus().getDescription(),
427                         PolicyResult.FAILURE_EXCEPTION);
428                 if (this.policyResult != null && this.policyResult.equals(PolicyResult.FAILURE_TIMEOUT)) {
429                     return null;
430                 }
431                 return PolicyResult.FAILURE_EXCEPTION;
432             case SUCCESS:
433                 //
434                 //
435                 //
436                 this.completeOperation(operationAttempt, appcResponse.getStatus().getDescription(),
437                         PolicyResult.SUCCESS);
438                 if (this.policyResult != null && this.policyResult.equals(PolicyResult.FAILURE_TIMEOUT)) {
439                     return null;
440                 }
441                 return PolicyResult.SUCCESS;
442             case FAILURE:
443                 //
444                 //
445                 //
446                 this.completeOperation(operationAttempt, appcResponse.getStatus().getDescription(),
447                         PolicyResult.FAILURE);
448                 if (this.policyResult != null && this.policyResult.equals(PolicyResult.FAILURE_TIMEOUT)) {
449                     return null;
450                 }
451                 return PolicyResult.FAILURE;
452             default:
453                 return null;
454         }
455     }
456
457     /**
458      * This method handles operation responses from LCM.
459      * 
460      * @param dmaapResponse the LCM response
461      * @return The result of the response handling
462      */
463     private PolicyResult onResponse(LcmResponseWrapper dmaapResponse) {
464         /*
465          * Parse out the operation attempt using the subrequestid
466          */
467         Integer operationAttempt = AppcLcmActorServiceProvider
468                 .parseOperationAttempt(dmaapResponse.getBody().getCommonHeader().getSubRequestId());
469         if (operationAttempt == null) {
470             this.completeOperation(operationAttempt, "Policy was unable to parse APP-C SubRequestID (it was null).",
471                     PolicyResult.FAILURE_EXCEPTION);
472         }
473
474         /*
475          * Process the APPCLCM response to see what PolicyResult should be returned
476          */
477         AbstractMap.SimpleEntry<PolicyResult, String> result =
478                 AppcLcmActorServiceProvider.processResponse(dmaapResponse);
479
480         if (result.getKey() != null) {
481             this.completeOperation(operationAttempt, result.getValue(), result.getKey());
482             if (PolicyResult.FAILURE_TIMEOUT.equals(this.policyResult)) {
483                 return null;
484             }
485             return result.getKey();
486         }
487         return null;
488     }
489
490     /**
491      * This method handles operation responses from SDNR.
492      * 
493      * @param dmaapResponse the SDNR response
494      * @return the result of the response handling
495      */
496     private PolicyResult onResponse(PciResponseWrapper dmaapResponse) {
497         /*
498          * Parse out the operation attempt using the subrequestid
499          */
500         Integer operationAttempt = SdnrActorServiceProvider
501                 .parseOperationAttempt(dmaapResponse.getBody().getCommonHeader().getSubRequestId());
502         if (operationAttempt == null) {
503             this.completeOperation(operationAttempt, "Policy was unable to parse SDNR SubRequestID.",
504                     PolicyResult.FAILURE_EXCEPTION);
505         }
506
507         /*
508          * Process the SDNR response to see what PolicyResult should be returned
509          */
510         SdnrActorServiceProvider.Pair<PolicyResult, String> result =
511                 SdnrActorServiceProvider.processResponse(dmaapResponse);
512
513         if (result.getResult() != null) {
514             this.completeOperation(operationAttempt, result.getMessage(), result.getResult());
515             if (PolicyResult.FAILURE_TIMEOUT.equals(this.policyResult)) {
516                 return null;
517             }
518             return result.getResult();
519         }
520         return null;
521     }
522
523     /**
524      * This method handles operation responses from SO.
525      * 
526      * @param msoResponse the SO response
527      * @return The result of the response handling
528      */
529     private PolicyResult onResponse(SOResponseWrapper msoResponse) {
530         switch (msoResponse.getSoResponse().getHttpResponseCode()) {
531             case 200:
532             case 202:
533                 //
534                 // Consider it as success
535                 //
536                 this.completeOperation(this.attempts, msoResponse.getSoResponse().getHttpResponseCode() + " Success",
537                         PolicyResult.SUCCESS);
538                 if (this.policyResult != null && this.policyResult.equals(PolicyResult.FAILURE_TIMEOUT)) {
539                     return null;
540                 }
541                 return PolicyResult.SUCCESS;
542             default:
543                 //
544                 // Consider it as failure
545                 //
546                 this.completeOperation(this.attempts, msoResponse.getSoResponse().getHttpResponseCode() + " Failed",
547                         PolicyResult.FAILURE);
548                 if (this.policyResult != null && this.policyResult.equals(PolicyResult.FAILURE_TIMEOUT)) {
549                     return null;
550                 }
551                 return PolicyResult.FAILURE;
552         }
553     }
554
555     /**
556      * This method handles operation responses from VFC.
557      * 
558      * @param vfcResponse the VFC response
559      * @return The result of the response handling
560      */
561     private PolicyResult onResponse(VFCResponse vfcResponse) {
562         if ("finished".equalsIgnoreCase(vfcResponse.getResponseDescriptor().getStatus())) {
563             //
564             // Consider it as success
565             //
566             this.completeOperation(this.attempts, " Success", PolicyResult.SUCCESS);
567             if (this.policyResult != null && this.policyResult.equals(PolicyResult.FAILURE_TIMEOUT)) {
568                 return null;
569             }
570             return PolicyResult.SUCCESS;
571         } else {
572             //
573             // Consider it as failure
574             //
575             this.completeOperation(this.attempts, " Failed", PolicyResult.FAILURE);
576             if (this.policyResult != null && this.policyResult.equals(PolicyResult.FAILURE_TIMEOUT)) {
577                 return null;
578             }
579             // increment operation attempts for retries
580             this.attempts += 1;
581             return PolicyResult.FAILURE;
582         }
583     }
584
585     /**
586      * Get the operation timeout.
587      * 
588      * @return the timeout
589      */
590     public Integer getOperationTimeout() {
591         //
592         // Sanity check
593         //
594         if (this.policy == null) {
595             logger.debug("getOperationTimeout returning 0");
596             return 0;
597         }
598         logger.debug("getOperationTimeout returning {}", this.policy.getTimeout());
599         return this.policy.getTimeout();
600     }
601
602     /**
603      * Get the operation timeout as a String.
604      * 
605      * @param defaultTimeout the default timeout
606      * @return the timeout as a String
607      */
608     public String getOperationTimeoutString(int defaultTimeout) {
609         Integer to = this.getOperationTimeout();
610         if (to == null || to == 0) {
611             return Integer.toString(defaultTimeout) + "s";
612         }
613         return to.toString() + "s";
614     }
615
616     public PolicyResult getOperationResult() {
617         return this.policyResult;
618     }
619
620     /**
621      * Get the operation as a message.
622      * 
623      * @return the operation as a message
624      */
625     public String getOperationMessage() {
626         if (this.currentOperation != null && this.currentOperation.clOperation != null) {
627             return this.currentOperation.clOperation.toMessage();
628         }
629
630         if (!this.operationHistory.isEmpty()) {
631             return this.operationHistory.getLast().clOperation.toMessage();
632         }
633         return null;
634     }
635
636     /**
637      * Get the operation as a message including the guard result.
638      * 
639      * @param guardResult the guard result
640      * @return the operation as a message including the guard result
641      */
642     public String getOperationMessage(String guardResult) {
643         if (this.currentOperation != null && this.currentOperation.clOperation != null) {
644             return this.currentOperation.clOperation.toMessage() + ", Guard result: " + guardResult;
645         }
646
647         if (!this.operationHistory.isEmpty()) {
648             return this.operationHistory.getLast().clOperation.toMessage() + ", Guard result: " + guardResult;
649         }
650         return null;
651     }
652
653     /**
654      * Get the operation history.
655      * 
656      * @return the operation history
657      */
658     public String getOperationHistory() {
659         if (this.currentOperation != null && this.currentOperation.clOperation != null) {
660             return this.currentOperation.clOperation.toHistory();
661         }
662
663         if (!this.operationHistory.isEmpty()) {
664             return this.operationHistory.getLast().clOperation.toHistory();
665         }
666         return null;
667     }
668
669     /**
670      * Get the history.
671      * 
672      * @return the list of control loop operations
673      */
674     public List<ControlLoopOperation> getHistory() {
675         LinkedList<ControlLoopOperation> history = new LinkedList<>();
676         for (Operation op : this.operationHistory) {
677             history.add(new ControlLoopOperation(op.clOperation));
678
679         }
680         return history;
681     }
682
683     /**
684      * Set the operation has timed out.
685      */
686     public void setOperationHasTimedOut() {
687         //
688         //
689         //
690         this.completeOperation(this.attempts, "Operation timed out", PolicyResult.FAILURE_TIMEOUT);
691     }
692
693     /**
694      * Set the operation has been denied by guard.
695      */
696     public void setOperationHasGuardDeny() {
697         //
698         //
699         //
700         this.completeOperation(this.attempts, "Operation denied by Guard", PolicyResult.FAILURE_GUARD);
701     }
702
703     public void setOperationHasException(String message) {
704         this.completeOperation(this.attempts, message, PolicyResult.FAILURE_EXCEPTION);
705     }
706
707     /**
708      * Is the operation complete.
709      * 
710      * @return <code>true</code> if the operation is complete, <code>false</code> otherwise
711      */
712     public boolean isOperationComplete() {
713         //
714         // Is there currently a result?
715         //
716         if (this.policyResult == null) {
717             //
718             // either we are in process or we
719             // haven't started
720             //
721             return false;
722         }
723         //
724         // We have some result, check if the operation failed
725         //
726         if (this.policyResult.equals(PolicyResult.FAILURE)) {
727             //
728             // Check if there were no retries specified
729             //
730             if (policy.getRetry() == null || policy.getRetry() == 0) {
731                 //
732                 // The result is the failure
733                 //
734                 return true;
735             }
736             //
737             // Check retries
738             //
739             if (this.isRetriesMaxedOut()) {
740                 //
741                 // No more attempts allowed, reset
742                 // that our actual result is failure due to retries
743                 //
744                 this.policyResult = PolicyResult.FAILURE_RETRIES;
745                 return true;
746             } else {
747                 //
748                 // There are more attempts available to try the
749                 // policy recipe.
750                 //
751                 return false;
752             }
753         }
754         //
755         // Other results mean we are done
756         //
757         return true;
758     }
759
760     public boolean isOperationRunning() {
761         return (this.currentOperation != null);
762     }
763
764     /**
765      * This method verifies that the operation manager may run an operation.
766      * 
767      * @return True if the operation can run, false otherwise
768      * @throws ControlLoopException if the operation cannot run
769      */
770     private void verifyOperatonCanRun() throws ControlLoopException {
771         //
772         // They shouldn't call us if we currently running something
773         //
774         if (this.currentOperation != null) {
775             //
776             // what do we do if we are already running an operation?
777             //
778             throw new ControlLoopException("current operation is not null (an operation is already running)");
779         }
780         //
781         // Check if we have maxed out on retries
782         //
783         if (this.policy.getRetry() == null || this.policy.getRetry() < 1) {
784             //
785             // No retries are allowed, so check have we even made
786             // one attempt to execute the operation?
787             //
788             if (this.attempts >= 1) {
789                 //
790                 // We have, let's ensure our PolicyResult is set
791                 //
792                 if (this.policyResult == null) {
793                     this.policyResult = PolicyResult.FAILURE_RETRIES;
794                 }
795                 //
796                 //
797                 //
798                 throw new ControlLoopException("current operation failed and retries are not allowed");
799             }
800         } else {
801             //
802             // Have we maxed out on retries?
803             //
804             if (this.attempts > this.policy.getRetry()) {
805                 if (this.policyResult == null) {
806                     this.policyResult = PolicyResult.FAILURE_RETRIES;
807                 }
808                 throw new ControlLoopException("current oepration has failed after " + this.attempts + " retries");
809             }
810         }
811     }
812
813     private boolean isRetriesMaxedOut() {
814         if (policy.getRetry() == null || policy.getRetry() == 0) {
815             //
816             // There were NO retries specified, so declare
817             // this as completed.
818             //
819             return (this.attempts > 0);
820         }
821         return (this.attempts > policy.getRetry());
822     }
823
824     private void storeOperationInDataBase() {
825         // Only store in DB if enabled
826         boolean guardEnabled = "false".equalsIgnoreCase(PolicyEngine.manager.getEnvironmentProperty("guard.disabled"));
827         if (!guardEnabled) {
828             return;
829         }
830
831
832         // DB Properties
833         Properties props = new Properties();
834         if (PolicyEngine.manager.getEnvironmentProperty(Util.ONAP_KEY_URL) != null
835                 && PolicyEngine.manager.getEnvironmentProperty(Util.ONAP_KEY_USER) != null
836                 && PolicyEngine.manager.getEnvironmentProperty(Util.ONAP_KEY_PASS) != null) {
837             props.put(Util.ECLIPSE_LINK_KEY_URL, PolicyEngine.manager.getEnvironmentProperty(Util.ONAP_KEY_URL));
838             props.put(Util.ECLIPSE_LINK_KEY_USER, PolicyEngine.manager.getEnvironmentProperty(Util.ONAP_KEY_USER));
839             props.put(Util.ECLIPSE_LINK_KEY_PASS, PolicyEngine.manager.getEnvironmentProperty(Util.ONAP_KEY_PASS));
840             props.put(PersistenceUnitProperties.CLASSLOADER, ControlLoopOperationManager.class.getClassLoader());
841         }
842
843
844         String opsHistPu = System.getProperty("OperationsHistoryPU");
845         if (!"TestOperationsHistoryPU".equals(opsHistPu)) {
846             opsHistPu = "OperationsHistoryPU";
847         } else {
848             props.clear();
849         }
850         EntityManager em;
851         try {
852             em = Persistence.createEntityManagerFactory(opsHistPu, props).createEntityManager();
853         } catch (Exception e) {
854             logger.error("storeOperationInDataBase threw: ", e);
855             return;
856         }
857
858         OperationsHistoryDbEntry newEntry = new OperationsHistoryDbEntry();
859
860         newEntry.setClosedLoopName(this.onset.getClosedLoopControlName());
861         newEntry.setRequestId(this.onset.getRequestId().toString());
862         newEntry.setActor(this.currentOperation.clOperation.getActor());
863         newEntry.setOperation(this.currentOperation.clOperation.getOperation());
864         newEntry.setTarget(this.targetEntity);
865         newEntry.setStarttime(Timestamp.from(this.currentOperation.clOperation.getStart()));
866         newEntry.setSubrequestId(this.currentOperation.clOperation.getSubRequestId());
867         newEntry.setEndtime(new Timestamp(this.currentOperation.clOperation.getEnd().toEpochMilli()));
868         newEntry.setMessage(this.currentOperation.clOperation.getMessage());
869         newEntry.setOutcome(this.currentOperation.clOperation.getOutcome());
870
871         em.getTransaction().begin();
872         em.persist(newEntry);
873         em.getTransaction().commit();
874
875         em.close();
876     }
877
878     private void completeOperation(Integer attempt, String message, PolicyResult result) {
879         if (attempt == null) {
880             logger.debug("attempt cannot be null (i.e. subRequestID)");
881             return;
882         }
883         if (this.currentOperation != null) {
884             if (this.currentOperation.attempt == attempt.intValue()) {
885                 this.currentOperation.clOperation.setEnd(Instant.now());
886                 this.currentOperation.clOperation.setMessage(message);
887                 this.currentOperation.clOperation.setOutcome(result.toString());
888                 this.currentOperation.policyResult = result;
889                 //
890                 // Save it in history
891                 //
892                 this.operationHistory.add(this.currentOperation);
893                 this.storeOperationInDataBase();
894                 //
895                 // Set our last result
896                 //
897                 this.policyResult = result;
898                 //
899                 // Clear the current operation field
900                 //
901                 this.currentOperation = null;
902                 return;
903             }
904             logger.debug("not current");
905         }
906         for (Operation op : this.operationHistory) {
907             if (op.attempt == attempt.intValue()) {
908                 op.clOperation.setEnd(Instant.now());
909                 op.clOperation.setMessage(message);
910                 op.clOperation.setOutcome(result.toString());
911                 op.policyResult = result;
912                 return;
913             }
914         }
915         logger.debug("Could not find associated operation");
916     }
917
918
919     /**
920      * Commit the abatement to the history database.
921      *
922      * @param message the abatement message
923      * @param outcome the abatement outcome
924      */
925     public void commitAbatement(String message, String outcome) {
926         logger.info("commitAbatement: {}. {}", message, outcome);
927         
928         if (this.currentOperation == null) {
929             try {
930                 this.currentOperation = this.operationHistory.getLast();
931             } catch (NoSuchElementException e) {
932                 logger.error("{}: commitAbatement threw an exception ", this, e);
933                 return;
934             }
935         }
936         this.currentOperation.clOperation.setEnd(Instant.now());
937         this.currentOperation.clOperation.setMessage(message);
938         this.currentOperation.clOperation.setOutcome(outcome);
939         //
940         // Store commit in DB
941         //
942         this.storeOperationInDataBase();
943         //
944         // Clear the current operation field
945         //
946         this.currentOperation = null;
947     }
948 }