ac36603a1f127bf8a3f6aeb1c05575299b50d4d9
[policy/drools-applications.git] /
1 /*-
2  * ============LICENSE_START=======================================================
3  * policy-yaml unit test
4  * ================================================================================
5  * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved.
6  * ================================================================================
7  * Licensed under the Apache License, Version 2.0 (the "License");
8  * you may not use this file except in compliance with the License.
9  * You may obtain a copy of the License at
10  * 
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  * 
13  * Unless required by applicable law or agreed to in writing, software
14  * distributed under the License is distributed on an "AS IS" BASIS,
15  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  * See the License for the specific language governing permissions and
17  * limitations under the License.
18  * ============LICENSE_END=========================================================
19  */
20
21 package org.onap.policy.controlloop.policy;
22
23 import static org.junit.Assert.assertEquals;
24 import static org.junit.Assert.assertFalse;
25 import static org.junit.Assert.assertNotNull;
26 import static org.junit.Assert.assertNull;
27 import static org.junit.Assert.assertTrue;
28 import static org.junit.Assert.fail;
29
30 import java.io.File;
31 import java.io.FileInputStream;
32 import java.io.FileNotFoundException;
33 import java.io.IOException;
34 import java.io.InputStream;
35 import java.util.UUID;
36
37 import org.junit.Ignore;
38 import org.junit.Rule;
39 import org.junit.Test;
40 import org.junit.rules.ExpectedException;
41 import org.onap.policy.aai.Pnf;
42 import org.onap.policy.aai.PnfType;
43 import org.onap.policy.controlloop.policy.builder.BuilderException;
44 import org.onap.policy.controlloop.policy.builder.ControlLoopPolicyBuilder;
45 import org.onap.policy.controlloop.policy.builder.Message;
46 import org.onap.policy.controlloop.policy.builder.MessageLevel;
47 import org.onap.policy.controlloop.policy.builder.Results;
48 import org.onap.policy.sdc.Resource;
49 import org.onap.policy.sdc.ResourceType;
50 import org.onap.policy.sdc.Service;
51 import org.yaml.snakeyaml.Yaml;
52 import org.yaml.snakeyaml.constructor.Constructor;
53 import org.yaml.snakeyaml.error.YAMLException;
54
55
56 public class ControlLoopPolicyBuilderTest {
57
58     @Rule
59     public ExpectedException expectedException = ExpectedException.none();
60
61     @Test
62     public void testControlLoop() {
63         try {
64             //
65             // Create a builder for our policy
66             //
67             ControlLoopPolicyBuilder builder =
68                     ControlLoopPolicyBuilder.Factory.buildControlLoop(UUID.randomUUID().toString(), 2400);
69             //
70             // Test add services
71             //
72             Service scp = new Service("vSCP");
73             Service usp = new Service("vUSP");
74             Service trinity = new Service("Trinity");
75             builder = builder.addService(scp, usp, trinity);
76             assertTrue(builder.getControlLoop().getServices().size() == 3);
77             //
78             // Test remove services
79             //
80             builder = builder.removeService(scp);
81             assertTrue(builder.getControlLoop().getServices().size() == 2);
82             builder = builder.removeAllServices();
83             assertTrue(builder.getControlLoop().getServices().size() == 0);
84             //
85             // Test add resources
86             //
87             Resource cts = new Resource("vCTS", ResourceType.VF);
88             Resource com = new Resource("vCTS", ResourceType.VF);
89             Resource rar = new Resource("vCTS", ResourceType.VF);
90             builder = builder.addResource(cts, com, rar);
91             assertTrue(builder.getControlLoop().getResources().size() == 3);
92             //
93             // Test remove resources
94             //
95             builder = builder.removeResource(cts);
96             assertTrue(builder.getControlLoop().getResources().size() == 2);
97             builder = builder.removeAllResources();
98             assertTrue(builder.getControlLoop().getResources().size() == 0);
99         } catch (BuilderException e) {
100             fail(e.getMessage());
101         }
102     }
103
104     @Test
105     public void testAddNullService() throws BuilderException {
106         ControlLoopPolicyBuilder builder =
107                 ControlLoopPolicyBuilder.Factory.buildControlLoop(UUID.randomUUID().toString(), 2400);
108         expectedException.expect(BuilderException.class);
109         expectedException.expectMessage("Service must not be null");
110         builder.addService((Service) null);
111     }
112
113     @Test
114     public void testAddInvalidService() throws BuilderException {
115         ControlLoopPolicyBuilder builder =
116                 ControlLoopPolicyBuilder.Factory.buildControlLoop(UUID.randomUUID().toString(), 2400);
117         expectedException.expect(BuilderException.class);
118         expectedException.expectMessage("Invalid service - need either a serviceUUID or serviceName");
119         builder.addService(new Service());
120     }
121
122     @Test
123     public void testAddServiceWithUuid() throws BuilderException {
124         ControlLoopPolicyBuilder builder =
125                 ControlLoopPolicyBuilder.Factory.buildControlLoop(UUID.randomUUID().toString(), 2400);
126         UUID uuid = UUID.randomUUID();
127         Service serviceWithUuid = new Service(uuid);
128         builder.addService(serviceWithUuid);
129         assertTrue(builder.getControlLoop().getServices().size() == 1);
130     }
131
132     @Test
133     public void testAddNullResource() throws BuilderException {
134         ControlLoopPolicyBuilder builder =
135                 ControlLoopPolicyBuilder.Factory.buildControlLoop(UUID.randomUUID().toString(), 2400);
136         expectedException.expect(BuilderException.class);
137         expectedException.expectMessage("Resource must not be null");
138         builder.addResource((Resource) null);
139     }
140
141
142     @Test
143     public void testAddInvalidResource() throws BuilderException {
144         ControlLoopPolicyBuilder builder =
145                 ControlLoopPolicyBuilder.Factory.buildControlLoop(UUID.randomUUID().toString(), 2400);
146         expectedException.expect(BuilderException.class);
147         expectedException.expectMessage("Invalid resource - need either resourceUUID or resourceName");
148         builder.addResource(new Resource());
149     }
150
151     @Test
152     public void testAddAndRemoveResourceWithUuid() throws BuilderException {
153         ControlLoopPolicyBuilder builder =
154                 ControlLoopPolicyBuilder.Factory.buildControlLoop(UUID.randomUUID().toString(), 2400);
155         UUID uuid = UUID.randomUUID();
156         Resource resourceWithUuid = new Resource(uuid);
157         builder.addResource(resourceWithUuid);
158         assertTrue(builder.getControlLoop().getResources().size() == 1);
159
160         builder.removeResource(resourceWithUuid);
161         assertTrue(builder.getControlLoop().getResources().size() == 0);
162     }
163
164     @Test
165     public void testRemoveNullResource() throws BuilderException {
166         ControlLoopPolicyBuilder builder =
167                 ControlLoopPolicyBuilder.Factory.buildControlLoop(UUID.randomUUID().toString(), 2400);
168         Resource resource = new Resource("resource1", ResourceType.VF);
169         builder.addResource(resource);
170         expectedException.expect(BuilderException.class);
171         expectedException.expectMessage("Resource must not be null");
172         builder.removeResource((Resource) null);
173     }
174
175     @Test
176     public void testRemoveResourceNoExistingResources() throws BuilderException {
177         ControlLoopPolicyBuilder builder =
178                 ControlLoopPolicyBuilder.Factory.buildControlLoop(UUID.randomUUID().toString(), 2400);
179         expectedException.expect(BuilderException.class);
180         expectedException.expectMessage("No existing resources to remove");
181         builder.removeResource(new Resource("resource1", ResourceType.VF));
182     }
183
184     @Test
185     public void testRemoveInvalidResource() throws BuilderException {
186         ControlLoopPolicyBuilder builder =
187                 ControlLoopPolicyBuilder.Factory.buildControlLoop(UUID.randomUUID().toString(), 2400);
188         Resource resource = new Resource("resource1", ResourceType.VF);
189         builder.addResource(resource);
190         expectedException.expect(BuilderException.class);
191         expectedException.expectMessage("Invalid resource - need either a resourceUUID or resourceName");
192         builder.removeResource(new Resource());
193     }
194
195     @Test
196     public void testRemoveUnknownResource() throws BuilderException {
197         ControlLoopPolicyBuilder builder =
198                 ControlLoopPolicyBuilder.Factory.buildControlLoop(UUID.randomUUID().toString(), 2400);
199         Resource resource = new Resource("resource1", ResourceType.VF);
200         builder.addResource(resource);
201         final String unknownResourceName = "reource2";
202         expectedException.expect(BuilderException.class);
203         expectedException.expectMessage("Unknown resource " + unknownResourceName);
204         builder.removeResource(new Resource(unknownResourceName, ResourceType.VF));
205     }
206
207     @Test
208     public void testControlLoopWithInitialResourceAndServices() {
209         try {
210             Resource cts = new Resource("vCTS", ResourceType.VF);
211             Service scp = new Service("vSCP");
212             Service usp = new Service("vUSP");
213             ControlLoopPolicyBuilder builder = ControlLoopPolicyBuilder.Factory
214                     .buildControlLoop(UUID.randomUUID().toString(), 2400, cts, scp, usp);
215             assertTrue(builder.getControlLoop().getResources().size() == 1);
216             assertTrue(builder.getControlLoop().getServices().size() == 2);
217         } catch (BuilderException e) {
218             fail(e.getMessage());
219         }
220     }
221
222     @Test
223     public void testControlLoopWithInitialResourcesAndService() {
224         try {
225             Resource cts = new Resource("vCTS", ResourceType.VF);
226             Resource com = new Resource("vCTS", ResourceType.VF);
227             Service scp = new Service("vSCP");
228             ControlLoopPolicyBuilder builder = ControlLoopPolicyBuilder.Factory
229                     .buildControlLoop(UUID.randomUUID().toString(), 2400, scp, cts, com);
230             assertTrue(builder.getControlLoop().getServices().size() == 1);
231             assertTrue(builder.getControlLoop().getResources().size() == 2);
232         } catch (BuilderException e) {
233             fail(e.getMessage());
234         }
235     }
236
237     @Test
238     @Ignore
239     // I'VE MARKED THIS TEST CASE AS IGNORE BECAUSE THE TEST CASE FAILS
240     // This test case fails because builder.getControlLoop() returns an instance of ControlLoop
241     // copied using
242     // the ControlLoop(ControlLoop controlLoop) constructor.
243     // This constructor does not copy the value of pnf into the newly created object
244     // On the face of it, this looks like a bug, but perhaps there is a reason for this
245     // PLEASE ADVISE IF THE BEHAVIOUR IS INCORRECT OR THE TEST CASE IS INVALID
246     public void testControlLoopForPnf() {
247         try {
248             Pnf pnf = new Pnf();
249             pnf.setPnfType(PnfType.ENODEB);
250             ControlLoopPolicyBuilder builder =
251                     ControlLoopPolicyBuilder.Factory.buildControlLoop(UUID.randomUUID().toString(), 2400, pnf);
252             assertEquals(pnf, builder.getControlLoop().getPnf());
253
254             builder.removePNF();
255             assertNull(builder.getControlLoop().getPnf());
256         } catch (BuilderException e) {
257             fail(e.getMessage());
258         }
259     }
260
261     @Test
262     @Ignore
263     // Fails for the same reason as the above test case
264     public void testSetAndRemovePnf() throws BuilderException {
265         ControlLoopPolicyBuilder builder =
266                 ControlLoopPolicyBuilder.Factory.buildControlLoop(UUID.randomUUID().toString(), 2400);
267         assertNull(builder.getControlLoop().getPnf());
268
269         Pnf pnf = new Pnf();
270         pnf.setPnfType(PnfType.ENODEB);
271         builder.setPNF(pnf);
272         assertEquals(pnf, builder.getControlLoop().getPnf());
273
274         builder.removePNF();
275         assertNull(builder.getControlLoop().getPnf());
276     }
277
278     @Test
279     public void testSetNullPnf() throws BuilderException {
280         ControlLoopPolicyBuilder builder =
281                 ControlLoopPolicyBuilder.Factory.buildControlLoop(UUID.randomUUID().toString(), 2400);
282         expectedException.expect(BuilderException.class);
283         expectedException.expectMessage("PNF must not be null");
284         builder.setPNF(null);
285     }
286
287     @Test
288     public void testSetInvalidPnf() throws BuilderException {
289         ControlLoopPolicyBuilder builder =
290                 ControlLoopPolicyBuilder.Factory.buildControlLoop(UUID.randomUUID().toString(), 2400);
291         expectedException.expect(BuilderException.class);
292         expectedException.expectMessage("Invalid PNF - need either pnfName or pnfType");
293         builder.setPNF(new Pnf());
294     }
295
296     @Test
297     public void testSetAbatement() throws BuilderException {
298         ControlLoopPolicyBuilder builder =
299                 ControlLoopPolicyBuilder.Factory.buildControlLoop(UUID.randomUUID().toString(), 2400);
300         assertFalse(builder.getControlLoop().getAbatement());
301         builder = builder.setAbatement(true);
302         assertTrue(builder.getControlLoop().getAbatement());
303     }
304
305     @Test
306     public void testSetNullAbatement() throws BuilderException {
307         ControlLoopPolicyBuilder builder =
308                 ControlLoopPolicyBuilder.Factory.buildControlLoop(UUID.randomUUID().toString(), 2400);
309         expectedException.expect(BuilderException.class);
310         expectedException.expectMessage("abatement must not be null");
311         builder = builder.setAbatement(null);
312     }
313
314     @Test
315     public void testTimeout() {
316         try {
317             //
318             // Create a builder for our policy
319             //
320             ControlLoopPolicyBuilder builder =
321                     ControlLoopPolicyBuilder.Factory.buildControlLoop(UUID.randomUUID().toString(), 2400);
322             //
323             // Test setTimeout
324             //
325             assertTrue(builder.getControlLoop().getTimeout() == 2400);
326             builder = builder.setTimeout(800);
327             assertTrue(builder.getControlLoop().getTimeout() == 800);
328             //
329             // Test calculateTimeout
330             //
331             Policy trigger =
332                     builder.setTriggerPolicy(PolicyParam.builder().id(UUID.randomUUID().toString())
333                             .name("Restart the VM")
334                             .description("Upon getting the trigger event, restart the VM")
335                             .actor("APPC")
336                             .target(new Target(TargetType.VM))
337                             .recipe("Restart")
338                             .payload(null)
339                             .retries(2)
340                             .timeout(300).build());
341             @SuppressWarnings("unused")
342             Policy onRestartFailurePolicy = builder.setPolicyForPolicyResult("Rebuild VM",
343                     "If the restart fails, rebuild it", "APPC", new Target(TargetType.VM), "Rebuild", null, 1, 600,
344                     trigger.getId(), PolicyResult.FAILURE, PolicyResult.FAILURE_RETRIES, PolicyResult.FAILURE_TIMEOUT);
345             assertTrue(builder.calculateTimeout().equals(new Integer(300 + 600)));
346             //
347         } catch (BuilderException e) {
348             fail(e.getMessage());
349         }
350     }
351
352     @Test
353     public void testTriggerPolicyMethods() {
354         try {
355             ControlLoopPolicyBuilder builder =
356                     ControlLoopPolicyBuilder.Factory.buildControlLoop(UUID.randomUUID().toString(), 2400);
357             //
358             // Test isOpenLoop
359             //
360             assertTrue(builder.isOpenLoop());
361             //
362             // Test set initial trigger policy
363             //
364             Policy triggerPolicy1 =
365                     builder.setTriggerPolicy(
366                             PolicyParam.builder().id(UUID.randomUUID().toString())
367                             .name("Restart the VM")
368                             .description("Upon getting the trigger event, restart the VM")
369                             .actor("APPC")
370                             .target(new Target(TargetType.VM))
371                             .recipe("Restart")
372                             .payload(null)
373                             .retries(2)
374                             .timeout(300).build());
375             assertTrue(builder.isOpenLoop() == false);
376             assertTrue(builder.getControlLoop().getTrigger_policy().equals(triggerPolicy1.getId()));
377             //
378             // Set trigger policy to a new policy
379             //
380             @SuppressWarnings("unused")
381             Policy triggerPolicy2 =
382                     builder.setTriggerPolicy(
383                             PolicyParam.builder()
384                             .id(UUID.randomUUID().toString())
385                             .name("Rebuild the VM")
386                             .description("Upon getting the trigger event, rebuild the VM")
387                             .actor("APPC")
388                             .target(new Target(TargetType.VM))
389                             .recipe("Rebuild")
390                             .payload(null)
391                             .retries(2)
392                             .timeout(300).build());
393             //
394             // Test set trigger policy to another existing policy
395             //
396             @SuppressWarnings("unused")
397             ControlLoop cl = builder.setExistingTriggerPolicy(triggerPolicy1.getId());
398             assertTrue(builder.getControlLoop().getTrigger_policy().equals(triggerPolicy1.getId()));
399             //
400             // Test get trigger policy
401             //
402             assertTrue(builder.getTriggerPolicy().equals(triggerPolicy1));
403             //
404         } catch (BuilderException e) {
405             fail(e.getMessage());
406         }
407     }
408
409     @Test
410     public void testSetTriggerPolicyNullPolicyId() throws BuilderException {
411         ControlLoopPolicyBuilder builder =
412                 ControlLoopPolicyBuilder.Factory.buildControlLoop(UUID.randomUUID().toString(), 2400);
413         expectedException.expect(BuilderException.class);
414         expectedException.expectMessage("Id must not be null");
415         builder.setExistingTriggerPolicy(null);
416     }
417
418     @Test
419     public void testSetTriggerPolicyNoPoliciesExist() throws BuilderException {
420         ControlLoopPolicyBuilder builder =
421                 ControlLoopPolicyBuilder.Factory.buildControlLoop(UUID.randomUUID().toString(), 2400);
422         final String unknownPolicyId = "100";
423         expectedException.expect(BuilderException.class);
424         expectedException.expectMessage("Unknown policy " + unknownPolicyId);
425         builder.setExistingTriggerPolicy(unknownPolicyId);
426     }
427
428     @Test
429     public void testSetTriggerPolicyUnknownPolicy() throws BuilderException {
430         ControlLoopPolicyBuilder builder =
431                 ControlLoopPolicyBuilder.Factory.buildControlLoop(UUID.randomUUID().toString(), 2400);
432         builder.setTriggerPolicy(
433                 PolicyParam.builder()
434                 .id(UUID.randomUUID().toString())
435                 .name("Restart the VM")
436                 .description("Upon getting the trigger event, restart the VM")
437                 .actor("APPC")
438                 .target(new Target(TargetType.VM))
439                 .recipe("Restart")
440                 .payload(null)
441                 .retries(2)
442                 .timeout(300).build());
443         final String unknownPolicyId = "100";
444         expectedException.expect(BuilderException.class);
445         expectedException.expectMessage("Unknown policy " + unknownPolicyId);
446         builder.setExistingTriggerPolicy(unknownPolicyId);
447     }
448
449     @Test
450     public void testAddRemovePolicies() {
451         try {
452             ControlLoopPolicyBuilder builder =
453                     ControlLoopPolicyBuilder.Factory.buildControlLoop(UUID.randomUUID().toString(), 2400);
454             Policy triggerPolicy =
455                     builder.setTriggerPolicy(
456                             PolicyParam.builder()
457                             .id(UUID.randomUUID().toString())
458                             .name("Restart the VM")
459                             .description("Upon getting the trigger event, restart the VM")
460                             .actor("APPC")
461                             .target(new Target(TargetType.VM))
462                             .recipe("Restart")
463                             .payload(null)
464                             .retries(2)
465                             .timeout(300).build());
466             //
467             // Test create a policy and chain it to the results of trigger policy
468             //
469             Policy onRestartFailurePolicy1 = builder.setPolicyForPolicyResult("Rebuild VM",
470                     "If the restart fails, rebuild it.", "APPC", new Target(TargetType.VM), "Rebuild", null, 1, 600,
471                     triggerPolicy.getId(), PolicyResult.FAILURE, PolicyResult.FAILURE_EXCEPTION,
472                     PolicyResult.FAILURE_RETRIES, PolicyResult.FAILURE_TIMEOUT, PolicyResult.FAILURE_GUARD);
473             //
474             assertTrue(builder.getTriggerPolicy().getFailure().equals(onRestartFailurePolicy1.getId()));
475             assertTrue(builder.getTriggerPolicy().getFailure_exception().equals(onRestartFailurePolicy1.getId()));
476             assertTrue(builder.getTriggerPolicy().getFailure_retries().equals(onRestartFailurePolicy1.getId()));
477             assertTrue(builder.getTriggerPolicy().getFailure_timeout().equals(onRestartFailurePolicy1.getId()));
478             assertTrue(builder.getTriggerPolicy().getFailure_guard().equals(onRestartFailurePolicy1.getId()));
479
480             //
481             // Test create a policy and chain it to the results of trigger policy success
482             //
483             Policy onSuccessPolicy1 = builder.setPolicyForPolicyResult("Do something",
484                     "If the restart succeeds, do something else.", "APPC", new Target(TargetType.VM), "SomethingElse",
485                     null, 1, 600, triggerPolicy.getId(), PolicyResult.SUCCESS);
486             //
487             assertTrue(builder.getTriggerPolicy().getSuccess().equals(onSuccessPolicy1.getId()));
488
489             //
490             // Test remove policy
491             //
492             boolean removed = builder.removePolicy(onRestartFailurePolicy1.getId());
493             assertTrue(removed);
494             assertTrue(builder.getTriggerPolicy().getFailure().equals(FinalResult.FINAL_FAILURE.toString()));
495             assertTrue(builder.getTriggerPolicy().getFailure_retries()
496                     .equals(FinalResult.FINAL_FAILURE_RETRIES.toString()));
497             assertTrue(builder.getTriggerPolicy().getFailure_timeout()
498                     .equals(FinalResult.FINAL_FAILURE_TIMEOUT.toString()));
499             assertTrue(
500                     builder.getTriggerPolicy().getFailure_guard().equals(FinalResult.FINAL_FAILURE_GUARD.toString()));
501             //
502             // Create another policy and chain it to the results of trigger policy
503             //
504             final Policy onRestartFailurePolicy2 =
505                     builder.setPolicyForPolicyResult("Rebuild VM", "If the restart fails, rebuild it.", "APPC",
506                             new Target(TargetType.VM), "Rebuild", null, 2, 600, triggerPolicy.getId(),
507                             PolicyResult.FAILURE, PolicyResult.FAILURE_RETRIES, PolicyResult.FAILURE_TIMEOUT);
508             //
509             // Test reset policy results
510             //
511             triggerPolicy = builder.resetPolicyResults(triggerPolicy.getId());
512             assertTrue(builder.getTriggerPolicy().getFailure().equals(FinalResult.FINAL_FAILURE.toString()));
513             assertTrue(builder.getTriggerPolicy().getFailure_retries()
514                     .equals(FinalResult.FINAL_FAILURE_RETRIES.toString()));
515             assertTrue(builder.getTriggerPolicy().getFailure_timeout()
516                     .equals(FinalResult.FINAL_FAILURE_TIMEOUT.toString()));
517             //
518             // Test set the policy results to an existing operational policy
519             //
520             Policy onRestartFailurePolicy3 =
521                     builder.setPolicyForPolicyResult(onRestartFailurePolicy2.getId(), triggerPolicy.getId(),
522                             PolicyResult.FAILURE, PolicyResult.FAILURE_RETRIES, PolicyResult.FAILURE_TIMEOUT);
523             assertTrue(builder.getTriggerPolicy().getFailure().equals(onRestartFailurePolicy3.getId()));
524             assertTrue(builder.getTriggerPolicy().getFailure_retries().equals(onRestartFailurePolicy3.getId()));
525             assertTrue(builder.getTriggerPolicy().getFailure_timeout().equals(onRestartFailurePolicy3.getId()));
526             //
527             // Test set the policy result for success to an existing operational policy
528             //
529             Policy onRestartFailurePolicy4 =
530                     builder.setPolicyForPolicyResult(onRestartFailurePolicy2.getId(), triggerPolicy.getId(),
531                             PolicyResult.FAILURE, PolicyResult.FAILURE_EXCEPTION, PolicyResult.FAILURE_GUARD,
532                             PolicyResult.FAILURE_RETRIES, PolicyResult.FAILURE_TIMEOUT, PolicyResult.SUCCESS);
533             assertTrue(builder.getTriggerPolicy().getFailure().equals(onRestartFailurePolicy4.getId()));
534             assertTrue(builder.getTriggerPolicy().getFailure_exception().equals(onRestartFailurePolicy4.getId()));
535             assertTrue(builder.getTriggerPolicy().getFailure_guard().equals(onRestartFailurePolicy4.getId()));
536             assertTrue(builder.getTriggerPolicy().getFailure_retries().equals(onRestartFailurePolicy4.getId()));
537             assertTrue(builder.getTriggerPolicy().getFailure_timeout().equals(onRestartFailurePolicy4.getId()));
538             assertTrue(builder.getTriggerPolicy().getSuccess().equals(onRestartFailurePolicy4.getId()));
539
540             //
541             // Test remove all existing operational policies
542             //
543             builder = builder.removeAllPolicies();
544             assertTrue(builder.getControlLoop().getTrigger_policy().equals(FinalResult.FINAL_OPENLOOP.toString()));
545             //
546         } catch (BuilderException e) {
547             fail(e.getMessage());
548         }
549     }
550
551     @Test
552     public void testAddToUnknownPolicy() throws BuilderException {
553         ControlLoopPolicyBuilder builder =
554                 ControlLoopPolicyBuilder.Factory.buildControlLoop(UUID.randomUUID().toString(), 2400);
555         final String policyId = "100";
556         expectedException.expect(BuilderException.class);
557         expectedException.expectMessage("Unknown policy " + policyId);
558
559         builder.setPolicyForPolicyResult("Rebuild VM", "If the restart fails, rebuild it.", "APPC",
560                 new Target(TargetType.VM), "Rebuild", null, 1, 600, policyId, PolicyResult.FAILURE,
561                 PolicyResult.FAILURE_RETRIES, PolicyResult.FAILURE_TIMEOUT, PolicyResult.FAILURE_GUARD);
562     }
563
564     @Test
565     public void testAddExistingPolicyToUnknownPolicy() throws BuilderException {
566         ControlLoopPolicyBuilder builder =
567                 ControlLoopPolicyBuilder.Factory.buildControlLoop(UUID.randomUUID().toString(), 2400);
568         Policy triggerPolicy =
569                 builder.setTriggerPolicy(
570                         PolicyParam.builder()
571                         .id(UUID.randomUUID().toString())
572                         .name("Restart the VM")
573                         .description("Upon getting the trigger event, restart the VM")
574                         .actor("APPC")
575                         .target(new Target(TargetType.VM))
576                         .recipe("Restart")
577                         .payload(null)
578                         .retries(2)
579                         .timeout(300).build());
580
581
582         Policy onRestartFailurePolicy = builder.setPolicyForPolicyResult("Rebuild VM",
583                 "If the restart fails, rebuild it.", "APPC", new Target(TargetType.VM), "Rebuild", null, 1, 600,
584                 triggerPolicy.getId(), PolicyResult.FAILURE);
585
586         final String unknownPolicyId = "100";
587         expectedException.expect(BuilderException.class);
588         expectedException.expectMessage(unknownPolicyId + " does not exist");
589
590         builder.setPolicyForPolicyResult(onRestartFailurePolicy.getId(), unknownPolicyId, PolicyResult.FAILURE);
591     }
592
593     @Test
594     public void testAddUnknownExistingPolicyToPolicy() throws BuilderException {
595         ControlLoopPolicyBuilder builder =
596                 ControlLoopPolicyBuilder.Factory.buildControlLoop(UUID.randomUUID().toString(), 2400);
597         Policy triggerPolicy =
598                 builder.setTriggerPolicy(
599                         PolicyParam.builder()
600                         .id(UUID.randomUUID().toString())
601                         .name("Restart the VM")
602                         .description("Upon getting the trigger event, restart the VM")
603                         .actor("APPC")
604                         .target(new Target(TargetType.VM))
605                         .recipe("Restart")
606                         .payload(null)
607                         .retries(2)
608                         .timeout(300).build());
609
610         final String unknownPolicyId = "100";
611         expectedException.expect(BuilderException.class);
612         expectedException.expectMessage("Operational policy " + unknownPolicyId + " does not exist");
613
614         builder.setPolicyForPolicyResult(unknownPolicyId, triggerPolicy.getId(), PolicyResult.FAILURE);
615     }
616
617     @Test
618     public void testAddOperationsAccumulateParams() {
619         try {
620             ControlLoopPolicyBuilder builder =
621                     ControlLoopPolicyBuilder.Factory.buildControlLoop(UUID.randomUUID().toString(), 2400);
622             Policy triggerPolicy =
623                     builder.setTriggerPolicy(
624                             PolicyParam.builder()
625                             .id(UUID.randomUUID().toString())
626                             .name("Restart the eNodeB")
627                             .description("Upon getting the trigger event, restart the eNodeB")
628                             .actor("RANController")
629                             .target(new Target(TargetType.PNF))
630                             .recipe("Restart")
631                             .payload(null)
632                             .retries(2)
633                             .timeout(300).build());
634             //
635             // Add the operationsAccumulateParams
636             //
637             triggerPolicy = builder.addOperationsAccumulateParams(triggerPolicy.getId(),
638                     new OperationsAccumulateParams("15m", 5));
639             assertNotNull(builder.getTriggerPolicy().getOperationsAccumulateParams());
640             assertTrue(builder.getTriggerPolicy().getOperationsAccumulateParams().getPeriod().equals("15m"));
641             assertTrue(builder.getTriggerPolicy().getOperationsAccumulateParams().getLimit() == 5);
642             //
643         } catch (BuilderException e) {
644             fail(e.getMessage());
645         }
646     }
647
648
649     @Test
650     public void testBuildSpecification() {
651         try {
652             //
653             // Create the builder
654             //
655             ControlLoopPolicyBuilder builder =
656                     ControlLoopPolicyBuilder.Factory.buildControlLoop(UUID.randomUUID().toString(), 800);
657             //
658             // Set the first invalid trigger policy
659             //
660             final Policy policy1 = builder.setTriggerPolicy(
661                     PolicyParam.builder()
662                     .id(UUID.randomUUID().toString())
663                     .name("Restart the VM")
664                     .description("Upon getting the trigger event, restart the VM")
665                     .actor(null)
666                     .target(null)
667                     .recipe("Instantiate")
668                     .payload(null)
669                     .retries(2)
670                     .timeout(300).build());
671             Results results = builder.buildSpecification();
672             //
673             // Check that ERRORs are in results for invalid policy arguments
674             //
675             boolean invalidActor = false;
676             boolean invalidRecipe = false;
677             boolean invalidTarget = false;
678             for (Message m : results.getMessages()) {
679                 if (m.getMessage().equals("Policy actor is null") && m.getLevel() == MessageLevel.ERROR) {
680                     invalidActor = true;
681                 }
682                 if (m.getMessage().equals("Policy recipe is invalid") && m.getLevel() == MessageLevel.ERROR) {
683                     invalidRecipe = true;
684                 }
685                 if (m.getMessage().equals("Policy target is null") && m.getLevel() == MessageLevel.ERROR) {
686                     invalidTarget = true;
687                 }
688             }
689             //
690             assertTrue(invalidActor);
691             assertTrue(invalidRecipe);
692             assertTrue(invalidTarget);
693             //
694             // Remove the invalid policy
695             //
696             // @SuppressWarnings("unused")
697             boolean removed = builder.removePolicy(policy1.getId());
698             assertTrue(removed);
699             assertTrue(builder.getTriggerPolicy() == null);
700             //
701             // Set a valid trigger policy
702             //
703             Policy policy1a = builder.setTriggerPolicy(
704                     PolicyParam.builder()
705                     .id(UUID.randomUUID().toString())
706                     .name("Rebuild VM")
707                     .description("If the restart fails, rebuild it.")
708                     .actor("APPC")
709                     .target(new Target(TargetType.VM))
710                     .recipe("Rebuild")
711                     .payload(null)
712                     .retries(1)
713                     .timeout(600).build());
714             //
715             // Set a second valid trigger policy
716             //
717             final Policy policy2 =
718                     builder.setTriggerPolicy(
719                             PolicyParam.builder()
720                             .id(UUID.randomUUID().toString())
721                             .name("Restart the VM")
722                             .description("Upon getting the trigger event, restart the VM")
723                             .actor("APPC")
724                             .target(new Target(TargetType.VM))
725                             .recipe("Restart")
726                             .payload(null)
727                             .retries(2)
728                             .timeout(300).build());
729             //
730             // Now, we have policy1 unreachable
731             //
732             results = builder.buildSpecification();
733             boolean unreachable = false;
734             for (Message m : results.getMessages()) {
735                 if (m.getMessage().equals("Policy " + policy1a.getId() + " is not reachable.")
736                         && m.getLevel() == MessageLevel.WARNING) {
737                     unreachable = true;
738                     break;
739                 }
740             }
741             assertTrue(unreachable);
742             //
743             // Set policy1a for the failure results of policy2
744             //
745             policy1a = builder.setPolicyForPolicyResult(policy1a.getId(), policy2.getId(), PolicyResult.FAILURE,
746                     PolicyResult.FAILURE_RETRIES, PolicyResult.FAILURE_TIMEOUT);
747             results = builder.buildSpecification();
748             boolean invalidTimeout = false;
749             for (Message m : results.getMessages()) {
750                 if (m.getMessage()
751                         .equals("controlLoop overall timeout is less than the sum of operational policy timeouts.")
752                         && m.getLevel() == MessageLevel.ERROR) {
753                     invalidTimeout = true;
754                     break;
755                 }
756             }
757             assertTrue(invalidTimeout);
758             //
759             // Remove policy2 (revert controlLoop back to open loop)
760             //
761             removed = builder.removePolicy(policy2.getId());
762             //
763             // ControlLoop is open loop now, but it still has policies (policy1)
764             //
765             results = builder.buildSpecification();
766             unreachable = false;
767             for (Message m : results.getMessages()) {
768                 if (m.getMessage().equals("Open Loop policy contains policies. The policies will never be invoked.")
769                         && m.getLevel() == MessageLevel.WARNING) {
770                     unreachable = true;
771                     break;
772                 }
773             }
774             assertTrue(unreachable);
775             //
776         } catch (BuilderException e) {
777             fail(e.getMessage());
778         }
779     }
780
781
782     @Test
783     public void test1() {
784         this.test("src/test/resources/v1.0.0/policy_Test.yaml");
785     }
786
787     @Test
788     public void testEvilYaml() {
789         try (InputStream is = new FileInputStream(new File("src/test/resources/v1.0.0/test_evil.yaml"))) {
790             //
791             // Read the yaml into our Java Object
792             //
793             Yaml yaml = new Yaml(new Constructor(ControlLoopPolicy.class));
794             yaml.load(is);
795         } catch (FileNotFoundException e) {
796             fail(e.getLocalizedMessage());
797         } catch (IOException e) {
798             fail(e.getLocalizedMessage());
799         } catch (YAMLException e) {
800             //
801             // Should have this
802             //
803         }
804     }
805
806     /**
807      * Does the actual test.
808      * 
809      * @param testFile input file
810      */
811     public void test(String testFile) {
812         try (InputStream is = new FileInputStream(new File(testFile))) {
813             //
814             // Read the yaml into our Java Object
815             //
816             Yaml yaml = new Yaml(new Constructor(ControlLoopPolicy.class));
817             Object obj = yaml.load(is);
818             assertNotNull(obj);
819             assertTrue(obj instanceof ControlLoopPolicy);
820             ControlLoopPolicy policyTobuild = (ControlLoopPolicy) obj;
821             //
822             // Now we're going to try to use the builder to build this.
823             //
824             ControlLoopPolicyBuilder builder = ControlLoopPolicyBuilder.Factory.buildControlLoop(
825                     policyTobuild.getControlLoop().getControlLoopName(), policyTobuild.getControlLoop().getTimeout());
826             //
827             // Add services
828             //
829             if (policyTobuild.getControlLoop().getServices() != null) {
830                 builder = builder.addService(policyTobuild.getControlLoop().getServices()
831                         .toArray(new Service[policyTobuild.getControlLoop().getServices().size()]));
832             }
833             //
834             // Add resources
835             //
836             if (policyTobuild.getControlLoop().getResources() != null) {
837                 builder = builder.addResource(policyTobuild.getControlLoop().getResources()
838                         .toArray(new Resource[policyTobuild.getControlLoop().getResources().size()]));
839             }
840             //
841             // Set pnf
842             //
843             if (policyTobuild.getControlLoop().getPnf() != null) {
844                 builder = builder.setPNF(policyTobuild.getControlLoop().getPnf());
845             }
846             //
847             // Add the policies and be sure to set the trigger policy
848             //
849             if (policyTobuild.getPolicies() != null) {
850                 for (Policy policy : policyTobuild.getPolicies()) {
851                     if (policy.getId() == policyTobuild.getControlLoop().getTrigger_policy()) {
852                         builder.setTriggerPolicy(
853                                 PolicyParam.builder()
854                                 .id(UUID.randomUUID().toString())
855                                 .name(policy.getName())
856                                 .description(policy.getDescription())
857                                 .actor(policy.getActor())
858                                 .target(policy.getTarget())
859                                 .recipe(policy.getRecipe())
860                                 .payload(null)
861                                 .retries(policy.getRetry())
862                                 .timeout(policy.getTimeout()).build());
863                     }
864                 }
865             }
866
867             // Question : how to change policy ID and results by using builder ??
868
869             @SuppressWarnings("unused")
870             Results results = builder.buildSpecification();
871
872         } catch (FileNotFoundException e) {
873             fail(e.getLocalizedMessage());
874         } catch (IOException e) {
875             fail(e.getLocalizedMessage());
876         } catch (BuilderException e) {
877             fail(e.getLocalizedMessage());
878         }
879
880     }
881
882 }