3133273f93008ebccb2f0e9b63efc7d64b4d1abe
[policy/drools-applications.git] /
1 /*-
2  * ============LICENSE_START=======================================================
3  * policy-yaml unit test
4  * ================================================================================
5  * Copyright (C) 2017 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 vSCP = new Service("vSCP");
73             Service vUSP = new Service("vUSP");
74             Service vTrinity = new Service("Trinity");
75             builder = builder.addService(vSCP, vUSP, vTrinity);
76             assertTrue(builder.getControlLoop().getServices().size() == 3);
77             //
78             // Test remove services
79             //
80             builder = builder.removeService(vSCP);
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 vCTS = new Resource("vCTS", ResourceType.VF);
88             Resource vCOM = new Resource("vCTS", ResourceType.VF);
89             Resource vRAR = new Resource("vCTS", ResourceType.VF);
90             builder = builder.addResource(vCTS, vCOM, vRAR);
91             assertTrue(builder.getControlLoop().getResources().size() == 3);
92             //
93             // Test remove resources
94             //
95             builder = builder.removeResource(vCTS);
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 vCTS = new Resource("vCTS", ResourceType.VF);
211             Service vSCP = new Service("vSCP");
212             Service vUSP = new Service("vUSP");
213             ControlLoopPolicyBuilder builder = ControlLoopPolicyBuilder.Factory
214                     .buildControlLoop(UUID.randomUUID().toString(), 2400, vCTS, vSCP, vUSP);
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 vCTS = new Resource("vCTS", ResourceType.VF);
226             Resource vCOM = new Resource("vCTS", ResourceType.VF);
227             Service vSCP = new Service("vSCP");
228             ControlLoopPolicyBuilder builder = ControlLoopPolicyBuilder.Factory
229                     .buildControlLoop(UUID.randomUUID().toString(), 2400, vSCP, vCTS, vCOM);
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("Restart the VM", "Upon getting the trigger event, restart the VM", "APPC",
333                             new Target(TargetType.VM), "Restart", null, 2, 300);
334             @SuppressWarnings("unused")
335             Policy onRestartFailurePolicy = builder.setPolicyForPolicyResult("Rebuild VM",
336                     "If the restart fails, rebuild it", "APPC", new Target(TargetType.VM), "Rebuild", null, 1, 600,
337                     trigger.getId(), PolicyResult.FAILURE, PolicyResult.FAILURE_RETRIES, PolicyResult.FAILURE_TIMEOUT);
338             assertTrue(builder.calculateTimeout().equals(new Integer(300 + 600)));
339             //
340         } catch (BuilderException e) {
341             fail(e.getMessage());
342         }
343     }
344
345     @Test
346     public void testTriggerPolicyMethods() {
347         try {
348             ControlLoopPolicyBuilder builder =
349                     ControlLoopPolicyBuilder.Factory.buildControlLoop(UUID.randomUUID().toString(), 2400);
350             //
351             // Test isOpenLoop
352             //
353             assertTrue(builder.isOpenLoop());
354             //
355             // Test set initial trigger policy
356             //
357             Policy triggerPolicy1 =
358                     builder.setTriggerPolicy("Restart the VM", "Upon getting the trigger event, restart the VM", "APPC",
359                             new Target(TargetType.VM), "Restart", null, 2, 300);
360             assertTrue(builder.isOpenLoop() == false);
361             assertTrue(builder.getControlLoop().getTrigger_policy().equals(triggerPolicy1.getId()));
362             //
363             // Set trigger policy to a new policy
364             //
365             @SuppressWarnings("unused")
366             Policy triggerPolicy2 =
367                     builder.setTriggerPolicy("Rebuild the VM", "Upon getting the trigger event, rebuild the VM", "APPC",
368                             new Target(TargetType.VM), "Rebuild", null, 2, 300);
369             //
370             // Test set trigger policy to another existing policy
371             //
372             @SuppressWarnings("unused")
373             ControlLoop cl = builder.setTriggerPolicy(triggerPolicy1.getId());
374             assertTrue(builder.getControlLoop().getTrigger_policy().equals(triggerPolicy1.getId()));
375             //
376             // Test get trigger policy
377             //
378             assertTrue(builder.getTriggerPolicy().equals(triggerPolicy1));
379             //
380         } catch (BuilderException e) {
381             fail(e.getMessage());
382         }
383     }
384
385     @Test
386     public void testSetTriggerPolicyNullPolicyId() throws BuilderException {
387         ControlLoopPolicyBuilder builder =
388                 ControlLoopPolicyBuilder.Factory.buildControlLoop(UUID.randomUUID().toString(), 2400);
389         expectedException.expect(BuilderException.class);
390         expectedException.expectMessage("Id must not be null");
391         builder.setTriggerPolicy(null);
392     }
393
394     @Test
395     public void testSetTriggerPolicyNoPoliciesExist() throws BuilderException {
396         ControlLoopPolicyBuilder builder =
397                 ControlLoopPolicyBuilder.Factory.buildControlLoop(UUID.randomUUID().toString(), 2400);
398         final String unknownPolicyId = "100";
399         expectedException.expect(BuilderException.class);
400         expectedException.expectMessage("Unknown policy " + unknownPolicyId);
401         builder.setTriggerPolicy(unknownPolicyId);
402     }
403
404     @Test
405     public void testSetTriggerPolicyUnknownPolicy() throws BuilderException {
406         ControlLoopPolicyBuilder builder =
407                 ControlLoopPolicyBuilder.Factory.buildControlLoop(UUID.randomUUID().toString(), 2400);
408         builder.setTriggerPolicy("Restart the VM", "Upon getting the trigger event, restart the VM", "APPC",
409                 new Target(TargetType.VM), "Restart", null, 2, 300);
410         final String unknownPolicyId = "100";
411         expectedException.expect(BuilderException.class);
412         expectedException.expectMessage("Unknown policy " + unknownPolicyId);
413         builder.setTriggerPolicy(unknownPolicyId);
414     }
415
416     @Test
417     public void testAddRemovePolicies() {
418         try {
419             ControlLoopPolicyBuilder builder =
420                     ControlLoopPolicyBuilder.Factory.buildControlLoop(UUID.randomUUID().toString(), 2400);
421             Policy triggerPolicy =
422                     builder.setTriggerPolicy("Restart the VM", "Upon getting the trigger event, restart the VM", "APPC",
423                             new Target(TargetType.VM), "Restart", null, 2, 300);
424             //
425             // Test create a policy and chain it to the results of trigger policy
426             //
427             Policy onRestartFailurePolicy1 = builder.setPolicyForPolicyResult("Rebuild VM",
428                     "If the restart fails, rebuild it.", "APPC", new Target(TargetType.VM), "Rebuild", null, 1, 600,
429                     triggerPolicy.getId(), PolicyResult.FAILURE, PolicyResult.FAILURE_EXCEPTION,
430                     PolicyResult.FAILURE_RETRIES, PolicyResult.FAILURE_TIMEOUT, PolicyResult.FAILURE_GUARD);
431             //
432             assertTrue(builder.getTriggerPolicy().getFailure().equals(onRestartFailurePolicy1.getId()));
433             assertTrue(builder.getTriggerPolicy().getFailure_exception().equals(onRestartFailurePolicy1.getId()));
434             assertTrue(builder.getTriggerPolicy().getFailure_retries().equals(onRestartFailurePolicy1.getId()));
435             assertTrue(builder.getTriggerPolicy().getFailure_timeout().equals(onRestartFailurePolicy1.getId()));
436             assertTrue(builder.getTriggerPolicy().getFailure_guard().equals(onRestartFailurePolicy1.getId()));
437
438             //
439             // Test create a policy and chain it to the results of trigger policy success
440             //
441             Policy onSuccessPolicy1 = builder.setPolicyForPolicyResult("Do something",
442                     "If the restart succeeds, do something else.", "APPC", new Target(TargetType.VM), "SomethingElse",
443                     null, 1, 600, triggerPolicy.getId(), PolicyResult.SUCCESS);
444             //
445             assertTrue(builder.getTriggerPolicy().getSuccess().equals(onSuccessPolicy1.getId()));
446
447             //
448             // Test remove policy
449             //
450             boolean removed = builder.removePolicy(onRestartFailurePolicy1.getId());
451             assertTrue(removed);
452             assertTrue(builder.getTriggerPolicy().getFailure().equals(FinalResult.FINAL_FAILURE.toString()));
453             assertTrue(builder.getTriggerPolicy().getFailure_retries()
454                     .equals(FinalResult.FINAL_FAILURE_RETRIES.toString()));
455             assertTrue(builder.getTriggerPolicy().getFailure_timeout()
456                     .equals(FinalResult.FINAL_FAILURE_TIMEOUT.toString()));
457             assertTrue(
458                     builder.getTriggerPolicy().getFailure_guard().equals(FinalResult.FINAL_FAILURE_GUARD.toString()));
459             //
460             // Create another policy and chain it to the results of trigger policy
461             //
462             Policy onRestartFailurePolicy2 =
463                     builder.setPolicyForPolicyResult("Rebuild VM", "If the restart fails, rebuild it.", "APPC",
464                             new Target(TargetType.VM), "Rebuild", null, 2, 600, triggerPolicy.getId(),
465                             PolicyResult.FAILURE, PolicyResult.FAILURE_RETRIES, PolicyResult.FAILURE_TIMEOUT);
466             //
467             // Test reset policy results
468             //
469             triggerPolicy = builder.resetPolicyResults(triggerPolicy.getId());
470             assertTrue(builder.getTriggerPolicy().getFailure().equals(FinalResult.FINAL_FAILURE.toString()));
471             assertTrue(builder.getTriggerPolicy().getFailure_retries()
472                     .equals(FinalResult.FINAL_FAILURE_RETRIES.toString()));
473             assertTrue(builder.getTriggerPolicy().getFailure_timeout()
474                     .equals(FinalResult.FINAL_FAILURE_TIMEOUT.toString()));
475             //
476             // Test set the policy results to an existing operational policy
477             //
478             onRestartFailurePolicy2 =
479                     builder.setPolicyForPolicyResult(onRestartFailurePolicy2.getId(), triggerPolicy.getId(),
480                             PolicyResult.FAILURE, PolicyResult.FAILURE_RETRIES, PolicyResult.FAILURE_TIMEOUT);
481             assertTrue(builder.getTriggerPolicy().getFailure().equals(onRestartFailurePolicy2.getId()));
482             assertTrue(builder.getTriggerPolicy().getFailure_retries().equals(onRestartFailurePolicy2.getId()));
483             assertTrue(builder.getTriggerPolicy().getFailure_timeout().equals(onRestartFailurePolicy2.getId()));
484             //
485             // Test set the policy result for success to an existing operational policy
486             //
487             onRestartFailurePolicy2 =
488                     builder.setPolicyForPolicyResult(onRestartFailurePolicy2.getId(), triggerPolicy.getId(),
489                             PolicyResult.FAILURE, PolicyResult.FAILURE_EXCEPTION, PolicyResult.FAILURE_GUARD,
490                             PolicyResult.FAILURE_RETRIES, PolicyResult.FAILURE_TIMEOUT, PolicyResult.SUCCESS);
491             assertTrue(builder.getTriggerPolicy().getFailure().equals(onRestartFailurePolicy2.getId()));
492             assertTrue(builder.getTriggerPolicy().getFailure_exception().equals(onRestartFailurePolicy2.getId()));
493             assertTrue(builder.getTriggerPolicy().getFailure_guard().equals(onRestartFailurePolicy2.getId()));
494             assertTrue(builder.getTriggerPolicy().getFailure_retries().equals(onRestartFailurePolicy2.getId()));
495             assertTrue(builder.getTriggerPolicy().getFailure_timeout().equals(onRestartFailurePolicy2.getId()));
496             assertTrue(builder.getTriggerPolicy().getSuccess().equals(onRestartFailurePolicy2.getId()));
497
498             //
499             // Test remove all existing operational policies
500             //
501             builder = builder.removeAllPolicies();
502             assertTrue(builder.getControlLoop().getTrigger_policy().equals(FinalResult.FINAL_OPENLOOP.toString()));
503             //
504         } catch (BuilderException e) {
505             fail(e.getMessage());
506         }
507     }
508
509     @Test
510     public void testAddToUnknownPolicy() throws BuilderException {
511         ControlLoopPolicyBuilder builder =
512                 ControlLoopPolicyBuilder.Factory.buildControlLoop(UUID.randomUUID().toString(), 2400);
513         final String policyId = "100";
514         expectedException.expect(BuilderException.class);
515         expectedException.expectMessage("Unknown policy " + policyId);
516
517         builder.setPolicyForPolicyResult("Rebuild VM", "If the restart fails, rebuild it.", "APPC",
518                 new Target(TargetType.VM), "Rebuild", null, 1, 600, policyId, PolicyResult.FAILURE,
519                 PolicyResult.FAILURE_RETRIES, PolicyResult.FAILURE_TIMEOUT, PolicyResult.FAILURE_GUARD);
520     }
521
522     @Test
523     public void testAddExistingPolicyToUnknownPolicy() throws BuilderException {
524         ControlLoopPolicyBuilder builder =
525                 ControlLoopPolicyBuilder.Factory.buildControlLoop(UUID.randomUUID().toString(), 2400);
526         Policy triggerPolicy =
527                 builder.setTriggerPolicy("Restart the VM", "Upon getting the trigger event, restart the VM", "APPC",
528                         new Target(TargetType.VM), "Restart", null, 2, 300);
529
530
531         Policy onRestartFailurePolicy = builder.setPolicyForPolicyResult("Rebuild VM",
532                 "If the restart fails, rebuild it.", "APPC", new Target(TargetType.VM), "Rebuild", null, 1, 600,
533                 triggerPolicy.getId(), PolicyResult.FAILURE);
534
535         final String unknownPolicyId = "100";
536         expectedException.expect(BuilderException.class);
537         expectedException.expectMessage(unknownPolicyId + " does not exist");
538
539         builder.setPolicyForPolicyResult(onRestartFailurePolicy.getId(), unknownPolicyId, PolicyResult.FAILURE);
540     }
541
542     @Test
543     public void testAddUnknownExistingPolicyToPolicy() throws BuilderException {
544         ControlLoopPolicyBuilder builder =
545                 ControlLoopPolicyBuilder.Factory.buildControlLoop(UUID.randomUUID().toString(), 2400);
546         Policy triggerPolicy =
547                 builder.setTriggerPolicy("Restart the VM", "Upon getting the trigger event, restart the VM", "APPC",
548                         new Target(TargetType.VM), "Restart", null, 2, 300);
549
550         final String unknownPolicyId = "100";
551         expectedException.expect(BuilderException.class);
552         expectedException.expectMessage("Operational policy " + unknownPolicyId + " does not exist");
553
554         builder.setPolicyForPolicyResult(unknownPolicyId, triggerPolicy.getId(), PolicyResult.FAILURE);
555     }
556
557     @Test
558     public void testAddOperationsAccumulateParams() {
559         try {
560             ControlLoopPolicyBuilder builder =
561                     ControlLoopPolicyBuilder.Factory.buildControlLoop(UUID.randomUUID().toString(), 2400);
562             Policy triggerPolicy =
563                     builder.setTriggerPolicy("Restart the eNodeB", "Upon getting the trigger event, restart the eNodeB",
564                             "RANController", new Target(TargetType.PNF), "Restart", null, 2, 300);
565             //
566             // Add the operationsAccumulateParams
567             //
568             triggerPolicy = builder.addOperationsAccumulateParams(triggerPolicy.getId(),
569                     new OperationsAccumulateParams("15m", 5));
570             assertNotNull(builder.getTriggerPolicy().getOperationsAccumulateParams());
571             assertTrue(builder.getTriggerPolicy().getOperationsAccumulateParams().getPeriod().equals("15m"));
572             assertTrue(builder.getTriggerPolicy().getOperationsAccumulateParams().getLimit() == 5);
573             //
574         } catch (BuilderException e) {
575             fail(e.getMessage());
576         }
577     }
578
579
580     @Test
581     public void testBuildSpecification() {
582         try {
583             //
584             // Create the builder
585             //
586             ControlLoopPolicyBuilder builder =
587                     ControlLoopPolicyBuilder.Factory.buildControlLoop(UUID.randomUUID().toString(), 800);
588             //
589             // Set the first invalid trigger policy
590             //
591             Policy policy1 = builder.setTriggerPolicy("Restart the VM",
592                     "Upon getting the trigger event, restart the VM", null, null, "Instantiate", null, 2, 300);
593             Results results = builder.buildSpecification();
594             //
595             // Check that ERRORs are in results for invalid policy arguments
596             //
597             boolean invalid_actor = false;
598             boolean invalid_recipe = false;
599             boolean invalid_target = false;
600             for (Message m : results.getMessages()) {
601                 if (m.getMessage().equals("Policy actor is null") && m.getLevel() == MessageLevel.ERROR) {
602                     invalid_actor = true;
603                 }
604                 if (m.getMessage().equals("Policy recipe is invalid") && m.getLevel() == MessageLevel.ERROR) {
605                     invalid_recipe = true;
606                 }
607                 if (m.getMessage().equals("Policy target is null") && m.getLevel() == MessageLevel.ERROR) {
608                     invalid_target = true;
609                 }
610             }
611             //
612             assertTrue(invalid_actor);
613             assertTrue(invalid_recipe);
614             assertTrue(invalid_target);
615             //
616             // Remove the invalid policy
617             //
618             // @SuppressWarnings("unused")
619             boolean removed = builder.removePolicy(policy1.getId());
620             assertTrue(removed);
621             assertTrue(builder.getTriggerPolicy() == null);
622             //
623             // Set a valid trigger policy
624             //
625             policy1 = builder.setTriggerPolicy("Rebuild VM", "If the restart fails, rebuild it.", "APPC",
626                     new Target(TargetType.VM), "Rebuild", null, 1, 600);
627             //
628             // Set a second valid trigger policy
629             //
630             Policy policy2 =
631                     builder.setTriggerPolicy("Restart the VM", "Upon getting the trigger event, restart the VM", "APPC",
632                             new Target(TargetType.VM), "Restart", null, 2, 300);
633             //
634             // Now, we have policy1 unreachable
635             //
636             results = builder.buildSpecification();
637             boolean unreachable = false;
638             for (Message m : results.getMessages()) {
639                 if (m.getMessage().equals("Policy " + policy1.getId() + " is not reachable.")
640                         && m.getLevel() == MessageLevel.WARNING) {
641                     unreachable = true;
642                     break;
643                 }
644             }
645             assertTrue(unreachable);
646             //
647             // Set policy1 for the failure results of policy2
648             //
649             policy1 = builder.setPolicyForPolicyResult(policy1.getId(), policy2.getId(), PolicyResult.FAILURE,
650                     PolicyResult.FAILURE_RETRIES, PolicyResult.FAILURE_TIMEOUT);
651             results = builder.buildSpecification();
652             boolean invalid_timeout = false;
653             for (Message m : results.getMessages()) {
654                 if (m.getMessage()
655                         .equals("controlLoop overall timeout is less than the sum of operational policy timeouts.")
656                         && m.getLevel() == MessageLevel.ERROR) {
657                     invalid_timeout = true;
658                     break;
659                 }
660             }
661             assertTrue(invalid_timeout);
662             //
663             // Remove policy2 (revert controlLoop back to open loop)
664             //
665             removed = builder.removePolicy(policy2.getId());
666             //
667             // ControlLoop is open loop now, but it still has policies (policy1)
668             //
669             results = builder.buildSpecification();
670             unreachable = false;
671             for (Message m : results.getMessages()) {
672                 if (m.getMessage().equals("Open Loop policy contains policies. The policies will never be invoked.")
673                         && m.getLevel() == MessageLevel.WARNING) {
674                     unreachable = true;
675                     break;
676                 }
677             }
678             assertTrue(unreachable);
679             //
680         } catch (BuilderException e) {
681             fail(e.getMessage());
682         }
683     }
684
685
686     @Test
687     public void test() {
688         this.test("src/test/resources/v1.0.0/policy_Test.yaml");
689     }
690
691     @Test
692     public void testEvilYaml() {
693         try (InputStream is = new FileInputStream(new File("src/test/resources/v1.0.0/test_evil.yaml"))) {
694             //
695             // Read the yaml into our Java Object
696             //
697             Yaml yaml = new Yaml(new Constructor(ControlLoopPolicy.class));
698             yaml.load(is);
699         } catch (FileNotFoundException e) {
700             fail(e.getLocalizedMessage());
701         } catch (IOException e) {
702             fail(e.getLocalizedMessage());
703         } catch (YAMLException e) {
704             //
705             // Should have this
706             //
707         }
708     }
709
710     public void test(String testFile) {
711         try (InputStream is = new FileInputStream(new File(testFile))) {
712             //
713             // Read the yaml into our Java Object
714             //
715             Yaml yaml = new Yaml(new Constructor(ControlLoopPolicy.class));
716             Object obj = yaml.load(is);
717             assertNotNull(obj);
718             assertTrue(obj instanceof ControlLoopPolicy);
719             ControlLoopPolicy policyTobuild = (ControlLoopPolicy) obj;
720             //
721             // Now we're going to try to use the builder to build this.
722             //
723             ControlLoopPolicyBuilder builder = ControlLoopPolicyBuilder.Factory.buildControlLoop(
724                     policyTobuild.getControlLoop().getControlLoopName(), policyTobuild.getControlLoop().getTimeout());
725             //
726             // Add services
727             //
728             if (policyTobuild.getControlLoop().getServices() != null) {
729                 builder = builder.addService(policyTobuild.getControlLoop().getServices()
730                         .toArray(new Service[policyTobuild.getControlLoop().getServices().size()]));
731             }
732             //
733             // Add resources
734             //
735             if (policyTobuild.getControlLoop().getResources() != null) {
736                 builder = builder.addResource(policyTobuild.getControlLoop().getResources()
737                         .toArray(new Resource[policyTobuild.getControlLoop().getResources().size()]));
738             }
739             //
740             // Set pnf
741             //
742             if (policyTobuild.getControlLoop().getPnf() != null) {
743                 builder = builder.setPNF(policyTobuild.getControlLoop().getPnf());
744             }
745             //
746             // Add the policies and be sure to set the trigger policy
747             //
748             if (policyTobuild.getPolicies() != null) {
749                 for (Policy policy : policyTobuild.getPolicies()) {
750                     if (policy.getId() == policyTobuild.getControlLoop().getTrigger_policy()) {
751                         builder.setTriggerPolicy(policy.getName(), policy.getDescription(), policy.getActor(),
752                                 policy.getTarget(), policy.getRecipe(), null, policy.getRetry(), policy.getTimeout());
753                     }
754                 }
755             }
756
757             // Question : how to change policy ID and results by using builder ??
758
759             @SuppressWarnings("unused")
760             Results results = builder.buildSpecification();
761
762         } catch (FileNotFoundException e) {
763             fail(e.getLocalizedMessage());
764         } catch (IOException e) {
765             fail(e.getLocalizedMessage());
766         } catch (BuilderException e) {
767             fail(e.getLocalizedMessage());
768         }
769
770     }
771
772 }