2 * ============LICENSE_START=======================================================
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
11 * http://www.apache.org/licenses/LICENSE-2.0
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=========================================================
21 package org.onap.policy.template.demo;
23 import static org.junit.Assert.fail;
26 import java.io.FileInputStream;
27 import java.io.FileNotFoundException;
28 import java.io.IOException;
29 import java.io.InputStream;
30 import java.nio.charset.StandardCharsets;
31 import java.nio.file.Files;
32 import java.nio.file.Path;
33 import java.nio.file.Paths;
34 import java.util.regex.Matcher;
35 import java.util.regex.Pattern;
37 import org.apache.commons.io.IOUtils;
38 import org.kie.api.KieServices;
39 import org.kie.api.builder.KieBuilder;
40 import org.kie.api.builder.KieFileSystem;
41 import org.kie.api.builder.Message;
42 import org.kie.api.builder.ReleaseId;
43 import org.kie.api.builder.Results;
44 import org.kie.api.builder.model.KieModuleModel;
45 import org.kie.api.runtime.KieContainer;
46 import org.kie.api.runtime.KieSession;
47 import org.onap.policy.controlloop.ControlLoopLogger;
48 import org.onap.policy.controlloop.impl.ControlLoopLoggerStdOutImpl;
49 import org.onap.policy.controlloop.policy.ControlLoopPolicy;
50 import org.onap.policy.controlloop.policy.guard.ControlLoopGuard;
51 import org.onap.policy.drools.http.server.HttpServletServer;
52 import org.onap.policy.drools.impl.PolicyEngineJUnitImpl;
53 import org.onap.policy.drools.system.PolicyEngine;
54 import org.onap.policy.guard.PolicyGuardYamlToXacml;
55 import org.slf4j.Logger;
56 import org.slf4j.LoggerFactory;
57 import org.yaml.snakeyaml.Yaml;
58 import org.yaml.snakeyaml.constructor.Constructor;
60 import com.att.research.xacml.api.pdp.PDPEngine;
61 import com.att.research.xacml.api.pdp.PDPEngineFactory;
62 import com.att.research.xacml.util.FactoryException;
63 import com.att.research.xacml.util.XACMLProperties;
65 public final class Util {
67 private static final Logger logger = LoggerFactory.getLogger(Util.class);
68 public static class Pair<A, B> {
72 public Pair(A a, B b) {
78 public static Pair<ControlLoopPolicy, String> loadYaml(String testFile) {
79 try (InputStream is = new FileInputStream(new File(testFile))) {
80 String contents = IOUtils.toString(is, StandardCharsets.UTF_8);
82 // Read the yaml into our Java Object
84 Yaml yaml = new Yaml(new Constructor(ControlLoopPolicy.class));
85 Object obj = yaml.load(contents);
87 //String ttt = ((ControlLoopPolicy)obj).policies.getFirst().payload.get("asdas");
88 logger.debug(contents);
89 //for(Policy policy : ((ControlLoopPolicy)obj).policies){
91 return new Pair<ControlLoopPolicy, String>((ControlLoopPolicy) obj, contents);
92 } catch (FileNotFoundException e) {
93 fail(e.getLocalizedMessage());
94 } catch (IOException e) {
95 fail(e.getLocalizedMessage());
100 public static ControlLoopGuard loadYamlGuard(String testFile) {
101 try (InputStream is = new FileInputStream(new File(testFile))) {
102 String contents = IOUtils.toString(is, StandardCharsets.UTF_8);
104 // Read the yaml into our Java Object
106 Yaml yaml = new Yaml(new Constructor(ControlLoopGuard.class));
107 Object obj = yaml.load(contents);
108 return (ControlLoopGuard) obj;
109 } catch (FileNotFoundException e) {
110 fail(e.getLocalizedMessage());
111 } catch (IOException e) {
112 fail(e.getLocalizedMessage());
117 public static HttpServletServer buildAaiSim() throws InterruptedException, IOException {
118 return org.onap.policy.simulators.Util.buildAaiSim();
121 public static HttpServletServer buildSoSim() throws InterruptedException, IOException {
122 return org.onap.policy.simulators.Util.buildSoSim();
125 public static HttpServletServer buildVfcSim() throws InterruptedException, IOException {
126 return org.onap.policy.simulators.Util.buildVfcSim();
129 public static HttpServletServer buildGuardSim() throws InterruptedException, IOException {
130 return org.onap.policy.simulators.Util.buildGuardSim();
133 private static String generatePolicy(String ruleContents,
134 String closedLoopControlName,
137 String policyVersion,
138 String controlLoopYaml) {
140 Pattern p = Pattern.compile("\\$\\{closedLoopControlName\\}");
141 Matcher m = p.matcher(ruleContents);
142 ruleContents = m.replaceAll(closedLoopControlName);
144 p = Pattern.compile("\\$\\{policyScope\\}");
145 m = p.matcher(ruleContents);
146 ruleContents = m.replaceAll(policyScope);
148 p = Pattern.compile("\\$\\{policyName\\}");
149 m = p.matcher(ruleContents);
150 ruleContents = m.replaceAll(policyName);
152 p = Pattern.compile("\\$\\{policyVersion\\}");
153 m = p.matcher(ruleContents);
154 ruleContents = m.replaceAll(policyVersion);
156 p = Pattern.compile("\\$\\{controlLoopYaml\\}");
157 m = p.matcher(ruleContents);
158 ruleContents = m.replaceAll(controlLoopYaml);
163 public static KieSession buildContainer(String droolsTemplate, String closedLoopControlName, String policyScope, String policyName, String policyVersion, String yamlSpecification) throws IOException {
165 // Get our Drools Kie factory
167 KieServices ks = KieServices.Factory.get();
169 KieModuleModel kModule = ks.newKieModuleModel();
171 logger.debug("KMODULE:" + System.lineSeparator() + kModule.toXML());
174 // Generate our drools rule from our template
176 KieFileSystem kfs = ks.newKieFileSystem();
178 kfs.writeKModuleXML(kModule.toXML());
180 Path rule = Paths.get(droolsTemplate);
181 String ruleTemplate = new String(Files.readAllBytes(rule));
182 String drlContents = generatePolicy(ruleTemplate,
183 closedLoopControlName,
189 kfs.write("src/main/resources/" + policyName + ".drl", ks.getResources().newByteArrayResource(drlContents.getBytes()));
194 KieBuilder builder = ks.newKieBuilder(kfs).buildAll();
195 Results results = builder.getResults();
196 if (results.hasMessages(Message.Level.ERROR)) {
197 for (Message msg : results.getMessages()) {
198 logger.error(msg.toString());
200 throw new RuntimeException("Drools Rule has Errors");
202 for (Message msg : results.getMessages()) {
203 logger.debug(msg.toString());
206 // Create our kie Session and container
208 ReleaseId releaseId = ks.getRepository().getDefaultReleaseId();
209 logger.debug(releaseId.toString());
210 KieContainer kContainer = ks.newKieContainer(releaseId);
212 return setupSession(kContainer.newKieSession());
215 private static KieSession setupSession (KieSession kieSession) {
219 // Create XACML Guard policy from YAML
220 // We prepare 4 Guards. Notice that Rebuilds recipe has two Guards (for checking policy combining algorithm)
222 PolicyGuardYamlToXacml.fromYamlToXacml("src/test/resources/yaml/policy_guard_appc_restart.yaml",
223 "src/main/resources/frequency_limiter_template.xml",
224 "src/test/resources/xacml/autogenerated_frequency_limiter_restart.xml");
226 PolicyGuardYamlToXacml.fromYamlToXacml("src/test/resources/yaml/policy_guard_appc_rebuild.yaml",
227 "src/main/resources/frequency_limiter_template.xml",
228 "src/test/resources/xacml/autogenerated_frequency_limiter_rebuild.xml");
230 PolicyGuardYamlToXacml.fromYamlToXacml("src/test/resources/yaml/policy_guard_appc_rebuild_1.yaml",
231 "src/main/resources/frequency_limiter_template.xml",
232 "src/test/resources/xacml/autogenerated_frequency_limiter_rebuild_1.xml");
234 PolicyGuardYamlToXacml.fromYamlToXacml("src/test/resources/yaml/policy_guard_appc_migrate.yaml",
235 "src/main/resources/frequency_limiter_template.xml",
236 "src/test/resources/xacml/autogenerated_frequency_limiter_migrate.xml");
238 PolicyGuardYamlToXacml.fromYamlToXacml("src/test/resources/yaml/policy_guard_appc_modifyconfig.yaml",
239 "src/main/resources/frequency_limiter_template.xml",
240 "src/test/resources/xacml/autogenerated_frequency_limiter_modifyconfig.xml");
242 PolicyGuardYamlToXacml.fromYamlToXacmlBlacklist("src/test/resources/yaml/policy_guard_appc_restart_blacklist.yaml",
243 "src/main/resources/blacklist_template.xml",
244 "src/test/resources/xacml/autogenerated_blacklist.xml");
248 // Insert our globals
250 final ControlLoopLogger controlLoopLogger = new ControlLoopLoggerStdOutImpl();
251 kieSession.setGlobal("Logger", controlLoopLogger);
252 final PolicyEngineJUnitImpl engine = new PolicyEngineJUnitImpl();
253 kieSession.setGlobal("Engine", engine);
257 // Creating an embedded XACML PDP
259 final PDPEngine xacmlPdpEngine;
260 System.setProperty(XACMLProperties.XACML_PROPERTIES_NAME, "src/test/resources/xacml/xacml_guard.properties");
262 PDPEngineFactory factory;
264 factory = PDPEngineFactory.newInstance();
265 xacmlPdpEngine = factory.newEngine();
266 kieSession.setGlobal("XacmlPdpEngine", xacmlPdpEngine);
267 } catch (FactoryException e1) {
268 e1.printStackTrace();
273 public static void setAAIProps(){
274 PolicyEngine.manager.setEnvironmentProperty("aai.url", "http://localhost:6666");
275 PolicyEngine.manager.setEnvironmentProperty("aai.username", "AAI");
276 PolicyEngine.manager.setEnvironmentProperty("aai.password", "AAI");
278 public static void setSOProps(){
279 PolicyEngine.manager.setEnvironmentProperty("so.url", "http://localhost:6667");
280 PolicyEngine.manager.setEnvironmentProperty("so.username", "SO");
281 PolicyEngine.manager.setEnvironmentProperty("so.password", "SO");