aboutsummaryrefslogtreecommitdiffstats
path: root/controlloop/common/eventmanager/src/main/java/org/onap/policy/controlloop/eventmanager/ControlLoopOperationManager.java
blob: 9cd2fb3504204284fe56771664c666451ec063dc (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
/*-
 * ============LICENSE_START=======================================================
 * controlloop operation manager
 * ================================================================================
 * Copyright (C) 2017-2019 AT&T Intellectual Property. All rights reserved.
 * Modifications Copyright (C) 2019 Huawei Technologies Co., Ltd. All rights reserved.
 * Modifications Copyright (C) 2019 Tech Mahindra
 * ================================================================================
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * ============LICENSE_END=========================================================
 */

package org.onap.policy.controlloop.eventmanager;

import java.io.Serializable;
import java.sql.Timestamp;
import java.time.Instant;
import java.util.AbstractMap;
import java.util.LinkedList;
import java.util.List;
import java.util.NoSuchElementException;
import java.util.Properties;
import javax.persistence.EntityManager;
import javax.persistence.Persistence;
import org.eclipse.persistence.config.PersistenceUnitProperties;
import org.onap.aai.domain.yang.GenericVnf;
import org.onap.policy.aai.util.AaiException;
import org.onap.policy.appc.Response;
import org.onap.policy.appc.ResponseCode;
import org.onap.policy.appclcm.LcmResponseWrapper;
import org.onap.policy.controlloop.ControlLoopEvent;
import org.onap.policy.controlloop.ControlLoopException;
import org.onap.policy.controlloop.ControlLoopOperation;
import org.onap.policy.controlloop.ControlLoopResponse;
import org.onap.policy.controlloop.VirtualControlLoopEvent;
import org.onap.policy.controlloop.actor.appc.AppcActorServiceProvider;
import org.onap.policy.controlloop.actor.appclcm.AppcLcmActorServiceProvider;
import org.onap.policy.controlloop.actor.sdnc.SdncActorServiceProvider;
import org.onap.policy.controlloop.actor.sdnr.SdnrActorServiceProvider;
import org.onap.policy.controlloop.actor.so.SoActorServiceProvider;
import org.onap.policy.controlloop.actor.vfc.VfcActorServiceProvider;
import org.onap.policy.controlloop.policy.Policy;
import org.onap.policy.controlloop.policy.PolicyResult;
import org.onap.policy.drools.system.PolicyEngine;
import org.onap.policy.guard.Util;
import org.onap.policy.sdnc.SdncResponse;
import org.onap.policy.sdnr.PciResponseWrapper;
import org.onap.policy.so.SoResponseWrapper;
import org.onap.policy.vfc.VfcResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class ControlLoopOperationManager implements Serializable {
    private static final long serialVersionUID = -3773199283624595410L;
    private static final Logger logger = LoggerFactory.getLogger(ControlLoopOperationManager.class);

    private static final String VSERVER_VSERVER_NAME = "vserver.vserver-name";
    private static final String GENERIC_VNF_VNF_NAME = "generic-vnf.vnf-name";
    private static final String GENERIC_VNF_VNF_ID = "generic-vnf.vnf-id";

    //
    // These properties are not changeable, but accessible
    // for Drools Rule statements.
    //
    public final ControlLoopEvent onset;
    public final Policy policy;

    //
    // Properties used to track the Operation
    //
    private int attempts = 0;
    private Operation currentOperation = null;
    private LinkedList<Operation> operationHistory = new LinkedList<>();
    private PolicyResult policyResult = null;
    private ControlLoopEventManager eventManager = null;
    private String targetEntity;
    private String guardApprovalStatus = "NONE";// "NONE", "PERMIT", "DENY"
    private transient Object operationRequest;

    /**
     * Construct an instance.
     *
     * @param onset the onset event
     * @param policy the policy
     * @param em the event manager
     * @throws ControlLoopException if an error occurs
     * @throws AaiException if an error occurs retrieving information from A&AI
     */
    public ControlLoopOperationManager(ControlLoopEvent onset, Policy policy, ControlLoopEventManager em)
            throws ControlLoopException, AaiException {
        this.onset = onset;
        this.policy = policy;
        this.guardApprovalStatus = "NONE";
        this.eventManager = em;
        this.targetEntity = getTarget(policy);

        //
        // Let's make a sanity check
        //
        switch (policy.getActor()) {
            case "APPC":
                if ("ModifyConfig".equalsIgnoreCase(policy.getRecipe())) {
                    /*
                     * The target vnf-id may not be the same as the source vnf-id specified in the yaml, the target
                     * vnf-id is retrieved by a named query to A&AI.
                     */
                    if (Boolean.valueOf(PolicyEngine.manager.getEnvironmentProperty("aai.customQuery"))) {
                        GenericVnf genvnf = this.eventManager.getCqResponse((VirtualControlLoopEvent) onset)
                                .getGenericVnfByModelInvariantId(policy.getTarget().getResourceID());
                        if (genvnf == null) {
                            logger.info("Target entity could not be found");
                            throw new AaiException("Target vnf-id could not be found");
                        }
                        this.targetEntity = genvnf.getVnfId();

                    } else {
                        this.targetEntity =
                                AppcLcmActorServiceProvider.vnfNamedQuery(policy.getTarget().getResourceID(),
                                        this.targetEntity, PolicyEngine.manager.getEnvironmentProperty("aai.url"),
                                        PolicyEngine.manager.getEnvironmentProperty("aai.username"),
                                        PolicyEngine.manager.getEnvironmentProperty("aai.password"));
                    }
                }
                break;
            case "SO":
                break;
            case "SDNR":
                break;
            case "VFC":
                break;
            case "SDNC":
                break;
            default:
                throw new ControlLoopException("ControlLoopEventManager: policy has an unknown actor.");
        }
    }


    public ControlLoopEventManager getEventManager() {
        return eventManager;
    }

    public void setEventManager(ControlLoopEventManager eventManager) {
        this.eventManager = eventManager;
    }

    public String getTargetEntity() {
        return this.targetEntity;
    }

    @Override
    public String toString() {
        return "ControlLoopOperationManager [onset=" + (onset != null ? onset.getRequestId() : "null") + ", policy="
                + (policy != null ? policy.getId() : "null") + ", attempts=" + attempts + ", policyResult="
                + policyResult + ", currentOperation=" + currentOperation + ", operationHistory=" + operationHistory
                + "]";
    }

    //
    // Internal class used for tracking
    //
    private class Operation implements Serializable {
        private static final long serialVersionUID = 1L;

        private ControlLoopOperation clOperation = new ControlLoopOperation();
        private PolicyResult policyResult = null;
        private int attempt = 0;

        @Override
        public String toString() {
            return "Operation [attempt=" + attempt + ", policyResult=" + policyResult + ", operation=" + clOperation
                    + "]";
        }
    }

    public Object getOperationRequest() {
        return operationRequest;
    }

    public String getGuardApprovalStatus() {
        return guardApprovalStatus;
    }

    public void setGuardApprovalStatus(String guardApprovalStatus) {
        this.guardApprovalStatus = guardApprovalStatus;
    }

    /**
     * Get the target for a policy.
     *
     * @param policy the policy
     * @return the target
     * @throws ControlLoopException if an error occurs
     * @throws AaiException if an error occurs retrieving information from A&AI
     */
    public String getTarget(Policy policy) throws ControlLoopException, AaiException {
        if (policy.getTarget() == null) {
            throw new ControlLoopException("The target is null");
        }

        if (policy.getTarget().getType() == null) {
            throw new ControlLoopException("The target type is null");
        }

        switch (policy.getTarget().getType()) {
            case PNF:
                throw new ControlLoopException("PNF target is not supported");
            case VM:
            case VNF:
                VirtualControlLoopEvent virtualOnset = (VirtualControlLoopEvent) this.onset;
                if (this.onset.getTarget().equalsIgnoreCase(VSERVER_VSERVER_NAME)) {
                    return virtualOnset.getAai().get(VSERVER_VSERVER_NAME);
                } else if (this.onset.getTarget().equalsIgnoreCase(GENERIC_VNF_VNF_ID)) {
                    return virtualOnset.getAai().get(GENERIC_VNF_VNF_ID);
                } else if (this.onset.getTarget().equalsIgnoreCase(GENERIC_VNF_VNF_NAME)) {
                    /*
                     * If the onset is enriched with the vnf-id, we don't need an A&AI response
                     */
                    if (virtualOnset.getAai().containsKey(GENERIC_VNF_VNF_ID)) {
                        return virtualOnset.getAai().get(GENERIC_VNF_VNF_ID);
                    }

                    /*
                     * If the vnf-name was retrieved from the onset then the vnf-id must be obtained from the event
                     * manager's A&AI GET query
                     */
                    String vnfId;
                    if (Boolean.valueOf(PolicyEngine.manager.getEnvironmentProperty("aai.customQuery"))) {
                        vnfId = this.eventManager.getCqResponse((VirtualControlLoopEvent) onset).getDefaultGenericVnf()
                                .getVnfId();
                    } else {
                        vnfId = this.eventManager.getVnfResponse().getVnfId();
                    }
                    if (vnfId == null) {
                        throw new AaiException("No vnf-id found");
                    }
                    return vnfId;
                }
                throw new ControlLoopException("Target does not match target type");
            case VFMODULE:
                VirtualControlLoopEvent virtualOnsetEvent = (VirtualControlLoopEvent) this.onset;
                if (this.onset.getTarget().equalsIgnoreCase(VSERVER_VSERVER_NAME)) {
                    return virtualOnsetEvent.getAai().get(VSERVER_VSERVER_NAME);
                } else if (this.onset.getTarget().equalsIgnoreCase(GENERIC_VNF_VNF_ID)) {
                    return virtualOnsetEvent.getAai().get(GENERIC_VNF_VNF_ID);
                } else if (this.onset.getTarget().equalsIgnoreCase(GENERIC_VNF_VNF_NAME)) {
                    /*
                     * If the onset is enriched with the vnf-id, we don't need an A&AI response
                     */
                    if (virtualOnsetEvent.getAai().containsKey(GENERIC_VNF_VNF_ID)) {
                        return virtualOnsetEvent.getAai().get(GENERIC_VNF_VNF_ID);
                    }

                    /*
                     * If the vnf-name was retrieved from the onset then the vnf-id must be obtained from the event
                     * manager's A&AI GET query
                     */
                    String vnfId;
                    if (Boolean.valueOf(PolicyEngine.manager.getEnvironmentProperty("aai.customQuery"))) {
                        vnfId = this.eventManager.getCqResponse((VirtualControlLoopEvent) onset).getDefaultGenericVnf()
                                .getVnfId();
                    } else {
                        vnfId = this.eventManager.getVnfResponse().getVnfId();
                    }
                    if (vnfId == null) {
                        throw new AaiException("No vnf-id found");
                    }
                    return vnfId;
                }
                throw new ControlLoopException("Target does not match target type");
            default:
                throw new ControlLoopException("The target type is not supported");
        }
    }

    /**
     * Start an operation.
     *
     * @param onset the onset event
     * @return the operation request
     * @throws ControlLoopException if an error occurs
     * @throws AaiException if error occurs
     */
    public Object startOperation(/* VirtualControlLoopEvent */ControlLoopEvent onset)
            throws ControlLoopException, AaiException {
        verifyOperatonCanRun();

        //
        // Setup
        //
        this.policyResult = null;
        Operation operation = new Operation();
        operation.attempt = ++this.attempts;
        operation.clOperation.setActor(this.policy.getActor());
        operation.clOperation.setOperation(this.policy.getRecipe());
        operation.clOperation.setTarget(this.policy.getTarget().toString());
        operation.clOperation.setSubRequestId(Integer.toString(operation.attempt));
        //
        // Now determine which actor we need to construct a request for
        //
        switch (policy.getActor()) {
            case "APPC":
                /*
                 * If the recipe is ModifyConfig, a legacy APPC request is constructed. Otherwise an LCMRequest is
                 * constructed.
                 */
                this.currentOperation = operation;
                if ("ModifyConfig".equalsIgnoreCase(policy.getRecipe())) {
                    this.operationRequest = AppcActorServiceProvider.constructRequest((VirtualControlLoopEvent) onset,
                            operation.clOperation, this.policy, this.targetEntity);
                } else {
                    this.operationRequest = AppcLcmActorServiceProvider.constructRequest(
                            (VirtualControlLoopEvent) onset, operation.clOperation, this.policy, this.targetEntity);
                }
                //
                // Save the operation
                //

                return operationRequest;
            case "SO":
                SoActorServiceProvider soActorSp = new SoActorServiceProvider();
                if (Boolean.valueOf(PolicyEngine.manager.getEnvironmentProperty("aai.customQuery"))) {
                    this.operationRequest =
                            soActorSp.constructRequestCq((VirtualControlLoopEvent) onset, operation.clOperation,
                                    this.policy, eventManager.getCqResponse((VirtualControlLoopEvent) onset));
                } else {
                    this.operationRequest = soActorSp.constructRequest((VirtualControlLoopEvent) onset,
                            operation.clOperation, this.policy, eventManager.getNqVserverFromAai());
                }

                // Save the operation
                this.currentOperation = operation;

                if (this.operationRequest == null) {
                    this.policyResult = PolicyResult.FAILURE;
                }

                return operationRequest;
            case "VFC":
                if (Boolean.valueOf(PolicyEngine.manager.getEnvironmentProperty("aai.customQuery"))) {
                    this.operationRequest = VfcActorServiceProvider.constructRequestCq((VirtualControlLoopEvent) onset,
                            operation.clOperation, this.policy,
                            eventManager.getCqResponse((VirtualControlLoopEvent) onset));
                } else {
                    this.operationRequest = VfcActorServiceProvider.constructRequest((VirtualControlLoopEvent) onset,
                            operation.clOperation, this.policy, this.eventManager.getVnfResponse(),
                            PolicyEngine.manager.getEnvironmentProperty("vfc.url"),
                            PolicyEngine.manager.getEnvironmentProperty("vfc.username"),
                            PolicyEngine.manager.getEnvironmentProperty("vfc.password"));
                }
                this.currentOperation = operation;
                if (this.operationRequest == null) {
                    this.policyResult = PolicyResult.FAILURE;
                }
                return operationRequest;
            case "SDNR":
                /*
                 * If the recipe is ModifyConfig or ModifyConfigANR, a SDNR request is constructed.
                 */
                this.currentOperation = operation;
                this.operationRequest = SdnrActorServiceProvider.constructRequest((VirtualControlLoopEvent) onset,
                        operation.clOperation, this.policy);
                //
                // Save the operation
                //
                if (this.operationRequest == null) {
                    this.policyResult = PolicyResult.FAILURE;
                }

                return operationRequest;
            case "SDNC":
                SdncActorServiceProvider provider = new SdncActorServiceProvider();
                this.operationRequest =
                        provider.constructRequest((VirtualControlLoopEvent) onset, operation.clOperation, this.policy);
                this.currentOperation = operation;
                if (this.operationRequest == null) {
                    this.policyResult = PolicyResult.FAILURE;
                }
                return operationRequest;
            default:
                throw new ControlLoopException("invalid actor " + policy.getActor() + " on policy");
        }
    }

    /**
     * Handle a response.
     *
     * @param response the response
     * @return a PolicyResult
     */
    public PolicyResult onResponse(Object response) {
        //
        // Which response is it?
        //
        if (response instanceof Response) {
            //
            // Cast APPC response and handle it
            //
            return onResponse((Response) response);
        } else if (response instanceof LcmResponseWrapper) {
            //
            // Cast LCM response and handle it
            //
            return onResponse((LcmResponseWrapper) response);
        } else if (response instanceof PciResponseWrapper) {
            //
            // Cast SDNR response and handle it
            //
            return onResponse((PciResponseWrapper) response);
        } else if (response instanceof SoResponseWrapper) {
            //
            // Cast SO response and handle it
            //
            return onResponse((SoResponseWrapper) response);
        } else if (response instanceof VfcResponse) {
            //
            // Cast VFC response and handle it
            //
            return onResponse((VfcResponse) response);
        } else if (response instanceof SdncResponse) {
            //
            // Cast SDNC response and handle it
            //
            return onResponse((SdncResponse) response);
        } else {
            return null;
        }
    }

    /**
     * This method handles operation responses from APPC.
     *
     * @param appcResponse the APPC response
     * @return The result of the response handling
     */
    private PolicyResult onResponse(Response appcResponse) {
        //
        // Determine which subrequestID (ie. attempt)
        //
        Integer operationAttempt = null;
        try {
            operationAttempt = Integer.parseInt(appcResponse.getCommonHeader().getSubRequestId());
        } catch (NumberFormatException e) {
            //
            // We cannot tell what happened if this doesn't exist
            //
            this.completeOperation(operationAttempt, "Policy was unable to parse APP-C SubRequestID (it was null).",
                    PolicyResult.FAILURE_EXCEPTION);
            return PolicyResult.FAILURE_EXCEPTION;
        }
        //
        // Sanity check the response message
        //
        if (appcResponse.getStatus() == null) {
            //
            // We cannot tell what happened if this doesn't exist
            //
            this.completeOperation(operationAttempt,
                    "Policy was unable to parse APP-C response status field (it was null).",
                    PolicyResult.FAILURE_EXCEPTION);
            return PolicyResult.FAILURE_EXCEPTION;
        }
        //
        // Get the Response Code
        //
        ResponseCode code = ResponseCode.toResponseCode(appcResponse.getStatus().getCode());
        if (code == null) {
            //
            // We are unaware of this code
            //
            this.completeOperation(operationAttempt, "Policy was unable to parse APP-C response status code field.",
                    PolicyResult.FAILURE_EXCEPTION);
            return PolicyResult.FAILURE_EXCEPTION;
        }
        //
        // Ok, let's figure out what APP-C's response is
        //
        switch (code) {
            case ACCEPT:
                //
                // This is good, they got our original message and
                // acknowledged it.
                //
                // Is there any need to track this?
                //
                return null;
            case ERROR:
            case REJECT:
                //
                // We'll consider these two codes as exceptions
                //
                this.completeOperation(operationAttempt, appcResponse.getStatus().getDescription(),
                        PolicyResult.FAILURE_EXCEPTION);
                if (this.policyResult != null && this.policyResult.equals(PolicyResult.FAILURE_TIMEOUT)) {
                    return null;
                }
                return PolicyResult.FAILURE_EXCEPTION;
            case SUCCESS:
                //
                //
                //
                this.completeOperation(operationAttempt, appcResponse.getStatus().getDescription(),
                        PolicyResult.SUCCESS);
                if (this.policyResult != null && this.policyResult.equals(PolicyResult.FAILURE_TIMEOUT)) {
                    return null;
                }
                return PolicyResult.SUCCESS;
            case FAILURE:
                //
                //
                //
                this.completeOperation(operationAttempt, appcResponse.getStatus().getDescription(),
                        PolicyResult.FAILURE);
                if (this.policyResult != null && this.policyResult.equals(PolicyResult.FAILURE_TIMEOUT)) {
                    return null;
                }
                return PolicyResult.FAILURE;
            default:
                return null;
        }
    }

    /**
     * This method handles operation responses from LCM.
     *
     * @param dmaapResponse the LCM response
     * @return The result of the response handling
     */
    private PolicyResult onResponse(LcmResponseWrapper dmaapResponse) {
        /*
         * Parse out the operation attempt using the subrequestid
         */
        Integer operationAttempt = AppcLcmActorServiceProvider
                .parseOperationAttempt(dmaapResponse.getBody().getCommonHeader().getSubRequestId());
        if (operationAttempt == null) {
            this.completeOperation(operationAttempt, "Policy was unable to parse APP-C SubRequestID (it was null).",
                    PolicyResult.FAILURE_EXCEPTION);
        }

        /*
         * Process the APPCLCM response to see what PolicyResult should be returned
         */
        AbstractMap.SimpleEntry<PolicyResult, String> result =
                AppcLcmActorServiceProvider.processResponse(dmaapResponse);

        if (result.getKey() != null) {
            this.completeOperation(operationAttempt, result.getValue(), result.getKey());
            if (PolicyResult.FAILURE_TIMEOUT.equals(this.policyResult)) {
                return null;
            }
            return result.getKey();
        }
        return null;
    }

    /**
     * This method handles operation responses from SDNR.
     *
     * @param dmaapResponse the SDNR response
     * @return the result of the response handling
     */
    private PolicyResult onResponse(PciResponseWrapper dmaapResponse) {
        /*
         * Parse out the operation attempt using the subrequestid
         */
        Integer operationAttempt = SdnrActorServiceProvider
                .parseOperationAttempt(dmaapResponse.getBody().getCommonHeader().getSubRequestId());
        if (operationAttempt == null) {
            this.completeOperation(operationAttempt, "Policy was unable to parse SDNR SubRequestID.",
                    PolicyResult.FAILURE_EXCEPTION);
        }

        /*
         * Process the SDNR response to see what PolicyResult should be returned
         */
        SdnrActorServiceProvider.Pair<PolicyResult, String> result =
                SdnrActorServiceProvider.processResponse(dmaapResponse);

        if (result.getResult() != null) {
            this.completeOperation(operationAttempt, result.getMessage(), result.getResult());
            if (PolicyResult.FAILURE_TIMEOUT.equals(this.policyResult)) {
                return null;
            }
            return result.getResult();
        }
        return null;
    }

    /**
     * This method handles operation responses from SO.
     *
     * @param msoResponse the SO response
     * @return The result of the response handling
     */
    private PolicyResult onResponse(SoResponseWrapper msoResponse) {
        switch (msoResponse.getSoResponse().getHttpResponseCode()) {
            case 200:
            case 202:
                //
                // Consider it as success
                //
                this.completeOperation(this.attempts, msoResponse.getSoResponse().getHttpResponseCode() + " Success",
                        PolicyResult.SUCCESS);
                if (this.policyResult != null && this.policyResult.equals(PolicyResult.FAILURE_TIMEOUT)) {
                    return null;
                }
                return PolicyResult.SUCCESS;
            default:
                //
                // Consider it as failure
                //
                this.completeOperation(this.attempts, msoResponse.getSoResponse().getHttpResponseCode() + " Failed",
                        PolicyResult.FAILURE);
                if (this.policyResult != null && this.policyResult.equals(PolicyResult.FAILURE_TIMEOUT)) {
                    return null;
                }
                return PolicyResult.FAILURE;
        }
    }

    /**
     * This method handles operation responses from VFC.
     *
     * @param vfcResponse the VFC response
     * @return The result of the response handling
     */
    private PolicyResult onResponse(VfcResponse vfcResponse) {
        if ("finished".equalsIgnoreCase(vfcResponse.getResponseDescriptor().getStatus())) {
            //
            // Consider it as success
            //
            this.completeOperation(this.attempts, " Success", PolicyResult.SUCCESS);
            if (this.policyResult != null && this.policyResult.equals(PolicyResult.FAILURE_TIMEOUT)) {
                return null;
            }
            return PolicyResult.SUCCESS;
        } else {
            //
            // Consider it as failure
            //
            this.completeOperation(this.attempts, " Failed", PolicyResult.FAILURE);
            if (this.policyResult != null && this.policyResult.equals(PolicyResult.FAILURE_TIMEOUT)) {
                return null;
            }
            // increment operation attempts for retries
            this.attempts += 1;
            return PolicyResult.FAILURE;
        }
    }

    /**
     * This method handles operation responses from SDNC.
     *
     * @param sdncResponse the VFC response
     * @return The result of the response handling
     */
    private PolicyResult onResponse(SdncResponse sdncResponse) {
        if ("200".equals(sdncResponse.getResponseOutput().getResponseCode())) {
            //
            // Consider it as success
            //
            this.completeOperation(this.attempts, " Success", PolicyResult.SUCCESS);
            if (this.policyResult != null && this.policyResult.equals(PolicyResult.FAILURE_TIMEOUT)) {
                return null;
            }
            return PolicyResult.SUCCESS;
        } else {
            //
            // Consider it as failure
            //
            this.completeOperation(this.attempts, " Failed", PolicyResult.FAILURE);
            if (this.policyResult != null && this.policyResult.equals(PolicyResult.FAILURE_TIMEOUT)) {
                return null;
            }
            // increment operation attempts for retries
            this.attempts += 1;
            return PolicyResult.FAILURE;
        }
    }

    /**
     * Get the operation timeout.
     *
     * @return the timeout
     */
    public Integer getOperationTimeout() {
        //
        // Sanity check
        //
        if (this.policy == null) {
            logger.debug("getOperationTimeout returning 0");
            return 0;
        }
        logger.debug("getOperationTimeout returning {}", this.policy.getTimeout());
        return this.policy.getTimeout();
    }

    /**
     * Get the operation timeout as a String.
     *
     * @param defaultTimeout the default timeout
     * @return the timeout as a String
     */
    public String getOperationTimeoutString(int defaultTimeout) {
        Integer to = this.getOperationTimeout();
        if (to == null || to == 0) {
            return Integer.toString(defaultTimeout) + "s";
        }
        return to.toString() + "s";
    }

    public PolicyResult getOperationResult() {
        return this.policyResult;
    }

    /**
     * Get the operation as a message.
     *
     * @return the operation as a message
     */
    public String getOperationMessage() {
        if (this.currentOperation != null && this.currentOperation.clOperation != null) {
            return this.currentOperation.clOperation.toMessage();
        }

        if (!this.operationHistory.isEmpty()) {
            return this.operationHistory.getLast().clOperation.toMessage();
        }
        return null;
    }

    /**
     * Get the operation as a message including the guard result.
     *
     * @param guardResult the guard result
     * @return the operation as a message including the guard result
     */
    public String getOperationMessage(String guardResult) {
        if (this.currentOperation != null && this.currentOperation.clOperation != null) {
            return this.currentOperation.clOperation.toMessage() + ", Guard result: " + guardResult;
        }

        if (!this.operationHistory.isEmpty()) {
            return this.operationHistory.getLast().clOperation.toMessage() + ", Guard result: " + guardResult;
        }
        return null;
    }

    /**
     * Get the operation history.
     *
     * @return the operation history
     */
    public String getOperationHistory() {
        if (this.currentOperation != null && this.currentOperation.clOperation != null) {
            return this.currentOperation.clOperation.toHistory();
        }

        if (!this.operationHistory.isEmpty()) {
            return this.operationHistory.getLast().clOperation.toHistory();
        }
        return null;
    }

    /**
     * Get the history.
     *
     * @return the list of control loop operations
     */
    public List<ControlLoopOperation> getHistory() {
        LinkedList<ControlLoopOperation> history = new LinkedList<>();
        for (Operation op : this.operationHistory) {
            history.add(new ControlLoopOperation(op.clOperation));

        }
        return history;
    }

    /**
     * Set the operation has timed out.
     */
    public void setOperationHasTimedOut() {
        //
        //
        //
        this.completeOperation(this.attempts, "Operation timed out", PolicyResult.FAILURE_TIMEOUT);
    }

    /**
     * Set the operation has been denied by guard.
     */
    public void setOperationHasGuardDeny() {
        //
        //
        //
        this.completeOperation(this.attempts, "Operation denied by Guard", PolicyResult.FAILURE_GUARD);
    }

    public void setOperationHasException(String message) {
        this.completeOperation(this.attempts, message, PolicyResult.FAILURE_EXCEPTION);
    }

    /**
     * Is the operation complete.
     *
     * @return <code>true</code> if the operation is complete, <code>false</code> otherwise
     */
    public boolean isOperationComplete() {
        //
        // Is there currently a result?
        //
        if (this.policyResult == null) {
            //
            // either we are in process or we
            // haven't started
            //
            return false;
        }
        //
        // We have some result, check if the operation failed
        //
        if (this.policyResult.equals(PolicyResult.FAILURE)) {
            //
            // Check if there were no retries specified
            //
            if (policy.getRetry() == null || policy.getRetry() == 0) {
                //
                // The result is the failure
                //
                return true;
            }
            //
            // Check retries
            //
            if (this.isRetriesMaxedOut()) {
                //
                // No more attempts allowed, reset
                // that our actual result is failure due to retries
                //
                this.policyResult = PolicyResult.FAILURE_RETRIES;
                return true;
            } else {
                //
                // There are more attempts available to try the
                // policy recipe.
                //
                return false;
            }
        }
        //
        // Other results mean we are done
        //
        return true;
    }

    public boolean isOperationRunning() {
        return (this.currentOperation != null);
    }

    /**
     * This method verifies that the operation manager may run an operation.
     *
     * @return True if the operation can run, false otherwise
     * @throws ControlLoopException if the operation cannot run
     */
    private void verifyOperatonCanRun() throws ControlLoopException {
        //
        // They shouldn't call us if we currently running something
        //
        if (this.currentOperation != null) {
            //
            // what do we do if we are already running an operation?
            //
            throw new ControlLoopException("current operation is not null (an operation is already running)");
        }
        //
        // Check if we have maxed out on retries
        //
        if (this.policy.getRetry() == null || this.policy.getRetry() < 1) {
            //
            // No retries are allowed, so check have we even made
            // one attempt to execute the operation?
            //
            if (this.attempts >= 1) {
                //
                // We have, let's ensure our PolicyResult is set
                //
                if (this.policyResult == null) {
                    this.policyResult = PolicyResult.FAILURE_RETRIES;
                }
                //
                //
                //
                throw new ControlLoopException("current operation failed and retries are not allowed");
            }
        } else {
            //
            // Have we maxed out on retries?
            //
            if (this.attempts > this.policy.getRetry()) {
                if (this.policyResult == null) {
                    this.policyResult = PolicyResult.FAILURE_RETRIES;
                }
                throw new ControlLoopException("current oepration has failed after " + this.attempts + " retries");
            }
        }
    }

    private boolean isRetriesMaxedOut() {
        if (policy.getRetry() == null || policy.getRetry() == 0) {
            //
            // There were NO retries specified, so declare
            // this as completed.
            //
            return (this.attempts > 0);
        }
        return (this.attempts > policy.getRetry());
    }

    private void storeOperationInDataBase() {
        // Only store in DB if enabled
        boolean guardEnabled = "false".equalsIgnoreCase(PolicyEngine.manager.getEnvironmentProperty("guard.disabled"));
        if (!guardEnabled) {
            return;
        }


        // DB Properties
        Properties props = new Properties();
        if (PolicyEngine.manager.getEnvironmentProperty(Util.ONAP_KEY_URL) != null
                && PolicyEngine.manager.getEnvironmentProperty(Util.ONAP_KEY_USER) != null
                && PolicyEngine.manager.getEnvironmentProperty(Util.ONAP_KEY_PASS) != null) {
            props.put(Util.ECLIPSE_LINK_KEY_URL, PolicyEngine.manager.getEnvironmentProperty(Util.ONAP_KEY_URL));
            props.put(Util.ECLIPSE_LINK_KEY_USER, PolicyEngine.manager.getEnvironmentProperty(Util.ONAP_KEY_USER));
            props.put(Util.ECLIPSE_LINK_KEY_PASS, PolicyEngine.manager.getEnvironmentProperty(Util.ONAP_KEY_PASS));
            props.put(PersistenceUnitProperties.CLASSLOADER, ControlLoopOperationManager.class.getClassLoader());
        }


        String opsHistPu = System.getProperty("OperationsHistoryPU");
        if (!"TestOperationsHistoryPU".equals(opsHistPu)) {
            opsHistPu = "OperationsHistoryPU";
        } else {
            props.clear();
        }
        EntityManager em;
        try {
            em = Persistence.createEntityManagerFactory(opsHistPu, props).createEntityManager();
        } catch (Exception e) {
            logger.error("storeOperationInDataBase threw: ", e);
            return;
        }

        OperationsHistoryDbEntry newEntry = new OperationsHistoryDbEntry();

        newEntry.setClosedLoopName(this.onset.getClosedLoopControlName());
        newEntry.setRequestId(this.onset.getRequestId().toString());
        newEntry.setActor(this.currentOperation.clOperation.getActor());
        newEntry.setOperation(this.currentOperation.clOperation.getOperation());
        newEntry.setTarget(this.targetEntity);
        newEntry.setStarttime(Timestamp.from(this.currentOperation.clOperation.getStart()));
        newEntry.setSubrequestId(this.currentOperation.clOperation.getSubRequestId());
        newEntry.setEndtime(new Timestamp(this.currentOperation.clOperation.getEnd().toEpochMilli()));
        newEntry.setMessage(this.currentOperation.clOperation.getMessage());
        newEntry.setOutcome(this.currentOperation.clOperation.getOutcome());

        em.getTransaction().begin();
        em.persist(newEntry);
        em.getTransaction().commit();

        em.close();
    }

    private void completeOperation(Integer attempt, String message, PolicyResult result) {
        if (attempt == null) {
            logger.debug("attempt cannot be null (i.e. subRequestID)");
            return;
        }
        if (this.currentOperation != null) {
            if (this.currentOperation.attempt == attempt.intValue()) {
                this.currentOperation.clOperation.setEnd(Instant.now());
                this.currentOperation.clOperation.setMessage(message);
                this.currentOperation.clOperation.setOutcome(result.toString());
                this.currentOperation.policyResult = result;
                //
                // Save it in history
                //
                this.operationHistory.add(this.currentOperation);
                this.storeOperationInDataBase();
                //
                // Set our last result
                //
                this.policyResult = result;
                //
                // Clear the current operation field
                //
                this.currentOperation = null;
                return;
            }
            logger.debug("not current");
        }
        for (Operation op : this.operationHistory) {
            if (op.attempt == attempt.intValue()) {
                op.clOperation.setEnd(Instant.now());
                op.clOperation.setMessage(message);
                op.clOperation.setOutcome(result.toString());
                op.policyResult = result;
                return;
            }
        }
        logger.debug("Could not find associated operation");
    }


    /**
     * Commit the abatement to the history database.
     *
     * @param message the abatement message
     * @param outcome the abatement outcome
     */
    public void commitAbatement(String message, String outcome) {
        logger.info("commitAbatement: {}. {}", message, outcome);

        if (this.currentOperation == null) {
            try {
                this.currentOperation = this.operationHistory.getLast();
            } catch (NoSuchElementException e) {
                logger.error("{}: commitAbatement threw an exception ", this, e);
                return;
            }
        }
        this.currentOperation.clOperation.setEnd(Instant.now());
        this.currentOperation.clOperation.setMessage(message);
        this.currentOperation.clOperation.setOutcome(outcome);
        //
        // Store commit in DB
        //
        this.storeOperationInDataBase();
        //
        // Clear the current operation field
        //
        this.currentOperation = null;
    }

    /**
     * Construct a ControlLoopResponse object from actor response and input event.
     *
     * @param response the response from actor
     * @param event the input event
     *
     * @return a ControlLoopResponse
     */
    public ControlLoopResponse getControlLoopResponse(Object response, VirtualControlLoopEvent event) {
        if (response instanceof PciResponseWrapper) {
            //
            // Cast SDNR response and handle it
            //
            return SdnrActorServiceProvider.getControlLoopResponse((PciResponseWrapper) response, event);
        } else {
            return null;
        }
    }

}