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