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